castle-web-cli 0.4.148 → 0.4.150
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/api.d.ts +14 -0
- package/dist/api.js +18 -0
- package/dist/castle-host/host.d.ts +17 -0
- package/dist/castle-host/host.js +58 -0
- package/dist/castleJson.d.ts +15 -0
- package/dist/castleJson.js +36 -0
- package/dist/devSessionChild.d.ts +1 -0
- package/dist/devSessionChild.js +129 -0
- package/dist/devSessionServer.d.ts +19 -0
- package/dist/devSessionServer.js +511 -0
- package/dist/index.js +8 -8
- package/dist/init.js +10 -2
- package/dist/list-decks.js +7 -6
- package/dist/preview.d.ts +1 -1
- package/dist/preview.js +4 -2
- package/dist/save-deck.js +63 -14
- package/dist/serve.js +269 -108
- package/dist/serveSecurity.d.ts +7 -1
- package/dist/serveSecurity.js +65 -16
- package/dist/serverBundle.d.ts +8 -0
- package/dist/serverBundle.js +82 -0
- package/dist/shell/assets/{index-CL9TuLXb.js → index-Dlhc3eZW.js} +42 -42
- package/dist/shell/assets/index-DwezawBs.css +1 -0
- package/dist/shell/index.html +2 -2
- package/kits/blank/castle.json +5 -2
- package/kits/physics-2d/behaviors/Collider.jsx +1 -2
- package/kits/physics-2d/behaviors/Joints.jsx +1 -1
- package/kits/physics-2d/castle.json +1 -1
- package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
- package/kits/physics-2d/editors/SceneEditor.jsx +319 -140
- package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
- package/kits/physics-2d/engine/blueprint.js +106 -14
- package/kits/physics-2d/engine/scene.js +9 -2
- package/kits/physics-2d/engine/ui.jsx +30 -2
- package/kits/physics-2d/engine/ui.module.css +59 -0
- package/kits/physics-3d/castle.json +1 -1
- package/kits/physics-3d/engine3d/PxModelEditor.jsx +29 -13
- package/kits/physics-3d/engine3d/Scene3DEditor.jsx +26 -7
- package/kits/physics-3d/engine3d/editorChrome.jsx +26 -1
- package/package.json +1 -1
- package/dist/shell/assets/index-DN8HQBnW.css +0 -1
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
import * as http from 'http';
|
|
5
|
+
import * as os from 'os';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import { fileURLToPath } from 'url';
|
|
8
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
9
|
+
import { readCastleJson, resolveServerConfig, } from './castleJson.js';
|
|
10
|
+
import { bundleServerModule } from './serverBundle.js';
|
|
11
|
+
const PROTOCOL_VERSION = 1;
|
|
12
|
+
const MAX_CLIENT_FRAME_BYTES = 16 * 1024;
|
|
13
|
+
const NONCE_TTL_MS = 60_000;
|
|
14
|
+
const CHILD_READY_TIMEOUT_MS = 15_000;
|
|
15
|
+
const CHILD_STOP_GRACE_MS = 2_000;
|
|
16
|
+
export async function startDevSessionServer(opts) {
|
|
17
|
+
const server = new DevSessionServerImpl(opts.projectDir, opts.log);
|
|
18
|
+
try {
|
|
19
|
+
await server.start();
|
|
20
|
+
return server;
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
await server.shutdown();
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
class DevSessionServerImpl {
|
|
28
|
+
projectDir;
|
|
29
|
+
log;
|
|
30
|
+
sessionId = 'dev';
|
|
31
|
+
port = 0;
|
|
32
|
+
server = http.createServer((_req, res) => res.writeHead(404).end());
|
|
33
|
+
clientWss = new WebSocketServer({ noServer: true, maxPayload: MAX_CLIENT_FRAME_BYTES });
|
|
34
|
+
platformWss = new WebSocketServer({ noServer: true, maxPayload: 80 * 1024 });
|
|
35
|
+
nonces = new Map();
|
|
36
|
+
reconnects = new Map();
|
|
37
|
+
players = new Map();
|
|
38
|
+
child = null;
|
|
39
|
+
platformSocket = null;
|
|
40
|
+
bootToken = '';
|
|
41
|
+
runtimeReady = false;
|
|
42
|
+
primaryPlayerId = null;
|
|
43
|
+
guestNumber = 0;
|
|
44
|
+
restartTimer = null;
|
|
45
|
+
restartQueue = Promise.resolve();
|
|
46
|
+
tempDir = null;
|
|
47
|
+
closed = false;
|
|
48
|
+
readyResolve = null;
|
|
49
|
+
readyReject = null;
|
|
50
|
+
serverEntry;
|
|
51
|
+
serverSettings;
|
|
52
|
+
constructor(projectDir, log) {
|
|
53
|
+
this.projectDir = projectDir;
|
|
54
|
+
this.log = log;
|
|
55
|
+
this.serverEntry = resolveServerConfig(projectDir)?.entry ?? 'server/index.js';
|
|
56
|
+
this.serverSettings = JSON.stringify(readCastleJson(projectDir)?.server ?? null);
|
|
57
|
+
this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
|
|
58
|
+
}
|
|
59
|
+
async start() {
|
|
60
|
+
await new Promise((resolve, reject) => {
|
|
61
|
+
this.server.once('error', reject);
|
|
62
|
+
this.server.listen(0, '127.0.0.1', () => {
|
|
63
|
+
this.server.off('error', reject);
|
|
64
|
+
const address = this.server.address();
|
|
65
|
+
if (!address || typeof address === 'string')
|
|
66
|
+
reject(new Error('dev session server has no port'));
|
|
67
|
+
else {
|
|
68
|
+
this.port = address.port;
|
|
69
|
+
resolve();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
await this.restartChild();
|
|
74
|
+
}
|
|
75
|
+
mintNonce(author) {
|
|
76
|
+
this.pruneNonces();
|
|
77
|
+
const nonce = randomUUID();
|
|
78
|
+
this.nonces.set(nonce, { author, mintedAt: Date.now() });
|
|
79
|
+
return nonce;
|
|
80
|
+
}
|
|
81
|
+
handleFilesChanged(message) {
|
|
82
|
+
const nextSettings = JSON.stringify(readCastleJson(this.projectDir)?.server ?? null);
|
|
83
|
+
const serverSettingsChanged = message.changes.some((change) => change.path === 'castle.json') &&
|
|
84
|
+
nextSettings !== this.serverSettings;
|
|
85
|
+
this.serverSettings = nextSettings;
|
|
86
|
+
if (!serverSettingsChanged &&
|
|
87
|
+
!message.changes.some((change) => change.path === this.serverEntry || change.path.startsWith('server/')))
|
|
88
|
+
return;
|
|
89
|
+
if (this.restartTimer)
|
|
90
|
+
clearTimeout(this.restartTimer);
|
|
91
|
+
this.restartTimer = setTimeout(() => {
|
|
92
|
+
this.restartTimer = null;
|
|
93
|
+
this.restartQueue = this.restartQueue.then(() => this.restartChild()).catch((error) => {
|
|
94
|
+
this.log('error', `restart failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
95
|
+
});
|
|
96
|
+
}, 100);
|
|
97
|
+
}
|
|
98
|
+
async shutdown() {
|
|
99
|
+
if (this.closed)
|
|
100
|
+
return;
|
|
101
|
+
this.closed = true;
|
|
102
|
+
if (this.restartTimer)
|
|
103
|
+
clearTimeout(this.restartTimer);
|
|
104
|
+
this.closeClients(1001, 'dev serve stopped');
|
|
105
|
+
await this.stopChild();
|
|
106
|
+
await Promise.all([
|
|
107
|
+
closeWebSocketServer(this.clientWss),
|
|
108
|
+
closeWebSocketServer(this.platformWss),
|
|
109
|
+
closeHttpServer(this.server),
|
|
110
|
+
]);
|
|
111
|
+
this.removeTempDir();
|
|
112
|
+
}
|
|
113
|
+
shutdownNow() {
|
|
114
|
+
this.closed = true;
|
|
115
|
+
if (this.restartTimer)
|
|
116
|
+
clearTimeout(this.restartTimer);
|
|
117
|
+
this.closeClients(1001, 'dev serve stopped');
|
|
118
|
+
this.platformSocket?.terminate();
|
|
119
|
+
this.child?.kill('SIGKILL');
|
|
120
|
+
this.server.close();
|
|
121
|
+
this.removeTempDir();
|
|
122
|
+
}
|
|
123
|
+
handleUpgrade(request, socket, head) {
|
|
124
|
+
let url;
|
|
125
|
+
try {
|
|
126
|
+
url = new URL(request.url ?? '/', 'ws://127.0.0.1');
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
rejectUpgrade(socket, 400);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (url.pathname === '/__castle/platform') {
|
|
133
|
+
this.upgradePlatform(request, socket, head, url);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (url.pathname !== '/__castle/mp') {
|
|
137
|
+
rejectUpgrade(socket, 404);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const auth = this.authenticateClient(url);
|
|
141
|
+
if (!auth || !this.runtimeReady) {
|
|
142
|
+
rejectUpgrade(socket, auth ? 503 : 401);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (auth.type === 'nonce')
|
|
146
|
+
this.nonces.delete(auth.nonce);
|
|
147
|
+
this.clientWss.handleUpgrade(request, socket, head, (ws) => this.attachClient(ws, auth));
|
|
148
|
+
}
|
|
149
|
+
upgradePlatform(request, socket, head, url) {
|
|
150
|
+
if (!this.bootToken || url.searchParams.get('bootToken') !== this.bootToken || this.platformSocket) {
|
|
151
|
+
rejectUpgrade(socket, 401);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
this.bootToken = '';
|
|
155
|
+
this.platformWss.handleUpgrade(request, socket, head, (ws) => this.attachPlatform(ws));
|
|
156
|
+
}
|
|
157
|
+
authenticateClient(url) {
|
|
158
|
+
const nonce = url.searchParams.get('nonce');
|
|
159
|
+
const reconnect = url.searchParams.get('reconnect');
|
|
160
|
+
if ((!nonce && !reconnect) || (nonce && reconnect))
|
|
161
|
+
return null;
|
|
162
|
+
if (nonce) {
|
|
163
|
+
const record = this.nonces.get(nonce);
|
|
164
|
+
if (!record || Date.now() - record.mintedAt > NONCE_TTL_MS) {
|
|
165
|
+
this.nonces.delete(nonce);
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
return { type: 'nonce', nonce, record };
|
|
169
|
+
}
|
|
170
|
+
const playerId = this.reconnects.get(reconnect);
|
|
171
|
+
const player = playerId ? this.players.get(playerId) : undefined;
|
|
172
|
+
if (!player || player.reconnectToken !== reconnect || player.socket)
|
|
173
|
+
return null;
|
|
174
|
+
return { type: 'reconnect', token: reconnect, playerId: playerId };
|
|
175
|
+
}
|
|
176
|
+
attachClient(socket, auth) {
|
|
177
|
+
let playerId;
|
|
178
|
+
let player;
|
|
179
|
+
if (auth.type === 'nonce') {
|
|
180
|
+
if (this.connectedPlayers().length >= this.currentConfig().maxPlayers) {
|
|
181
|
+
socket.close(1008, 'session is full');
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
playerId = randomUUID();
|
|
185
|
+
const isFirstConnection = this.primaryPlayerId === null && this.connectedPlayers().length === 0;
|
|
186
|
+
const identity = isFirstConnection ? auth.record.author : this.nextGuest();
|
|
187
|
+
if (isFirstConnection)
|
|
188
|
+
this.primaryPlayerId = playerId;
|
|
189
|
+
player = { identity, reconnectToken: this.rotateReconnect(playerId), socket };
|
|
190
|
+
this.players.set(playerId, player);
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
playerId = auth.playerId;
|
|
194
|
+
player = this.players.get(playerId);
|
|
195
|
+
this.reconnects.delete(auth.token);
|
|
196
|
+
player.reconnectToken = this.rotateReconnect(playerId);
|
|
197
|
+
player.socket = socket;
|
|
198
|
+
}
|
|
199
|
+
socket.on('message', (data, isBinary) => this.handleClientMessage(playerId, socket, data, isBinary));
|
|
200
|
+
socket.on('close', (code) => this.detachClient(playerId, socket, code));
|
|
201
|
+
socket.on('error', () => undefined);
|
|
202
|
+
this.sendClient(socket, {
|
|
203
|
+
t: 'hello',
|
|
204
|
+
playerId,
|
|
205
|
+
reconnectToken: player.reconnectToken,
|
|
206
|
+
sessionId: this.sessionId,
|
|
207
|
+
mode: 'named',
|
|
208
|
+
});
|
|
209
|
+
this.sendPlatform({
|
|
210
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
211
|
+
t: 'playerJoined',
|
|
212
|
+
player: { playerId, ...player.identity },
|
|
213
|
+
});
|
|
214
|
+
this.broadcastRoster();
|
|
215
|
+
}
|
|
216
|
+
handleClientMessage(playerId, socket, data, isBinary) {
|
|
217
|
+
if (isBinary) {
|
|
218
|
+
socket.close(1003, 'binary frames are not supported');
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
let frame;
|
|
222
|
+
try {
|
|
223
|
+
frame = asRecord(JSON.parse(data.toString()));
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
socket.close(1007, 'invalid JSON');
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (frame.t === 'ping') {
|
|
230
|
+
this.sendClient(socket, { t: 'pong' });
|
|
231
|
+
}
|
|
232
|
+
else if (frame.t === 'm' && Object.prototype.hasOwnProperty.call(frame, 'd')) {
|
|
233
|
+
this.sendPlatform({ protocolVersion: PROTOCOL_VERSION, t: 'clientMessage', playerId, d: frame.d });
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
socket.close(1008, 'invalid client frame');
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
detachClient(playerId, socket, code) {
|
|
240
|
+
const player = this.players.get(playerId);
|
|
241
|
+
if (!player || player.socket !== socket)
|
|
242
|
+
return;
|
|
243
|
+
player.socket = undefined;
|
|
244
|
+
this.sendPlatform({ protocolVersion: PROTOCOL_VERSION, t: 'playerLeft', playerId });
|
|
245
|
+
if (code === 1000) {
|
|
246
|
+
this.reconnects.delete(player.reconnectToken);
|
|
247
|
+
this.players.delete(playerId);
|
|
248
|
+
if (this.primaryPlayerId === playerId)
|
|
249
|
+
this.primaryPlayerId = null;
|
|
250
|
+
}
|
|
251
|
+
this.broadcastRoster();
|
|
252
|
+
}
|
|
253
|
+
attachPlatform(socket) {
|
|
254
|
+
this.platformSocket = socket;
|
|
255
|
+
socket.on('message', (data, isBinary) => this.handleRuntimeMessage(data, isBinary));
|
|
256
|
+
socket.on('close', () => this.runtimeClosed(socket));
|
|
257
|
+
socket.on('error', () => undefined);
|
|
258
|
+
const config = this.currentConfig();
|
|
259
|
+
this.sendPlatform({
|
|
260
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
261
|
+
t: 'init',
|
|
262
|
+
sessionId: this.sessionId,
|
|
263
|
+
deckId: readCastleJson(this.projectDir)?.deckId ?? 'dev',
|
|
264
|
+
mode: 'named',
|
|
265
|
+
config: { tickRate: config.tickRate, maxPlayers: config.maxPlayers },
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
handleRuntimeMessage(data, isBinary) {
|
|
269
|
+
if (isBinary) {
|
|
270
|
+
this.platformSocket?.close(1003, 'binary frames are not supported');
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
let frame;
|
|
274
|
+
try {
|
|
275
|
+
frame = asRecord(JSON.parse(data.toString()));
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
this.platformSocket?.close(1007, 'invalid JSON');
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (frame.protocolVersion !== PROTOCOL_VERSION)
|
|
282
|
+
return;
|
|
283
|
+
if (frame.t === 'ready') {
|
|
284
|
+
this.runtimeReady = true;
|
|
285
|
+
this.readyResolve?.();
|
|
286
|
+
this.clearReadyWaiters();
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (!this.runtimeReady)
|
|
290
|
+
return;
|
|
291
|
+
if (frame.t === 'sendTo' && typeof frame.playerId === 'string') {
|
|
292
|
+
const socket = this.players.get(frame.playerId)?.socket;
|
|
293
|
+
const payload = parseAuthorPayload(frame.d);
|
|
294
|
+
if (socket && payload.ok)
|
|
295
|
+
this.sendClient(socket, { t: 'm', d: payload.value });
|
|
296
|
+
}
|
|
297
|
+
else if (frame.t === 'broadcast') {
|
|
298
|
+
const payload = parseAuthorPayload(frame.d);
|
|
299
|
+
if (payload.ok)
|
|
300
|
+
for (const player of this.players.values()) {
|
|
301
|
+
if (player.socket)
|
|
302
|
+
this.sendClient(player.socket, { t: 'm', d: payload.value });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
else if (frame.t === 'kick' && typeof frame.playerId === 'string') {
|
|
306
|
+
this.kick(frame.playerId, typeof frame.reason === 'string' ? frame.reason : undefined);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
runtimeClosed(socket) {
|
|
310
|
+
if (this.platformSocket !== socket)
|
|
311
|
+
return;
|
|
312
|
+
this.platformSocket = null;
|
|
313
|
+
const wasReady = this.runtimeReady;
|
|
314
|
+
this.runtimeReady = false;
|
|
315
|
+
if (!wasReady)
|
|
316
|
+
this.readyReject?.(new Error('dev server child closed before ready'));
|
|
317
|
+
this.clearReadyWaiters();
|
|
318
|
+
if (!this.closed && wasReady)
|
|
319
|
+
this.closeClients(1012, 'dev server stopped');
|
|
320
|
+
}
|
|
321
|
+
async restartChild() {
|
|
322
|
+
if (this.closed)
|
|
323
|
+
return;
|
|
324
|
+
this.runtimeReady = false;
|
|
325
|
+
this.closeClients(1012, 'dev server restarting');
|
|
326
|
+
await this.stopChild();
|
|
327
|
+
const config = resolveServerConfig(this.projectDir);
|
|
328
|
+
if (!config)
|
|
329
|
+
throw new Error('multiplayer server entry is unavailable');
|
|
330
|
+
this.serverEntry = config.entry;
|
|
331
|
+
const code = await bundleServerModule(this.projectDir, config, false);
|
|
332
|
+
this.removeTempDir();
|
|
333
|
+
this.tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'castle-dev-session-'));
|
|
334
|
+
const bundlePath = path.join(this.tempDir, 'server.mjs');
|
|
335
|
+
fs.writeFileSync(bundlePath, code, 'utf8');
|
|
336
|
+
this.bootToken = randomUUID();
|
|
337
|
+
const ready = new Promise((resolve, reject) => {
|
|
338
|
+
this.readyResolve = resolve;
|
|
339
|
+
this.readyReject = reject;
|
|
340
|
+
});
|
|
341
|
+
const childPath = fileURLToPath(new URL('./devSessionChild.js', import.meta.url));
|
|
342
|
+
const child = spawn(process.execPath, [childPath], {
|
|
343
|
+
cwd: this.projectDir,
|
|
344
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
345
|
+
env: {
|
|
346
|
+
...process.env,
|
|
347
|
+
CASTLE_DEV_SESSION_CHANNEL_URL: `ws://127.0.0.1:${this.port}/__castle/platform`,
|
|
348
|
+
CASTLE_DEV_SESSION_BOOT_TOKEN: this.bootToken,
|
|
349
|
+
CASTLE_DEV_SESSION_BUNDLE_PATH: bundlePath,
|
|
350
|
+
},
|
|
351
|
+
});
|
|
352
|
+
this.child = child;
|
|
353
|
+
pipeChildOutput(child.stdout, 'log', this.log);
|
|
354
|
+
pipeChildOutput(child.stderr, 'error', this.log);
|
|
355
|
+
child.once('exit', () => {
|
|
356
|
+
if (this.child !== child)
|
|
357
|
+
return;
|
|
358
|
+
this.child = null;
|
|
359
|
+
if (!this.runtimeReady)
|
|
360
|
+
this.readyReject?.(new Error('dev server child exited before ready'));
|
|
361
|
+
});
|
|
362
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
363
|
+
setTimeout(() => reject(new Error('dev server child timed out before ready')), CHILD_READY_TIMEOUT_MS);
|
|
364
|
+
});
|
|
365
|
+
await Promise.race([ready, timeout]);
|
|
366
|
+
this.log('log', 'ready');
|
|
367
|
+
}
|
|
368
|
+
async stopChild() {
|
|
369
|
+
this.bootToken = '';
|
|
370
|
+
this.runtimeReady = false;
|
|
371
|
+
this.platformSocket?.terminate();
|
|
372
|
+
this.platformSocket = null;
|
|
373
|
+
const child = this.child;
|
|
374
|
+
this.child = null;
|
|
375
|
+
if (!child || child.exitCode !== null)
|
|
376
|
+
return;
|
|
377
|
+
const exited = new Promise((resolve) => child.once('exit', () => resolve()));
|
|
378
|
+
child.kill('SIGTERM');
|
|
379
|
+
const graceful = await Promise.race([
|
|
380
|
+
exited.then(() => true),
|
|
381
|
+
new Promise((resolve) => setTimeout(() => resolve(false), CHILD_STOP_GRACE_MS)),
|
|
382
|
+
]);
|
|
383
|
+
if (!graceful && child.exitCode === null) {
|
|
384
|
+
child.kill('SIGKILL');
|
|
385
|
+
await exited;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
currentConfig() {
|
|
389
|
+
return resolveServerConfig(this.projectDir) ?? { entry: 'server/index.js', tickRate: 20, maxPlayers: 8 };
|
|
390
|
+
}
|
|
391
|
+
sendPlatform(frame) {
|
|
392
|
+
if (this.platformSocket?.readyState === WebSocket.OPEN)
|
|
393
|
+
this.platformSocket.send(JSON.stringify(frame));
|
|
394
|
+
}
|
|
395
|
+
sendClient(socket, frame) {
|
|
396
|
+
if (socket.readyState !== WebSocket.OPEN)
|
|
397
|
+
return;
|
|
398
|
+
const text = JSON.stringify(frame);
|
|
399
|
+
if (Buffer.byteLength(text) > MAX_CLIENT_FRAME_BYTES) {
|
|
400
|
+
this.log('error', 'dropped a server message larger than 16KB');
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
socket.send(text);
|
|
404
|
+
}
|
|
405
|
+
broadcastRoster() {
|
|
406
|
+
const players = this.connectedPlayers();
|
|
407
|
+
for (const player of this.players.values()) {
|
|
408
|
+
if (player.socket)
|
|
409
|
+
this.sendClient(player.socket, { t: 'roster', players });
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
connectedPlayers() {
|
|
413
|
+
const connected = [];
|
|
414
|
+
for (const [playerId, player] of this.players) {
|
|
415
|
+
if (player.socket?.readyState === WebSocket.OPEN)
|
|
416
|
+
connected.push({ playerId, ...player.identity });
|
|
417
|
+
}
|
|
418
|
+
return connected;
|
|
419
|
+
}
|
|
420
|
+
closeClients(code, reason) {
|
|
421
|
+
for (const player of this.players.values()) {
|
|
422
|
+
const socket = player.socket;
|
|
423
|
+
player.socket = undefined;
|
|
424
|
+
socket?.close(code, reason);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
kick(playerId, reason) {
|
|
428
|
+
const player = this.players.get(playerId);
|
|
429
|
+
if (!player)
|
|
430
|
+
return;
|
|
431
|
+
this.reconnects.delete(player.reconnectToken);
|
|
432
|
+
this.players.delete(playerId);
|
|
433
|
+
if (this.primaryPlayerId === playerId)
|
|
434
|
+
this.primaryPlayerId = null;
|
|
435
|
+
if (player.socket) {
|
|
436
|
+
this.sendClient(player.socket, { t: 'bye', ...(reason ? { reason } : {}) });
|
|
437
|
+
player.socket.close(4002, 'kicked');
|
|
438
|
+
}
|
|
439
|
+
this.broadcastRoster();
|
|
440
|
+
}
|
|
441
|
+
rotateReconnect(playerId) {
|
|
442
|
+
const token = randomUUID();
|
|
443
|
+
this.reconnects.set(token, playerId);
|
|
444
|
+
return token;
|
|
445
|
+
}
|
|
446
|
+
nextGuest() {
|
|
447
|
+
this.guestNumber += 1;
|
|
448
|
+
return {
|
|
449
|
+
userId: `dev-guest-${this.guestNumber}`,
|
|
450
|
+
username: `Guest ${this.guestNumber}`,
|
|
451
|
+
isAnonymous: true,
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
pruneNonces() {
|
|
455
|
+
const cutoff = Date.now() - NONCE_TTL_MS;
|
|
456
|
+
for (const [nonce, record] of this.nonces)
|
|
457
|
+
if (record.mintedAt < cutoff)
|
|
458
|
+
this.nonces.delete(nonce);
|
|
459
|
+
}
|
|
460
|
+
clearReadyWaiters() {
|
|
461
|
+
this.readyResolve = null;
|
|
462
|
+
this.readyReject = null;
|
|
463
|
+
}
|
|
464
|
+
removeTempDir() {
|
|
465
|
+
if (!this.tempDir)
|
|
466
|
+
return;
|
|
467
|
+
fs.rmSync(this.tempDir, { recursive: true, force: true });
|
|
468
|
+
this.tempDir = null;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
function parseAuthorPayload(value) {
|
|
472
|
+
if (typeof value !== 'string')
|
|
473
|
+
return { ok: false };
|
|
474
|
+
try {
|
|
475
|
+
return { ok: true, value: JSON.parse(value) };
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
return { ok: false };
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function pipeChildOutput(stream, level, log) {
|
|
482
|
+
if (!stream)
|
|
483
|
+
return;
|
|
484
|
+
let pending = '';
|
|
485
|
+
stream.on('data', (chunk) => {
|
|
486
|
+
pending += chunk.toString();
|
|
487
|
+
const lines = pending.split(/\r?\n/);
|
|
488
|
+
pending = lines.pop() ?? '';
|
|
489
|
+
for (const line of lines)
|
|
490
|
+
if (line)
|
|
491
|
+
log(level, line);
|
|
492
|
+
});
|
|
493
|
+
stream.on('end', () => {
|
|
494
|
+
if (pending)
|
|
495
|
+
log(level, pending);
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
function asRecord(value) {
|
|
499
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
500
|
+
throw new Error('not a record');
|
|
501
|
+
return value;
|
|
502
|
+
}
|
|
503
|
+
function rejectUpgrade(socket, status) {
|
|
504
|
+
socket.end(`HTTP/1.1 ${status} Rejected\r\nConnection: close\r\n\r\n`);
|
|
505
|
+
}
|
|
506
|
+
function closeWebSocketServer(server) {
|
|
507
|
+
return new Promise((resolve) => server.close(() => resolve()));
|
|
508
|
+
}
|
|
509
|
+
function closeHttpServer(server) {
|
|
510
|
+
return new Promise((resolve) => server.close(() => resolve()));
|
|
511
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -68,20 +68,20 @@ function getFlagValue(flag) {
|
|
|
68
68
|
function hasFlag(flag) {
|
|
69
69
|
return args.includes(flag);
|
|
70
70
|
}
|
|
71
|
-
function
|
|
71
|
+
function readServeSocketPort(dir) {
|
|
72
72
|
try {
|
|
73
73
|
const serveJson = JSON.parse(fs.readFileSync(path.join(path.resolve(dir), '.castle', 'serve.json'), 'utf-8'));
|
|
74
|
-
return serveJson.wsPort;
|
|
74
|
+
return serveJson.port ?? serveJson.wsPort;
|
|
75
75
|
}
|
|
76
76
|
catch {
|
|
77
77
|
return undefined;
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
|
-
function
|
|
80
|
+
function getServeSocketPort(dir) {
|
|
81
81
|
const explicit = getFlagValue('--port');
|
|
82
82
|
if (explicit)
|
|
83
83
|
return parseInt(explicit, 10);
|
|
84
|
-
const fromServe =
|
|
84
|
+
const fromServe = readServeSocketPort(dir);
|
|
85
85
|
if (fromServe)
|
|
86
86
|
return fromServe;
|
|
87
87
|
return 3738;
|
|
@@ -253,9 +253,9 @@ async function main() {
|
|
|
253
253
|
}
|
|
254
254
|
case 'restart': {
|
|
255
255
|
const dir = findPositionalDir();
|
|
256
|
-
const
|
|
256
|
+
const servePort = getServeSocketPort(dir);
|
|
257
257
|
const { default: WS } = await import('ws');
|
|
258
|
-
const ws = new WS(`ws://localhost:${
|
|
258
|
+
const ws = new WS(`ws://localhost:${servePort}/__castle/ws`);
|
|
259
259
|
ws.on('open', () => {
|
|
260
260
|
ws.send(JSON.stringify({ type: 'restart' }));
|
|
261
261
|
setTimeout(() => {
|
|
@@ -272,8 +272,8 @@ async function main() {
|
|
|
272
272
|
case 'screenshot': {
|
|
273
273
|
const dir = findPositionalDir();
|
|
274
274
|
const outFile = getFlagValue('--out') ?? 'screenshot.png';
|
|
275
|
-
const
|
|
276
|
-
const ws = await connectWS(
|
|
275
|
+
const servePort = getServeSocketPort(dir);
|
|
276
|
+
const ws = await connectWS(servePort);
|
|
277
277
|
const base64 = await takeScreenshot(ws);
|
|
278
278
|
ws.close();
|
|
279
279
|
fs.writeFileSync(outFile, Buffer.from(base64, 'base64'));
|
package/dist/init.js
CHANGED
|
@@ -46,7 +46,7 @@ export const BARE_DOCS_KIT = 'blank';
|
|
|
46
46
|
// Registry version of castle-web-sdk to inject when scaffolding from a
|
|
47
47
|
// globally-installed castle-web (not from inside the workspace). Bumped
|
|
48
48
|
// alongside cli/sdk version bumps.
|
|
49
|
-
const PUBLISHED_SDK_VERSION = '0.4.
|
|
49
|
+
const PUBLISHED_SDK_VERSION = '0.4.19';
|
|
50
50
|
// The account the first-party kits are (to be) published under, so a kit
|
|
51
51
|
// imported from the CLI's copy is named the same as one fetched from the server.
|
|
52
52
|
const KIT_AUTHOR = 'castle';
|
|
@@ -265,8 +265,16 @@ function writeDeckIndexHtml(projectDir, alias, title, mainFile) {
|
|
|
265
265
|
// Give a deck the scene its kit says to start from, with every path that names a
|
|
266
266
|
// kit file rewritten to reach it through the import. Exported because both
|
|
267
267
|
// scaffold paths need it: `init --kit`, and adopting a kit via `add-import`.
|
|
268
|
+
//
|
|
269
|
+
// Shipping a starter scene is also what makes a kit a scene kit, which is why a
|
|
270
|
+
// kit without one is left alone rather than seeded an empty scene: `blank`
|
|
271
|
+
// declares no `.scene` type and ships no editor for it, so the file it used to
|
|
272
|
+
// get was one nothing in the deck could open. Asking the kit for the file it
|
|
273
|
+
// declares keeps that judgement the kit's -- the CLI knows no `.scene`.
|
|
268
274
|
export function writeStarterScene(projectDir, kitDir, alias) {
|
|
269
275
|
const scene = readJsonFile(path.join(kitDir, deckStarterScene(kitDir)));
|
|
276
|
+
if (!scene)
|
|
277
|
+
return;
|
|
270
278
|
const prefix = `${IMPORTS_DIR}/${alias}/`;
|
|
271
279
|
const rewrite = (value) => {
|
|
272
280
|
if (typeof value === 'string') {
|
|
@@ -280,7 +288,7 @@ export function writeStarterScene(projectDir, kitDir, alias) {
|
|
|
280
288
|
return value;
|
|
281
289
|
};
|
|
282
290
|
fs.mkdirSync(path.join(projectDir, 'scenes'), { recursive: true });
|
|
283
|
-
writeJsonFile(path.join(projectDir, 'scenes', 'main.scene'),
|
|
291
|
+
writeJsonFile(path.join(projectDir, 'scenes', 'main.scene'), rewrite(scene));
|
|
284
292
|
}
|
|
285
293
|
// A kit may ship a starter `theme.style` (deck-level styling, e.g. the color
|
|
286
294
|
// palette). Like the starter scene, it is deck content: the engine reads it
|
package/dist/list-decks.js
CHANGED
|
@@ -22,10 +22,11 @@ const BROWSER_TIMEOUT_MS = 20_000;
|
|
|
22
22
|
function isKind(value) {
|
|
23
23
|
return KINDS.includes(value);
|
|
24
24
|
}
|
|
25
|
-
function
|
|
25
|
+
function serveSocketPort(deckDir) {
|
|
26
26
|
try {
|
|
27
27
|
const raw = fs.readFileSync(path.join(deckDir, '.castle', 'serve.json'), 'utf8');
|
|
28
|
-
const
|
|
28
|
+
const info = JSON.parse(raw);
|
|
29
|
+
const port = info.port ?? info.wsPort;
|
|
29
30
|
return typeof port === 'number' ? port : null;
|
|
30
31
|
}
|
|
31
32
|
catch {
|
|
@@ -35,10 +36,10 @@ function serveWsPort(deckDir) {
|
|
|
35
36
|
// Null means nobody answered: no serve, or no browser on the other end of it.
|
|
36
37
|
// A browser that answers "not signed in" is an ANSWER and comes back as one.
|
|
37
38
|
async function askBrowser(deckDir, kind) {
|
|
38
|
-
const
|
|
39
|
-
if (
|
|
39
|
+
const servePort = serveSocketPort(deckDir);
|
|
40
|
+
if (servePort === null)
|
|
40
41
|
return null;
|
|
41
|
-
const ws = await connectWS(
|
|
42
|
+
const ws = await connectWS(servePort).catch(() => null);
|
|
42
43
|
if (!ws)
|
|
43
44
|
return null;
|
|
44
45
|
const requestId = Math.random().toString(36).slice(2);
|
|
@@ -88,7 +89,7 @@ export async function listDecks(dir, options = {}) {
|
|
|
88
89
|
if (!list) {
|
|
89
90
|
// No serve at all means this is a plain local CLI, where the login is ours
|
|
90
91
|
// to have. With a serve up, the missing piece is a browser on it instead.
|
|
91
|
-
console.error(
|
|
92
|
+
console.error(serveSocketPort(deckDir) === null
|
|
92
93
|
? 'Not signed in. Run `castle-web login` first.'
|
|
93
94
|
: 'Cannot list decks: nothing is connected to this deck in a browser, and the listing comes from the browser session. Open this deck in the editor and run this again.');
|
|
94
95
|
process.exit(1);
|
package/dist/preview.d.ts
CHANGED
package/dist/preview.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
export async function connectWS(
|
|
1
|
+
export async function connectWS(servePort) {
|
|
2
2
|
const { default: WS } = await import('ws');
|
|
3
3
|
return new Promise((resolve, reject) => {
|
|
4
|
-
|
|
4
|
+
// Old serves proxy this path to their P+1 socket; new serves upgrade it on
|
|
5
|
+
// the main port. This makes CLI commands compatible across the transition.
|
|
6
|
+
const ws = new WS(`ws://localhost:${servePort}/__castle/ws`);
|
|
5
7
|
ws.on('error', () => reject(new Error('Could not connect. Is castle-web serve running?')));
|
|
6
8
|
ws.on('open', () => resolve(ws));
|
|
7
9
|
});
|