castle-web-cli 0.4.209 → 0.4.211
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 +10 -0
- package/dist/api.js +31 -0
- package/dist/castle-host/host.js +83 -0
- package/dist/gitRemote.d.ts +49 -0
- package/dist/gitRemote.js +376 -0
- package/dist/index.js +83 -0
- package/dist/modulePreload.d.ts +14 -0
- package/dist/modulePreload.js +150 -0
- package/dist/platformDoc.js +1 -1
- package/dist/serve.js +2 -0
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/castle.d.ts +1 -1
- package/kits/base/sdk/commands.d.ts +31 -1
- package/kits/base/sdk/multiplayerVoice.d.ts +26 -2
- package/kits/base/sdk/multiplayerVoice.js +118 -3
- package/package.json +1 -1
package/dist/api.d.ts
CHANGED
|
@@ -170,4 +170,14 @@ export interface DeckMeta {
|
|
|
170
170
|
export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
|
|
171
171
|
export declare function webDeckSource(deckId: string): Promise<WebDeckSource | null>;
|
|
172
172
|
export declare function saveWebDeckSource(deckId: string, uploadId: string): Promise<WebDeckSource>;
|
|
173
|
+
export type CloudDeckKit = 'PHYSICS_2D' | 'PHYSICS_3D' | 'MULTIPLAYER_2D' | 'MULTIPLAYER_3D' | 'TURN_BASED' | 'NONE';
|
|
174
|
+
export interface RegisteredCloudDeck {
|
|
175
|
+
deckId: string;
|
|
176
|
+
initialCardId: string;
|
|
177
|
+
}
|
|
178
|
+
export declare function registerCloudDeck(operationId: string, title: string, kit: CloudDeckKit): Promise<RegisteredCloudDeck>;
|
|
179
|
+
export type GitEnvironment = 'staging' | 'production';
|
|
180
|
+
export declare function ensureGitRepo(deckId: string, environment: GitEnvironment): Promise<{
|
|
181
|
+
remoteUrl: string;
|
|
182
|
+
}>;
|
|
173
183
|
export {};
|
package/dist/api.js
CHANGED
|
@@ -301,3 +301,34 @@ export async function saveWebDeckSource(deckId, uploadId) {
|
|
|
301
301
|
handleAPIError(data);
|
|
302
302
|
return pickData(data, 'saveWebDeckSource');
|
|
303
303
|
}
|
|
304
|
+
// Mints a deck id server-side before anything is published, the way the cloud
|
|
305
|
+
// editor creates a deck. Idempotent by `operationId`. Ghost refuses it without the
|
|
306
|
+
// `cloud_editor` gate or from a sandbox session.
|
|
307
|
+
export async function registerCloudDeck(operationId, title, kit) {
|
|
308
|
+
const data = await graphql(`mutation($operationId: String!, $title: String!, $bootstrap: CloudDeckBootstrapInput!) {
|
|
309
|
+
registerCloudDeck(operationId: $operationId, title: $title, bootstrap: $bootstrap) {
|
|
310
|
+
deckId
|
|
311
|
+
initialCardId
|
|
312
|
+
}
|
|
313
|
+
}`, { operationId, title, bootstrap: { kind: 'KIT', kit } });
|
|
314
|
+
handleAPIError(data);
|
|
315
|
+
const result = pickData(data, 'registerCloudDeck');
|
|
316
|
+
if (!result?.deckId || !result.initialCardId) {
|
|
317
|
+
throw new Error('registerCloudDeck returned no deck.');
|
|
318
|
+
}
|
|
319
|
+
return result;
|
|
320
|
+
}
|
|
321
|
+
// Creates the deck's Castle git repo for one environment if it has none. Idempotent.
|
|
322
|
+
export async function ensureGitRepo(deckId, environment) {
|
|
323
|
+
const data = await graphql(`mutation($deckId: ID!, $environment: String!) {
|
|
324
|
+
ensureGitRepo(deckId: $deckId, environment: $environment) {
|
|
325
|
+
remoteUrl
|
|
326
|
+
}
|
|
327
|
+
}`, { deckId, environment });
|
|
328
|
+
handleAPIError(data);
|
|
329
|
+
const result = pickData(data, 'ensureGitRepo');
|
|
330
|
+
if (typeof result?.remoteUrl !== 'string') {
|
|
331
|
+
throw new Error('ensureGitRepo returned no remote URL.');
|
|
332
|
+
}
|
|
333
|
+
return { remoteUrl: result.remoteUrl };
|
|
334
|
+
}
|
package/dist/castle-host/host.js
CHANGED
|
@@ -44,6 +44,7 @@ const COMMAND_NAMES = [
|
|
|
44
44
|
"voice.requestJoin",
|
|
45
45
|
"voice.leave",
|
|
46
46
|
"voice.setMix",
|
|
47
|
+
"voice.setSpatial",
|
|
47
48
|
"characters.open",
|
|
48
49
|
"characters.send",
|
|
49
50
|
"characters.status",
|
|
@@ -184,6 +185,8 @@ function runCommand(ctx, command, params, caps, options) {
|
|
|
184
185
|
return voiceRequestJoin(ctx, params, caps, options.signal);
|
|
185
186
|
case "voice.leave":
|
|
186
187
|
return voiceLeave(ctx, params, caps);
|
|
188
|
+
case "voice.setSpatial":
|
|
189
|
+
return Promise.resolve(voiceSetSpatial(ctx, params, caps));
|
|
187
190
|
case "voice.setMix":
|
|
188
191
|
return Promise.resolve(voiceSetMix(ctx, params, caps));
|
|
189
192
|
case "characters.open":
|
|
@@ -411,6 +414,86 @@ function voiceSetMix(ctx, params, caps) {
|
|
|
411
414
|
caps.voice.setMix(sessionId, mix, ctx);
|
|
412
415
|
return { ok: true };
|
|
413
416
|
}
|
|
417
|
+
// World coordinates past this are a confused deck, not a big world.
|
|
418
|
+
const VOICE_COORDINATE_LIMIT = 1_000_000;
|
|
419
|
+
const VOICE_DISTANCE_MODELS = ["linear", "inverse", "exponential"];
|
|
420
|
+
function voiceVector(value) {
|
|
421
|
+
if (!Array.isArray(value) || value.length !== 3)
|
|
422
|
+
return null;
|
|
423
|
+
const vector = value.map((component) => typeof component === "number" && Number.isFinite(component)
|
|
424
|
+
? Math.min(VOICE_COORDINATE_LIMIT, Math.max(-VOICE_COORDINATE_LIMIT, component))
|
|
425
|
+
: NaN);
|
|
426
|
+
return vector.every((component) => !Number.isNaN(component))
|
|
427
|
+
? vector
|
|
428
|
+
: null;
|
|
429
|
+
}
|
|
430
|
+
function isZero(vector) {
|
|
431
|
+
return vector[0] === 0 && vector[1] === 0 && vector[2] === 0;
|
|
432
|
+
}
|
|
433
|
+
// A camera looking straight down (a top-down deck) with the default y-up has forward
|
|
434
|
+
// parallel to up, which leaves no left or right: every voice would play centered.
|
|
435
|
+
// Swap in an up that is perpendicular, so the top of the screen (-z) stays "ahead".
|
|
436
|
+
function perpendicularUp(forward, up) {
|
|
437
|
+
const cross = [
|
|
438
|
+
forward[1] * up[2] - forward[2] * up[1],
|
|
439
|
+
forward[2] * up[0] - forward[0] * up[2],
|
|
440
|
+
forward[0] * up[1] - forward[1] * up[0],
|
|
441
|
+
];
|
|
442
|
+
const crossLength = Math.hypot(cross[0], cross[1], cross[2]);
|
|
443
|
+
const scale = Math.hypot(...forward) * Math.hypot(...up);
|
|
444
|
+
if (crossLength > 1e-6 * scale)
|
|
445
|
+
return up;
|
|
446
|
+
return Math.abs(forward[2]) < 0.9 * Math.hypot(...forward) ? [0, 0, -1] : [0, 1, 0];
|
|
447
|
+
}
|
|
448
|
+
function voiceSetSpatial(ctx, params, caps) {
|
|
449
|
+
const sessionId = voiceSessionId(params, "voice.setSpatial");
|
|
450
|
+
const update = {};
|
|
451
|
+
const listener = params.listener;
|
|
452
|
+
if (listener && typeof listener === "object") {
|
|
453
|
+
const position = voiceVector(listener.position);
|
|
454
|
+
const forward = voiceVector(listener.forward);
|
|
455
|
+
const up = listener.up === undefined ? [0, 1, 0] : voiceVector(listener.up);
|
|
456
|
+
// A zero forward or up has no direction to face.
|
|
457
|
+
if (position && forward && up && !isZero(forward) && !isZero(up)) {
|
|
458
|
+
update.listener = { position, forward, up: perpendicularUp(forward, up) };
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const rawPositions = params.positions;
|
|
462
|
+
if (rawPositions && typeof rawPositions === "object" && !Array.isArray(rawPositions)) {
|
|
463
|
+
const positions = Object.create(null);
|
|
464
|
+
const entries = Object.entries(rawPositions).slice(0, VOICE_MIX_MAX_ENTRIES);
|
|
465
|
+
for (const [userId, value] of entries) {
|
|
466
|
+
if (!userId || userId.length > 64 || RESERVED_MIX_KEYS.has(userId))
|
|
467
|
+
continue;
|
|
468
|
+
if (value === null) {
|
|
469
|
+
positions[userId] = null;
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
const position = voiceVector(value);
|
|
473
|
+
if (position)
|
|
474
|
+
positions[userId] = position;
|
|
475
|
+
}
|
|
476
|
+
if (Object.keys(positions).length > 0)
|
|
477
|
+
update.positions = positions;
|
|
478
|
+
}
|
|
479
|
+
const options = params.options;
|
|
480
|
+
if (options && typeof options === "object") {
|
|
481
|
+
const model = VOICE_DISTANCE_MODELS.includes(options.distanceModel)
|
|
482
|
+
? options.distanceModel
|
|
483
|
+
: "inverse";
|
|
484
|
+
const refDistance = finiteOr(options.refDistance, 1, 0.01, VOICE_COORDINATE_LIMIT);
|
|
485
|
+
update.options = {
|
|
486
|
+
distanceModel: model,
|
|
487
|
+
refDistance,
|
|
488
|
+
maxDistance: Math.max(refDistance, finiteOr(options.maxDistance, 100, 0.01, VOICE_COORDINATE_LIMIT)),
|
|
489
|
+
rolloff: finiteOr(options.rolloff, 1, 0, 100),
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
if (caps.voice?.setSpatial && (update.listener || update.positions || update.options)) {
|
|
493
|
+
caps.voice.setSpatial(sessionId, update, ctx);
|
|
494
|
+
}
|
|
495
|
+
return { ok: true };
|
|
496
|
+
}
|
|
414
497
|
function finiteOr(value, fallback, min, max) {
|
|
415
498
|
return typeof value === "number" && Number.isFinite(value)
|
|
416
499
|
? Math.min(max, Math.max(min, value))
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { CloudDeckKit, GitEnvironment, RegisteredCloudDeck } from './api.js';
|
|
2
|
+
export declare const GIT_HOSTS: Record<GitEnvironment, string>;
|
|
3
|
+
export declare const GIT_REMOTE_NAME = "castle";
|
|
4
|
+
export declare const CREDENTIAL_HELPER = "!castle-web git credential";
|
|
5
|
+
export declare const DEFAULT_GITIGNORE: string;
|
|
6
|
+
export declare function isSandboxToken(token: string | undefined | null): boolean;
|
|
7
|
+
export declare function credentialConfigKey(environment: GitEnvironment): string;
|
|
8
|
+
export interface CredentialAnswer {
|
|
9
|
+
stdout: string;
|
|
10
|
+
stderr: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function answerCredentialRequest(action: string, input: string, opts: {
|
|
13
|
+
token: string | null;
|
|
14
|
+
envToken: string | undefined;
|
|
15
|
+
}): CredentialAnswer;
|
|
16
|
+
export interface GitResult {
|
|
17
|
+
status: number | null;
|
|
18
|
+
stdout: string;
|
|
19
|
+
stderr: string;
|
|
20
|
+
error?: Error;
|
|
21
|
+
}
|
|
22
|
+
export interface GitInitDeps {
|
|
23
|
+
token: string | null;
|
|
24
|
+
envToken: string | undefined;
|
|
25
|
+
registerCloudDeck(operationId: string, title: string, kit: CloudDeckKit): Promise<RegisteredCloudDeck>;
|
|
26
|
+
ensureGitRepo(deckId: string, environment: GitEnvironment): Promise<{
|
|
27
|
+
remoteUrl: string;
|
|
28
|
+
}>;
|
|
29
|
+
git(args: string[], cwd: string): GitResult;
|
|
30
|
+
newOperationId(): string;
|
|
31
|
+
castleWebOnPath(): boolean;
|
|
32
|
+
log(message: string): void;
|
|
33
|
+
warn(message: string): void;
|
|
34
|
+
}
|
|
35
|
+
export declare function isOnPath(name: string, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
|
|
36
|
+
export declare function runGit(args: string[], cwd: string): GitResult;
|
|
37
|
+
export declare function cloudKitFor(castleJson: Record<string, unknown> | null): CloudDeckKit;
|
|
38
|
+
export declare const PENDING_INIT_FILE: string;
|
|
39
|
+
export interface GitInitResult {
|
|
40
|
+
deckId: string;
|
|
41
|
+
remoteUrl: string;
|
|
42
|
+
registered: boolean;
|
|
43
|
+
initialized: boolean;
|
|
44
|
+
wroteGitignore: boolean;
|
|
45
|
+
remote: 'added' | 'updated' | 'unchanged';
|
|
46
|
+
}
|
|
47
|
+
export declare function gitInit(dirArg: string, opts: {
|
|
48
|
+
environment: GitEnvironment;
|
|
49
|
+
}, deps: GitInitDeps): Promise<GitInitResult>;
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { spawnSync } from 'child_process';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import * as path from 'path';
|
|
4
|
+
import { readCastleJsonOrThrow } from './castleJson.js';
|
|
5
|
+
// Castle-hosted git remotes (castle-sandboxes docs/git-remotes-phase1.md): each deck
|
|
6
|
+
// gets `https://git.castle.xyz/<deckId>.git`, served by the sandbox proxy, which
|
|
7
|
+
// takes the user's Castle session token as the Basic auth password. `git init` wires
|
|
8
|
+
// a local repo to it; `git credential` is the helper git calls to get that token.
|
|
9
|
+
export const GIT_HOSTS = {
|
|
10
|
+
production: 'git.castle.xyz',
|
|
11
|
+
staging: 'git-staging.castle.xyz',
|
|
12
|
+
};
|
|
13
|
+
export const GIT_REMOTE_NAME = 'castle';
|
|
14
|
+
// Runs through the shell as `castle-web git credential <action>`, so the helper
|
|
15
|
+
// needs no binary of its own.
|
|
16
|
+
export const CREDENTIAL_HELPER = '!castle-web git credential';
|
|
17
|
+
// The kits' own .gitignore: build output, dependencies, and imports/ (other decks'
|
|
18
|
+
// files, restored from castle.json's pins).
|
|
19
|
+
export const DEFAULT_GITIGNORE = ['node_modules/', 'dist/', '.castle/', '.vite/', '/imports/', ''].join('\n');
|
|
20
|
+
// Inside a cloud sandbox CASTLE_TOKEN is the llm-proxy's per-boot HMAC token,
|
|
21
|
+
// `v1.<base64url payload>.<base64url hmac>`, not a Castle session. The git proxy
|
|
22
|
+
// would reject it anyway; refusing here keeps it from being sent off-host at all.
|
|
23
|
+
const SANDBOX_TOKEN_RE = /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
24
|
+
export function isSandboxToken(token) {
|
|
25
|
+
return typeof token === 'string' && SANDBOX_TOKEN_RE.test(token);
|
|
26
|
+
}
|
|
27
|
+
export function credentialConfigKey(environment) {
|
|
28
|
+
return `credential.https://${GIT_HOSTS[environment]}.helper`;
|
|
29
|
+
}
|
|
30
|
+
function parseCredentialInput(input) {
|
|
31
|
+
const fields = new Map();
|
|
32
|
+
for (const line of input.split('\n')) {
|
|
33
|
+
const trimmed = line.replace(/\r$/, '');
|
|
34
|
+
if (trimmed === '')
|
|
35
|
+
break;
|
|
36
|
+
const eq = trimmed.indexOf('=');
|
|
37
|
+
if (eq <= 0)
|
|
38
|
+
continue;
|
|
39
|
+
fields.set(trimmed.slice(0, eq), trimmed.slice(eq + 1));
|
|
40
|
+
}
|
|
41
|
+
return fields;
|
|
42
|
+
}
|
|
43
|
+
const CASTLE_GIT_HOSTS = new Set(Object.values(GIT_HOSTS));
|
|
44
|
+
// git's credential-helper protocol (gitcredentials(7)). Only `get` answers, and only
|
|
45
|
+
// for the Castle git hosts over https; `store` and `erase` do nothing, since the
|
|
46
|
+
// token belongs to `castle-web login`. A refusal says `quit=1` so git stops rather
|
|
47
|
+
// than prompting for a password the user doesn't have.
|
|
48
|
+
export function answerCredentialRequest(action, input, opts) {
|
|
49
|
+
if (action !== 'get')
|
|
50
|
+
return { stdout: '', stderr: '' };
|
|
51
|
+
const fields = parseCredentialInput(input);
|
|
52
|
+
const host = fields.get('host');
|
|
53
|
+
if (fields.get('protocol') !== 'https' || !host || !CASTLE_GIT_HOSTS.has(host)) {
|
|
54
|
+
return { stdout: '', stderr: '' };
|
|
55
|
+
}
|
|
56
|
+
if (isSandboxToken(opts.envToken)) {
|
|
57
|
+
return {
|
|
58
|
+
stdout: 'quit=1\n',
|
|
59
|
+
stderr: 'castle-web: CASTLE_TOKEN is a cloud sandbox token, which Castle git remotes do not accept.\n',
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const token = opts.token;
|
|
63
|
+
if (!token) {
|
|
64
|
+
return {
|
|
65
|
+
stdout: 'quit=1\n',
|
|
66
|
+
stderr: 'castle-web: not logged in. Run `castle-web login`, then retry.\n',
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
if (/[\n\r\0]/.test(token)) {
|
|
70
|
+
return { stdout: 'quit=1\n', stderr: 'castle-web: the stored Castle token is malformed.\n' };
|
|
71
|
+
}
|
|
72
|
+
return { stdout: `username=castle\npassword=${token}\n`, stderr: '' };
|
|
73
|
+
}
|
|
74
|
+
// A PATH lookup with no spawn: is there an executable `name` in one of its dirs?
|
|
75
|
+
export function isOnPath(name, env = process.env, platform = process.platform) {
|
|
76
|
+
const dirs = (env.PATH ?? env.Path ?? '').split(path.delimiter).filter(Boolean);
|
|
77
|
+
const exts = platform === 'win32' ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)] : [''];
|
|
78
|
+
for (const dir of dirs) {
|
|
79
|
+
for (const ext of exts) {
|
|
80
|
+
const candidate = path.join(dir, name + ext);
|
|
81
|
+
try {
|
|
82
|
+
if (!fs.statSync(candidate).isFile())
|
|
83
|
+
continue;
|
|
84
|
+
if (platform !== 'win32')
|
|
85
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
// not here
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
export function runGit(args, cwd) {
|
|
96
|
+
// Force git's untranslated messages: callers match stderr text (e.g. "not a git repository"),
|
|
97
|
+
// which a localized git would print in another language.
|
|
98
|
+
const result = spawnSync('git', args, {
|
|
99
|
+
cwd,
|
|
100
|
+
encoding: 'utf-8',
|
|
101
|
+
env: { ...process.env, LC_ALL: 'C', LANGUAGE: 'C' },
|
|
102
|
+
});
|
|
103
|
+
return {
|
|
104
|
+
status: result.status,
|
|
105
|
+
stdout: result.stdout ?? '',
|
|
106
|
+
stderr: result.stderr ?? '',
|
|
107
|
+
error: result.error,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const STORAGE_KIT_TO_CLOUD = {
|
|
111
|
+
'physics-2d': 'PHYSICS_2D',
|
|
112
|
+
'physics-3d': 'PHYSICS_3D',
|
|
113
|
+
'multiplayer-2d': 'MULTIPLAYER_2D',
|
|
114
|
+
'multiplayer-3d': 'MULTIPLAYER_3D',
|
|
115
|
+
'turn-based': 'TURN_BASED',
|
|
116
|
+
};
|
|
117
|
+
// The kit a deck was scaffolded from, as registerCloudDeck names it: the builtin
|
|
118
|
+
// import it pinned directly (not one another import brought in). A deck on no kit,
|
|
119
|
+
// or on a kit the cloud doesn't list, registers as NONE.
|
|
120
|
+
export function cloudKitFor(castleJson) {
|
|
121
|
+
const imports = castleJson?.imports;
|
|
122
|
+
if (!imports || typeof imports !== 'object')
|
|
123
|
+
return 'NONE';
|
|
124
|
+
for (const pin of Object.values(imports)) {
|
|
125
|
+
if (!pin || typeof pin !== 'object')
|
|
126
|
+
continue;
|
|
127
|
+
const { source, kit, via } = pin;
|
|
128
|
+
if (source !== 'builtin' || via !== undefined || typeof kit !== 'string')
|
|
129
|
+
continue;
|
|
130
|
+
const cloud = STORAGE_KIT_TO_CLOUD[kit];
|
|
131
|
+
if (cloud)
|
|
132
|
+
return cloud;
|
|
133
|
+
}
|
|
134
|
+
return 'NONE';
|
|
135
|
+
}
|
|
136
|
+
function errorCode(e) {
|
|
137
|
+
const code = e?.extensions?.code;
|
|
138
|
+
return typeof code === 'string' ? code : undefined;
|
|
139
|
+
}
|
|
140
|
+
function explainRegisterFailure(e) {
|
|
141
|
+
const code = errorCode(e);
|
|
142
|
+
const detail = e instanceof Error ? e.message : String(e);
|
|
143
|
+
if (code === 'FEATURE_NOT_ENABLED') {
|
|
144
|
+
return new Error(`Castle refused to create a deck for this directory: the cloud editor isn't enabled for your account. (${detail})`);
|
|
145
|
+
}
|
|
146
|
+
if (code === 'CLOUD_DECK_AUTH_REQUIRED' || code === 'LOGIN_REQUIRED' || code === 'SIGN_UP_REQUIRED') {
|
|
147
|
+
return new Error(`Castle refused to create a deck: it needs a signed-in Castle account. Run \`castle-web login\`. (${detail})`);
|
|
148
|
+
}
|
|
149
|
+
return new Error(`Could not create a Castle deck for this directory: ${detail}`);
|
|
150
|
+
}
|
|
151
|
+
function git(deps, args, cwd) {
|
|
152
|
+
const result = deps.git(args, cwd);
|
|
153
|
+
if (result.error && result.error.code === 'ENOENT') {
|
|
154
|
+
throw new Error('git is not installed (or not on PATH).');
|
|
155
|
+
}
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
function gitOrThrow(deps, args, cwd) {
|
|
159
|
+
const result = git(deps, args, cwd);
|
|
160
|
+
if (result.status !== 0) {
|
|
161
|
+
const why = (result.stderr || result.stdout || result.error?.message || '').trim();
|
|
162
|
+
throw new Error(`\`git ${args.join(' ')}\` failed${why ? `: ${why}` : ''}`);
|
|
163
|
+
}
|
|
164
|
+
return result.stdout;
|
|
165
|
+
}
|
|
166
|
+
function sameDir(a, b) {
|
|
167
|
+
try {
|
|
168
|
+
return fs.realpathSync(a) === fs.realpathSync(b);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return path.resolve(a) === path.resolve(b);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// A deck dir that is its own repo is used as is; one with no repo gets `git init`.
|
|
175
|
+
// One inside ANOTHER repo (a decks monorepo) is refused, before any server call:
|
|
176
|
+
// the castle remote would then push that whole repo's history, and a nested repo
|
|
177
|
+
// is a surprise either way.
|
|
178
|
+
// Only git's own "not a git repository" means there is none; any other failure
|
|
179
|
+
// (dubious ownership, a broken .git) is surfaced, since reading it as "no repo"
|
|
180
|
+
// would `git init` a nested repo inside one git refused to open.
|
|
181
|
+
function hasOwnRepo(deps, dir) {
|
|
182
|
+
const top = git(deps, ['rev-parse', '--show-toplevel'], dir);
|
|
183
|
+
if (top.status !== 0) {
|
|
184
|
+
if (/not a git repository/i.test(top.stderr))
|
|
185
|
+
return false;
|
|
186
|
+
const why = (top.stderr || top.stdout || top.error?.message || '').trim();
|
|
187
|
+
throw new Error(`git could not read the repo at ${dir}${why ? `: ${why}` : ''}`);
|
|
188
|
+
}
|
|
189
|
+
const toplevel = top.stdout.trim();
|
|
190
|
+
if (sameDir(toplevel, dir))
|
|
191
|
+
return true;
|
|
192
|
+
throw new Error(`${dir} is inside the git repo at ${toplevel}. Run \`castle-web git init\` on a deck that is its own repo, or at that repo's root.`);
|
|
193
|
+
}
|
|
194
|
+
function initRepo(deps, dir) {
|
|
195
|
+
const withMain = git(deps, ['init', '--initial-branch=main'], dir);
|
|
196
|
+
if (withMain.status !== 0)
|
|
197
|
+
gitOrThrow(deps, ['init'], dir);
|
|
198
|
+
}
|
|
199
|
+
function isCastleGitUrl(url) {
|
|
200
|
+
try {
|
|
201
|
+
const parsed = new URL(url);
|
|
202
|
+
return parsed.protocol === 'https:' && CASTLE_GIT_HOSTS.has(parsed.host);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// A pushurl would send pushes somewhere other than the url this sets, so it goes.
|
|
209
|
+
function clearPushUrl(deps, dir) {
|
|
210
|
+
const key = `remote.${GIT_REMOTE_NAME}.pushurl`;
|
|
211
|
+
const current = git(deps, ['config', '--local', '--get-all', key], dir);
|
|
212
|
+
if (current.status !== 0 || !current.stdout.trim())
|
|
213
|
+
return;
|
|
214
|
+
gitOrThrow(deps, ['config', '--local', '--unset-all', key], dir);
|
|
215
|
+
deps.warn(`Removed ${key} (${current.stdout.trim().split('\n').join(', ')}), so pushes go to the Castle remote.`);
|
|
216
|
+
}
|
|
217
|
+
function setRemote(deps, dir, remoteUrl) {
|
|
218
|
+
const current = git(deps, ['remote', 'get-url', GIT_REMOTE_NAME], dir);
|
|
219
|
+
if (current.status === 0) {
|
|
220
|
+
clearPushUrl(deps, dir);
|
|
221
|
+
const previous = current.stdout.trim();
|
|
222
|
+
if (previous === remoteUrl)
|
|
223
|
+
return 'unchanged';
|
|
224
|
+
gitOrThrow(deps, ['remote', 'set-url', GIT_REMOTE_NAME, remoteUrl], dir);
|
|
225
|
+
if (!isCastleGitUrl(previous)) {
|
|
226
|
+
deps.warn(`Warning: the "${GIT_REMOTE_NAME}" remote pointed at ${previous}; it now points at ${remoteUrl}.`);
|
|
227
|
+
}
|
|
228
|
+
return 'updated';
|
|
229
|
+
}
|
|
230
|
+
gitOrThrow(deps, ['remote', 'add', GIT_REMOTE_NAME, remoteUrl], dir);
|
|
231
|
+
return 'added';
|
|
232
|
+
}
|
|
233
|
+
// What to tell the user to run next: push the current branch, or commit first.
|
|
234
|
+
function pushHint(deps, dir) {
|
|
235
|
+
const branchResult = git(deps, ['symbolic-ref', '--quiet', '--short', 'HEAD'], dir);
|
|
236
|
+
const branch = branchResult.status === 0 ? branchResult.stdout.trim() : '';
|
|
237
|
+
const hasCommit = git(deps, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], dir).status === 0;
|
|
238
|
+
const push = branch ? `git push -u ${GIT_REMOTE_NAME} ${branch}` : `git push ${GIT_REMOTE_NAME} HEAD:main`;
|
|
239
|
+
if (!hasCommit) {
|
|
240
|
+
return `The repo has no commits yet. Commit first (git add -A && git commit -m "First version"), then push with: ${push}`;
|
|
241
|
+
}
|
|
242
|
+
return `Push with: ${push}`;
|
|
243
|
+
}
|
|
244
|
+
// registerCloudDeck is idempotent by operationId, so the id is written down before
|
|
245
|
+
// the call and reused until castle.json has the deckId: a lost response, or a
|
|
246
|
+
// castle.json write that failed, then retries into the same deck, not a second one.
|
|
247
|
+
// .castle/ is the deck's local, gitignored state.
|
|
248
|
+
export const PENDING_INIT_FILE = path.join('.castle', 'git-init.json');
|
|
249
|
+
function readPendingOperationId(dir) {
|
|
250
|
+
try {
|
|
251
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(dir, PENDING_INIT_FILE), 'utf-8'));
|
|
252
|
+
const id = parsed?.operationId;
|
|
253
|
+
return typeof id === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(id) ? id : null;
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function writePendingOperationId(dir, operationId) {
|
|
260
|
+
const file = path.join(dir, PENDING_INIT_FILE);
|
|
261
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
262
|
+
fs.writeFileSync(file, JSON.stringify({ operationId }, null, 2) + '\n', 'utf-8');
|
|
263
|
+
}
|
|
264
|
+
function clearPendingOperationId(dir) {
|
|
265
|
+
fs.rmSync(path.join(dir, PENDING_INIT_FILE), { force: true });
|
|
266
|
+
}
|
|
267
|
+
// The helper is set in the repo's own config, keyed to the Castle git host. An empty
|
|
268
|
+
// entry first resets the helper list for that URL, so a global helper (osxkeychain,
|
|
269
|
+
// manager) neither answers ahead of this one with a stale token nor stores the
|
|
270
|
+
// Castle token after a successful push.
|
|
271
|
+
function setCredentialHelper(deps, dir, environment) {
|
|
272
|
+
const key = credentialConfigKey(environment);
|
|
273
|
+
const unset = git(deps, ['config', '--local', '--unset-all', key], dir);
|
|
274
|
+
// 5: the key wasn't set, which is the first-run case.
|
|
275
|
+
if (unset.status !== 0 && unset.status !== 5) {
|
|
276
|
+
gitOrThrow(deps, ['config', '--local', '--unset-all', key], dir);
|
|
277
|
+
}
|
|
278
|
+
gitOrThrow(deps, ['config', '--local', '--add', key, ''], dir);
|
|
279
|
+
gitOrThrow(deps, ['config', '--local', '--add', key, CREDENTIAL_HELPER], dir);
|
|
280
|
+
}
|
|
281
|
+
function expectedRemoteUrl(environment, deckId) {
|
|
282
|
+
return `https://${GIT_HOSTS[environment]}/${deckId}.git`;
|
|
283
|
+
}
|
|
284
|
+
export async function gitInit(dirArg, opts, deps) {
|
|
285
|
+
const { environment } = opts;
|
|
286
|
+
if (isSandboxToken(deps.envToken)) {
|
|
287
|
+
throw new Error('Castle git remotes are not available from a cloud sandbox yet: CASTLE_TOKEN here is a sandbox token.');
|
|
288
|
+
}
|
|
289
|
+
if (!deps.token)
|
|
290
|
+
throw new Error('Not logged in. Run `castle-web login`.');
|
|
291
|
+
const dir = path.resolve(dirArg);
|
|
292
|
+
// Only a deck: never a folder made up on the spot, or one that isn't a deck.
|
|
293
|
+
let isDir = false;
|
|
294
|
+
try {
|
|
295
|
+
isDir = fs.statSync(dir).isDirectory();
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
isDir = false;
|
|
299
|
+
}
|
|
300
|
+
if (!isDir) {
|
|
301
|
+
throw new Error(`${dir} does not exist. Create a deck with \`castle-web init <dir>\` first.`);
|
|
302
|
+
}
|
|
303
|
+
const castleJsonPath = path.join(dir, 'castle.json');
|
|
304
|
+
if (!fs.existsSync(castleJsonPath)) {
|
|
305
|
+
throw new Error(`${dir} has no castle.json, so it isn't a Castle deck. Create one with \`castle-web init <dir>\`, or run this in a deck's directory.`);
|
|
306
|
+
}
|
|
307
|
+
// Before touching the server, so a machine without git doesn't get a deck for nothing.
|
|
308
|
+
gitOrThrow(deps, ['--version'], dir);
|
|
309
|
+
const repoExists = hasOwnRepo(deps, dir);
|
|
310
|
+
// 1. The deck: castle.json's, or a new one minted server-side.
|
|
311
|
+
const castleJson = readCastleJsonOrThrow(dir);
|
|
312
|
+
let deckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : '';
|
|
313
|
+
let registered = false;
|
|
314
|
+
if (!deckId) {
|
|
315
|
+
const rawTitle = typeof castleJson?.title === 'string' && castleJson.title.trim()
|
|
316
|
+
? castleJson.title.trim()
|
|
317
|
+
: path.basename(dir);
|
|
318
|
+
const title = rawTitle.slice(0, 255);
|
|
319
|
+
let operationId = readPendingOperationId(dir);
|
|
320
|
+
if (!operationId) {
|
|
321
|
+
operationId = deps.newOperationId();
|
|
322
|
+
writePendingOperationId(dir, operationId);
|
|
323
|
+
}
|
|
324
|
+
let deck;
|
|
325
|
+
try {
|
|
326
|
+
deck = await deps.registerCloudDeck(operationId, title, cloudKitFor(castleJson));
|
|
327
|
+
}
|
|
328
|
+
catch (e) {
|
|
329
|
+
throw explainRegisterFailure(e);
|
|
330
|
+
}
|
|
331
|
+
deckId = deck.deckId;
|
|
332
|
+
// The card id is the placeholder card the server made, so a later save-deck
|
|
333
|
+
// publishes onto it rather than minting a second card.
|
|
334
|
+
const next = { ...(castleJson ?? {}), deckId, cardId: deck.initialCardId };
|
|
335
|
+
fs.writeFileSync(castleJsonPath, JSON.stringify(next, null, 2) + '\n', 'utf-8');
|
|
336
|
+
clearPendingOperationId(dir);
|
|
337
|
+
registered = true;
|
|
338
|
+
deps.log(`Created deck "${title}" (${deckId}). Saved castle.json.`);
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
// A leftover from a run that registered but died before clearing it.
|
|
342
|
+
clearPendingOperationId(dir);
|
|
343
|
+
}
|
|
344
|
+
// 2. The repo on Castle's side.
|
|
345
|
+
const { remoteUrl } = await deps.ensureGitRepo(deckId, environment);
|
|
346
|
+
const expected = expectedRemoteUrl(environment, deckId);
|
|
347
|
+
if (remoteUrl !== expected) {
|
|
348
|
+
// The credential helper is keyed to GIT_HOSTS; a remote anywhere else would
|
|
349
|
+
// either get no token or, worse, be the wrong deck.
|
|
350
|
+
throw new Error(`Castle returned an unexpected remote URL ${remoteUrl} (expected ${expected}).`);
|
|
351
|
+
}
|
|
352
|
+
// 3. The local repo.
|
|
353
|
+
const initialized = !repoExists;
|
|
354
|
+
if (initialized)
|
|
355
|
+
initRepo(deps, dir);
|
|
356
|
+
const gitignorePath = path.join(dir, '.gitignore');
|
|
357
|
+
let wroteGitignore = false;
|
|
358
|
+
if (!fs.existsSync(gitignorePath)) {
|
|
359
|
+
fs.writeFileSync(gitignorePath, DEFAULT_GITIGNORE, 'utf-8');
|
|
360
|
+
wroteGitignore = true;
|
|
361
|
+
}
|
|
362
|
+
const remote = setRemote(deps, dir, remoteUrl);
|
|
363
|
+
setCredentialHelper(deps, dir, environment);
|
|
364
|
+
if (initialized)
|
|
365
|
+
deps.log(`Initialized a git repo in ${dir}.`);
|
|
366
|
+
if (wroteGitignore)
|
|
367
|
+
deps.log('Wrote .gitignore.');
|
|
368
|
+
deps.log(remote === 'unchanged'
|
|
369
|
+
? `Remote "${GIT_REMOTE_NAME}" already points at ${remoteUrl}.`
|
|
370
|
+
: `Remote "${GIT_REMOTE_NAME}" ${remote}: ${remoteUrl}`);
|
|
371
|
+
if (!deps.castleWebOnPath()) {
|
|
372
|
+
deps.warn('Warning: `castle-web` is not on PATH. git runs `castle-web git credential` to get your Castle token, so pushes will fail to authenticate until it is (npm install -g castle-web-cli).');
|
|
373
|
+
}
|
|
374
|
+
deps.log(pushHint(deps, dir));
|
|
375
|
+
return { deckId, remoteUrl, registered, initialized, wroteGitignore, remote };
|
|
376
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
2
3
|
import * as fs from 'fs';
|
|
3
4
|
import * as path from 'path';
|
|
4
5
|
import { login } from './login.js';
|
|
@@ -76,6 +77,17 @@ function getFlagValue(flag) {
|
|
|
76
77
|
function hasFlag(flag) {
|
|
77
78
|
return args.includes(flag);
|
|
78
79
|
}
|
|
80
|
+
function readStdin() {
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
let input = '';
|
|
83
|
+
process.stdin.setEncoding('utf-8');
|
|
84
|
+
process.stdin.on('data', (chunk) => {
|
|
85
|
+
input += chunk;
|
|
86
|
+
});
|
|
87
|
+
process.stdin.on('end', () => resolve(input));
|
|
88
|
+
process.stdin.on('error', reject);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
79
91
|
function readServeSocketPort(dir) {
|
|
80
92
|
try {
|
|
81
93
|
const serveJson = JSON.parse(fs.readFileSync(path.join(path.resolve(dir), '.castle', 'serve.json'), 'utf-8'));
|
|
@@ -153,6 +165,8 @@ function usage() {
|
|
|
153
165
|
castle-web list-versions [version] [--dir DIR] (defaults to the latest version)
|
|
154
166
|
castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
|
|
155
167
|
castle-web restore-version <version> [--force] [--dir DIR]
|
|
168
|
+
castle-web git init [dir] [--dir DIR] [--staging] (connects the deck to its Castle git remote: git push castle <branch>)
|
|
169
|
+
castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git init sets it up)
|
|
156
170
|
castle-web login
|
|
157
171
|
castle-web whoami
|
|
158
172
|
castle-web --version
|
|
@@ -163,6 +177,72 @@ ${kitLines}
|
|
|
163
177
|
After init, read the scaffolded deck's CLAUDE.md (also AGENTS.md) for the kit's full author guide.`);
|
|
164
178
|
process.exit(1);
|
|
165
179
|
}
|
|
180
|
+
// `git init`'s own arguments, strictly: an unknown flag is an error rather than
|
|
181
|
+
// ignored, since a typo'd `--staging` would otherwise target production.
|
|
182
|
+
function parseGitInitArgs() {
|
|
183
|
+
let dir;
|
|
184
|
+
let staging = false;
|
|
185
|
+
const setDir = (value) => {
|
|
186
|
+
if (dir !== undefined && path.resolve(dir) !== path.resolve(value)) {
|
|
187
|
+
throw new Error(`git init takes one deck directory; got ${dir} and ${value}.`);
|
|
188
|
+
}
|
|
189
|
+
dir = value;
|
|
190
|
+
};
|
|
191
|
+
let sawSubcommand = false;
|
|
192
|
+
for (let i = 1; i < args.length; i++) {
|
|
193
|
+
const arg = args[i];
|
|
194
|
+
if (!sawSubcommand && arg === 'init') {
|
|
195
|
+
sawSubcommand = true;
|
|
196
|
+
}
|
|
197
|
+
else if (arg === '--staging') {
|
|
198
|
+
staging = true;
|
|
199
|
+
}
|
|
200
|
+
else if (arg === '--dir') {
|
|
201
|
+
const value = args[++i];
|
|
202
|
+
if (value === undefined || value.startsWith('-'))
|
|
203
|
+
throw new Error('--dir needs a directory.');
|
|
204
|
+
setDir(value);
|
|
205
|
+
}
|
|
206
|
+
else if (arg.startsWith('-')) {
|
|
207
|
+
throw new Error(`Unknown option for git init: ${arg} (it takes [dir] [--dir DIR] [--staging]).`);
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
setDir(arg);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return { dir: dir ?? '.', staging };
|
|
214
|
+
}
|
|
215
|
+
// `castle-web git init [dir] [--dir DIR] [--staging]` and `castle-web git credential <action>`.
|
|
216
|
+
async function gitCommand() {
|
|
217
|
+
const [sub, arg] = readPositionals();
|
|
218
|
+
const gitRemote = await import('./gitRemote.js');
|
|
219
|
+
if (sub === 'credential') {
|
|
220
|
+
// git's credential-helper protocol: key=value lines on stdin, the answer on
|
|
221
|
+
// stdout. Nothing else may print to stdout here.
|
|
222
|
+
const input = await readStdin();
|
|
223
|
+
const answer = gitRemote.answerCredentialRequest(arg ?? '', input, {
|
|
224
|
+
token: config.getToken(),
|
|
225
|
+
envToken: process.env.CASTLE_TOKEN,
|
|
226
|
+
});
|
|
227
|
+
process.stderr.write(answer.stderr);
|
|
228
|
+
process.stdout.write(answer.stdout);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (sub !== 'init')
|
|
232
|
+
usage();
|
|
233
|
+
const initArgs = parseGitInitArgs();
|
|
234
|
+
await gitRemote.gitInit(initArgs.dir, { environment: initArgs.staging ? 'staging' : 'production' }, {
|
|
235
|
+
token: config.getToken(),
|
|
236
|
+
envToken: process.env.CASTLE_TOKEN,
|
|
237
|
+
registerCloudDeck: api.registerCloudDeck,
|
|
238
|
+
ensureGitRepo: api.ensureGitRepo,
|
|
239
|
+
git: gitRemote.runGit,
|
|
240
|
+
newOperationId: () => `castle-web-git-init:${randomUUID()}`,
|
|
241
|
+
castleWebOnPath: () => gitRemote.isOnPath('castle-web'),
|
|
242
|
+
log: (message) => console.log(message),
|
|
243
|
+
warn: (message) => console.error(message),
|
|
244
|
+
});
|
|
245
|
+
}
|
|
166
246
|
async function main() {
|
|
167
247
|
// Before the switch: `--version` is a flag, not a command, and it has to work
|
|
168
248
|
// when there is no command at all. Which version is installed is the first
|
|
@@ -341,6 +421,9 @@ async function main() {
|
|
|
341
421
|
await runMcpPlaytestServer(path.resolve(dir), getFlagValue('--task-id'));
|
|
342
422
|
return;
|
|
343
423
|
}
|
|
424
|
+
case 'git':
|
|
425
|
+
await gitCommand();
|
|
426
|
+
break;
|
|
344
427
|
case 'login':
|
|
345
428
|
await login();
|
|
346
429
|
break;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { EnvironmentModuleNode, Plugin } from 'vite';
|
|
2
|
+
export declare function isPreloadableModuleUrl(url: string): boolean;
|
|
3
|
+
export declare function moduleEntrySrcs(html: string): string[];
|
|
4
|
+
type PreloadGraph = {
|
|
5
|
+
transformRequest(url: string): Promise<unknown>;
|
|
6
|
+
getModuleByUrl(url: string): Promise<EnvironmentModuleNode | undefined>;
|
|
7
|
+
};
|
|
8
|
+
export declare function isStaticImportIn(code: string, url: string): boolean;
|
|
9
|
+
export declare function collectModulePreloads(graph: PreloadGraph, entries: string[], budgetMs?: number): Promise<string[]>;
|
|
10
|
+
export declare function modulePreloadPlugin(options: {
|
|
11
|
+
enabled: boolean;
|
|
12
|
+
budgetMs?: number;
|
|
13
|
+
}): Plugin;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// The dev server hands a deck's modules to the browser one file at a time, and
|
|
2
|
+
// the browser only learns a module's imports once that module has arrived. A
|
|
3
|
+
// kit deck is 150-300 modules deep in that chain, so on a phone every level
|
|
4
|
+
// costs a network round trip: physics-2d measured 1.5 s on localhost and 6.5 s
|
|
5
|
+
// at 150 ms RTT. Listing the whole static graph up front as modulepreload links
|
|
6
|
+
// lets the browser fetch it in parallel instead, while each module is still
|
|
7
|
+
// served, cached and executed exactly as before.
|
|
8
|
+
//
|
|
9
|
+
// Off unless CASTLE_MODULE_PRELOAD=1, so the sandbox image decides.
|
|
10
|
+
const DEFAULT_BUDGET_MS = 1500;
|
|
11
|
+
// Listed links, not walked modules: the walk itself is bounded by the budget.
|
|
12
|
+
const MAX_MODULES = 1000;
|
|
13
|
+
// Only plain script modules. Anything Vite serves under an `?import`, `?raw`,
|
|
14
|
+
// `?url` or `?worker` style query, and every non-script file (scenes, json,
|
|
15
|
+
// styles, assets), is left for the page to ask for itself: preloading a URL
|
|
16
|
+
// the page never imports would fetch twice, and preloading a non-module one
|
|
17
|
+
// would log a load error into the deck's console.
|
|
18
|
+
const SCRIPT_URL = /^\/(?!\/)[^?#]*\.(?:m?[jt]sx?)(?:\?v=[\w.-]+)?$/;
|
|
19
|
+
export function isPreloadableModuleUrl(url) {
|
|
20
|
+
return SCRIPT_URL.test(url);
|
|
21
|
+
}
|
|
22
|
+
// `<script type="module" src="/...">` entries of the page as Vite will serve it.
|
|
23
|
+
export function moduleEntrySrcs(html) {
|
|
24
|
+
const srcs = [];
|
|
25
|
+
for (const tag of html.match(/<script\b[^>]*>/gi) ?? []) {
|
|
26
|
+
if (!/\btype\s*=\s*["']?module\b/i.test(tag))
|
|
27
|
+
continue;
|
|
28
|
+
const src = /\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag);
|
|
29
|
+
const value = src?.[1] ?? src?.[2] ?? src?.[3];
|
|
30
|
+
if (value && value.startsWith('/') && !value.startsWith('//'))
|
|
31
|
+
srcs.push(value);
|
|
32
|
+
}
|
|
33
|
+
return srcs;
|
|
34
|
+
}
|
|
35
|
+
// Vite rewrites each import to a URL and records it, minus any HMR timestamp,
|
|
36
|
+
// in `staticImportedUrls`; that recorded string is what the browser asks for,
|
|
37
|
+
// so it is what gets preloaded. It can differ from the child node's own url: a
|
|
38
|
+
// shared chunk inside an optimized dep is imported with its importer's `?v=`.
|
|
39
|
+
function childNode(byUrl, importUrl) {
|
|
40
|
+
return byUrl.get(importUrl) ?? byUrl.get(importUrl.replace(/[?&]v=[\w.-]+$/, ''));
|
|
41
|
+
}
|
|
42
|
+
// Vite's `staticImportedUrls` holds every literal import specifier, dynamic ones
|
|
43
|
+
// included (`import('./x.js')`, a lazy `import.meta.glob`). Those load on demand,
|
|
44
|
+
// so only a URL the transformed code imports statically -- `import "u"`,
|
|
45
|
+
// `from "u"` -- is preloaded and walked.
|
|
46
|
+
function escapeRegExp(value) {
|
|
47
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
48
|
+
}
|
|
49
|
+
export function isStaticImportIn(code, url) {
|
|
50
|
+
const u = escapeRegExp(url);
|
|
51
|
+
return new RegExp(`(?:\\bfrom|\\bimport)\\s*(["'])${u}(?:[?&]t=\\d+)?\\1`).test(code);
|
|
52
|
+
}
|
|
53
|
+
// Walk the static import graph below `entries`, transforming modules the
|
|
54
|
+
// server has not seen yet (work the browser's requests would otherwise wait
|
|
55
|
+
// on one by one). A module is listed only once its own transform succeeded.
|
|
56
|
+
// The walk is raced against the budget, so a slow transform (a dependency
|
|
57
|
+
// re-optimization, a plugin that never settles) cannot hold the page: when
|
|
58
|
+
// the timer fires the list so far is returned and the rest load the ordinary way.
|
|
59
|
+
export async function collectModulePreloads(graph, entries, budgetMs = DEFAULT_BUDGET_MS) {
|
|
60
|
+
const out = [];
|
|
61
|
+
let stopped = false;
|
|
62
|
+
const walk = async () => {
|
|
63
|
+
const seen = new Set(entries);
|
|
64
|
+
let level = entries.map((url) => ({ url, href: null }));
|
|
65
|
+
while (level.length && !stopped) {
|
|
66
|
+
const next = [];
|
|
67
|
+
await Promise.all(level.map(async ({ url, href }) => {
|
|
68
|
+
let mod = await graph.getModuleByUrl(url);
|
|
69
|
+
if (!mod?.transformResult) {
|
|
70
|
+
try {
|
|
71
|
+
await graph.transformRequest(url);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return; // The page will hit the same error and report it itself.
|
|
75
|
+
}
|
|
76
|
+
mod = await graph.getModuleByUrl(url);
|
|
77
|
+
}
|
|
78
|
+
if (!mod?.transformResult || stopped)
|
|
79
|
+
return;
|
|
80
|
+
if (href && out.length < MAX_MODULES)
|
|
81
|
+
out.push(href);
|
|
82
|
+
const staticUrls = mod.staticImportedUrls;
|
|
83
|
+
const code = mod.transformResult.code;
|
|
84
|
+
if (!staticUrls || typeof code !== 'string')
|
|
85
|
+
return;
|
|
86
|
+
const byUrl = new Map([...mod.importedModules].map((child) => [child.url, child]));
|
|
87
|
+
for (const importUrl of staticUrls) {
|
|
88
|
+
if (!isStaticImportIn(code, importUrl))
|
|
89
|
+
continue;
|
|
90
|
+
const child = childNode(byUrl, importUrl);
|
|
91
|
+
if (!child || seen.has(child.url))
|
|
92
|
+
continue;
|
|
93
|
+
seen.add(child.url);
|
|
94
|
+
// A timestamped import carries `t=` at a position that depends on its
|
|
95
|
+
// other queries; skip rather than risk a second fetch. HMR is off, so
|
|
96
|
+
// this is rare (Vite still stamps pruned modules).
|
|
97
|
+
if (child.type !== 'js' || child.lastHMRTimestamp > 0)
|
|
98
|
+
continue;
|
|
99
|
+
if (!isPreloadableModuleUrl(importUrl))
|
|
100
|
+
continue;
|
|
101
|
+
next.push({ url: child.url, href: importUrl });
|
|
102
|
+
}
|
|
103
|
+
}));
|
|
104
|
+
level = next;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
let timer;
|
|
108
|
+
const timeout = new Promise((resolve) => {
|
|
109
|
+
timer = setTimeout(resolve, budgetMs);
|
|
110
|
+
});
|
|
111
|
+
await Promise.race([walk().catch(() => { }), timeout]);
|
|
112
|
+
stopped = true;
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
return out.slice();
|
|
115
|
+
}
|
|
116
|
+
export function modulePreloadPlugin(options) {
|
|
117
|
+
let server = null;
|
|
118
|
+
return {
|
|
119
|
+
name: 'castle-module-preload',
|
|
120
|
+
apply: 'serve',
|
|
121
|
+
configureServer(s) {
|
|
122
|
+
server = s;
|
|
123
|
+
},
|
|
124
|
+
transformIndexHtml: {
|
|
125
|
+
order: 'post',
|
|
126
|
+
async handler(html) {
|
|
127
|
+
const client = server?.environments?.client;
|
|
128
|
+
if (!options.enabled || !client)
|
|
129
|
+
return html;
|
|
130
|
+
const graph = {
|
|
131
|
+
transformRequest: (url) => client.transformRequest(url),
|
|
132
|
+
getModuleByUrl: (url) => client.moduleGraph.getModuleByUrl(url),
|
|
133
|
+
};
|
|
134
|
+
let urls;
|
|
135
|
+
try {
|
|
136
|
+
urls = await collectModulePreloads(graph, moduleEntrySrcs(html), options.budgetMs);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return html; // An optimisation only: never cost the page itself.
|
|
140
|
+
}
|
|
141
|
+
const tags = urls.map((href) => ({
|
|
142
|
+
tag: 'link',
|
|
143
|
+
attrs: { rel: 'modulepreload', href },
|
|
144
|
+
injectTo: 'head',
|
|
145
|
+
}));
|
|
146
|
+
return { html, tags };
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
package/dist/platformDoc.js
CHANGED
|
@@ -229,7 +229,7 @@ const COMMON_SECTIONS = `## Imports are read-only
|
|
|
229
229
|
|
|
230
230
|
- **Read \`${MULTIPLAYER_DOC_REL}\` before writing or changing a server entry or client netcode by hand.** It carries what this section leaves out: the outbound frame budget in practice, the snapshot pattern, self-healing events, and the reconnect and disconnect handling a hand-rolled session gets wrong. A deck built on the \`castle.multiplayer-2d\` / \`castle.multiplayer-3d\` (or \`castle.turn-based\`) kits already does all of that and normally writes nothing against the raw session API.
|
|
231
231
|
- **A deck becomes multiplayer by having a server entry** — no flag, no dashboard. The entry is \`castle.json\`'s \`server.main\` when set (a kit deck points it under \`imports/\`), otherwise the first of \`server/index.{js,ts,mjs}\` or \`code/server/index.{js,ts,mjs}\` that exists; removing the entry turns multiplayer off on the next \`save-deck\`. Castle runs that module as a real server process, one per session, shared by the players in it. Other options under \`server\`: \`maxPlayers\` (max 24), and \`tickRate\` (defaults to 20, max 30; 0 turns ticks off).
|
|
232
|
-
- **Voice chat comes with multiplayer; the deck doesn't build it.** Castle runs the call, the microphone prompt and the mute/push-to-talk controls outside the card, so a deck never touches audio or the mic. \`connection.voice\` lets a deck ask the player to join (\`requestJoin()\` shows Castle's prompt), follow \`state\` and \`onSpeaking(playerIds => ...)\` for talking indicators, and \`setMix({ [playerId]: { gain, pan } })\` for proximity chat (gain 0-1, pan -1 to 1). \`state\` is \`"unavailable"\` in solo, in local dev, and wherever voice isn't offered, so draw voice UI only when it isn't. Call \`requestJoin()\` from a player action (a "Join voice" button): if they decline, asking again within 10 seconds answers \`"declined"\` without a prompt. Turn voice off for a deck with \`"voice": { "enabled": false }\` in \`castle.json\`.
|
|
232
|
+
- **Voice chat comes with multiplayer; the deck doesn't build it.** Castle runs the call, the microphone prompt and the mute/push-to-talk controls outside the card, so a deck never touches audio or the mic. \`connection.voice\` lets a deck ask the player to join (\`requestJoin()\` shows Castle's prompt), follow \`state\` and \`onSpeaking(playerIds => ...)\` for talking indicators, and \`setMix({ [playerId]: { gain, pan } })\` for simple proximity chat (gain 0-1, pan -1 to 1). For 3D voice, \`setListener({ position: [x, y, z], forward: [x, y, z] })\` (usually the local player's camera, y up) and \`setPositions({ [playerId]: [x, y, z] })\` place each voice in the world, with distance falloff and direction (best on headphones); \`setSpatialOptions({ refDistance, maxDistance, rolloff, distanceModel })\` tunes the falloff. Update them as things move; they are sent ten times a second. \`state\` is \`"unavailable"\` in solo, in local dev, and wherever voice isn't offered, so draw voice UI only when it isn't. Call \`requestJoin()\` from a player action (a "Join voice" button): if they decline, asking again within 10 seconds answers \`"declined"\` without a prompt. Turn voice off for a deck with \`"voice": { "enabled": false }\` in \`castle.json\`.
|
|
233
233
|
- **The server module default-exports lifecycle callbacks**, each taking the session first:
|
|
234
234
|
|
|
235
235
|
\`\`\`js
|
package/dist/serve.js
CHANGED
|
@@ -11,6 +11,7 @@ import { createAgentServer } from './agent.js';
|
|
|
11
11
|
import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugin, } from './vitePlugins.js';
|
|
12
12
|
import { viteClientStubPlugin } from './viteClientStub.js';
|
|
13
13
|
import { paramsRegisterPlugin } from './paramsRegisterPlugin.js';
|
|
14
|
+
import { modulePreloadPlugin } from './modulePreload.js';
|
|
14
15
|
import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
|
|
15
16
|
import { installFilesChangedWatcher } from './filesChanged.js';
|
|
16
17
|
import { applyDeckWrite, createTuneLedger } from './paramsTunes.js';
|
|
@@ -1226,6 +1227,7 @@ export async function serve(dir, options = {}) {
|
|
|
1226
1227
|
paramsRegisterPlugin(projectDir, tuneLedger),
|
|
1227
1228
|
sceneFilesPlugin(),
|
|
1228
1229
|
scriptErrorsPlugin(scriptErrors),
|
|
1230
|
+
modulePreloadPlugin({ enabled: process.env.CASTLE_MODULE_PRELOAD === '1' }),
|
|
1229
1231
|
],
|
|
1230
1232
|
server: {
|
|
1231
1233
|
port,
|
package/kits/base/castle.json
CHANGED
|
@@ -15,7 +15,7 @@ export { Lifecycle } from "./lifecycle";
|
|
|
15
15
|
export type { CastleLifecycleApi } from "./lifecycle";
|
|
16
16
|
export { Multiplayer } from "./multiplayer";
|
|
17
17
|
export type { CastleMultiplayerApi, MultiplayerConnection, MultiplayerConnectionState, MultiplayerJoinOptions, MultiplayerRoster, MultiplayerStateMetadata, } from "./multiplayer";
|
|
18
|
-
export type { MultiplayerVoice, VoiceJoinStatus, VoiceMixEntry, VoiceState, } from "./multiplayerVoice";
|
|
18
|
+
export type { MultiplayerVoice, VoiceJoinStatus, VoiceListener, VoiceMixEntry, VoiceSpatialOptions, VoiceState, VoiceVector, } from "./multiplayerVoice";
|
|
19
19
|
export type { MultiplayerSoloReason } from "./commands";
|
|
20
20
|
export { MAX_CLIENT_FRAME_BYTES, MAX_PLAYERS_CAP } from "./multiplayerProtocol";
|
|
21
21
|
export type { ClientByeFrame, ClientHelloFrame, ClientMessageFrame, ClientPingFrame, ClientPongFrame, ClientReplacedFrame, ClientRosterFrame, ClientToPlatformFrame, ClientToPlatformMessageFrame, MultiplayerPlayer, PlayerIdentity, PlatformToClientFrame, SessionPlayer, SessionType, } from "./multiplayerProtocol";
|
|
@@ -108,9 +108,33 @@ export type VoiceJoinStatus = "joined" | "declined" | "unavailable";
|
|
|
108
108
|
export interface VoiceMixEntry {
|
|
109
109
|
/** 0 (silent) to 1 (full). */
|
|
110
110
|
gain?: number;
|
|
111
|
-
/** -1 (left) to 1 (right). */
|
|
111
|
+
/** -1 (left) to 1 (right). Ignored for a player with a 3D position. */
|
|
112
112
|
pan?: number;
|
|
113
113
|
}
|
|
114
|
+
export type VoiceVector = [number, number, number];
|
|
115
|
+
export interface VoiceListener {
|
|
116
|
+
position: VoiceVector;
|
|
117
|
+
/** The direction the listener faces; need not be normalized. */
|
|
118
|
+
forward: VoiceVector;
|
|
119
|
+
/** Defaults to [0, 1, 0]. */
|
|
120
|
+
up?: VoiceVector;
|
|
121
|
+
}
|
|
122
|
+
export interface VoiceSpatialOptions {
|
|
123
|
+
/** How volume falls off with distance; default "inverse". */
|
|
124
|
+
distanceModel?: "linear" | "inverse" | "exponential";
|
|
125
|
+
/** Distance at which a voice is at full volume; default 1. */
|
|
126
|
+
refDistance?: number;
|
|
127
|
+
/** Beyond this, a voice gets no quieter ("linear": silent); default 100. */
|
|
128
|
+
maxDistance?: number;
|
|
129
|
+
/** How fast volume falls off; default 1. */
|
|
130
|
+
rolloff?: number;
|
|
131
|
+
}
|
|
132
|
+
export interface VoiceSpatialUpdate {
|
|
133
|
+
listener?: VoiceListener;
|
|
134
|
+
/** Keyed by userId. `null` returns a player to plain gain and pan. */
|
|
135
|
+
positions?: Record<string, VoiceVector | null>;
|
|
136
|
+
options?: VoiceSpatialOptions;
|
|
137
|
+
}
|
|
114
138
|
export interface CharacterSummary {
|
|
115
139
|
id: string;
|
|
116
140
|
version: string;
|
|
@@ -316,6 +340,9 @@ export interface CommandParams {
|
|
|
316
340
|
sessionId: string;
|
|
317
341
|
mix: Record<string, VoiceMixEntry>;
|
|
318
342
|
};
|
|
343
|
+
"voice.setSpatial": {
|
|
344
|
+
sessionId: string;
|
|
345
|
+
} & VoiceSpatialUpdate;
|
|
319
346
|
"characters.open": {
|
|
320
347
|
characterId: string;
|
|
321
348
|
};
|
|
@@ -450,6 +477,9 @@ export interface CommandResult {
|
|
|
450
477
|
"voice.setMix": {
|
|
451
478
|
ok: true;
|
|
452
479
|
};
|
|
480
|
+
"voice.setSpatial": {
|
|
481
|
+
ok: true;
|
|
482
|
+
};
|
|
453
483
|
"characters.open": CharacterAdmission;
|
|
454
484
|
"characters.send": CharacterOperation;
|
|
455
485
|
"characters.status": CharacterOperation;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { VoiceEvent, VoiceJoinStatus, VoiceMixEntry, VoiceState } from "./commands";
|
|
1
|
+
import type { VoiceEvent, VoiceJoinStatus, VoiceListener, VoiceMixEntry, VoiceSpatialOptions, VoiceState, VoiceVector } from "./commands";
|
|
2
2
|
import type { MultiplayerPlayer } from "./multiplayerProtocol";
|
|
3
3
|
export declare const VOICE_MIX_INTERVAL_MS = 100;
|
|
4
|
-
export type { VoiceJoinStatus, VoiceMixEntry, VoiceState };
|
|
4
|
+
export type { VoiceJoinStatus, VoiceListener, VoiceMixEntry, VoiceSpatialOptions, VoiceState, VoiceVector, };
|
|
5
5
|
export interface MultiplayerVoice {
|
|
6
6
|
/** "unavailable" when this host, deck, session or player can't have voice. */
|
|
7
7
|
readonly state: VoiceState;
|
|
@@ -18,6 +18,19 @@ export interface MultiplayerVoice {
|
|
|
18
18
|
* full volume, centered). Sent at most ten times a second; the latest values win.
|
|
19
19
|
*/
|
|
20
20
|
setMix(mix: Record<string, VoiceMixEntry>): void;
|
|
21
|
+
/**
|
|
22
|
+
* 3D voice: where the listener (usually the local player's camera) is and faces, in
|
|
23
|
+
* the deck's world units, y up. With positions set, voices come from their place in
|
|
24
|
+
* the world (distance, left/right, front/behind, above/below; best on headphones).
|
|
25
|
+
*/
|
|
26
|
+
setListener(listener: VoiceListener): void;
|
|
27
|
+
/**
|
|
28
|
+
* Where each player's voice comes from, keyed by playerId. `null` returns a player
|
|
29
|
+
* to plain gain and pan. Their `setMix` gain still applies; their pan does not.
|
|
30
|
+
*/
|
|
31
|
+
setPositions(positions: Record<string, VoiceVector | null>): void;
|
|
32
|
+
/** How voices fade with distance. Defaults: inverse, refDistance 1, maxDistance 100, rolloff 1. */
|
|
33
|
+
setSpatialOptions(options: VoiceSpatialOptions): void;
|
|
21
34
|
onState(callback: (state: VoiceState) => void): () => void;
|
|
22
35
|
/** The playerIds speaking right now; called whenever that set changes. */
|
|
23
36
|
onSpeaking(callback: (playerIds: string[]) => void): () => void;
|
|
@@ -39,6 +52,12 @@ export declare class MultiplayerVoiceImpl implements MultiplayerVoice {
|
|
|
39
52
|
private speaking;
|
|
40
53
|
private pendingMix;
|
|
41
54
|
private sentMix;
|
|
55
|
+
private pendingListener;
|
|
56
|
+
private pendingPositions;
|
|
57
|
+
private pendingOptions;
|
|
58
|
+
private sentListener;
|
|
59
|
+
private sentPositions;
|
|
60
|
+
private sentOptions;
|
|
42
61
|
private mixTimer;
|
|
43
62
|
private lastMixSentAt;
|
|
44
63
|
private disposed;
|
|
@@ -51,6 +70,9 @@ export declare class MultiplayerVoiceImpl implements MultiplayerVoice {
|
|
|
51
70
|
private askToJoin;
|
|
52
71
|
leave(): void;
|
|
53
72
|
setMix(mix: Record<string, VoiceMixEntry>): void;
|
|
73
|
+
setListener(listener: VoiceListener): void;
|
|
74
|
+
setPositions(positions: Record<string, VoiceVector | null>): void;
|
|
75
|
+
setSpatialOptions(options: VoiceSpatialOptions): void;
|
|
54
76
|
onState(callback: (state: VoiceState) => void): () => void;
|
|
55
77
|
onSpeaking(callback: (playerIds: string[]) => void): () => void;
|
|
56
78
|
receive(event: VoiceEvent): void;
|
|
@@ -62,6 +84,8 @@ export declare class MultiplayerVoiceImpl implements MultiplayerVoice {
|
|
|
62
84
|
private sendLeave;
|
|
63
85
|
private setState;
|
|
64
86
|
private emitSpeaking;
|
|
87
|
+
private hasPending;
|
|
65
88
|
private scheduleMix;
|
|
66
89
|
private flushMix;
|
|
90
|
+
private takeSpatial;
|
|
67
91
|
}
|
|
@@ -31,6 +31,13 @@ export class MultiplayerVoiceImpl {
|
|
|
31
31
|
speaking = [];
|
|
32
32
|
pendingMix = {};
|
|
33
33
|
sentMix = {};
|
|
34
|
+
// Spatial state: pending (not yet sent) and sent (re-sent when a call restarts).
|
|
35
|
+
pendingListener = null;
|
|
36
|
+
pendingPositions = {};
|
|
37
|
+
pendingOptions = null;
|
|
38
|
+
sentListener = null;
|
|
39
|
+
sentPositions = {};
|
|
40
|
+
sentOptions = null;
|
|
34
41
|
mixTimer = null;
|
|
35
42
|
lastMixSentAt = 0;
|
|
36
43
|
disposed = false;
|
|
@@ -163,6 +170,45 @@ export class MultiplayerVoiceImpl {
|
|
|
163
170
|
}
|
|
164
171
|
this.scheduleMix();
|
|
165
172
|
}
|
|
173
|
+
setListener(listener) {
|
|
174
|
+
if (this.disposed || !listener || typeof listener !== "object")
|
|
175
|
+
return;
|
|
176
|
+
const position = vector(listener.position);
|
|
177
|
+
const forward = vector(listener.forward);
|
|
178
|
+
const up = listener.up === undefined ? undefined : vector(listener.up);
|
|
179
|
+
// A zero direction faces nowhere (a player standing still, say): keep the last
|
|
180
|
+
// listener rather than send one the host would drop.
|
|
181
|
+
if (!position || !forward || up === null || isZero(forward) || (up && isZero(up)))
|
|
182
|
+
return;
|
|
183
|
+
this.pendingListener = up ? { position, forward, up } : { position, forward };
|
|
184
|
+
this.scheduleMix();
|
|
185
|
+
}
|
|
186
|
+
setPositions(positions) {
|
|
187
|
+
if (this.disposed || !positions || typeof positions !== "object")
|
|
188
|
+
return;
|
|
189
|
+
const players = this.access.players();
|
|
190
|
+
for (const [playerId, value] of Object.entries(positions)) {
|
|
191
|
+
const player = players.find((candidate) => candidate.playerId === playerId);
|
|
192
|
+
if (!player)
|
|
193
|
+
continue;
|
|
194
|
+
if (value === null) {
|
|
195
|
+
this.pendingPositions[player.userId] = null;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const position = vector(value);
|
|
199
|
+
if (position)
|
|
200
|
+
this.pendingPositions[player.userId] = position;
|
|
201
|
+
}
|
|
202
|
+
this.scheduleMix();
|
|
203
|
+
}
|
|
204
|
+
setSpatialOptions(options) {
|
|
205
|
+
if (this.disposed || !options || typeof options !== "object")
|
|
206
|
+
return;
|
|
207
|
+
// Cumulative: the host fills every missing field with its default, so each send
|
|
208
|
+
// carries everything the deck has set so far.
|
|
209
|
+
this.pendingOptions = { ...this.sentOptions, ...this.pendingOptions, ...options };
|
|
210
|
+
this.scheduleMix();
|
|
211
|
+
}
|
|
166
212
|
onState(callback) {
|
|
167
213
|
this.states.add(callback);
|
|
168
214
|
callListener(callback, this.currentState);
|
|
@@ -198,6 +244,14 @@ export class MultiplayerVoiceImpl {
|
|
|
198
244
|
if (!userIds.has(userId))
|
|
199
245
|
delete this.sentMix[userId];
|
|
200
246
|
}
|
|
247
|
+
for (const userId of Object.keys(this.pendingPositions)) {
|
|
248
|
+
if (!userIds.has(userId))
|
|
249
|
+
delete this.pendingPositions[userId];
|
|
250
|
+
}
|
|
251
|
+
for (const userId of Object.keys(this.sentPositions)) {
|
|
252
|
+
if (!userIds.has(userId))
|
|
253
|
+
delete this.sentPositions[userId];
|
|
254
|
+
}
|
|
201
255
|
this.emitSpeaking();
|
|
202
256
|
}
|
|
203
257
|
// The game connection ended: voice for its session goes with it.
|
|
@@ -230,6 +284,12 @@ export class MultiplayerVoiceImpl {
|
|
|
230
284
|
this.speakingUserIds = [];
|
|
231
285
|
this.pendingMix = {};
|
|
232
286
|
this.sentMix = {};
|
|
287
|
+
this.pendingListener = null;
|
|
288
|
+
this.pendingPositions = {};
|
|
289
|
+
this.pendingOptions = null;
|
|
290
|
+
this.sentListener = null;
|
|
291
|
+
this.sentPositions = {};
|
|
292
|
+
this.sentOptions = null;
|
|
233
293
|
this.emitSpeaking();
|
|
234
294
|
}
|
|
235
295
|
sendLeave(sessionId) {
|
|
@@ -249,6 +309,12 @@ export class MultiplayerVoiceImpl {
|
|
|
249
309
|
for (const userId of Object.keys(this.sentMix)) {
|
|
250
310
|
this.pendingMix[userId] ??= {};
|
|
251
311
|
}
|
|
312
|
+
this.pendingListener ??= this.sentListener;
|
|
313
|
+
this.pendingOptions ??= this.sentOptions;
|
|
314
|
+
for (const [userId, position] of Object.entries(this.sentPositions)) {
|
|
315
|
+
if (!(userId in this.pendingPositions))
|
|
316
|
+
this.pendingPositions[userId] = position;
|
|
317
|
+
}
|
|
252
318
|
this.scheduleMix();
|
|
253
319
|
}
|
|
254
320
|
}
|
|
@@ -265,8 +331,14 @@ export class MultiplayerVoiceImpl {
|
|
|
265
331
|
for (const callback of this.speakers)
|
|
266
332
|
callListener(callback, playerIds.slice());
|
|
267
333
|
}
|
|
334
|
+
hasPending() {
|
|
335
|
+
return (Object.keys(this.pendingMix).length > 0 ||
|
|
336
|
+
Object.keys(this.pendingPositions).length > 0 ||
|
|
337
|
+
this.pendingListener !== null ||
|
|
338
|
+
this.pendingOptions !== null);
|
|
339
|
+
}
|
|
268
340
|
scheduleMix() {
|
|
269
|
-
if (this.mixTimer !== null ||
|
|
341
|
+
if (this.mixTimer !== null || !this.hasPending())
|
|
270
342
|
return;
|
|
271
343
|
const wait = Math.max(0, this.lastMixSentAt + VOICE_MIX_INTERVAL_MS - Date.now());
|
|
272
344
|
this.mixTimer = setTimeout(() => {
|
|
@@ -290,11 +362,54 @@ export class MultiplayerVoiceImpl {
|
|
|
290
362
|
mix[userId] = full;
|
|
291
363
|
}
|
|
292
364
|
this.pendingMix = {};
|
|
293
|
-
|
|
365
|
+
const spatial = this.takeSpatial(userIds);
|
|
366
|
+
if (Object.keys(mix).length === 0 && !spatial)
|
|
294
367
|
return;
|
|
295
368
|
this.lastMixSentAt = Date.now();
|
|
296
|
-
|
|
369
|
+
if (Object.keys(mix).length > 0) {
|
|
370
|
+
void hostRequest("voice.setMix", { sessionId: this.voiceSessionId, mix }).catch(() => { });
|
|
371
|
+
}
|
|
372
|
+
if (spatial) {
|
|
373
|
+
void hostRequest("voice.setSpatial", { sessionId: this.voiceSessionId, ...spatial }).catch(() => { });
|
|
374
|
+
}
|
|
297
375
|
}
|
|
376
|
+
takeSpatial(userIds) {
|
|
377
|
+
const update = {};
|
|
378
|
+
if (this.pendingListener) {
|
|
379
|
+
update.listener = this.pendingListener;
|
|
380
|
+
this.sentListener = this.pendingListener;
|
|
381
|
+
}
|
|
382
|
+
if (this.pendingOptions) {
|
|
383
|
+
update.options = this.pendingOptions;
|
|
384
|
+
this.sentOptions = this.pendingOptions;
|
|
385
|
+
}
|
|
386
|
+
const positions = {};
|
|
387
|
+
for (const [userId, position] of Object.entries(this.pendingPositions)) {
|
|
388
|
+
if (!userIds.has(userId))
|
|
389
|
+
continue;
|
|
390
|
+
positions[userId] = position;
|
|
391
|
+
if (position)
|
|
392
|
+
this.sentPositions[userId] = position;
|
|
393
|
+
else
|
|
394
|
+
delete this.sentPositions[userId];
|
|
395
|
+
}
|
|
396
|
+
if (Object.keys(positions).length > 0)
|
|
397
|
+
update.positions = positions;
|
|
398
|
+
this.pendingListener = null;
|
|
399
|
+
this.pendingOptions = null;
|
|
400
|
+
this.pendingPositions = {};
|
|
401
|
+
return update.listener || update.options || update.positions ? update : null;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
function vector(value) {
|
|
405
|
+
return Array.isArray(value) &&
|
|
406
|
+
value.length === 3 &&
|
|
407
|
+
value.every((component) => typeof component === "number" && Number.isFinite(component))
|
|
408
|
+
? [value[0], value[1], value[2]]
|
|
409
|
+
: null;
|
|
410
|
+
}
|
|
411
|
+
function isZero(value) {
|
|
412
|
+
return value[0] === 0 && value[1] === 0 && value[2] === 0;
|
|
298
413
|
}
|
|
299
414
|
function clamp(value, min, max) {
|
|
300
415
|
return Math.min(max, Math.max(min, value));
|