ludicord 4.1.2 → 4.2.0
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/README.md +2 -0
- package/dist/activity/index.d.ts +4 -0
- package/dist/activity/index.js +2 -0
- package/dist/activity/performance.d.ts +17 -0
- package/dist/activity/performance.js +56 -0
- package/dist/compiler/client-entry.js +1 -1
- package/dist/config/defaults.js +14 -0
- package/dist/config/index.d.ts +1 -1
- package/dist/config/types.d.ts +19 -0
- package/dist/docs/README.md +1 -1
- package/dist/docs/activity-rooms.md +1 -1
- package/dist/docs/ai-agents.md +1 -1
- package/dist/docs/api-reference.md +3 -1
- package/dist/docs/api-routes.md +1 -1
- package/dist/docs/build.md +1 -1
- package/dist/docs/cli.md +1 -1
- package/dist/docs/configuration.md +3 -1
- package/dist/docs/deployment.md +1 -1
- package/dist/docs/development.md +21 -1
- package/dist/docs/discord-developer-portal.md +1 -1
- package/dist/docs/discord-sdk.md +1 -1
- package/dist/docs/distribution.md +1 -1
- package/dist/docs/embeds.md +1 -1
- package/dist/docs/environment-variables.md +1 -1
- package/dist/docs/getting-started.md +1 -1
- package/dist/docs/installation.md +2 -2
- package/dist/docs/login.md +1 -1
- package/dist/docs/migration.md +11 -5
- package/dist/docs/mobile-layout.md +1 -1
- package/dist/docs/navigation.md +1 -1
- package/dist/docs/pages.md +1 -1
- package/dist/docs/participants.md +1 -1
- package/dist/docs/prefix-router.md +1 -1
- package/dist/docs/project-structure.md +1 -1
- package/dist/docs/recipes.md +1 -1
- package/dist/docs/security.md +1 -1
- package/dist/docs/start.md +1 -1
- package/dist/docs/state-and-effects.md +1 -1
- package/dist/docs/troubleshooting.md +1 -1
- package/dist/docs/voice-events.md +1 -1
- package/dist/docs/websockets.md +39 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/runtime/client/performance-data.d.ts +12 -0
- package/dist/runtime/client/performance-data.js +22 -0
- package/dist/runtime/client/startup.js +12 -0
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/index.js +2 -0
- package/dist/skills/ludicord/SKILL.md +2 -2
- package/dist/skills/ludicord/manifest.yaml +1 -1
- package/dist/version.js +1 -1
- package/dist/ws/client.d.ts +47 -0
- package/dist/ws/client.js +193 -12
- package/dist/ws/health.d.ts +1 -0
- package/dist/ws/health.js +2 -0
- package/dist/ws/index.d.ts +2 -2
- package/dist/ws/index.js +1 -1
- package/dist/ws/server.js +14 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ export { LUDICORD_VERSION } from "./version.js";
|
|
|
2
2
|
export { defineMetadata } from "./metadata/index.js";
|
|
3
3
|
export { Link, } from "./navigation/link.js";
|
|
4
4
|
export { PrefixLink, prefixHref } from "./navigation/prefix-link.js";
|
|
5
|
-
export { clearActivityQueryCache, useActivityLifecycle, useActivityPresence, useActivityQuery, useActivityStorage, useGameLoop, useSharedActivityState, } from "./activity/index.js";
|
|
5
|
+
export { clearActivityQueryCache, useActivityLifecycle, useActivityPresence, useActivityQuery, useActivityStorage, useGameLoop, useSharedActivityState, useActivityPerformance, getActivityStartupTimings, subscribeActivityStartupTimings, } from "./activity/index.js";
|
|
6
6
|
export { LudicordActivity, LudicordErrorBoundary, LudicordLoadingBoundary, EmbedOutlet, useActivityPrefix, usePageParams, } from "./runtime/client/embed-router.js";
|
|
7
7
|
export { LudicordMinimizeProvider, useLudicordMinimize, } from "./runtime/client/minimize.js";
|
|
8
8
|
export { Minimize } from "./runtime/client/minimize-card.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface LudicordStartupTiming {
|
|
2
|
+
readonly stage: string;
|
|
3
|
+
readonly startMs: number;
|
|
4
|
+
readonly durationMs: number;
|
|
5
|
+
readonly status: "complete" | "error" | "skipped";
|
|
6
|
+
}
|
|
7
|
+
export declare const EMPTY_STARTUP_TIMINGS: readonly LudicordStartupTiming[];
|
|
8
|
+
/** A stable immutable snapshot of this page scope's startup measurements. */
|
|
9
|
+
export declare const getActivityStartupTimings: () => readonly LudicordStartupTiming[];
|
|
10
|
+
export declare const subscribeActivityStartupTimings: (listener: () => void) => (() => void);
|
|
11
|
+
export declare function resetActivityStartupTimings(): void;
|
|
12
|
+
export declare function recordActivityStartupTiming(stage: string, startMs: number, durationMs: number, status?: LudicordStartupTiming["status"]): void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const EMPTY_STARTUP_TIMINGS = Object.freeze([]);
|
|
2
|
+
let timings = EMPTY_STARTUP_TIMINGS;
|
|
3
|
+
const listeners = new Set();
|
|
4
|
+
/** A stable immutable snapshot of this page scope's startup measurements. */
|
|
5
|
+
export const getActivityStartupTimings = () => timings;
|
|
6
|
+
export const subscribeActivityStartupTimings = (listener) => {
|
|
7
|
+
listeners.add(listener);
|
|
8
|
+
return () => { listeners.delete(listener); };
|
|
9
|
+
};
|
|
10
|
+
export function resetActivityStartupTimings() {
|
|
11
|
+
timings = EMPTY_STARTUP_TIMINGS;
|
|
12
|
+
for (const listener of listeners)
|
|
13
|
+
listener();
|
|
14
|
+
}
|
|
15
|
+
export function recordActivityStartupTiming(stage, startMs, durationMs, status = "complete") {
|
|
16
|
+
// Generated startup has nine fixed stage names; retain a bounded snapshot.
|
|
17
|
+
if (timings.length >= 16 || timings.some((entry) => entry.stage === stage))
|
|
18
|
+
return;
|
|
19
|
+
timings = Object.freeze([...timings, Object.freeze({ stage, startMs, durationMs, status })]);
|
|
20
|
+
for (const listener of listeners)
|
|
21
|
+
listener();
|
|
22
|
+
}
|
|
@@ -2,10 +2,13 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import { Suspense, createElement, lazy, useEffect } from "react";
|
|
3
3
|
import { STARTUP_SHELL_STYLE } from "../startup-shell.js";
|
|
4
4
|
import { reportClientError, useLudicordFiles } from "./files.js";
|
|
5
|
+
import { recordActivityStartupTiming, resetActivityStartupTimings } from "./performance-data.js";
|
|
5
6
|
const PREFIX = "ludicord:startup:";
|
|
6
7
|
let startup;
|
|
7
8
|
// Opted in by the generated entry only; standalone runtime consumers are untouched.
|
|
8
9
|
export function beginActivityStartup() {
|
|
10
|
+
startup = undefined;
|
|
11
|
+
resetActivityStartupTimings();
|
|
9
12
|
const timing = globalThis.performance;
|
|
10
13
|
if (typeof timing?.mark !== "function" || typeof timing.measure !== "function")
|
|
11
14
|
return () => undefined;
|
|
@@ -22,6 +25,9 @@ export function beginActivityStartup() {
|
|
|
22
25
|
const current = { performance: timing, recorded: new Set(["runtime"]) };
|
|
23
26
|
startup = current;
|
|
24
27
|
timing.measure(`${PREFIX}runtime`, { start: 0, end: timing.now() });
|
|
28
|
+
const runtime = timing.getEntriesByName(`${PREFIX}runtime`, "measure").at(-1);
|
|
29
|
+
if (runtime !== undefined)
|
|
30
|
+
recordActivityStartupTiming("runtime", runtime.startTime, runtime.duration);
|
|
25
31
|
return () => { if (startup === current)
|
|
26
32
|
startup = undefined; };
|
|
27
33
|
}
|
|
@@ -40,6 +46,9 @@ export function startStartupStage(stage) {
|
|
|
40
46
|
const end = `${PREFIX}${stage}:end`;
|
|
41
47
|
current.performance.mark(end);
|
|
42
48
|
current.performance.measure(`${PREFIX}${stage}`, { start, end, detail: { status } });
|
|
49
|
+
const entry = current.performance.getEntriesByName(`${PREFIX}${stage}`, "measure").at(-1);
|
|
50
|
+
if (entry !== undefined)
|
|
51
|
+
recordActivityStartupTiming(stage, entry.startTime, entry.duration, status);
|
|
43
52
|
};
|
|
44
53
|
}
|
|
45
54
|
export function recordStartupMilestone(milestone) {
|
|
@@ -48,6 +57,9 @@ export function recordStartupMilestone(milestone) {
|
|
|
48
57
|
return;
|
|
49
58
|
current.recorded.add(milestone);
|
|
50
59
|
current.performance.measure(`${PREFIX}${milestone}`, { start: 0, end: current.performance.now() });
|
|
60
|
+
const entry = current.performance.getEntriesByName(`${PREFIX}${milestone}`, "measure").at(-1);
|
|
61
|
+
if (entry !== undefined)
|
|
62
|
+
recordActivityStartupTiming(milestone, entry.startTime, entry.duration);
|
|
51
63
|
}
|
|
52
64
|
export function StartupCommit({ children, milestone }) {
|
|
53
65
|
useEffect(() => recordStartupMilestone(milestone), [milestone]);
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
export { useActivityPerformance } from "../activity/performance.js";
|
|
2
|
+
export type { LudicordActivityPerformance, LudicordActivityPerformanceOptions } from "../activity/performance.js";
|
|
3
|
+
export { getActivityStartupTimings, subscribeActivityStartupTimings } from "./client/performance-data.js";
|
|
4
|
+
export type { LudicordStartupTiming } from "./client/performance-data.js";
|
|
1
5
|
export declare function useLudicordRuntime(): {
|
|
2
6
|
readonly environment: string;
|
|
3
7
|
readonly version: string;
|
package/dist/runtime/index.js
CHANGED
|
@@ -3,6 +3,8 @@ import { useDiscord } from "../discord/runtime.js";
|
|
|
3
3
|
import { useAuthStatus } from "../auth/client.js";
|
|
4
4
|
import { subscribeWebSocketRuntime, isWebSocketRuntimeReady } from "../ws/client.js";
|
|
5
5
|
import { LUDICORD_VERSION } from "../version.js";
|
|
6
|
+
export { useActivityPerformance } from "../activity/performance.js";
|
|
7
|
+
export { getActivityStartupTimings, subscribeActivityStartupTimings } from "./client/performance-data.js";
|
|
6
8
|
export function useLudicordRuntime() {
|
|
7
9
|
const discord = useDiscord();
|
|
8
10
|
const authStatus = useAuthStatus();
|
|
@@ -3,7 +3,7 @@ name: ludicord
|
|
|
3
3
|
description: "Build, modify, debug, review, or document Ludicord Discord Activities. Use for Activity roots, embeds, typed navigation, React state and effects, API or WebSocket routes, shared Activity state, Discord SDK data, participants, voice, authentication, security, configuration, compiler plugins, WebAssembly, development diagnostics, deployment, migration, and release compatibility."
|
|
4
4
|
metadata:
|
|
5
5
|
author: ludicord
|
|
6
|
-
version: "4.
|
|
6
|
+
version: "4.2.0"
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
# Ludicord
|
|
@@ -287,7 +287,7 @@ npx create-ludicord-app@latest my-activity --tailwind # scripted styling choice
|
|
|
287
287
|
npx create-ludicord-app@latest my-activity --no-tailwind
|
|
288
288
|
```
|
|
289
289
|
|
|
290
|
-
Generated 4.
|
|
290
|
+
Generated 4.2.0 projects intentionally include only `dev`, `build`, and
|
|
291
291
|
`start` scripts. Run advanced commands with the project's package runner.
|
|
292
292
|
|
|
293
293
|
## Routed Intelligence References
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const LUDICORD_VERSION = "4.
|
|
1
|
+
export const LUDICORD_VERSION = "4.2.0";
|
package/dist/ws/client.d.ts
CHANGED
|
@@ -15,11 +15,18 @@ export declare const isWebSocketRuntimeReady: () => boolean;
|
|
|
15
15
|
export interface LudicordWSConnectionOptions {
|
|
16
16
|
readonly enabled?: boolean;
|
|
17
17
|
readonly autoConnect?: boolean;
|
|
18
|
+
readonly connectionTimeout?: number;
|
|
19
|
+
readonly healthCheck?: {
|
|
20
|
+
readonly enabled?: boolean;
|
|
21
|
+
readonly interval?: number;
|
|
22
|
+
readonly timeout?: number;
|
|
23
|
+
};
|
|
18
24
|
readonly reconnect?: {
|
|
19
25
|
readonly enabled?: boolean;
|
|
20
26
|
readonly attempts?: number;
|
|
21
27
|
readonly initialDelay?: number;
|
|
22
28
|
readonly maxDelay?: number;
|
|
29
|
+
readonly jitter?: number;
|
|
23
30
|
};
|
|
24
31
|
readonly webSocketFactory?: (url: string) => BrowserSocket;
|
|
25
32
|
}
|
|
@@ -28,6 +35,9 @@ export interface LudicordWSAckOptions {
|
|
|
28
35
|
}
|
|
29
36
|
export interface LudicordWSConnection {
|
|
30
37
|
readonly status: LudicordWSStatus;
|
|
38
|
+
readonly diagnostics: LudicordWSDiagnostics;
|
|
39
|
+
getDiagnostics(): LudicordWSDiagnostics;
|
|
40
|
+
subscribeDiagnostics(listener: () => void): () => void;
|
|
31
41
|
emit(event: string, data?: unknown): void;
|
|
32
42
|
emitWithAck(event: string, data?: unknown, options?: LudicordWSAckOptions): Promise<void>;
|
|
33
43
|
on(event: string, listener: (data: unknown) => void): () => void;
|
|
@@ -35,6 +45,22 @@ export interface LudicordWSConnection {
|
|
|
35
45
|
close(): void;
|
|
36
46
|
reconnect(): void;
|
|
37
47
|
}
|
|
48
|
+
/** Local connection data only. Times are Unix milliseconds; latency is round-trip milliseconds. */
|
|
49
|
+
export interface LudicordWSDiagnostics {
|
|
50
|
+
readonly status: LudicordWSStatus;
|
|
51
|
+
readonly connectionAttempts: number;
|
|
52
|
+
readonly reconnectAttempts: number;
|
|
53
|
+
readonly reconnectCount: number;
|
|
54
|
+
readonly nextReconnectDelayMs: number | null;
|
|
55
|
+
readonly latencyMs: number | null;
|
|
56
|
+
readonly lastConnectedAt: number | null;
|
|
57
|
+
readonly lastErrorCode: string | null;
|
|
58
|
+
readonly lastClose: {
|
|
59
|
+
readonly code: number;
|
|
60
|
+
readonly reason: string;
|
|
61
|
+
readonly wasClean: boolean;
|
|
62
|
+
} | null;
|
|
63
|
+
}
|
|
38
64
|
export declare class LudicordWebSocketConnection {
|
|
39
65
|
private readonly route;
|
|
40
66
|
private statusValue;
|
|
@@ -48,14 +74,33 @@ export declare class LudicordWebSocketConnection {
|
|
|
48
74
|
private readonly factory;
|
|
49
75
|
private readonly enabled;
|
|
50
76
|
private resumeListenersInstalled;
|
|
77
|
+
private readonly connectionTimeout;
|
|
78
|
+
private readonly healthOptions;
|
|
79
|
+
private connectionTimer;
|
|
80
|
+
private healthTimer;
|
|
81
|
+
private probeTimer;
|
|
82
|
+
private probe;
|
|
83
|
+
private healthSupported;
|
|
84
|
+
private openedBefore;
|
|
85
|
+
private diagnosticsValue;
|
|
51
86
|
private acknowledgementCounter;
|
|
52
87
|
private readonly acknowledgements;
|
|
53
88
|
constructor(route: LudicordWSRoute, options?: LudicordWSConnectionOptions);
|
|
54
89
|
readonly subscribe: (listener: () => void) => (() => void);
|
|
55
90
|
readonly getStatus: () => LudicordWSStatus;
|
|
91
|
+
readonly getDiagnostics: () => LudicordWSDiagnostics;
|
|
92
|
+
readonly subscribeDiagnostics: (listener: () => void) => (() => void);
|
|
93
|
+
get diagnostics(): LudicordWSDiagnostics;
|
|
94
|
+
private updateDiagnostics;
|
|
56
95
|
private setStatus;
|
|
57
96
|
private connect;
|
|
58
97
|
private scheduleReconnect;
|
|
98
|
+
private clearConnectionTimer;
|
|
99
|
+
private clearProbe;
|
|
100
|
+
private clearHealthCheck;
|
|
101
|
+
private scheduleHealthCheck;
|
|
102
|
+
private checkHealth;
|
|
103
|
+
private failConnection;
|
|
59
104
|
private clearReconnectTimer;
|
|
60
105
|
private readonly resume;
|
|
61
106
|
private installResumeListeners;
|
|
@@ -70,4 +115,6 @@ export declare class LudicordWebSocketConnection {
|
|
|
70
115
|
start(): void;
|
|
71
116
|
}
|
|
72
117
|
export declare function useWS(route: LudicordWSRoute, options?: LudicordWSConnectionOptions): LudicordWSConnection;
|
|
118
|
+
/** Opt into reactive connection metrics separately from normal event consumers. */
|
|
119
|
+
export declare function useWSDiagnostics(connection: Pick<LudicordWSConnection, "getDiagnostics" | "subscribeDiagnostics">): LudicordWSDiagnostics;
|
|
73
120
|
export {};
|
package/dist/ws/client.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { useEffect, useMemo, useSyncExternalStore, } from "react";
|
|
2
2
|
import { useLudicordAuth } from "../auth/client.js";
|
|
3
3
|
import { getLudicordLaunchId, LUDICORD_LAUNCH_QUERY } from "../sessions/launch.js";
|
|
4
|
+
import { LUDICORD_HEALTH_QUERY } from "./health.js";
|
|
4
5
|
const openConnections = new Set();
|
|
5
6
|
const runtimeListeners = new Set();
|
|
6
7
|
export const subscribeWebSocketRuntime = (listener) => { runtimeListeners.add(listener); return () => { runtimeListeners.delete(listener); }; };
|
|
7
8
|
export const isWebSocketRuntimeReady = () => openConnections.size > 0;
|
|
8
|
-
function websocketUrl(route) {
|
|
9
|
+
function websocketUrl(route, healthCheck) {
|
|
9
10
|
if (/^wss?:\/\//.test(route)) {
|
|
10
11
|
const absolute = new URL(route);
|
|
11
12
|
absolute.searchParams.set(LUDICORD_LAUNCH_QUERY, getLudicordLaunchId());
|
|
13
|
+
absolute.searchParams.delete(LUDICORD_HEALTH_QUERY);
|
|
14
|
+
if (healthCheck)
|
|
15
|
+
absolute.searchParams.set(LUDICORD_HEALTH_QUERY, "1");
|
|
12
16
|
return absolute.href;
|
|
13
17
|
}
|
|
14
18
|
if (typeof window === "undefined") {
|
|
@@ -19,6 +23,8 @@ function websocketUrl(route) {
|
|
|
19
23
|
const path = normalized;
|
|
20
24
|
const absolute = new URL(`${protocol}//${window.location.host}${path}`);
|
|
21
25
|
absolute.searchParams.set(LUDICORD_LAUNCH_QUERY, getLudicordLaunchId());
|
|
26
|
+
if (healthCheck)
|
|
27
|
+
absolute.searchParams.set(LUDICORD_HEALTH_QUERY, "1");
|
|
22
28
|
return absolute.href;
|
|
23
29
|
}
|
|
24
30
|
function assertEventName(event) {
|
|
@@ -41,6 +47,18 @@ export class LudicordWebSocketConnection {
|
|
|
41
47
|
factory;
|
|
42
48
|
enabled;
|
|
43
49
|
resumeListenersInstalled = false;
|
|
50
|
+
connectionTimeout;
|
|
51
|
+
healthOptions;
|
|
52
|
+
connectionTimer = null;
|
|
53
|
+
healthTimer = null;
|
|
54
|
+
probeTimer = null;
|
|
55
|
+
probe = null;
|
|
56
|
+
healthSupported = false;
|
|
57
|
+
openedBefore = false;
|
|
58
|
+
diagnosticsValue = Object.freeze({
|
|
59
|
+
status: "idle", connectionAttempts: 0, reconnectAttempts: 0, reconnectCount: 0,
|
|
60
|
+
nextReconnectDelayMs: null, latencyMs: null, lastConnectedAt: null, lastErrorCode: null, lastClose: null,
|
|
61
|
+
});
|
|
44
62
|
acknowledgementCounter = 0;
|
|
45
63
|
acknowledgements = new Map();
|
|
46
64
|
constructor(route, options = {}) {
|
|
@@ -52,7 +70,28 @@ export class LudicordWebSocketConnection {
|
|
|
52
70
|
attempts: options.reconnect?.attempts ?? defaults?.reconnect?.attempts ?? 10,
|
|
53
71
|
initialDelay: options.reconnect?.initialDelay ?? defaults?.reconnect?.initialDelay ?? 500,
|
|
54
72
|
maxDelay: options.reconnect?.maxDelay ?? defaults?.reconnect?.maxDelay ?? 10_000,
|
|
73
|
+
jitter: options.reconnect?.jitter ?? defaults?.reconnect?.jitter ?? 0.2,
|
|
55
74
|
};
|
|
75
|
+
this.connectionTimeout = options.connectionTimeout ?? defaults?.connectionTimeout ?? 10_000;
|
|
76
|
+
this.healthOptions = {
|
|
77
|
+
enabled: options.healthCheck?.enabled ?? defaults?.healthCheck?.enabled ?? true,
|
|
78
|
+
interval: options.healthCheck?.interval ?? defaults?.healthCheck?.interval ?? 15_000,
|
|
79
|
+
timeout: options.healthCheck?.timeout ?? defaults?.healthCheck?.timeout ?? 10_000,
|
|
80
|
+
};
|
|
81
|
+
const integer = (value, min, max, field) => {
|
|
82
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
83
|
+
throw new TypeError(`LUDICORD0004: Invalid WebSocket ${field}.`);
|
|
84
|
+
};
|
|
85
|
+
integer(this.connectionTimeout, 100, 120_000, "connectionTimeout");
|
|
86
|
+
integer(this.healthOptions.interval, 1_000, 300_000, "healthCheck.interval");
|
|
87
|
+
integer(this.healthOptions.timeout, 100, 120_000, "healthCheck.timeout");
|
|
88
|
+
integer(this.reconnectOptions.attempts, 0, 10_000, "reconnect.attempts");
|
|
89
|
+
integer(this.reconnectOptions.initialDelay, 0, 2_147_483_647, "reconnect.initialDelay");
|
|
90
|
+
integer(this.reconnectOptions.maxDelay, this.reconnectOptions.initialDelay, 2_147_483_647, "reconnect.maxDelay");
|
|
91
|
+
if (!Number.isFinite(this.reconnectOptions.jitter) || this.reconnectOptions.jitter < 0 || this.reconnectOptions.jitter > 1 ||
|
|
92
|
+
typeof this.healthOptions.enabled !== "boolean" || typeof this.reconnectOptions.enabled !== "boolean" || typeof this.enabled !== "boolean") {
|
|
93
|
+
throw new TypeError("LUDICORD0004: Invalid WebSocket recovery options.");
|
|
94
|
+
}
|
|
56
95
|
this.factory =
|
|
57
96
|
options.webSocketFactory ??
|
|
58
97
|
((url) => new WebSocket(url));
|
|
@@ -64,6 +103,14 @@ export class LudicordWebSocketConnection {
|
|
|
64
103
|
return () => this.statusListeners.delete(listener);
|
|
65
104
|
};
|
|
66
105
|
getStatus = () => this.statusValue;
|
|
106
|
+
getDiagnostics = () => this.diagnosticsValue;
|
|
107
|
+
subscribeDiagnostics = this.subscribe;
|
|
108
|
+
get diagnostics() { return this.diagnosticsValue; }
|
|
109
|
+
updateDiagnostics(patch) {
|
|
110
|
+
this.diagnosticsValue = Object.freeze({ ...this.diagnosticsValue, ...patch });
|
|
111
|
+
for (const listener of this.statusListeners)
|
|
112
|
+
listener();
|
|
113
|
+
}
|
|
67
114
|
setStatus(status) {
|
|
68
115
|
const wasReady = openConnections.size > 0;
|
|
69
116
|
if (status === "open")
|
|
@@ -74,8 +121,7 @@ export class LudicordWebSocketConnection {
|
|
|
74
121
|
for (const listener of runtimeListeners)
|
|
75
122
|
listener();
|
|
76
123
|
this.statusValue = status;
|
|
77
|
-
|
|
78
|
-
listener();
|
|
124
|
+
this.updateDiagnostics({ status, reconnectAttempts: this.reconnectAttempts });
|
|
79
125
|
}
|
|
80
126
|
connect() {
|
|
81
127
|
if (!this.enabled) {
|
|
@@ -84,19 +130,31 @@ export class LudicordWebSocketConnection {
|
|
|
84
130
|
}
|
|
85
131
|
this.clearReconnectTimer();
|
|
86
132
|
this.manuallyClosed = false;
|
|
133
|
+
this.updateDiagnostics({ connectionAttempts: this.diagnosticsValue.connectionAttempts + 1, nextReconnectDelayMs: null });
|
|
87
134
|
this.setStatus(this.reconnectAttempts === 0 ? "connecting" : "reconnecting");
|
|
88
135
|
let socket;
|
|
89
136
|
try {
|
|
90
|
-
socket = this.factory(websocketUrl(this.route));
|
|
137
|
+
socket = this.factory(websocketUrl(this.route, this.healthOptions.enabled));
|
|
91
138
|
}
|
|
92
139
|
catch {
|
|
93
|
-
this.
|
|
140
|
+
this.failConnection("LUDICORD9102");
|
|
94
141
|
return;
|
|
95
142
|
}
|
|
96
143
|
this.socket = socket;
|
|
144
|
+
this.connectionTimer = setTimeout(() => {
|
|
145
|
+
if (this.socket === socket)
|
|
146
|
+
this.failConnection("LUDICORD9105");
|
|
147
|
+
}, this.connectionTimeout);
|
|
148
|
+
this.connectionTimer.unref?.();
|
|
97
149
|
socket.onopen = () => {
|
|
98
150
|
if (this.socket !== socket)
|
|
99
151
|
return;
|
|
152
|
+
this.clearConnectionTimer();
|
|
153
|
+
this.updateDiagnostics({
|
|
154
|
+
lastConnectedAt: Date.now(), lastErrorCode: null,
|
|
155
|
+
reconnectCount: this.diagnosticsValue.reconnectCount + (this.openedBefore ? 1 : 0),
|
|
156
|
+
});
|
|
157
|
+
this.openedBefore = true;
|
|
100
158
|
this.reconnectAttempts = 0;
|
|
101
159
|
this.setStatus("open");
|
|
102
160
|
};
|
|
@@ -113,6 +171,24 @@ export class LudicordWebSocketConnection {
|
|
|
113
171
|
const internal = typeof envelope.data === "object" && envelope.data !== null
|
|
114
172
|
? envelope.data
|
|
115
173
|
: null;
|
|
174
|
+
if (envelope.event === "$ludicord:ready") {
|
|
175
|
+
if (internal?.healthCheck === true && !this.healthSupported) {
|
|
176
|
+
this.healthSupported = true;
|
|
177
|
+
this.checkHealth();
|
|
178
|
+
}
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (envelope.event === "$ludicord:pong") {
|
|
182
|
+
if (this.probe !== null && internal?.id === this.probe.id) {
|
|
183
|
+
this.updateDiagnostics({ latencyMs: Math.max(0, performance.now() - this.probe.startedAt) });
|
|
184
|
+
this.clearProbe();
|
|
185
|
+
this.scheduleHealthCheck();
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (envelope.event === "$ludicord:error" && typeof internal?.code === "string" && /^LUDICORD[A-Z0-9_]{1,96}$/.test(internal.code)) {
|
|
190
|
+
this.updateDiagnostics({ lastErrorCode: internal.code });
|
|
191
|
+
}
|
|
116
192
|
if (envelope.event === "$ludicord:ack" && typeof internal?.id === "string") {
|
|
117
193
|
const acknowledgement = this.acknowledgements.get(internal.id);
|
|
118
194
|
if (acknowledgement !== undefined) {
|
|
@@ -141,12 +217,15 @@ export class LudicordWebSocketConnection {
|
|
|
141
217
|
socket.onerror = () => {
|
|
142
218
|
if (this.socket !== socket)
|
|
143
219
|
return;
|
|
144
|
-
this.
|
|
220
|
+
this.failConnection("LUDICORD9107");
|
|
145
221
|
};
|
|
146
|
-
socket.onclose = () => {
|
|
222
|
+
socket.onclose = (event) => {
|
|
147
223
|
if (this.socket !== socket)
|
|
148
224
|
return;
|
|
225
|
+
this.clearConnectionTimer();
|
|
226
|
+
this.clearHealthCheck();
|
|
149
227
|
this.socket = null;
|
|
228
|
+
this.updateDiagnostics({ latencyMs: null, lastClose: Object.freeze({ code: event.code ?? 1006, reason: event.reason ?? "", wasClean: event.wasClean === true }) });
|
|
150
229
|
this.rejectAcknowledgements("LUDICORD9104: WebSocket closed before the server acknowledged the event.");
|
|
151
230
|
if (this.manuallyClosed || !this.reconnectOptions.enabled) {
|
|
152
231
|
this.setStatus("closed");
|
|
@@ -160,10 +239,82 @@ export class LudicordWebSocketConnection {
|
|
|
160
239
|
this.setStatus("closed");
|
|
161
240
|
return;
|
|
162
241
|
}
|
|
163
|
-
const
|
|
242
|
+
const baseDelay = Math.min(this.reconnectOptions.initialDelay * 2 ** this.reconnectAttempts, this.reconnectOptions.maxDelay);
|
|
243
|
+
const delay = Math.min(this.reconnectOptions.maxDelay, Math.max(0, Math.round(baseDelay * (1 + this.reconnectOptions.jitter * (Math.random() * 2 - 1)))));
|
|
164
244
|
this.reconnectAttempts += 1;
|
|
245
|
+
this.updateDiagnostics({ nextReconnectDelayMs: delay });
|
|
165
246
|
this.setStatus("reconnecting");
|
|
166
247
|
this.reconnectTimer = setTimeout(() => this.connect(), delay);
|
|
248
|
+
this.reconnectTimer.unref?.();
|
|
249
|
+
}
|
|
250
|
+
clearConnectionTimer() {
|
|
251
|
+
if (this.connectionTimer !== null)
|
|
252
|
+
clearTimeout(this.connectionTimer);
|
|
253
|
+
this.connectionTimer = null;
|
|
254
|
+
}
|
|
255
|
+
clearProbe() {
|
|
256
|
+
if (this.probeTimer !== null)
|
|
257
|
+
clearTimeout(this.probeTimer);
|
|
258
|
+
this.probeTimer = null;
|
|
259
|
+
this.probe = null;
|
|
260
|
+
}
|
|
261
|
+
clearHealthCheck() {
|
|
262
|
+
if (this.healthTimer !== null)
|
|
263
|
+
clearTimeout(this.healthTimer);
|
|
264
|
+
this.healthTimer = null;
|
|
265
|
+
this.clearProbe();
|
|
266
|
+
this.healthSupported = false;
|
|
267
|
+
}
|
|
268
|
+
scheduleHealthCheck() {
|
|
269
|
+
if (this.healthTimer !== null)
|
|
270
|
+
clearTimeout(this.healthTimer);
|
|
271
|
+
this.healthTimer = setTimeout(() => { this.healthTimer = null; this.checkHealth(); }, this.healthOptions.interval);
|
|
272
|
+
this.healthTimer.unref?.();
|
|
273
|
+
}
|
|
274
|
+
checkHealth() {
|
|
275
|
+
if (!this.healthOptions.enabled || !this.healthSupported || this.socket?.readyState !== 1 || this.probe !== null)
|
|
276
|
+
return;
|
|
277
|
+
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
|
|
278
|
+
this.scheduleHealthCheck();
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const id = `health_${++this.acknowledgementCounter}`;
|
|
282
|
+
this.probe = { id, startedAt: performance.now() };
|
|
283
|
+
this.probeTimer = setTimeout(() => {
|
|
284
|
+
this.probeTimer = null;
|
|
285
|
+
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
|
|
286
|
+
this.clearProbe();
|
|
287
|
+
this.scheduleHealthCheck();
|
|
288
|
+
}
|
|
289
|
+
else
|
|
290
|
+
this.failConnection("LUDICORD9106");
|
|
291
|
+
}, this.healthOptions.timeout);
|
|
292
|
+
this.probeTimer.unref?.();
|
|
293
|
+
try {
|
|
294
|
+
this.socket.send(JSON.stringify({ v: 1, type: "ping", id }));
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
this.failConnection("LUDICORD9107");
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
failConnection(code) {
|
|
301
|
+
this.clearConnectionTimer();
|
|
302
|
+
this.clearHealthCheck();
|
|
303
|
+
const socket = this.socket;
|
|
304
|
+
this.socket = null;
|
|
305
|
+
if (socket !== null) {
|
|
306
|
+
socket.onopen = socket.onmessage = socket.onclose = socket.onerror = null;
|
|
307
|
+
try {
|
|
308
|
+
socket.close(4000, code);
|
|
309
|
+
}
|
|
310
|
+
catch { /* Already closed or failed handshake. */ }
|
|
311
|
+
}
|
|
312
|
+
this.rejectAcknowledgements(`${code}: WebSocket connection was interrupted.`);
|
|
313
|
+
this.updateDiagnostics({ lastErrorCode: code, latencyMs: null });
|
|
314
|
+
if (this.manuallyClosed || !this.reconnectOptions.enabled)
|
|
315
|
+
this.setStatus("error");
|
|
316
|
+
else
|
|
317
|
+
this.scheduleReconnect();
|
|
167
318
|
}
|
|
168
319
|
clearReconnectTimer() {
|
|
169
320
|
if (this.reconnectTimer !== null) {
|
|
@@ -174,14 +325,31 @@ export class LudicordWebSocketConnection {
|
|
|
174
325
|
resume = () => {
|
|
175
326
|
if (!this.enabled || this.manuallyClosed)
|
|
176
327
|
return;
|
|
328
|
+
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
|
|
329
|
+
// Cancel the outstanding deadline before the browser freezes timers.
|
|
330
|
+
this.clearProbe();
|
|
331
|
+
if (this.healthSupported && this.healthOptions.enabled)
|
|
332
|
+
this.scheduleHealthCheck();
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (!this.reconnectOptions.enabled)
|
|
336
|
+
return;
|
|
177
337
|
if (typeof navigator !== "undefined" && navigator.onLine === false)
|
|
178
338
|
return;
|
|
179
|
-
if (
|
|
339
|
+
if (this.socket?.readyState === 1) {
|
|
340
|
+
// A socket can remain OPEN after a suspended browser loses its transport.
|
|
341
|
+
this.clearProbe();
|
|
342
|
+
this.checkHealth();
|
|
180
343
|
return;
|
|
181
|
-
|
|
344
|
+
}
|
|
345
|
+
if (this.socket?.readyState === 0)
|
|
182
346
|
return;
|
|
347
|
+
if (this.socket !== null)
|
|
348
|
+
this.failConnection("LUDICORD9107");
|
|
183
349
|
this.reconnectAttempts = 0;
|
|
184
350
|
this.clearReconnectTimer();
|
|
351
|
+
this.clearConnectionTimer();
|
|
352
|
+
this.clearHealthCheck();
|
|
185
353
|
this.connect();
|
|
186
354
|
};
|
|
187
355
|
installResumeListeners() {
|
|
@@ -259,15 +427,21 @@ export class LudicordWebSocketConnection {
|
|
|
259
427
|
close() {
|
|
260
428
|
this.manuallyClosed = true;
|
|
261
429
|
this.clearReconnectTimer();
|
|
430
|
+
this.clearConnectionTimer();
|
|
431
|
+
this.clearHealthCheck();
|
|
262
432
|
this.removeResumeListeners();
|
|
263
433
|
this.rejectAcknowledgements("LUDICORD9104: WebSocket closed before the server acknowledged the event.");
|
|
264
434
|
const socket = this.socket;
|
|
265
435
|
this.socket = null;
|
|
266
436
|
if (socket !== null) {
|
|
267
437
|
socket.onopen = socket.onmessage = socket.onclose = socket.onerror = null;
|
|
268
|
-
|
|
438
|
+
try {
|
|
439
|
+
socket.close(1000, "Client closed");
|
|
440
|
+
}
|
|
441
|
+
catch { /* Failed handshake already disposed. */ }
|
|
269
442
|
}
|
|
270
443
|
this.setStatus("closed");
|
|
444
|
+
this.updateDiagnostics({ nextReconnectDelayMs: null, latencyMs: null });
|
|
271
445
|
}
|
|
272
446
|
reconnect() {
|
|
273
447
|
this.close();
|
|
@@ -285,11 +459,14 @@ export function useWS(route, options = {}) {
|
|
|
285
459
|
const auth = useLudicordAuth();
|
|
286
460
|
const authRequired = globalThis.__LUDICORD_PUBLIC_CONFIG__?.authRequired === true;
|
|
287
461
|
const authReady = !authRequired || (auth.session !== null && auth.session.expiresAt > Date.now());
|
|
288
|
-
const connection = useMemo(() => new LudicordWebSocketConnection(route, { ...options, ...(authReady ? {} : { enabled: false }), autoConnect: false }), [route, authReady, options.enabled, options.webSocketFactory, options.reconnect?.enabled, options.reconnect?.attempts, options.reconnect?.initialDelay, options.reconnect?.maxDelay]);
|
|
462
|
+
const connection = useMemo(() => new LudicordWebSocketConnection(route, { ...options, ...(authReady ? {} : { enabled: false }), autoConnect: false }), [route, authReady, options.enabled, options.webSocketFactory, options.connectionTimeout, options.healthCheck?.enabled, options.healthCheck?.interval, options.healthCheck?.timeout, options.reconnect?.enabled, options.reconnect?.attempts, options.reconnect?.initialDelay, options.reconnect?.maxDelay, options.reconnect?.jitter]);
|
|
289
463
|
useEffect(() => { connection.start(); return () => connection.close(); }, [connection]);
|
|
290
464
|
const status = useSyncExternalStore(connection.subscribe, connection.getStatus, connection.getStatus);
|
|
291
465
|
return useMemo(() => ({
|
|
292
466
|
status,
|
|
467
|
+
get diagnostics() { return connection.getDiagnostics(); },
|
|
468
|
+
getDiagnostics: connection.getDiagnostics,
|
|
469
|
+
subscribeDiagnostics: connection.subscribeDiagnostics,
|
|
293
470
|
emit: (event, data) => connection.emit(event, data),
|
|
294
471
|
emitWithAck: (event, data, ackOptions) => connection.emitWithAck(event, data, ackOptions),
|
|
295
472
|
on: (event, listener) => connection.on(event, listener),
|
|
@@ -298,3 +475,7 @@ export function useWS(route, options = {}) {
|
|
|
298
475
|
reconnect: () => connection.reconnect(),
|
|
299
476
|
}), [connection, status]);
|
|
300
477
|
}
|
|
478
|
+
/** Opt into reactive connection metrics separately from normal event consumers. */
|
|
479
|
+
export function useWSDiagnostics(connection) {
|
|
480
|
+
return useSyncExternalStore(connection.subscribeDiagnostics, connection.getDiagnostics, connection.getDiagnostics);
|
|
481
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const LUDICORD_HEALTH_QUERY = "ludicord_health";
|
package/dist/ws/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { useWS } from "./client.js";
|
|
1
|
+
export { useWS, useWSDiagnostics } from "./client.js";
|
|
2
2
|
export { defineWS } from "./server.js";
|
|
3
3
|
export { createMemorySharedStateStore, defineSharedActivityState } from "./shared-state.js";
|
|
4
4
|
export type { LudicordWebSocketAdapter, LudicordWebSocketAdapterListener, LudicordWebSocketAdapterMessage, LudicordWebSocketAdapterTarget, } from "./adapter.js";
|
|
5
|
-
export type { LudicordWSConnection, LudicordWSConnectionOptions, LudicordWSAckOptions, LudicordWSStatus, } from "./client.js";
|
|
5
|
+
export type { LudicordWSConnection, LudicordWSConnectionOptions, LudicordWSAckOptions, LudicordWSStatus, LudicordWSDiagnostics, } from "./client.js";
|
|
6
6
|
export type { LudicordWebSocketClient, LudicordWebSocketRoute, LudicordWebSocketServerContext, LudicordWSEventEnvelope, WebSocketRuntimeOptions, } from "./server.js";
|
|
7
7
|
export type { LudicordSharedStateContext, LudicordSharedStateOptions, LudicordSharedStateStore, LudicordSharedStateValue, } from "./shared-state.js";
|
package/dist/ws/index.js
CHANGED
package/dist/ws/server.js
CHANGED
|
@@ -6,6 +6,7 @@ import { compareRouteSpecificity, matchRoutePattern } from "../router/match.js";
|
|
|
6
6
|
import { parseSessionCookie } from "../sessions/cookies.js";
|
|
7
7
|
import { LUDICORD_LAUNCH_QUERY, normalizeLudicordLaunchId } from "../sessions/launch.js";
|
|
8
8
|
import { isLudicordHostAllowed, isLudicordOriginAllowed, resolveLudicordAllowedHosts } from "../server/request-security.js";
|
|
9
|
+
import { LUDICORD_HEALTH_QUERY } from "./health.js";
|
|
9
10
|
const INTERNAL_EVENT_PREFIX = "$ludicord:";
|
|
10
11
|
function isReservedEvent(event) {
|
|
11
12
|
return (event.startsWith(INTERNAL_EVENT_PREFIX) ||
|
|
@@ -447,6 +448,9 @@ export function attachWebSocketRuntime(httpServer, options) {
|
|
|
447
448
|
const client = new RuntimeClient(webSocket, session, selected.match.params, rooms, currentRouteBroadcast, backpressureLimit, backpressureStrategy, maxQueuedMessages, selected.route.route);
|
|
448
449
|
clients.add(client);
|
|
449
450
|
currentRouteClients.add(client);
|
|
451
|
+
// Capability negotiation keeps new clients compatible with older servers.
|
|
452
|
+
if (requestUrl.searchParams.get(LUDICORD_HEALTH_QUERY) === "1")
|
|
453
|
+
client.sendInternal("ready", { healthCheck: true });
|
|
450
454
|
if (adapter?.join !== undefined)
|
|
451
455
|
runAdapter(() => adapter.join(routeTarget(selected.route.route), client.id));
|
|
452
456
|
webSocket.on("error", () => {
|
|
@@ -499,6 +503,16 @@ export function attachWebSocketRuntime(httpServer, options) {
|
|
|
499
503
|
client.sendInternal("error", { code: "LUDICORD_MALFORMED_JSON" });
|
|
500
504
|
return;
|
|
501
505
|
}
|
|
506
|
+
if (typeof envelope === "object" && envelope !== null &&
|
|
507
|
+
envelope.v === 1 && envelope.type === "ping") {
|
|
508
|
+
const id = envelope.id;
|
|
509
|
+
if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
|
|
510
|
+
client.sendInternal("error", { code: "LUDICORD_INVALID_EVENT_ID" });
|
|
511
|
+
}
|
|
512
|
+
else
|
|
513
|
+
client.sendInternal("pong", { id });
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
502
516
|
if (typeof envelope !== "object" ||
|
|
503
517
|
envelope === null ||
|
|
504
518
|
envelope.v !== 1 ||
|