@rpgjs/server 5.0.0-alpha.42 → 5.0.0-alpha.43

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.
@@ -0,0 +1,516 @@
1
+ import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import { PartyConnection } from "./connection";
4
+ import { createMapUpdateHeaders, resolveMapUpdateToken, updateMap } from "./map";
5
+ import { PartyRoom } from "./room";
6
+ import type {
7
+ CreateRpgServerTransportOptions,
8
+ HandleNodeRequestOptions,
9
+ RpgTransportRequestLike,
10
+ RpgTransportServer,
11
+ RpgTransportServerConstructor,
12
+ RpgWebSocketConnection,
13
+ RpgWebSocketRequestLike,
14
+ RpgWebSocketServer,
15
+ SendMapUpdateOptions,
16
+ } from "./types";
17
+
18
+ type PartiesFetchInit = {
19
+ body?: any;
20
+ headers?: HeadersInit | IncomingHttpHeaders | Map<string, string | undefined>;
21
+ method?: string;
22
+ };
23
+
24
+ function normalizePathPrefix(path: string, fallback: string): string {
25
+ const trimmed = (path || fallback).trim();
26
+ if (!trimmed) {
27
+ return fallback;
28
+ }
29
+ const prefixed = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
30
+ return prefixed !== "/" ? prefixed.replace(/\/+$/, "") : prefixed;
31
+ }
32
+
33
+ function hasPathPrefix(pathname: string, prefix: string): boolean {
34
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
35
+ }
36
+
37
+ function prependMountedPath(pathname: string, mountedPath?: string): string {
38
+ if (!mountedPath) {
39
+ return pathname;
40
+ }
41
+ const normalizedMountedPath = normalizePathPrefix(mountedPath, "/");
42
+ if (hasPathPrefix(pathname, normalizedMountedPath)) {
43
+ return pathname;
44
+ }
45
+ if (pathname === "/") {
46
+ return normalizedMountedPath;
47
+ }
48
+ return `${normalizedMountedPath}${pathname.startsWith("/") ? pathname : `/${pathname}`}`.replace(/\/{2,}/g, "/");
49
+ }
50
+
51
+ function parseHttpRoute(pathname: string, partiesPath: string): { roomId: string; requestPath: string } | null {
52
+ if (!hasPathPrefix(pathname, partiesPath)) {
53
+ return null;
54
+ }
55
+
56
+ const remainder = pathname.slice(partiesPath.length);
57
+ const segments = remainder.split("/").filter(Boolean);
58
+ if (segments.length < 2) {
59
+ return null;
60
+ }
61
+
62
+ return {
63
+ roomId: segments[0],
64
+ requestPath: `/${segments.slice(1).join("/")}`,
65
+ };
66
+ }
67
+
68
+ function parseSocketRoute(pathname: string, partiesPath: string): { roomId: string } | null {
69
+ if (!hasPathPrefix(pathname, partiesPath)) {
70
+ return null;
71
+ }
72
+
73
+ const remainder = pathname.slice(partiesPath.length);
74
+ const segments = remainder.split("/").filter(Boolean);
75
+ if (segments.length < 1) {
76
+ return null;
77
+ }
78
+
79
+ return { roomId: segments[0] };
80
+ }
81
+
82
+ function toHeaders(
83
+ input?: Headers | HeadersInit | IncomingHttpHeaders | Map<string, string | undefined>,
84
+ ): Headers {
85
+ if (!input) {
86
+ return new Headers();
87
+ }
88
+ if (input instanceof Headers) {
89
+ return new Headers(input);
90
+ }
91
+ if (Array.isArray(input)) {
92
+ return new Headers(input);
93
+ }
94
+ if (input instanceof Map) {
95
+ const headers = new Headers();
96
+ for (const [key, value] of input) {
97
+ if (typeof value !== "undefined") {
98
+ headers.set(key, value);
99
+ }
100
+ }
101
+ return headers;
102
+ }
103
+
104
+ const headers = new Headers();
105
+ Object.entries(input).forEach(([key, value]) => {
106
+ if (Array.isArray(value)) {
107
+ if (typeof value[0] !== "undefined") {
108
+ headers.set(key, value[0]);
109
+ }
110
+ return;
111
+ }
112
+ if (typeof value !== "undefined") {
113
+ headers.set(key, String(value));
114
+ }
115
+ });
116
+ return headers;
117
+ }
118
+
119
+ function createRequestLike(url: string, method: string, headers: Headers, bodyText: string): RpgTransportRequestLike {
120
+ return {
121
+ url,
122
+ method,
123
+ headers,
124
+ json: async () => {
125
+ if (!bodyText) {
126
+ return undefined;
127
+ }
128
+ return JSON.parse(bodyText);
129
+ },
130
+ text: async () => bodyText,
131
+ };
132
+ }
133
+
134
+ async function normalizeEngineResponse(result: any): Promise<Response> {
135
+ if (result instanceof Response) {
136
+ return result;
137
+ }
138
+ if (typeof result === "string") {
139
+ return new Response(result, {
140
+ status: 200,
141
+ headers: {
142
+ "Content-Type": "text/plain",
143
+ },
144
+ });
145
+ }
146
+
147
+ return new Response(JSON.stringify(result ?? {}), {
148
+ status: 200,
149
+ headers: {
150
+ "Content-Type": "application/json",
151
+ },
152
+ });
153
+ }
154
+
155
+ async function sendNodeResponse(res: ServerResponse, response: Response): Promise<void> {
156
+ res.statusCode = response.status;
157
+ response.headers.forEach((value, key) => {
158
+ res.setHeader(key, value);
159
+ });
160
+ res.end(await response.text());
161
+ }
162
+
163
+ async function readNodeBody(req: IncomingMessage): Promise<string> {
164
+ return await new Promise<string>((resolve, reject) => {
165
+ const chunks: Buffer[] = [];
166
+ req.on("data", (chunk: Buffer | string) => {
167
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
168
+ });
169
+ req.on("end", () => {
170
+ resolve(Buffer.concat(chunks).toString("utf8"));
171
+ });
172
+ req.on("error", reject);
173
+ });
174
+ }
175
+
176
+ function resolveUrlFromSocketRequest(request: RpgWebSocketRequestLike): { headers: Headers; method?: string; rawUrl: string; url: URL } {
177
+ const headers = toHeaders(request.headers);
178
+ const host = headers.get("host") || "localhost";
179
+ const rawUrl = request.url || "/";
180
+ const url = new URL(rawUrl, `http://${host}`);
181
+ return {
182
+ headers,
183
+ method: request.method,
184
+ rawUrl,
185
+ url,
186
+ };
187
+ }
188
+
189
+ function createConnectionContext(url: URL, headers: Headers, method?: string): any {
190
+ const normalizedHeaders = new Map<string, string>();
191
+ headers.forEach((value, key) => {
192
+ normalizedHeaders.set(key.toLowerCase(), value);
193
+ });
194
+
195
+ return {
196
+ request: {
197
+ headers: {
198
+ has: (name: string) => normalizedHeaders.has(name.toLowerCase()),
199
+ get: (name: string) => normalizedHeaders.get(name.toLowerCase()),
200
+ entries: () => normalizedHeaders.entries(),
201
+ keys: () => normalizedHeaders.keys(),
202
+ values: () => normalizedHeaders.values(),
203
+ },
204
+ method,
205
+ url: url.toString(),
206
+ },
207
+ url,
208
+ };
209
+ }
210
+
211
+ export class RpgServerTransport {
212
+ private partiesPath: string;
213
+ private readonly initializeMaps: boolean;
214
+ private readonly mapUpdateToken: string;
215
+ private readonly tiledBasePaths?: string[];
216
+ private readonly rooms = new Map<string, PartyRoom>();
217
+ private readonly servers = new Map<string, RpgTransportServer>();
218
+ private lastKnownHost = "";
219
+
220
+ constructor(
221
+ private readonly serverModule: RpgTransportServerConstructor,
222
+ options: CreateRpgServerTransportOptions = {},
223
+ ) {
224
+ this.initializeMaps = options.initializeMaps ?? true;
225
+ this.mapUpdateToken = resolveMapUpdateToken(options.mapUpdateToken);
226
+ this.partiesPath = normalizePathPrefix(options.partiesPath || "/parties/main", "/parties/main");
227
+ this.tiledBasePaths = options.tiledBasePaths;
228
+ }
229
+
230
+ getRoom(roomId: string): PartyRoom | undefined {
231
+ return this.rooms.get(roomId);
232
+ }
233
+
234
+ getServer(roomId: string): RpgTransportServer | undefined {
235
+ return this.servers.get(roomId);
236
+ }
237
+
238
+ private async ensureRoomAndServer(roomId: string, host?: string): Promise<{ room: PartyRoom; rpgServer: RpgTransportServer }> {
239
+ if (host) {
240
+ this.lastKnownHost = host;
241
+ }
242
+
243
+ let room = this.rooms.get(roomId);
244
+ if (!room) {
245
+ room = new PartyRoom(roomId);
246
+ this.rooms.set(roomId, room);
247
+ console.log(`Created new room: ${roomId}`);
248
+ }
249
+
250
+ let rpgServer = this.servers.get(roomId);
251
+ if (!rpgServer) {
252
+ rpgServer = new this.serverModule(room);
253
+ this.servers.set(roomId, rpgServer);
254
+ console.log(`Created new server instance for room: ${roomId}`);
255
+
256
+ if (typeof rpgServer.onStart === "function") {
257
+ try {
258
+ await rpgServer.onStart();
259
+ console.log(`Server started for room: ${roomId}`);
260
+ } catch (error) {
261
+ console.error(`Error starting server for room ${roomId}:`, error);
262
+ }
263
+ }
264
+
265
+ if (this.initializeMaps) {
266
+ await updateMap(roomId, rpgServer, {
267
+ host: host || this.lastKnownHost,
268
+ mapUpdateToken: this.mapUpdateToken,
269
+ tiledBasePaths: this.tiledBasePaths,
270
+ });
271
+ }
272
+ }
273
+
274
+ room.context.parties = this.buildPartiesContext();
275
+ return { room, rpgServer };
276
+ }
277
+
278
+ private buildPartiesContext() {
279
+ return {
280
+ main: {
281
+ get: async (targetRoomId: string) => {
282
+ return {
283
+ fetch: async (path: string, init?: PartiesFetchInit) => {
284
+ const method = (init?.method || "GET").toUpperCase();
285
+ const headers = toHeaders(init?.headers);
286
+ const requestPath = path.startsWith("/") ? path : `/${path}`;
287
+ let bodyText = "";
288
+
289
+ if (typeof init?.body === "string") {
290
+ bodyText = init.body;
291
+ } else if (typeof init?.body !== "undefined") {
292
+ bodyText = JSON.stringify(init.body);
293
+ }
294
+
295
+ return this.dispatchRoomRequest(
296
+ targetRoomId,
297
+ createRequestLike(
298
+ `http://localhost${this.partiesPath}/${targetRoomId}${requestPath}`,
299
+ method,
300
+ headers,
301
+ bodyText,
302
+ ),
303
+ this.lastKnownHost,
304
+ );
305
+ },
306
+ };
307
+ },
308
+ },
309
+ } as any;
310
+ }
311
+
312
+ private async dispatchRoomRequest(roomId: string, requestLike: RpgTransportRequestLike, host?: string): Promise<Response> {
313
+ const { room, rpgServer } = await this.ensureRoomAndServer(roomId, host);
314
+ room.context.parties = this.buildPartiesContext();
315
+ const result = await rpgServer.onRequest?.(requestLike);
316
+ return normalizeEngineResponse(result);
317
+ }
318
+
319
+ async fetch(request: Request | string | URL, init?: RequestInit): Promise<Response> {
320
+ const webRequest = request instanceof Request ? request : new Request(String(request), init);
321
+ const url = new URL(webRequest.url);
322
+ const route = parseHttpRoute(url.pathname, this.partiesPath);
323
+ if (!route) {
324
+ return new Response(JSON.stringify({ error: "Not found" }), {
325
+ status: 404,
326
+ headers: {
327
+ "Content-Type": "application/json",
328
+ },
329
+ });
330
+ }
331
+
332
+ const bodyText = await webRequest.text();
333
+ return this.dispatchRoomRequest(
334
+ route.roomId,
335
+ createRequestLike(webRequest.url, webRequest.method.toUpperCase(), toHeaders(webRequest.headers), bodyText),
336
+ url.host,
337
+ );
338
+ }
339
+
340
+ async updateMap(mapId: string, payload: any, options: SendMapUpdateOptions = {}): Promise<Response> {
341
+ const roomId = mapId.startsWith("map-") ? mapId : `map-${mapId}`;
342
+ const headers = createMapUpdateHeaders(this.mapUpdateToken, options.headers);
343
+ if (!headers.has("content-type")) {
344
+ headers.set("content-type", "application/json");
345
+ }
346
+
347
+ return this.dispatchRoomRequest(
348
+ roomId,
349
+ createRequestLike(
350
+ `http://localhost${this.partiesPath}/${roomId}/map/update`,
351
+ "POST",
352
+ headers,
353
+ JSON.stringify(payload),
354
+ ),
355
+ options.host ?? this.lastKnownHost,
356
+ );
357
+ }
358
+
359
+ async handleNodeRequest(
360
+ req: IncomingMessage,
361
+ res: ServerResponse,
362
+ next?: () => void,
363
+ options: HandleNodeRequestOptions = {},
364
+ ): Promise<boolean> {
365
+ try {
366
+ const headers = toHeaders(req.headers);
367
+ const host = headers.get("host") || "localhost";
368
+ const url = new URL(req.url || "/", `http://${host}`);
369
+ const normalizedPathname = prependMountedPath(url.pathname, options.mountedPath);
370
+ const normalizedUrl = new URL(url.toString());
371
+ normalizedUrl.pathname = normalizedPathname;
372
+
373
+ const route = parseHttpRoute(normalizedUrl.pathname, this.partiesPath);
374
+ if (!route) {
375
+ next?.();
376
+ return false;
377
+ }
378
+
379
+ const bodyText = await readNodeBody(req);
380
+ const response = await this.dispatchRoomRequest(
381
+ route.roomId,
382
+ createRequestLike(normalizedUrl.toString(), (req.method || "GET").toUpperCase(), headers, bodyText),
383
+ host,
384
+ );
385
+
386
+ await sendNodeResponse(res, response);
387
+ return true;
388
+ } catch (error) {
389
+ console.error("Error handling RPG-JS request:", error);
390
+ res.statusCode = 500;
391
+ res.setHeader("Content-Type", "application/json");
392
+ res.end(JSON.stringify({ error: "Internal server error" }));
393
+ return true;
394
+ }
395
+ }
396
+
397
+ async acceptWebSocket(ws: RpgWebSocketConnection, request: RpgWebSocketRequestLike): Promise<boolean> {
398
+ const normalizedRequest = resolveUrlFromSocketRequest(request);
399
+ const route = parseSocketRoute(normalizedRequest.url.pathname, this.partiesPath);
400
+ if (!route) {
401
+ return false;
402
+ }
403
+
404
+ try {
405
+ console.log(`WebSocket upgrade request: ${normalizedRequest.url.pathname}`);
406
+
407
+ const queryParams = Object.fromEntries(normalizedRequest.url.searchParams.entries());
408
+ console.log(`Room: ${route.roomId}, Query params:`, queryParams);
409
+
410
+ const { room, rpgServer } = await this.ensureRoomAndServer(route.roomId, normalizedRequest.url.host);
411
+ room.context.parties = this.buildPartiesContext();
412
+
413
+ const connection = new PartyConnection(ws, queryParams._pk, normalizedRequest.rawUrl);
414
+ room.addConnection(connection);
415
+
416
+ console.log(`WebSocket connection established: ${connection.id} in room: ${route.roomId}`);
417
+
418
+ let isClosed = false;
419
+ const cleanup = async (logMessage?: string, error?: Error) => {
420
+ if (isClosed) {
421
+ return;
422
+ }
423
+ isClosed = true;
424
+ if (logMessage) {
425
+ console.log(logMessage);
426
+ }
427
+ if (error) {
428
+ console.error("WebSocket error:", error);
429
+ }
430
+ room.removeConnection(connection.id);
431
+ await rpgServer.onClose?.(connection as any);
432
+ };
433
+
434
+ ws.on("message", async (data: Buffer | string) => {
435
+ try {
436
+ const rawMessage = typeof data === "string" ? data : data.toString();
437
+
438
+ if (PartyConnection.packetLossEnabled && PartyConnection.packetLossRate > 0) {
439
+ if (!PartyConnection.packetLossFilter || rawMessage.includes(PartyConnection.packetLossFilter)) {
440
+ const random = Math.random();
441
+ if (random < PartyConnection.packetLossRate) {
442
+ console.log(
443
+ `\x1b[31m[PACKET LOSS]\x1b[0m Connection ${connection.id}: Server dropped an incoming packet (${(PartyConnection.packetLossRate * 100).toFixed(1)}% loss rate)`,
444
+ );
445
+ console.log(`\x1b[33m[PACKET DATA]\x1b[0m ${rawMessage.slice(0, 100)}${rawMessage.length > 100 ? "..." : ""}`);
446
+ return;
447
+ }
448
+ }
449
+ }
450
+
451
+ connection.bufferIncoming(rawMessage, async (batch: string[]) => {
452
+ for (const message of batch) {
453
+ await rpgServer.onMessage?.(message, connection as any);
454
+ }
455
+ });
456
+ } catch (error) {
457
+ console.error("Error processing WebSocket message:", error);
458
+ }
459
+ });
460
+
461
+ ws.on("close", () => {
462
+ void cleanup(`WebSocket connection closed: ${connection.id} from room: ${route.roomId}`);
463
+ });
464
+
465
+ ws.on("error", (error: Error) => {
466
+ void cleanup(undefined, error);
467
+ });
468
+
469
+ if (typeof rpgServer.onConnect === "function") {
470
+ await rpgServer.onConnect(
471
+ connection as any,
472
+ createConnectionContext(normalizedRequest.url, normalizedRequest.headers, normalizedRequest.method) as any,
473
+ );
474
+ }
475
+
476
+ await connection.send({
477
+ type: "connected",
478
+ id: connection.id,
479
+ message: "Connected to RPG-JS server",
480
+ });
481
+
482
+ return true;
483
+ } catch (error) {
484
+ console.error("Error establishing WebSocket connection:", error);
485
+ ws.close();
486
+ return true;
487
+ }
488
+ }
489
+
490
+ async handleUpgrade(
491
+ wsServer: RpgWebSocketServer,
492
+ request: IncomingMessage,
493
+ socket: Duplex,
494
+ head: Buffer,
495
+ ): Promise<boolean> {
496
+ const headers = toHeaders(request.headers);
497
+ const host = headers.get("host") || "localhost";
498
+ const url = new URL(request.url || "/", `http://${host}`);
499
+ if (!parseSocketRoute(url.pathname, this.partiesPath)) {
500
+ return false;
501
+ }
502
+
503
+ wsServer.handleUpgrade(request, socket, head, (ws) => {
504
+ void this.acceptWebSocket(ws, request);
505
+ });
506
+
507
+ return true;
508
+ }
509
+ }
510
+
511
+ export function createRpgServerTransport(
512
+ serverModule: RpgTransportServerConstructor,
513
+ options?: CreateRpgServerTransportOptions,
514
+ ): RpgServerTransport {
515
+ return new RpgServerTransport(serverModule, options);
516
+ }
@@ -0,0 +1,61 @@
1
+ import type { IncomingHttpHeaders, IncomingMessage } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import type { RpgServerEngine } from "../RpgServerEngine";
4
+
5
+ export interface RpgWebSocketConnection {
6
+ readyState: number;
7
+ send(data: string): void;
8
+ close(): void;
9
+ on(event: string, callback: (...args: any[]) => void): void;
10
+ }
11
+
12
+ export interface RpgWebSocketServer {
13
+ handleUpgrade(
14
+ request: IncomingMessage,
15
+ socket: Duplex,
16
+ head: Buffer,
17
+ callback: (ws: RpgWebSocketConnection) => void,
18
+ ): void;
19
+ close(): void;
20
+ }
21
+
22
+ export interface RpgTransportRequestLike {
23
+ url: string;
24
+ method?: string;
25
+ headers?: Headers | HeadersInit | IncomingHttpHeaders | Map<string, string | undefined>;
26
+ text(): Promise<string>;
27
+ json(): Promise<any>;
28
+ }
29
+
30
+ export interface RpgWebSocketRequestLike {
31
+ url?: string;
32
+ method?: string;
33
+ headers?: Headers | HeadersInit | IncomingHttpHeaders | Map<string, string | undefined>;
34
+ }
35
+
36
+ export type RpgTransportServer = RpgServerEngine & {
37
+ onStart?(): void | Promise<void>;
38
+ onRequest?(req: RpgTransportRequestLike): any | Promise<any>;
39
+ onMessage?(message: string, connection: any): void | Promise<void>;
40
+ onClose?(connection: any): void | Promise<void>;
41
+ onConnect?(connection: any, context: any): void | Promise<void>;
42
+ maps?: any[];
43
+ };
44
+
45
+ export type RpgTransportServerConstructor = new (room: any) => RpgTransportServer;
46
+
47
+ export interface CreateRpgServerTransportOptions {
48
+ initializeMaps?: boolean;
49
+ mapUpdateToken?: string;
50
+ partiesPath?: string;
51
+ tiledBasePaths?: string[];
52
+ }
53
+
54
+ export interface HandleNodeRequestOptions {
55
+ mountedPath?: string;
56
+ }
57
+
58
+ export interface SendMapUpdateOptions {
59
+ headers?: HeadersInit | IncomingHttpHeaders | Map<string, string | undefined>;
60
+ host?: string;
61
+ }
package/src/rooms/map.ts CHANGED
@@ -30,6 +30,7 @@ import { EventMode } from "../decorators/event";
30
30
  import { BaseRoom } from "./BaseRoom";
31
31
  import { buildSaveSlotMeta, resolveSaveStorageStrategy } from "../services/save";
32
32
  import { Log } from "../logs/log";
33
+ import { isMapUpdateAuthorized, MAP_UPDATE_TOKEN_ENV, MAP_UPDATE_TOKEN_HEADER } from "../node/map";
33
34
 
34
35
  function isRpgLog(error: unknown): error is Log {
35
36
  return error instanceof Log
@@ -74,6 +75,16 @@ const MapUpdateSchema = z.object({
74
75
  width: z.number(),
75
76
  /** Height of the map in pixels (required) */
76
77
  height: z.number(),
78
+ /** Map events to spawn (optional) */
79
+ events: z.array(z.any()).optional(),
80
+ /** Optional static hitboxes (custom maps) */
81
+ hitboxes: z.array(z.any()).optional(),
82
+ /** Parsed tiled map payload (optional) */
83
+ parsedMap: z.any().optional(),
84
+ /** Raw map source payload (optional) */
85
+ data: z.any().optional(),
86
+ /** Optional map params payload */
87
+ params: z.any().optional(),
77
88
  });
78
89
 
79
90
  const SAFE_MAP_WIDTH = 1000;
@@ -1136,6 +1147,18 @@ export class RpgMap extends RpgCommonMap<RpgPlayer> implements RoomOnJoin {
1136
1147
  method: "POST"
1137
1148
  }, MapUpdateSchema as any)
1138
1149
  async updateMap(request: Request) {
1150
+ if (!isMapUpdateAuthorized(request.headers)) {
1151
+ return new Response(JSON.stringify({
1152
+ error: "Unauthorized map update",
1153
+ message: `Provide ${MAP_UPDATE_TOKEN_HEADER} or Authorization: Bearer <token> to call /map/update when ${MAP_UPDATE_TOKEN_ENV} is set.`,
1154
+ }), {
1155
+ status: 401,
1156
+ headers: {
1157
+ "Content-Type": "application/json",
1158
+ },
1159
+ });
1160
+ }
1161
+
1139
1162
  const map = await request.json()
1140
1163
  this.data.set(map)
1141
1164
  this.globalConfig = map.config