castle-web-cli 0.4.149 → 0.4.151
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.d.ts +1 -0
- package/dist/agent.js +12 -4
- package/dist/api.d.ts +45 -1
- package/dist/api.js +34 -2
- package/dist/castle-host/host.d.ts +17 -0
- package/dist/castle-host/host.js +10 -7
- 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/headlessCover.js +28 -0
- package/dist/index.js +8 -8
- package/dist/init.js +9 -1
- package/dist/list-decks.js +7 -6
- package/dist/native/playtest-remote.d.ts +3 -0
- package/dist/native/playtest-remote.js +113 -0
- package/dist/preview.d.ts +1 -1
- package/dist/preview.js +4 -2
- package/dist/save-deck.js +82 -16
- package/dist/serve.js +245 -88
- package/dist/serveSecurity.d.ts +7 -1
- package/dist/serveSecurity.js +61 -10
- package/dist/serverBundle.d.ts +8 -0
- package/dist/serverBundle.js +82 -0
- package/dist/shell/assets/{index-BzFzFtEP.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/agent/children.json +1 -0
- package/kits/blank/.castle/agent/messages.json +9 -0
- package/kits/blank/.castle/agent/pending-sends.json +1 -0
- package/kits/blank/.castle/agent/tasks/index.md +2 -0
- package/kits/blank/.castle/docs/platform.md +36 -0
- package/kits/blank/castle.json +5 -2
- package/kits/blank/node_modules/.vite/deps/_metadata.json +8 -0
- package/kits/blank/node_modules/.vite/deps/package.json +3 -0
- 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 +171 -57
- 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/package.json +1 -1
- package/dist/shell/assets/index-DN8HQBnW.css +0 -1
package/dist/agent.d.ts
CHANGED
|
@@ -78,6 +78,7 @@ export declare function createAgentServer(opts: {
|
|
|
78
78
|
deckLabel: string;
|
|
79
79
|
port?: number;
|
|
80
80
|
playtestServeUrl?: string;
|
|
81
|
+
browserContentUrl?: () => string | null;
|
|
81
82
|
restart?: () => void;
|
|
82
83
|
authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'agent') => boolean;
|
|
83
84
|
}): AgentServer;
|
package/dist/agent.js
CHANGED
|
@@ -36,6 +36,7 @@ import { cancelLogin, logout, startLogin, submitLoginCode } from './byo-login.js
|
|
|
36
36
|
import { runAgentNative } from './native/loop.js';
|
|
37
37
|
import { createPlaytestBrowserManager, } from './native/playtest-browser.js';
|
|
38
38
|
import { createPlaywrightPlaytestExecutor } from './native/playtest-executor.js';
|
|
39
|
+
import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
|
|
39
40
|
export const AGENT_WS_PATH = '/__castle/agent';
|
|
40
41
|
export const AGENT_ATTACHMENT_PREFIX = '/__castle/agent/attachments/';
|
|
41
42
|
// Playtest frame PNGs (tasks/<id>/playtest/<file>.png), served for the
|
|
@@ -3988,10 +3989,15 @@ export function createAgentServer(opts) {
|
|
|
3988
3989
|
// playtest call (each call still gets its own fresh browser context +
|
|
3989
3990
|
// page -- see playtest-executor.ts). Lazily launched on first use; never
|
|
3990
3991
|
// touched at all if no task ever calls playtest.
|
|
3991
|
-
const
|
|
3992
|
+
const remotePlaytest = opts.browserContentUrl
|
|
3993
|
+
? createRemotePlaytestExecutor(opts.browserContentUrl)
|
|
3994
|
+
: null;
|
|
3995
|
+
const playtestBrowserManager = remotePlaytest
|
|
3996
|
+
? null
|
|
3997
|
+
: createPlaytestBrowserManager();
|
|
3992
3998
|
const playtest = opts.port
|
|
3993
3999
|
? {
|
|
3994
|
-
executor: createPlaywrightPlaytestExecutor(playtestBrowserManager),
|
|
4000
|
+
executor: remotePlaytest ?? createPlaywrightPlaytestExecutor(playtestBrowserManager),
|
|
3995
4001
|
// `localhost`, NOT 127.0.0.1: a serve started without --host leaves
|
|
3996
4002
|
// Vite on its default host, which binds ONLY [::1] on macOS --
|
|
3997
4003
|
// 127.0.0.1 never answers there, and playtest would fail every call
|
|
@@ -4001,7 +4007,9 @@ export function createAgentServer(opts) {
|
|
|
4001
4007
|
// Kicks off the one-time Chromium download in the background at
|
|
4002
4008
|
// smith-task start (see runTaskAgentIn) -- single-flight with any
|
|
4003
4009
|
// real playtest call, silent on every failure path.
|
|
4004
|
-
prewarm:
|
|
4010
|
+
prewarm: playtestBrowserManager
|
|
4011
|
+
? () => playtestBrowserManager.prewarm()
|
|
4012
|
+
: undefined,
|
|
4005
4013
|
}
|
|
4006
4014
|
: undefined;
|
|
4007
4015
|
const taskChildren = new Set();
|
|
@@ -4246,7 +4254,7 @@ export function createAgentServer(opts) {
|
|
|
4246
4254
|
usageFeed.stop();
|
|
4247
4255
|
accountsFeed.stop();
|
|
4248
4256
|
wss.close();
|
|
4249
|
-
void playtestBrowserManager
|
|
4257
|
+
void playtestBrowserManager?.shutdown();
|
|
4250
4258
|
}
|
|
4251
4259
|
return { handleUpgrade, handleHttpRequest, shutdown };
|
|
4252
4260
|
}
|
package/dist/api.d.ts
CHANGED
|
@@ -5,7 +5,33 @@ interface GraphqlResponse {
|
|
|
5
5
|
extensions?: Record<string, unknown>;
|
|
6
6
|
}>;
|
|
7
7
|
}
|
|
8
|
-
export declare function graphql(query: string, variables?: Record<string, unknown
|
|
8
|
+
export declare function graphql(query: string, variables?: Record<string, unknown>, options?: {
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}): Promise<GraphqlResponse>;
|
|
12
|
+
export type BrowserOperation = {
|
|
13
|
+
kind: 'playtest';
|
|
14
|
+
durationMs: number;
|
|
15
|
+
actions: Array<{
|
|
16
|
+
t: number;
|
|
17
|
+
type: 'down' | 'move' | 'up' | 'tap' | 'key';
|
|
18
|
+
x?: number;
|
|
19
|
+
y?: number;
|
|
20
|
+
key?: string;
|
|
21
|
+
durationMs?: number;
|
|
22
|
+
}>;
|
|
23
|
+
screenshots: number[];
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'cover';
|
|
26
|
+
};
|
|
27
|
+
export interface BrowserJobResult {
|
|
28
|
+
protocolVersion: number;
|
|
29
|
+
jobId: string;
|
|
30
|
+
operation: 'playtest' | 'cover';
|
|
31
|
+
ok: boolean;
|
|
32
|
+
[key: string]: unknown;
|
|
33
|
+
}
|
|
34
|
+
export declare function runBrowserJob(contentGrant: string, operation: BrowserOperation, signal?: AbortSignal): Promise<BrowserJobResult>;
|
|
9
35
|
export declare function startCLILogin(): Promise<{
|
|
10
36
|
pollToken: string;
|
|
11
37
|
url: string;
|
|
@@ -92,6 +118,24 @@ export interface WebDeckSourceUploadConfig {
|
|
|
92
118
|
postFields: Record<string, string>;
|
|
93
119
|
}
|
|
94
120
|
export declare function createWebDeckSourceUploadConfig(deckId: string): Promise<WebDeckSourceUploadConfig>;
|
|
121
|
+
export interface CauldronServerBundleUploadConfig {
|
|
122
|
+
deckId: string;
|
|
123
|
+
uploadId: string;
|
|
124
|
+
postUrl: string;
|
|
125
|
+
postFields: Record<string, string>;
|
|
126
|
+
}
|
|
127
|
+
export declare function createCauldronServerBundleUploadConfig(deckId: string): Promise<CauldronServerBundleUploadConfig>;
|
|
128
|
+
export interface CauldronServerConfig {
|
|
129
|
+
tickRate: number;
|
|
130
|
+
maxPlayers: number;
|
|
131
|
+
}
|
|
132
|
+
export interface CauldronServerBundleResult {
|
|
133
|
+
deckId: string;
|
|
134
|
+
version: string;
|
|
135
|
+
sha256: string;
|
|
136
|
+
sizeBytes: number;
|
|
137
|
+
}
|
|
138
|
+
export declare function saveCauldronServerBundle(deckId: string, uploadId: string | null, serverConfig?: CauldronServerConfig): Promise<CauldronServerBundleResult | null>;
|
|
95
139
|
export interface WebDeckSource {
|
|
96
140
|
deckId: string;
|
|
97
141
|
archiveUrl: string;
|
package/dist/api.js
CHANGED
|
@@ -3,7 +3,7 @@ import * as config from './config.js';
|
|
|
3
3
|
// sandboxes (which also set CASTLE_TOKEN to a sandbox-scoped credential). Unset anywhere
|
|
4
4
|
// else, so normal installs always talk to the real API.
|
|
5
5
|
const API_HOST = process.env.CASTLE_API_URL || 'https://api.castle.xyz/graphql';
|
|
6
|
-
export async function graphql(query, variables) {
|
|
6
|
+
export async function graphql(query, variables, options = {}) {
|
|
7
7
|
const token = config.getToken();
|
|
8
8
|
const headers = {
|
|
9
9
|
'X-OS': 'cli',
|
|
@@ -13,14 +13,25 @@ export async function graphql(query, variables) {
|
|
|
13
13
|
};
|
|
14
14
|
if (token)
|
|
15
15
|
headers['X-Auth-Token'] = token;
|
|
16
|
+
const timeoutSignal = AbortSignal.timeout(options.timeoutMs ?? 10_000);
|
|
17
|
+
const signal = options.signal
|
|
18
|
+
? AbortSignal.any([timeoutSignal, options.signal])
|
|
19
|
+
: timeoutSignal;
|
|
16
20
|
const res = await fetch(API_HOST, {
|
|
17
21
|
method: 'POST',
|
|
18
22
|
headers,
|
|
19
23
|
body: JSON.stringify(variables ? { query, variables } : { query }),
|
|
20
|
-
signal
|
|
24
|
+
signal,
|
|
21
25
|
});
|
|
22
26
|
return res.json();
|
|
23
27
|
}
|
|
28
|
+
export async function runBrowserJob(contentGrant, operation, signal) {
|
|
29
|
+
const data = await graphql(`mutation($contentGrant: String!, $operation: Json!) {
|
|
30
|
+
runBrowserJob(contentGrant: $contentGrant, operation: $operation)
|
|
31
|
+
}`, { contentGrant, operation }, { timeoutMs: 85_000, signal });
|
|
32
|
+
handleAPIError(data);
|
|
33
|
+
return pickData(data, 'runBrowserJob');
|
|
34
|
+
}
|
|
24
35
|
// Castle masks every ClientError's message to "Unexpected error." and puts the
|
|
25
36
|
// real one in `extensions.code` -- so the bare message is the same string for a
|
|
26
37
|
// permissions failure, a missing deck, and a bad argument. Carry the code in the
|
|
@@ -203,6 +214,27 @@ export async function createWebDeckSourceUploadConfig(deckId) {
|
|
|
203
214
|
handleAPIError(data);
|
|
204
215
|
return pickData(data, 'createWebDeckSourceUploadConfig');
|
|
205
216
|
}
|
|
217
|
+
export async function createCauldronServerBundleUploadConfig(deckId) {
|
|
218
|
+
const data = await graphql(`mutation($deckId: ID!) {
|
|
219
|
+
createCauldronServerBundleUploadConfig(deckId: $deckId) {
|
|
220
|
+
deckId uploadId postUrl postFields
|
|
221
|
+
}
|
|
222
|
+
}`, { deckId });
|
|
223
|
+
handleAPIError(data);
|
|
224
|
+
return pickData(data, 'createCauldronServerBundleUploadConfig');
|
|
225
|
+
}
|
|
226
|
+
export async function saveCauldronServerBundle(deckId, uploadId, serverConfig) {
|
|
227
|
+
const data = await graphql(`mutation($deckId: ID!, $uploadId: String, $config: Json) {
|
|
228
|
+
saveCauldronServerBundle(deckId: $deckId, uploadId: $uploadId, config: $config) {
|
|
229
|
+
deckId
|
|
230
|
+
version
|
|
231
|
+
sha256
|
|
232
|
+
sizeBytes
|
|
233
|
+
}
|
|
234
|
+
}`, { deckId, uploadId, ...(serverConfig ? { config: serverConfig } : {}) });
|
|
235
|
+
handleAPIError(data);
|
|
236
|
+
return pickData(data, 'saveCauldronServerBundle');
|
|
237
|
+
}
|
|
206
238
|
// Title + author, for naming an import. Readable without auth for the same decks
|
|
207
239
|
// webDeckSource is (unlisted ones), so this works in a sandbox with no login.
|
|
208
240
|
export async function deckMeta(deckId) {
|
|
@@ -13,6 +13,7 @@ export interface HostContext {
|
|
|
13
13
|
username: string | null;
|
|
14
14
|
isAnonymous?: boolean;
|
|
15
15
|
deepLinkUri?: string | null;
|
|
16
|
+
partyId?: string | null;
|
|
16
17
|
}
|
|
17
18
|
|
|
18
19
|
export interface GraphqlError {
|
|
@@ -45,6 +46,22 @@ export interface HostCapabilities {
|
|
|
45
46
|
leaderboardShowsParties?: boolean;
|
|
46
47
|
onStreakCredit?: (credit: LeaderboardStreakCredit) => void;
|
|
47
48
|
logAnalyticsEvent?: (event: string, properties: Record<string, unknown>) => void;
|
|
49
|
+
getMultiplayerSession?: (
|
|
50
|
+
params: MultiplayerGetSessionParams,
|
|
51
|
+
ctx: HostContext,
|
|
52
|
+
) => Promise<MultiplayerGetSessionResult>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface MultiplayerGetSessionParams {
|
|
56
|
+
mode: 'named' | 'party' | 'public';
|
|
57
|
+
key?: string | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface MultiplayerGetSessionResult {
|
|
61
|
+
status: 'ok' | 'solo' | 'unavailable';
|
|
62
|
+
url: string | null;
|
|
63
|
+
nonce: string | null;
|
|
64
|
+
sessionId: string | null;
|
|
48
65
|
}
|
|
49
66
|
|
|
50
67
|
export interface LeaderboardStreakCredit {
|
package/dist/castle-host/host.js
CHANGED
|
@@ -86,6 +86,9 @@ export async function executeCommand(ctx, command, params, capabilities) {
|
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
function runCommand(ctx, command, params, caps) {
|
|
89
|
+
if (command === "multiplayer.getSession" && caps.getMultiplayerSession) {
|
|
90
|
+
return caps.getMultiplayerSession(multiplayerSessionRequest(params), ctx);
|
|
91
|
+
}
|
|
89
92
|
if (isPlatformCommand(command)) {
|
|
90
93
|
return runPlatformCommand(ctx, command, params, caps);
|
|
91
94
|
}
|
|
@@ -123,19 +126,19 @@ function runCommand(ctx, command, params, caps) {
|
|
|
123
126
|
}
|
|
124
127
|
}
|
|
125
128
|
async function multiplayerGetSession(ctx, params, caps) {
|
|
129
|
+
const request = multiplayerSessionRequest(params);
|
|
130
|
+
const deckId = requireDeckId(ctx, "multiplayer.getSession");
|
|
131
|
+
const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode: request.mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
|
|
132
|
+
return multiplayerSessionResult(data.getCauldronMultiplayerSession);
|
|
133
|
+
}
|
|
134
|
+
function multiplayerSessionRequest(params) {
|
|
126
135
|
const mode = asMultiplayerMode(params.mode);
|
|
127
|
-
|
|
136
|
+
return {
|
|
128
137
|
mode,
|
|
129
138
|
key: mode === "named"
|
|
130
139
|
? asString(params.key, "key", "multiplayer.getSession")
|
|
131
140
|
: null,
|
|
132
141
|
};
|
|
133
|
-
if (caps.getMultiplayerSession) {
|
|
134
|
-
return caps.getMultiplayerSession(request, ctx);
|
|
135
|
-
}
|
|
136
|
-
const deckId = requireDeckId(ctx, "multiplayer.getSession");
|
|
137
|
-
const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
|
|
138
|
-
return multiplayerSessionResult(data.getCauldronMultiplayerSession);
|
|
139
142
|
}
|
|
140
143
|
function multiplayerSessionResult(value) {
|
|
141
144
|
const sessionId = asOptionalString(value?.sessionId);
|
package/dist/castleJson.d.ts
CHANGED
|
@@ -18,11 +18,26 @@ export interface CastleJson {
|
|
|
18
18
|
agent?: {
|
|
19
19
|
plan?: 'on' | 'off';
|
|
20
20
|
};
|
|
21
|
+
server?: {
|
|
22
|
+
main?: string;
|
|
23
|
+
tickRate?: number;
|
|
24
|
+
maxPlayers?: number;
|
|
25
|
+
};
|
|
21
26
|
importWhenRemixed?: boolean;
|
|
22
27
|
starterScene?: string;
|
|
23
28
|
[key: string]: unknown;
|
|
24
29
|
}
|
|
25
30
|
export declare const DEFAULT_STARTER_SCENE = "scenes/main.scene";
|
|
31
|
+
export declare const DEFAULT_SERVER_TICK_RATE = 20;
|
|
32
|
+
export declare const DEFAULT_SERVER_MAX_PLAYERS = 8;
|
|
33
|
+
export declare const SERVER_TICK_RATE_CAP = 30;
|
|
34
|
+
export declare const SERVER_MAX_PLAYERS_CAP = 24;
|
|
35
|
+
export interface ResolvedServerConfig {
|
|
36
|
+
entry: string;
|
|
37
|
+
tickRate: number;
|
|
38
|
+
maxPlayers: number;
|
|
39
|
+
}
|
|
40
|
+
export declare function resolveServerConfig(dir: string): ResolvedServerConfig | null;
|
|
26
41
|
export declare function deckStarterScene(dir: string): string;
|
|
27
42
|
export declare const DEFAULT_MAIN = "main.jsx";
|
|
28
43
|
export declare function deckMainFile(dir: string): string;
|
package/dist/castleJson.js
CHANGED
|
@@ -7,6 +7,42 @@ import picomatch from 'picomatch';
|
|
|
7
7
|
// cycle.
|
|
8
8
|
export const IMPORTS_DIR = 'imports';
|
|
9
9
|
export const DEFAULT_STARTER_SCENE = 'scenes/main.scene';
|
|
10
|
+
export const DEFAULT_SERVER_TICK_RATE = 20;
|
|
11
|
+
export const DEFAULT_SERVER_MAX_PLAYERS = 8;
|
|
12
|
+
export const SERVER_TICK_RATE_CAP = 30;
|
|
13
|
+
export const SERVER_MAX_PLAYERS_CAP = 24;
|
|
14
|
+
const DEFAULT_SERVER_ENTRIES = [
|
|
15
|
+
'server/index.js',
|
|
16
|
+
'server/index.ts',
|
|
17
|
+
'server/index.mjs',
|
|
18
|
+
];
|
|
19
|
+
export function resolveServerConfig(dir) {
|
|
20
|
+
const server = readCastleJson(dir)?.server;
|
|
21
|
+
const declared = typeof server?.main === 'string' ? server.main.trim() : '';
|
|
22
|
+
const entry = declared || DEFAULT_SERVER_ENTRIES.find((candidate) => fs.existsSync(path.join(dir, candidate)));
|
|
23
|
+
if (!entry || !isSafeServerEntry(dir, entry))
|
|
24
|
+
return null;
|
|
25
|
+
return {
|
|
26
|
+
entry,
|
|
27
|
+
tickRate: clampNumber(server?.tickRate, DEFAULT_SERVER_TICK_RATE, 0, SERVER_TICK_RATE_CAP),
|
|
28
|
+
maxPlayers: Math.floor(clampNumber(server?.maxPlayers, DEFAULT_SERVER_MAX_PLAYERS, 1, SERVER_MAX_PLAYERS_CAP)),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function isSafeServerEntry(dir, entry) {
|
|
32
|
+
if (!/\.(?:js|ts|mjs)$/.test(entry))
|
|
33
|
+
return false;
|
|
34
|
+
const absolute = path.resolve(dir, entry);
|
|
35
|
+
const relative = path.relative(dir, absolute);
|
|
36
|
+
return (relative !== '' &&
|
|
37
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
38
|
+
relative !== '..' &&
|
|
39
|
+
!path.isAbsolute(relative) &&
|
|
40
|
+
fs.existsSync(absolute));
|
|
41
|
+
}
|
|
42
|
+
function clampNumber(value, fallback, min, max) {
|
|
43
|
+
const number = typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
|
44
|
+
return Math.min(max, Math.max(min, number));
|
|
45
|
+
}
|
|
10
46
|
export function deckStarterScene(dir) {
|
|
11
47
|
const declared = readCastleJson(dir)?.starterScene;
|
|
12
48
|
return typeof declared === 'string' && declared.trim() ? declared.trim() : DEFAULT_STARTER_SCENE;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { pathToFileURL } from 'url';
|
|
2
|
+
import WebSocket from 'ws';
|
|
3
|
+
const PROTOCOL_VERSION = 1;
|
|
4
|
+
class PlatformEvents {
|
|
5
|
+
callbacks = new Map();
|
|
6
|
+
on(event, callback) {
|
|
7
|
+
const callbacks = this.callbacks.get(event) ?? [];
|
|
8
|
+
callbacks.push(callback);
|
|
9
|
+
this.callbacks.set(event, callbacks);
|
|
10
|
+
}
|
|
11
|
+
async emit(event, ...args) {
|
|
12
|
+
for (const callback of this.callbacks.get(event) ?? [])
|
|
13
|
+
await callback(...args);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const channelUrl = new URL(requiredEnv('CASTLE_DEV_SESSION_CHANNEL_URL'));
|
|
17
|
+
channelUrl.searchParams.set('bootToken', requiredEnv('CASTLE_DEV_SESSION_BOOT_TOKEN'));
|
|
18
|
+
const bundlePath = requiredEnv('CASTLE_DEV_SESSION_BUNDLE_PATH');
|
|
19
|
+
const socket = new WebSocket(channelUrl);
|
|
20
|
+
let events = null;
|
|
21
|
+
let initialized = false;
|
|
22
|
+
let shuttingDown = false;
|
|
23
|
+
let messageQueue = Promise.resolve();
|
|
24
|
+
socket.on('message', (data, isBinary) => {
|
|
25
|
+
messageQueue = messageQueue.then(() => handleMessage(data, isBinary));
|
|
26
|
+
void messageQueue.catch(fail);
|
|
27
|
+
});
|
|
28
|
+
socket.on('error', (error) => console.error(`platform channel error: ${error.message}`));
|
|
29
|
+
socket.on('close', () => {
|
|
30
|
+
if (!shuttingDown)
|
|
31
|
+
process.exit(1);
|
|
32
|
+
});
|
|
33
|
+
async function handleMessage(data, isBinary) {
|
|
34
|
+
if (isBinary)
|
|
35
|
+
throw new Error('platform channel sent a binary frame');
|
|
36
|
+
const frame = parseFrame(data.toString());
|
|
37
|
+
if (!initialized) {
|
|
38
|
+
if (frame.t !== 'init')
|
|
39
|
+
throw new Error('expected init as the first platform frame');
|
|
40
|
+
initialized = true;
|
|
41
|
+
events = new PlatformEvents();
|
|
42
|
+
const bundle = (await import(pathToFileURL(bundlePath).href));
|
|
43
|
+
const boot = bundle.__castleBootSession;
|
|
44
|
+
if (typeof boot !== 'function')
|
|
45
|
+
throw new Error('server bundle has no __castleBootSession export');
|
|
46
|
+
await boot(createPlatformHandle(frame, events));
|
|
47
|
+
send({ protocolVersion: PROTOCOL_VERSION, t: 'ready' });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (!events)
|
|
51
|
+
throw new Error('platform event dispatcher unavailable');
|
|
52
|
+
await dispatch(events, frame);
|
|
53
|
+
}
|
|
54
|
+
function createPlatformHandle(init, platformEvents) {
|
|
55
|
+
const config = asRecord(init.config);
|
|
56
|
+
return {
|
|
57
|
+
send(connId, text) {
|
|
58
|
+
send({ protocolVersion: PROTOCOL_VERSION, t: 'sendTo', playerId: connId, d: text });
|
|
59
|
+
},
|
|
60
|
+
broadcast(text) {
|
|
61
|
+
send({ protocolVersion: PROTOCOL_VERSION, t: 'broadcast', d: text });
|
|
62
|
+
},
|
|
63
|
+
disconnect(connId, code) {
|
|
64
|
+
send({ protocolVersion: PROTOCOL_VERSION, t: 'kick', playerId: connId, reason: String(code) });
|
|
65
|
+
},
|
|
66
|
+
on(event, callback) {
|
|
67
|
+
platformEvents.on(event, callback);
|
|
68
|
+
},
|
|
69
|
+
config: Object.freeze({
|
|
70
|
+
sessionId: String(init.sessionId),
|
|
71
|
+
deckId: String(init.deckId),
|
|
72
|
+
mode: 'named',
|
|
73
|
+
tickRate: Number(config.tickRate),
|
|
74
|
+
maxPlayers: Number(config.maxPlayers),
|
|
75
|
+
}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
async function dispatch(platformEvents, frame) {
|
|
79
|
+
switch (frame.t) {
|
|
80
|
+
case 'init':
|
|
81
|
+
throw new Error('received duplicate init frame');
|
|
82
|
+
case 'playerJoined': {
|
|
83
|
+
const player = asRecord(frame.player);
|
|
84
|
+
await platformEvents.emit('join', player.playerId, player);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
case 'playerLeft':
|
|
88
|
+
await platformEvents.emit('leave', frame.playerId);
|
|
89
|
+
return;
|
|
90
|
+
case 'clientMessage':
|
|
91
|
+
await platformEvents.emit('message', frame.playerId, JSON.stringify(frame.d));
|
|
92
|
+
return;
|
|
93
|
+
case 'replaced':
|
|
94
|
+
await platformEvents.emit('replaced');
|
|
95
|
+
return;
|
|
96
|
+
case 'shutdown':
|
|
97
|
+
shuttingDown = true;
|
|
98
|
+
await platformEvents.emit('shutdown', frame.reason);
|
|
99
|
+
socket.close(1000, 'shutdown');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function parseFrame(text) {
|
|
103
|
+
const value = asRecord(JSON.parse(text));
|
|
104
|
+
if (value.protocolVersion !== PROTOCOL_VERSION || typeof value.t !== 'string') {
|
|
105
|
+
throw new Error('platform channel sent an invalid frame');
|
|
106
|
+
}
|
|
107
|
+
return value;
|
|
108
|
+
}
|
|
109
|
+
function send(frame) {
|
|
110
|
+
if (socket.readyState !== WebSocket.OPEN)
|
|
111
|
+
throw new Error('platform channel is not open');
|
|
112
|
+
socket.send(JSON.stringify(frame));
|
|
113
|
+
}
|
|
114
|
+
function asRecord(value) {
|
|
115
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
116
|
+
throw new Error('platform channel sent an invalid frame');
|
|
117
|
+
}
|
|
118
|
+
return value;
|
|
119
|
+
}
|
|
120
|
+
function requiredEnv(name) {
|
|
121
|
+
const value = process.env[name];
|
|
122
|
+
if (!value)
|
|
123
|
+
throw new Error(`${name} is required`);
|
|
124
|
+
return value;
|
|
125
|
+
}
|
|
126
|
+
function fail(error) {
|
|
127
|
+
console.error(error instanceof Error ? error.stack ?? error.message : String(error));
|
|
128
|
+
process.exit(1);
|
|
129
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { FilesChangedMessage } from './filesChanged.js';
|
|
2
|
+
export interface DevPlayerIdentity {
|
|
3
|
+
userId: string;
|
|
4
|
+
username: string;
|
|
5
|
+
isAnonymous: boolean;
|
|
6
|
+
scopedUserId?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface DevSessionServer {
|
|
9
|
+
readonly port: number;
|
|
10
|
+
readonly sessionId: 'dev';
|
|
11
|
+
mintNonce(author: DevPlayerIdentity): string;
|
|
12
|
+
handleFilesChanged(message: FilesChangedMessage): void;
|
|
13
|
+
shutdown(): Promise<void>;
|
|
14
|
+
shutdownNow(): void;
|
|
15
|
+
}
|
|
16
|
+
export declare function startDevSessionServer(opts: {
|
|
17
|
+
projectDir: string;
|
|
18
|
+
log: (level: 'log' | 'error', text: string) => void;
|
|
19
|
+
}): Promise<DevSessionServer>;
|