@colyseus/core 0.15.52 → 0.15.54
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/build/MatchMaker.js +35 -8
- package/build/MatchMaker.js.map +2 -2
- package/build/MatchMaker.mjs +35 -8
- package/build/MatchMaker.mjs.map +2 -2
- package/build/Room.d.ts +21 -3
- package/build/Room.js +50 -7
- package/build/Room.js.map +2 -2
- package/build/Room.mjs +52 -9
- package/build/Room.mjs.map +2 -2
- package/build/Server.js.map +2 -2
- package/build/Server.mjs.map +2 -2
- package/build/Stats.d.ts +2 -0
- package/build/Stats.js +22 -2
- package/build/Stats.js.map +2 -2
- package/build/Stats.mjs +20 -2
- package/build/Stats.mjs.map +2 -2
- package/build/errors/RoomExceptions.d.ts +39 -0
- package/build/errors/RoomExceptions.js +100 -0
- package/build/errors/RoomExceptions.js.map +7 -0
- package/build/errors/RoomExceptions.mjs +70 -0
- package/build/errors/RoomExceptions.mjs.map +7 -0
- package/build/index.d.ts +1 -0
- package/build/index.js +19 -0
- package/build/index.js.map +2 -2
- package/build/index.mjs +20 -0
- package/build/index.mjs.map +2 -2
- package/build/matchmaker/Lobby.d.ts +2 -2
- package/build/matchmaker/Lobby.js.map +2 -2
- package/build/matchmaker/Lobby.mjs.map +2 -2
- package/build/matchmaker/driver/index.js +2 -2
- package/build/matchmaker/driver/index.js.map +2 -2
- package/build/matchmaker/driver/index.mjs +2 -2
- package/build/matchmaker/driver/index.mjs.map +2 -2
- package/build/rooms/LobbyRoom.d.ts +4 -4
- package/build/rooms/LobbyRoom.js.map +2 -2
- package/build/rooms/LobbyRoom.mjs.map +2 -2
- package/build/utils/Utils.d.ts +3 -0
- package/build/utils/Utils.js +25 -2
- package/build/utils/Utils.js.map +2 -2
- package/build/utils/Utils.mjs +23 -1
- package/build/utils/Utils.mjs.map +2 -2
- package/package.json +1 -1
package/build/Server.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/Server.ts"],
|
|
4
|
-
"sourcesContent": ["import http, { IncomingMessage, ServerResponse } from 'http';\nimport greeting from \"@colyseus/greeting-banner\";\n\nimport { debugAndPrintError, debugMatchMaking } from './Debug';\nimport * as matchMaker from './MatchMaker';\nimport { RegisteredHandler } from './matchmaker/RegisteredHandler';\nimport { Presence } from './presence/Presence';\n\nimport { Room } from './Room';\nimport { Type } from './utils/types';\nimport { getBearerToken, registerGracefulShutdown } from './utils/Utils';\n\nimport { registerNode, unregisterNode} from './discovery';\n\nimport { LocalPresence } from './presence/LocalPresence';\nimport { LocalDriver } from './matchmaker/driver';\n\nimport { Transport } from './Transport';\nimport { logger, setLogger } from './Logger';\nimport { setDevMode, isDevMode } from './utils/DevMode';\n\nexport type ServerOptions = {\n publicAddress?: string,\n presence?: Presence,\n driver?: matchMaker.MatchMakerDriver,\n transport?: Transport,\n gracefullyShutdown?: boolean,\n logger?: any;\n\n /**\n * Custom function to determine which process should handle room creation.\n * Default: assign new rooms the process with least amount of rooms created\n */\n selectProcessIdToCreateRoom?: matchMaker.SelectProcessIdCallback;\n\n /**\n * If enabled, rooms are going to be restored in the server-side upon restart,\n * clients are going to automatically re-connect when server reboots.\n *\n * Beware of \"schema mismatch\" issues. When updating Schema structures and\n * reloading existing data, you may see \"schema mismatch\" errors in the\n * client-side.\n *\n * (This operation is costly and should not be used in a production\n * environment)\n */\n devMode?: boolean,\n\n /**\n * Display greeting message on server start.\n * Default: true\n */\n greet?: boolean,\n\n /**\n * Options below are now part of WebSocketTransport (@colyseus/ws-transport)\n * TODO: remove me on 0.15.0\n */\n /** @deprecated */\n pingInterval?: number,\n\n /** @deprecated */\n pingMaxRetries?: number,\n\n /** @deprecated */\n verifyClient?: any,\n\n /** @deprecated */\n server?: http.Server,\n};\n\nexport class Server {\n public transport: Transport;\n\n protected presence: Presence;\n protected driver: matchMaker.MatchMakerDriver;\n\n protected port: number;\n protected greet: boolean;\n\n //@ts-expect-error\n private _originalRoomOnMessage: typeof Room.prototype._onMessage | null = null;\n\n constructor(options: ServerOptions = {}) {\n const { gracefullyShutdown = true, greet = true } = options;\n\n setDevMode(options.devMode === true);\n\n this.presence = options.presence || new LocalPresence();\n this.driver = options.driver || new LocalDriver();\n this.greet = greet;\n\n this.attach(options);\n\n matchMaker.setup(\n this.presence,\n this.driver,\n options.publicAddress,\n options.selectProcessIdToCreateRoom,\n );\n\n if (gracefullyShutdown) {\n registerGracefulShutdown((err) => this.gracefullyShutdown(true, err));\n }\n\n if (options.logger) {\n setLogger(options.logger);\n }\n }\n\n public attach(options: ServerOptions) {\n /**\n * Display deprecation warnings for moved Transport options.\n * TODO: Remove me on 0.15\n */\n if (\n options.pingInterval !== undefined ||\n options.pingMaxRetries !== undefined ||\n options.server !== undefined ||\n options.verifyClient !== undefined\n ) {\n logger.warn(\"DEPRECATION WARNING: 'pingInterval', 'pingMaxRetries', 'server', and 'verifyClient' Server options will be permanently moved to WebSocketTransport on v0.15\");\n logger.warn(`new Server({\n transport: new WebSocketTransport({\n pingInterval: ...,\n pingMaxRetries: ...,\n server: ...,\n verifyClient: ...\n })\n})`);\n logger.warn(\"\uD83D\uDC49 Documentation: https://docs.colyseus.io/server/transport/\")\n }\n\n const transport = options.transport || this.getDefaultTransport(options);\n delete options.transport;\n\n this.transport = transport;\n\n if (this.transport.server) {\n // @ts-ignore\n this.transport.server.once('listening', () => this.registerProcessForDiscovery());\n this.attachMatchMakingRoutes(this.transport.server as http.Server);\n }\n }\n\n /**\n * Bind the server into the port specified.\n *\n * @param port\n * @param hostname\n * @param backlog\n * @param listeningListener\n */\n public async listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function) {\n this.port = port;\n\n //\n // Make sure matchmaker is ready before accepting connections\n // (isDevMode: matchmaker may take extra milliseconds to restore the rooms)\n //\n await matchMaker.accept();\n\n /**\n * Greetings!\n */\n if (this.greet) {\n console.log(greeting);\n }\n\n return new Promise<void>((resolve, reject) => {\n // @ts-ignore\n this.transport.server?.on('error', (err) => reject(err));\n this.transport.listen(port, hostname, backlog, (err) => {\n if (listeningListener) {\n listeningListener(err);\n }\n\n if (err) {\n reject(err);\n\n } else {\n resolve();\n }\n });\n });\n }\n\n public async registerProcessForDiscovery() {\n // register node for proxy/service discovery\n await registerNode(this.presence, {\n port: this.port,\n processId: matchMaker.processId,\n });\n }\n\n /**\n * Define a new type of room for matchmaking.\n *\n * @param name public room identifier for match-making.\n * @param roomClass Room class definition\n * @param defaultOptions default options for `onCreate`\n */\n public define<T extends Type<Room>>(\n roomClass: T,\n defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n ): RegisteredHandler\n public define<T extends Type<Room>>(\n name: string,\n roomClass: T,\n defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n ): RegisteredHandler\n public define<T extends Type<Room>>(\n nameOrHandler: string | T,\n handlerOrOptions: T | Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n ): RegisteredHandler {\n const name = (typeof(nameOrHandler) === \"string\")\n ? nameOrHandler\n : nameOrHandler.name;\n\n const roomClass = (typeof(nameOrHandler) === \"string\")\n ? handlerOrOptions\n : nameOrHandler;\n\n const options = (typeof(nameOrHandler) === \"string\")\n ? defaultOptions\n : handlerOrOptions;\n\n return matchMaker.defineRoomType(name, roomClass, options);\n }\n\n /**\n * Remove a room definition from matchmaking.\n * This method does not destroy any room. It only dissallows matchmaking\n */\n public removeRoomType(name: string): void {\n matchMaker.removeRoomType(name);\n }\n\n public async gracefullyShutdown(exit: boolean = true, err?: Error) {\n if (matchMaker.isGracefullyShuttingDown) {\n return;\n }\n\n await unregisterNode(this.presence, {\n port: this.port,\n processId: matchMaker.processId,\n });\n\n try {\n await this.onBeforeShutdownCallback();\n await matchMaker.gracefullyShutdown();\n this.transport.shutdown();\n this.presence.shutdown();\n this.driver.shutdown();\n await this.onShutdownCallback();\n\n } catch (e) {\n debugAndPrintError(`error during shutdown: ${e}`);\n\n } finally {\n if (exit) {\n process.exit((err && !isDevMode) ? 1 : 0);\n }\n }\n }\n\n /**\n * Add simulated latency between client and server.\n * @param milliseconds round trip latency in milliseconds.\n */\n public simulateLatency(milliseconds: number) {\n if (milliseconds > 0) {\n logger.warn(`\uD83D\uDCF6\uFE0F\u2757 Colyseus latency simulation enabled \u2192 ${milliseconds}ms latency for round trip.`);\n } else {\n logger.warn(`\uD83D\uDCF6\uFE0F\u2757 Colyseus latency simulation disabled.`);\n }\n\n const halfwayMS = (milliseconds / 2);\n this.transport.simulateLatency(halfwayMS);\n\n if (this._originalRoomOnMessage == null) {\n /* tslint:disable:no-string-literal */\n this._originalRoomOnMessage = Room.prototype['_onMessage'];\n }\n\n const originalOnMessage = this._originalRoomOnMessage;\n\n /* tslint:disable:no-string-literal */\n Room.prototype['_onMessage'] = milliseconds <= Number.EPSILON ? originalOnMessage : function (client, buffer) {\n // uWebSockets.js: duplicate buffer because it is cleared at native layer before the timeout.\n const cachedBuffer = Buffer.from(buffer);\n setTimeout(() => originalOnMessage.call(this, client, cachedBuffer), halfwayMS);\n };\n }\n\n /**\n * Register a callback that is going to be executed before the server shuts down.\n * @param callback\n */\n public onShutdown(callback: () => void | Promise<any>) {\n this.onShutdownCallback = callback;\n }\n\n public onBeforeShutdown(callback: () => void | Promise<any>) {\n this.onBeforeShutdownCallback = callback;\n }\n\n protected getDefaultTransport(_: any): Transport {\n throw new Error(\"Please provide a 'transport' layer. Default transport not set.\");\n }\n\n protected onShutdownCallback: () => void | Promise<any> =\n () => Promise.resolve()\n\n protected onBeforeShutdownCallback: () => void | Promise<any> =\n () => Promise.resolve()\n\n protected attachMatchMakingRoutes(server: http.Server) {\n const listeners = server.listeners('request').slice(0);\n server.removeAllListeners('request');\n\n server.on('request', (req, res) => {\n if (req.url.indexOf(`/${matchMaker.controller.matchmakeRoute}`) !== -1) {\n debugMatchMaking('received matchmake request: %s', req.url);\n this.handleMatchMakeRequest(req, res);\n\n } else {\n for (let i = 0, l = listeners.length; i < l; i++) {\n listeners[i].call(server, req, res);\n }\n }\n });\n }\n\n protected async handleMatchMakeRequest(req: IncomingMessage, res: ServerResponse) {\n // do not accept matchmaking requests if already shutting down\n if (matchMaker.isGracefullyShuttingDown) {\n res.writeHead(503, {});\n res.end();\n return;\n }\n\n const headers = Object.assign(\n {},\n matchMaker.controller.DEFAULT_CORS_HEADERS,\n matchMaker.controller.getCorsHeaders.call(undefined, req)\n );\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204, headers);\n res.end();\n\n } else if (req.method === 'POST') {\n const matchedParams = req.url.match(matchMaker.controller.allowedRoomNameChars);\n const matchmakeIndex = matchedParams.indexOf(matchMaker.controller.matchmakeRoute);\n const method = matchedParams[matchmakeIndex + 1];\n const roomName = matchedParams[matchmakeIndex + 2] || '';\n\n const data = [];\n req.on('data', (chunk) => data.push(chunk));\n req.on('end', async () => {\n headers['Content-Type'] = 'application/json';\n res.writeHead(200, headers);\n\n try {\n const clientOptions = JSON.parse(Buffer.concat(data).toString());\n const response = await matchMaker.controller.invokeMethod(\n method,\n roomName,\n clientOptions,\n { token: getBearerToken(req.headers['authorization']), request: req },\n );\n res.write(JSON.stringify(response));\n\n } catch (e) {\n res.write(JSON.stringify({ code: e.code, error: e.message, }));\n }\n\n res.end();\n });\n\n } else if (req.method === 'GET') {\n const matchedParams = req.url.match(matchMaker.controller.allowedRoomNameChars);\n const roomName = matchedParams.length > 1 ? matchedParams[matchedParams.length - 1] : \"\";\n\n headers['Content-Type'] = 'application/json';\n res.writeHead(200, headers);\n res.write(JSON.stringify(await matchMaker.controller.getAvailableRooms(roomName)));\n res.end();\n }\n\n }\n\n\n}\n"],
|
|
5
|
-
"mappings": "AACA,OAAO,cAAc;AAErB,SAAS,oBAAoB,wBAAwB;AACrD,YAAY,gBAAgB;AAI5B,SAAS,YAAY;AAErB,SAAS,gBAAgB,gCAAgC;AAEzD,SAAS,cAAc,sBAAqB;AAE5C,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAG5B,SAAS,QAAQ,iBAAiB;AAClC,SAAS,YAAY,iBAAiB;AAoD/B,MAAM,OAAO;AAAA,EAYlB,YAAY,UAAyB,CAAC,GAAG;AAFzC,SAAQ,yBAAkE;
|
|
4
|
+
"sourcesContent": ["import http, { IncomingMessage, ServerResponse } from 'http';\nimport greeting from \"@colyseus/greeting-banner\";\n\nimport { debugAndPrintError, debugMatchMaking } from './Debug';\nimport * as matchMaker from './MatchMaker';\nimport { RegisteredHandler } from './matchmaker/RegisteredHandler';\nimport { Presence } from './presence/Presence';\n\nimport { Room } from './Room';\nimport { Type } from './utils/types';\nimport { getBearerToken, registerGracefulShutdown } from './utils/Utils';\n\nimport { registerNode, unregisterNode} from './discovery';\n\nimport { LocalPresence } from './presence/LocalPresence';\nimport { LocalDriver } from './matchmaker/driver';\n\nimport { Transport } from './Transport';\nimport { logger, setLogger } from './Logger';\nimport { setDevMode, isDevMode } from './utils/DevMode';\n\nexport type ServerOptions = {\n publicAddress?: string,\n presence?: Presence,\n driver?: matchMaker.MatchMakerDriver,\n transport?: Transport,\n gracefullyShutdown?: boolean,\n logger?: any;\n\n /**\n * Custom function to determine which process should handle room creation.\n * Default: assign new rooms the process with least amount of rooms created\n */\n selectProcessIdToCreateRoom?: matchMaker.SelectProcessIdCallback;\n\n /**\n * If enabled, rooms are going to be restored in the server-side upon restart,\n * clients are going to automatically re-connect when server reboots.\n *\n * Beware of \"schema mismatch\" issues. When updating Schema structures and\n * reloading existing data, you may see \"schema mismatch\" errors in the\n * client-side.\n *\n * (This operation is costly and should not be used in a production\n * environment)\n */\n devMode?: boolean,\n\n /**\n * Display greeting message on server start.\n * Default: true\n */\n greet?: boolean,\n\n /**\n * Options below are now part of WebSocketTransport (@colyseus/ws-transport)\n * TODO: remove me on 0.15.0\n */\n /** @deprecated */\n pingInterval?: number,\n\n /** @deprecated */\n pingMaxRetries?: number,\n\n /** @deprecated */\n verifyClient?: any,\n\n /** @deprecated */\n server?: http.Server,\n};\n\nexport class Server {\n public transport: Transport;\n\n protected presence: Presence;\n protected driver: matchMaker.MatchMakerDriver;\n\n protected port: number;\n protected greet: boolean;\n\n //@ts-expect-error\n private _originalRoomOnMessage: typeof Room.prototype._onMessage | null = null;\n\n constructor(options: ServerOptions = {}) {\n const { gracefullyShutdown = true, greet = true } = options;\n\n setDevMode(options.devMode === true);\n\n this.presence = options.presence || new LocalPresence();\n this.driver = options.driver || new LocalDriver();\n this.greet = greet;\n\n this.attach(options);\n\n matchMaker.setup(\n this.presence,\n this.driver,\n options.publicAddress,\n options.selectProcessIdToCreateRoom,\n );\n\n if (gracefullyShutdown) {\n registerGracefulShutdown((err) => this.gracefullyShutdown(true, err));\n }\n\n if (options.logger) {\n setLogger(options.logger);\n }\n }\n\n public attach(options: ServerOptions) {\n /**\n * Display deprecation warnings for moved Transport options.\n * TODO: Remove me on 0.15\n */\n if (\n options.pingInterval !== undefined ||\n options.pingMaxRetries !== undefined ||\n options.server !== undefined ||\n options.verifyClient !== undefined\n ) {\n logger.warn(\"DEPRECATION WARNING: 'pingInterval', 'pingMaxRetries', 'server', and 'verifyClient' Server options will be permanently moved to WebSocketTransport on v0.15\");\n logger.warn(`new Server({\n transport: new WebSocketTransport({\n pingInterval: ...,\n pingMaxRetries: ...,\n server: ...,\n verifyClient: ...\n })\n})`);\n logger.warn(\"\uD83D\uDC49 Documentation: https://docs.colyseus.io/server/transport/\")\n }\n\n const transport = options.transport || this.getDefaultTransport(options);\n delete options.transport;\n\n this.transport = transport;\n\n if (this.transport.server) {\n // @ts-ignore\n this.transport.server.once('listening', () => this.registerProcessForDiscovery());\n this.attachMatchMakingRoutes(this.transport.server as http.Server);\n }\n }\n\n /**\n * Bind the server into the port specified.\n *\n * @param port\n * @param hostname\n * @param backlog\n * @param listeningListener\n */\n public async listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function) {\n this.port = port;\n\n //\n // Make sure matchmaker is ready before accepting connections\n // (isDevMode: matchmaker may take extra milliseconds to restore the rooms)\n //\n await matchMaker.accept();\n\n /**\n * Greetings!\n */\n if (this.greet) {\n console.log(greeting);\n }\n\n return new Promise<void>((resolve, reject) => {\n // @ts-ignore\n this.transport.server?.on('error', (err) => reject(err));\n this.transport.listen(port, hostname, backlog, (err) => {\n if (listeningListener) {\n listeningListener(err);\n }\n\n if (err) {\n reject(err);\n\n } else {\n resolve();\n }\n });\n });\n }\n\n public async registerProcessForDiscovery() {\n // register node for proxy/service discovery\n await registerNode(this.presence, {\n port: this.port,\n processId: matchMaker.processId,\n });\n }\n\n /**\n * Define a new type of room for matchmaking.\n *\n * @param name public room identifier for match-making.\n * @param roomClass Room class definition\n * @param defaultOptions default options for `onCreate`\n */\n public define<T extends Type<Room>>(\n roomClass: T,\n defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n ): RegisteredHandler\n public define<T extends Type<Room>>(\n name: string,\n roomClass: T,\n defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n ): RegisteredHandler\n public define<T extends Type<Room>>(\n nameOrHandler: string | T,\n handlerOrOptions: T | Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0],\n ): RegisteredHandler {\n const name = (typeof(nameOrHandler) === \"string\")\n ? nameOrHandler\n : nameOrHandler.name;\n\n const roomClass = (typeof(nameOrHandler) === \"string\")\n ? handlerOrOptions\n : nameOrHandler;\n\n const options = (typeof(nameOrHandler) === \"string\")\n ? defaultOptions\n : handlerOrOptions;\n\n return matchMaker.defineRoomType(name, roomClass, options);\n }\n\n /**\n * Remove a room definition from matchmaking.\n * This method does not destroy any room. It only dissallows matchmaking\n */\n public removeRoomType(name: string): void {\n matchMaker.removeRoomType(name);\n }\n\n public async gracefullyShutdown(exit: boolean = true, err?: Error) {\n if (matchMaker.isGracefullyShuttingDown) {\n return;\n }\n\n await unregisterNode(this.presence, {\n port: this.port,\n processId: matchMaker.processId,\n });\n\n try {\n // custom \"before shutdown\" method\n await this.onBeforeShutdownCallback();\n\n await matchMaker.gracefullyShutdown();\n this.transport.shutdown();\n this.presence.shutdown();\n this.driver.shutdown();\n\n // custom \"after shutdown\" method\n await this.onShutdownCallback();\n\n } catch (e) {\n debugAndPrintError(`error during shutdown: ${e}`);\n\n } finally {\n if (exit) {\n process.exit((err && !isDevMode) ? 1 : 0);\n }\n }\n }\n\n /**\n * Add simulated latency between client and server.\n * @param milliseconds round trip latency in milliseconds.\n */\n public simulateLatency(milliseconds: number) {\n if (milliseconds > 0) {\n logger.warn(`\uD83D\uDCF6\uFE0F\u2757 Colyseus latency simulation enabled \u2192 ${milliseconds}ms latency for round trip.`);\n } else {\n logger.warn(`\uD83D\uDCF6\uFE0F\u2757 Colyseus latency simulation disabled.`);\n }\n\n const halfwayMS = (milliseconds / 2);\n this.transport.simulateLatency(halfwayMS);\n\n if (this._originalRoomOnMessage == null) {\n /* tslint:disable:no-string-literal */\n this._originalRoomOnMessage = Room.prototype['_onMessage'];\n }\n\n const originalOnMessage = this._originalRoomOnMessage;\n\n /* tslint:disable:no-string-literal */\n Room.prototype['_onMessage'] = milliseconds <= Number.EPSILON ? originalOnMessage : function (client, buffer) {\n // uWebSockets.js: duplicate buffer because it is cleared at native layer before the timeout.\n const cachedBuffer = Buffer.from(buffer);\n setTimeout(() => originalOnMessage.call(this, client, cachedBuffer), halfwayMS);\n };\n }\n\n /**\n * Register a callback that is going to be executed before the server shuts down.\n * @param callback\n */\n public onShutdown(callback: () => void | Promise<any>) {\n this.onShutdownCallback = callback;\n }\n\n public onBeforeShutdown(callback: () => void | Promise<any>) {\n this.onBeforeShutdownCallback = callback;\n }\n\n protected getDefaultTransport(_: any): Transport {\n throw new Error(\"Please provide a 'transport' layer. Default transport not set.\");\n }\n\n protected onShutdownCallback: () => void | Promise<any> =\n () => Promise.resolve()\n\n protected onBeforeShutdownCallback: () => void | Promise<any> =\n () => Promise.resolve()\n\n protected attachMatchMakingRoutes(server: http.Server) {\n const listeners = server.listeners('request').slice(0);\n server.removeAllListeners('request');\n\n server.on('request', (req, res) => {\n if (req.url.indexOf(`/${matchMaker.controller.matchmakeRoute}`) !== -1) {\n debugMatchMaking('received matchmake request: %s', req.url);\n this.handleMatchMakeRequest(req, res);\n\n } else {\n for (let i = 0, l = listeners.length; i < l; i++) {\n listeners[i].call(server, req, res);\n }\n }\n });\n }\n\n protected async handleMatchMakeRequest(req: IncomingMessage, res: ServerResponse) {\n // do not accept matchmaking requests if already shutting down\n if (matchMaker.isGracefullyShuttingDown) {\n res.writeHead(503, {});\n res.end();\n return;\n }\n\n const headers = Object.assign(\n {},\n matchMaker.controller.DEFAULT_CORS_HEADERS,\n matchMaker.controller.getCorsHeaders.call(undefined, req)\n );\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204, headers);\n res.end();\n\n } else if (req.method === 'POST') {\n const matchedParams = req.url.match(matchMaker.controller.allowedRoomNameChars);\n const matchmakeIndex = matchedParams.indexOf(matchMaker.controller.matchmakeRoute);\n const method = matchedParams[matchmakeIndex + 1];\n const roomName = matchedParams[matchmakeIndex + 2] || '';\n\n const data = [];\n req.on('data', (chunk) => data.push(chunk));\n req.on('end', async () => {\n headers['Content-Type'] = 'application/json';\n res.writeHead(200, headers);\n\n try {\n const clientOptions = JSON.parse(Buffer.concat(data).toString());\n const response = await matchMaker.controller.invokeMethod(\n method,\n roomName,\n clientOptions,\n { token: getBearerToken(req.headers['authorization']), request: req },\n );\n res.write(JSON.stringify(response));\n\n } catch (e) {\n res.write(JSON.stringify({ code: e.code, error: e.message, }));\n }\n\n res.end();\n });\n\n } else if (req.method === 'GET') {\n const matchedParams = req.url.match(matchMaker.controller.allowedRoomNameChars);\n const roomName = matchedParams.length > 1 ? matchedParams[matchedParams.length - 1] : \"\";\n\n headers['Content-Type'] = 'application/json';\n res.writeHead(200, headers);\n res.write(JSON.stringify(await matchMaker.controller.getAvailableRooms(roomName)));\n res.end();\n }\n\n }\n\n\n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AAA,YACA,EAAE,OAAO,eAAe,IAAI,QAAQ,gBAAgB,GAAG,SAAS,IAAI;AAAA,UACtE;AACA,cAAI,MAAM,KAAK,UAAU,QAAQ,CAAC;AAAA,QAEpC,SAAS,GAAP;AACA,cAAI,MAAM,KAAK,UAAU,EAAE,MAAM,EAAE,MAAM,OAAO,EAAE,QAAS,CAAC,CAAC;AAAA,QAC/D;AAEA,YAAI,IAAI;AAAA,MACV,CAAC;AAAA,IAEH,WAAW,IAAI,WAAW,OAAO;AAC/B,YAAM,gBAAgB,IAAI,IAAI,MAAM,WAAW,WAAW,oBAAoB;AAC9E,YAAM,WAAW,cAAc,SAAS,IAAI,cAAc,cAAc,SAAS,KAAK;AAEtF,cAAQ,kBAAkB;AAC1B,UAAI,UAAU,KAAK,OAAO;AAC1B,UAAI,MAAM,KAAK,UAAU,MAAM,WAAW,WAAW,kBAAkB,QAAQ,CAAC,CAAC;AACjF,UAAI,IAAI;AAAA,IACV;AAAA,EAEF;AAGF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/build/Stats.d.ts
CHANGED
|
@@ -10,3 +10,5 @@ export declare function persist(forceNow?: boolean): any;
|
|
|
10
10
|
export declare function reset(_persist?: boolean): void;
|
|
11
11
|
export declare function excludeProcess(_processId: string): boolean | Promise<boolean>;
|
|
12
12
|
export declare function getGlobalCCU(): Promise<number>;
|
|
13
|
+
export declare function setAutoPersistInterval(): void;
|
|
14
|
+
export declare function clearAutoPersistInterval(): void;
|
package/build/Stats.js
CHANGED
|
@@ -23,12 +23,14 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
23
23
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
24
24
|
var Stats_exports = {};
|
|
25
25
|
__export(Stats_exports, {
|
|
26
|
+
clearAutoPersistInterval: () => clearAutoPersistInterval,
|
|
26
27
|
excludeProcess: () => excludeProcess,
|
|
27
28
|
fetchAll: () => fetchAll,
|
|
28
29
|
getGlobalCCU: () => getGlobalCCU,
|
|
29
30
|
local: () => local,
|
|
30
31
|
persist: () => persist,
|
|
31
|
-
reset: () => reset
|
|
32
|
+
reset: () => reset,
|
|
33
|
+
setAutoPersistInterval: () => setAutoPersistInterval
|
|
32
34
|
});
|
|
33
35
|
module.exports = __toCommonJS(Stats_exports);
|
|
34
36
|
var import_MatchMaker = require("./MatchMaker");
|
|
@@ -58,6 +60,9 @@ let lastPersisted = 0;
|
|
|
58
60
|
let persistTimeout = void 0;
|
|
59
61
|
const persistInterval = 1e3;
|
|
60
62
|
function persist(forceNow = false) {
|
|
63
|
+
if (import_MatchMaker.state === import_MatchMaker.MatchMakerState.SHUTTING_DOWN) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
61
66
|
const now = Date.now();
|
|
62
67
|
if (forceNow || now - lastPersisted > persistInterval) {
|
|
63
68
|
lastPersisted = now;
|
|
@@ -83,15 +88,30 @@ async function getGlobalCCU() {
|
|
|
83
88
|
const allStats = await fetchAll();
|
|
84
89
|
return allStats.reduce((prev, next) => prev + next.ccu, 0);
|
|
85
90
|
}
|
|
91
|
+
let autoPersistInterval = void 0;
|
|
92
|
+
function setAutoPersistInterval() {
|
|
93
|
+
const interval = 60 * 1e3;
|
|
94
|
+
autoPersistInterval = setInterval(() => {
|
|
95
|
+
const now = Date.now();
|
|
96
|
+
if (now - lastPersisted > interval) {
|
|
97
|
+
persist();
|
|
98
|
+
}
|
|
99
|
+
}, interval);
|
|
100
|
+
}
|
|
101
|
+
function clearAutoPersistInterval() {
|
|
102
|
+
clearInterval(autoPersistInterval);
|
|
103
|
+
}
|
|
86
104
|
function getRoomCountKey() {
|
|
87
105
|
return "roomcount";
|
|
88
106
|
}
|
|
89
107
|
// Annotate the CommonJS export names for ESM import in node:
|
|
90
108
|
0 && (module.exports = {
|
|
109
|
+
clearAutoPersistInterval,
|
|
91
110
|
excludeProcess,
|
|
92
111
|
fetchAll,
|
|
93
112
|
getGlobalCCU,
|
|
94
113
|
local,
|
|
95
114
|
persist,
|
|
96
|
-
reset
|
|
115
|
+
reset,
|
|
116
|
+
setAutoPersistInterval
|
|
97
117
|
});
|
package/build/Stats.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/Stats.ts"],
|
|
4
|
-
"sourcesContent": ["import { presence, processId } from \"./MatchMaker\";\n\nexport type Stats = {\n roomCount: number;\n ccu: number;\n}\n\nexport let local: Stats = {\n roomCount: 0,\n ccu: 0,\n};\n\n//\n// Attach local metrics to PM2 (if available)\n//\n// @ts-ignore\nimport('@pm2/io')\n .then((io) => {\n io.default.metric({ id: 'app/stats/ccu', name: 'ccu', value: () => local.ccu });\n io.default.metric({ id: 'app/stats/roomcount', name: 'roomcount', value: () => local.roomCount });\n })\n .catch(() => { });\n\nexport async function fetchAll() {\n // TODO: cache this value to avoid querying too often\n const allStats: Array<Stats & { processId: string }> = [];\n const allProcesses = await presence.hgetall(getRoomCountKey());\n for (let remoteProcessId in allProcesses) {\n if (remoteProcessId === processId) {\n allStats.push({ processId, roomCount: local.roomCount, ccu: local.ccu, });\n\n } else {\n const [roomCount, ccu] = allProcesses[remoteProcessId].split(',').map(Number);\n allStats.push({ processId: remoteProcessId, roomCount, ccu });\n }\n }\n return allStats;\n}\n\nlet lastPersisted = 0;\nlet persistTimeout = undefined;\nconst persistInterval = 1000;\n\nexport function persist(forceNow: boolean = false) {\n /**\n * Avoid persisting
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import { MatchMakerState, presence, processId, state } from \"./MatchMaker\";\n\nexport type Stats = {\n roomCount: number;\n ccu: number;\n}\n\nexport let local: Stats = {\n roomCount: 0,\n ccu: 0,\n};\n\n//\n// Attach local metrics to PM2 (if available)\n//\n// @ts-ignore\nimport('@pm2/io')\n .then((io) => {\n io.default.metric({ id: 'app/stats/ccu', name: 'ccu', value: () => local.ccu });\n io.default.metric({ id: 'app/stats/roomcount', name: 'roomcount', value: () => local.roomCount });\n })\n .catch(() => { });\n\nexport async function fetchAll() {\n // TODO: cache this value to avoid querying too often\n const allStats: Array<Stats & { processId: string }> = [];\n const allProcesses = await presence.hgetall(getRoomCountKey());\n\n for (let remoteProcessId in allProcesses) {\n if (remoteProcessId === processId) {\n allStats.push({ processId, roomCount: local.roomCount, ccu: local.ccu, });\n\n } else {\n const [roomCount, ccu] = allProcesses[remoteProcessId].split(',').map(Number);\n allStats.push({ processId: remoteProcessId, roomCount, ccu });\n }\n }\n\n return allStats;\n}\n\nlet lastPersisted = 0;\nlet persistTimeout = undefined;\nconst persistInterval = 1000;\n\nexport function persist(forceNow: boolean = false) {\n // skip if shutting down\n if (state === MatchMakerState.SHUTTING_DOWN) {\n return;\n }\n\n /**\n * Avoid persisting more than once per second.\n */\n const now = Date.now();\n\n if (forceNow || (now - lastPersisted > persistInterval)) {\n lastPersisted = now;\n return presence.hset(getRoomCountKey(), processId, `${local.roomCount},${local.ccu}`);\n\n } else {\n clearTimeout(persistTimeout);\n persistTimeout = setTimeout(persist, persistInterval);\n }\n}\n\nexport function reset(_persist: boolean = true) {\n local.roomCount = 0;\n local.ccu = 0;\n\n if (_persist) {\n lastPersisted = 0;\n clearTimeout(persistTimeout);\n persist();\n }\n}\n\nexport function excludeProcess(_processId: string) {\n return presence.hdel(getRoomCountKey(), _processId);\n}\n\nexport async function getGlobalCCU() {\n const allStats = await fetchAll();\n return allStats.reduce((prev, next) => prev + next.ccu, 0);\n}\n\n/**\n * Auto-persist every minute.\n */\nlet autoPersistInterval = undefined;\n\nexport function setAutoPersistInterval() {\n const interval = 60 * 1000;// 1 minute\n\n autoPersistInterval = setInterval(() => {\n const now = Date.now();\n\n if (now - lastPersisted > interval) {\n persist();\n }\n }, interval);\n}\n\nexport function clearAutoPersistInterval() {\n clearInterval(autoP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AAAA,EAEtF,OAAO;AACL,iBAAa,cAAc;AAC3B,qBAAiB,WAAW,SAAS,eAAe;AAAA,EACtD;AACF;AAEO,SAAS,MAAM,WAAoB,MAAM;AAC9C,QAAM,YAAY;AAClB,QAAM,MAAM;AAEZ,MAAI,UAAU;AACZ,oBAAgB;AAChB,iBAAa,cAAc;AAC3B,YAAQ;AAAA,EACV;AACF;AAEO,SAAS,eAAe,YAAoB;AACjD,SAAO,2BAAS,KAAK,gBAAgB,GAAG,UAAU;AACpD;AAEA,eAAsB,eAAe;AACnC,QAAM,WAAW,MAAM,SAAS;AAChC,SAAO,SAAS,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,CAAC;AAC3D;AAKA,IAAI,sBAAsB;AAEnB,SAAS,yBAAyB;AACvC,QAAM,WAAW,KAAK;AAEtB,wBAAsB,YAAY,MAAM;AACtC,UAAM,MAAM,KAAK,IAAI;AAErB,QAAI,MAAM,gBAAgB,UAAU;AAClC,cAAQ;AAAA,IACV;AAAA,EACF,GAAG,QAAQ;AACb;AAEO,SAAS,2BAA2B;AACzC,gBAAc,mBAAmB;AACnC;AAEA,SAAS,kBAAkB;AACzB,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/build/Stats.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { presence, processId } from "./MatchMaker";
|
|
1
|
+
import { MatchMakerState, presence, processId, state } from "./MatchMaker";
|
|
2
2
|
let local = {
|
|
3
3
|
roomCount: 0,
|
|
4
4
|
ccu: 0
|
|
@@ -25,6 +25,9 @@ let lastPersisted = 0;
|
|
|
25
25
|
let persistTimeout = void 0;
|
|
26
26
|
const persistInterval = 1e3;
|
|
27
27
|
function persist(forceNow = false) {
|
|
28
|
+
if (state === MatchMakerState.SHUTTING_DOWN) {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
28
31
|
const now = Date.now();
|
|
29
32
|
if (forceNow || now - lastPersisted > persistInterval) {
|
|
30
33
|
lastPersisted = now;
|
|
@@ -50,14 +53,29 @@ async function getGlobalCCU() {
|
|
|
50
53
|
const allStats = await fetchAll();
|
|
51
54
|
return allStats.reduce((prev, next) => prev + next.ccu, 0);
|
|
52
55
|
}
|
|
56
|
+
let autoPersistInterval = void 0;
|
|
57
|
+
function setAutoPersistInterval() {
|
|
58
|
+
const interval = 60 * 1e3;
|
|
59
|
+
autoPersistInterval = setInterval(() => {
|
|
60
|
+
const now = Date.now();
|
|
61
|
+
if (now - lastPersisted > interval) {
|
|
62
|
+
persist();
|
|
63
|
+
}
|
|
64
|
+
}, interval);
|
|
65
|
+
}
|
|
66
|
+
function clearAutoPersistInterval() {
|
|
67
|
+
clearInterval(autoPersistInterval);
|
|
68
|
+
}
|
|
53
69
|
function getRoomCountKey() {
|
|
54
70
|
return "roomcount";
|
|
55
71
|
}
|
|
56
72
|
export {
|
|
73
|
+
clearAutoPersistInterval,
|
|
57
74
|
excludeProcess,
|
|
58
75
|
fetchAll,
|
|
59
76
|
getGlobalCCU,
|
|
60
77
|
local,
|
|
61
78
|
persist,
|
|
62
|
-
reset
|
|
79
|
+
reset,
|
|
80
|
+
setAutoPersistInterval
|
|
63
81
|
};
|
package/build/Stats.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/Stats.ts"],
|
|
4
|
-
"sourcesContent": ["import { presence, processId } from \"./MatchMaker\";\n\nexport type Stats = {\n roomCount: number;\n ccu: number;\n}\n\nexport let local: Stats = {\n roomCount: 0,\n ccu: 0,\n};\n\n//\n// Attach local metrics to PM2 (if available)\n//\n// @ts-ignore\nimport('@pm2/io')\n .then((io) => {\n io.default.metric({ id: 'app/stats/ccu', name: 'ccu', value: () => local.ccu });\n io.default.metric({ id: 'app/stats/roomcount', name: 'roomcount', value: () => local.roomCount });\n })\n .catch(() => { });\n\nexport async function fetchAll() {\n // TODO: cache this value to avoid querying too often\n const allStats: Array<Stats & { processId: string }> = [];\n const allProcesses = await presence.hgetall(getRoomCountKey());\n for (let remoteProcessId in allProcesses) {\n if (remoteProcessId === processId) {\n allStats.push({ processId, roomCount: local.roomCount, ccu: local.ccu, });\n\n } else {\n const [roomCount, ccu] = allProcesses[remoteProcessId].split(',').map(Number);\n allStats.push({ processId: remoteProcessId, roomCount, ccu });\n }\n }\n return allStats;\n}\n\nlet lastPersisted = 0;\nlet persistTimeout = undefined;\nconst persistInterval = 1000;\n\nexport function persist(forceNow: boolean = false) {\n /**\n * Avoid persisting
|
|
5
|
-
"mappings": "AAAA,SAAS,UAAU,
|
|
4
|
+
"sourcesContent": ["import { MatchMakerState, presence, processId, state } from \"./MatchMaker\";\n\nexport type Stats = {\n roomCount: number;\n ccu: number;\n}\n\nexport let local: Stats = {\n roomCount: 0,\n ccu: 0,\n};\n\n//\n// Attach local metrics to PM2 (if available)\n//\n// @ts-ignore\nimport('@pm2/io')\n .then((io) => {\n io.default.metric({ id: 'app/stats/ccu', name: 'ccu', value: () => local.ccu });\n io.default.metric({ id: 'app/stats/roomcount', name: 'roomcount', value: () => local.roomCount });\n })\n .catch(() => { });\n\nexport async function fetchAll() {\n // TODO: cache this value to avoid querying too often\n const allStats: Array<Stats & { processId: string }> = [];\n const allProcesses = await presence.hgetall(getRoomCountKey());\n\n for (let remoteProcessId in allProcesses) {\n if (remoteProcessId === processId) {\n allStats.push({ processId, roomCount: local.roomCount, ccu: local.ccu, });\n\n } else {\n const [roomCount, ccu] = allProcesses[remoteProcessId].split(',').map(Number);\n allStats.push({ processId: remoteProcessId, roomCount, ccu });\n }\n }\n\n return allStats;\n}\n\nlet lastPersisted = 0;\nlet persistTimeout = undefined;\nconst persistInterval = 1000;\n\nexport function persist(forceNow: boolean = false) {\n // skip if shutting down\n if (state === MatchMakerState.SHUTTING_DOWN) {\n return;\n }\n\n /**\n * Avoid persisting more than once per second.\n */\n const now = Date.now();\n\n if (forceNow || (now - lastPersisted > persistInterval)) {\n lastPersisted = now;\n return presence.hset(getRoomCountKey(), processId, `${local.roomCount},${local.ccu}`);\n\n } else {\n clearTimeout(persistTimeout);\n persistTimeout = setTimeout(persist, persistInterval);\n }\n}\n\nexport function reset(_persist: boolean = true) {\n local.roomCount = 0;\n local.ccu = 0;\n\n if (_persist) {\n lastPersisted = 0;\n clearTimeout(persistTimeout);\n persist();\n }\n}\n\nexport function excludeProcess(_processId: string) {\n return presence.hdel(getRoomCountKey(), _processId);\n}\n\nexport async function getGlobalCCU() {\n const allStats = await fetchAll();\n return allStats.reduce((prev, next) => prev + next.ccu, 0);\n}\n\n/**\n * Auto-persist every minute.\n */\nlet autoPersistInterval = undefined;\n\nexport function setAutoPersistInterval() {\n const interval = 60 * 1000;// 1 minute\n\n autoPersistInterval = setInterval(() => {\n const now = Date.now();\n\n if (now - lastPersisted > interval) {\n persist();\n }\n }, interval);\n}\n\nexport function clearAutoPersistInterval() {\n clearInterval(autoPersistInterval);\n}\n\nfunction getRoomCountKey() {\n return 'roomcount';\n}"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB,UAAU,WAAW,aAAa;AAOrD,IAAI,QAAe;AAAA,EACxB,WAAW;AAAA,EACX,KAAK;AACP;AAMA,OAAO,WACJ,KAAK,CAAC,OAAO;AACZ,KAAG,QAAQ,OAAO,EAAE,IAAI,iBAAiB,MAAM,OAAO,OAAO,MAAM,MAAM,IAAI,CAAC;AAC9E,KAAG,QAAQ,OAAO,EAAE,IAAI,uBAAuB,MAAM,aAAa,OAAO,MAAM,MAAM,UAAU,CAAC;AAClG,CAAC,EACA,MAAM,MAAM;AAAE,CAAC;AAElB,eAAsB,WAAW;AAE/B,QAAM,WAAiD,CAAC;AACxD,QAAM,eAAe,MAAM,SAAS,QAAQ,gBAAgB,CAAC;AAE7D,WAAS,mBAAmB,cAAc;AACxC,QAAI,oBAAoB,WAAW;AACjC,eAAS,KAAK,EAAE,WAAW,WAAW,MAAM,WAAW,KAAK,MAAM,IAAK,CAAC;AAAA,IAE1E,OAAO;A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names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Client } from '../Transport';
|
|
2
|
+
import type { ExtractAuthData, ExtractUserData, Room } from '../Room';
|
|
3
|
+
export type RoomException<R extends Room = Room> = OnCreateException<R> | OnAuthException<R> | OnJoinException<R> | OnLeaveException<R> | OnDisposeException | OnMessageException<R> | SimulationIntervalException | TimedEventException;
|
|
4
|
+
export declare class OnCreateException<R extends Room = Room> extends Error {
|
|
5
|
+
options: Parameters<R['onCreate']>[0];
|
|
6
|
+
constructor(cause: Error, message: string, options: Parameters<R['onCreate']>[0]);
|
|
7
|
+
}
|
|
8
|
+
export declare class OnAuthException<R extends Room = Room> extends Error {
|
|
9
|
+
client: Parameters<R['onAuth']>[0];
|
|
10
|
+
options: Parameters<R['onAuth']>[1];
|
|
11
|
+
constructor(cause: Error, message: string, client: Parameters<R['onAuth']>[0], options: Parameters<R['onAuth']>[1]);
|
|
12
|
+
}
|
|
13
|
+
export declare class OnJoinException<R extends Room = Room> extends Error {
|
|
14
|
+
client: Parameters<R['onJoin']>[0];
|
|
15
|
+
options: Parameters<R['onJoin']>[1];
|
|
16
|
+
auth: Parameters<R['onJoin']>[2];
|
|
17
|
+
constructor(cause: Error, message: string, client: Parameters<R['onJoin']>[0], options: Parameters<R['onJoin']>[1], auth: Parameters<R['onJoin']>[2]);
|
|
18
|
+
}
|
|
19
|
+
export declare class OnLeaveException<R extends Room = Room> extends Error {
|
|
20
|
+
client: Parameters<R['onLeave']>[0];
|
|
21
|
+
consented: Parameters<R['onLeave']>[1];
|
|
22
|
+
constructor(cause: Error, message: string, client: Parameters<R['onLeave']>[0], consented: Parameters<R['onLeave']>[1]);
|
|
23
|
+
}
|
|
24
|
+
export declare class OnDisposeException extends Error {
|
|
25
|
+
constructor(cause: Error, message: string);
|
|
26
|
+
}
|
|
27
|
+
export declare class OnMessageException<R extends Room = Room, MessagePayload = any> extends Error {
|
|
28
|
+
client: Client<ExtractUserData<R['clients']>, ExtractAuthData<R['clients']>>;
|
|
29
|
+
payload: MessagePayload;
|
|
30
|
+
type: string;
|
|
31
|
+
constructor(cause: Error, message: string, client: Client<ExtractUserData<R['clients']>, ExtractAuthData<R['clients']>>, payload: MessagePayload, type: string);
|
|
32
|
+
}
|
|
33
|
+
export declare class SimulationIntervalException extends Error {
|
|
34
|
+
constructor(cause: Error, message: string);
|
|
35
|
+
}
|
|
36
|
+
export declare class TimedEventException extends Error {
|
|
37
|
+
args: any[];
|
|
38
|
+
constructor(cause: Error, message: string, ...args: any[]);
|
|
39
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var RoomExceptions_exports = {};
|
|
19
|
+
__export(RoomExceptions_exports, {
|
|
20
|
+
OnAuthException: () => OnAuthException,
|
|
21
|
+
OnCreateException: () => OnCreateException,
|
|
22
|
+
OnDisposeException: () => OnDisposeException,
|
|
23
|
+
OnJoinException: () => OnJoinException,
|
|
24
|
+
OnLeaveException: () => OnLeaveException,
|
|
25
|
+
OnMessageException: () => OnMessageException,
|
|
26
|
+
SimulationIntervalException: () => SimulationIntervalException,
|
|
27
|
+
TimedEventException: () => TimedEventException
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(RoomExceptions_exports);
|
|
30
|
+
class OnCreateException extends Error {
|
|
31
|
+
constructor(cause, message, options) {
|
|
32
|
+
super(message, { cause });
|
|
33
|
+
this.options = options;
|
|
34
|
+
this.name = "OnCreateException";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
class OnAuthException extends Error {
|
|
38
|
+
constructor(cause, message, client, options) {
|
|
39
|
+
super(message, { cause });
|
|
40
|
+
this.client = client;
|
|
41
|
+
this.options = options;
|
|
42
|
+
this.name = "OnAuthException";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
class OnJoinException extends Error {
|
|
46
|
+
constructor(cause, message, client, options, auth) {
|
|
47
|
+
super(message, { cause });
|
|
48
|
+
this.client = client;
|
|
49
|
+
this.options = options;
|
|
50
|
+
this.auth = auth;
|
|
51
|
+
this.name = "OnJoinException";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
class OnLeaveException extends Error {
|
|
55
|
+
constructor(cause, message, client, consented) {
|
|
56
|
+
super(message, { cause });
|
|
57
|
+
this.client = client;
|
|
58
|
+
this.consented = consented;
|
|
59
|
+
this.name = "OnLeaveException";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
class OnDisposeException extends Error {
|
|
63
|
+
constructor(cause, message) {
|
|
64
|
+
super(message, { cause });
|
|
65
|
+
this.name = "OnDisposeException";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
class OnMessageException extends Error {
|
|
69
|
+
constructor(cause, message, client, payload, type) {
|
|
70
|
+
super(message, { cause });
|
|
71
|
+
this.client = client;
|
|
72
|
+
this.payload = payload;
|
|
73
|
+
this.type = type;
|
|
74
|
+
this.name = "OnMessageException";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
class SimulationIntervalException extends Error {
|
|
78
|
+
constructor(cause, message) {
|
|
79
|
+
super(message, { cause });
|
|
80
|
+
this.name = "SimulationIntervalException";
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
class TimedEventException extends Error {
|
|
84
|
+
constructor(cause, message, ...args) {
|
|
85
|
+
super(message, { cause });
|
|
86
|
+
this.name = "TimedEventException";
|
|
87
|
+
this.args = args;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
91
|
+
0 && (module.exports = {
|
|
92
|
+
OnAuthException,
|
|
93
|
+
OnCreateException,
|
|
94
|
+
OnDisposeException,
|
|
95
|
+
OnJoinException,
|
|
96
|
+
OnLeaveException,
|
|
97
|
+
OnMessageException,
|
|
98
|
+
SimulationIntervalException,
|
|
99
|
+
TimedEventException
|
|
100
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/errors/RoomExceptions.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Client } from '../Transport';\nimport type { ExtractAuthData, ExtractUserData, Room } from '../Room';\n\nexport type RoomException<R extends Room = Room> =\n OnCreateException<R> |\n OnAuthException<R> |\n OnJoinException<R> |\n OnLeaveException<R> |\n OnDisposeException |\n OnMessageException<R> |\n SimulationIntervalException |\n TimedEventException;\n\nexport class OnCreateException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public options: Parameters<R['onCreate']>[0],\n ) {\n super(message, { cause });\n this.name = 'OnCreateException';\n }\n}\n\nexport class OnAuthException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Parameters<R['onAuth']>[0],\n public options: Parameters<R['onAuth']>[1],\n ) {\n super(message, { cause });\n this.name = 'OnAuthException';\n }\n}\n\nexport class OnJoinException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Parameters<R['onJoin']>[0],\n public options: Parameters<R['onJoin']>[1],\n public auth: Parameters<R['onJoin']>[2],\n ) {\n super(message, { cause });\n this.name = 'OnJoinException';\n }\n}\n\nexport class OnLeaveException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Parameters<R['onLeave']>[0],\n public consented: Parameters<R['onLeave']>[1],\n ) {\n super(message, { cause });\n this.name = 'OnLeaveException';\n }\n}\n\nexport class OnDisposeException extends Error {\n constructor(\n cause: Error,\n message: string,\n ) {\n super(message, { cause });\n this.name = 'OnDisposeException';\n }\n}\n\nexport class OnMessageException<R extends Room = Room, MessagePayload = any> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Client<ExtractUserData<R['clients']>, ExtractAuthData<R['clients']>>,\n public payload: MessagePayload,\n public type: string,\n ) {\n super(message, { cause });\n this.name = 'OnMessageException';\n }\n}\n\nexport class SimulationIntervalException extends Error {\n constructor(\n cause: Error,\n message: string,\n ) {\n super(message, { cause });\n this.name = 'SimulationIntervalException';\n }\n}\n\nexport class TimedEventException extends Error {\n public args: any[];\n constructor(\n cause: Error,\n message: string,\n ...args: any[]\n ) {\n super(message, { cause });\n this.name = 'TimedEventException';\n this.args = args;\n }\n}"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaO,MAAM,0BAAiD,MAAM;AAAA,EAClE,YACE,OACA,SACO,SACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAFjB;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,wBAA+C,MAAM;AAAA,EAChE,YACE,OACA,SACO,QACA,SACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAHjB;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,wBAA+C,MAAM;AAAA,EAChE,YACE,OACA,SACO,QACA,SACA,MACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAJjB;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,yBAAgD,MAAM;AAAA,EACjE,YACE,OACA,SACO,QACA,WACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAHjB;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,2BAA2B,MAAM;AAAA,EAC5C,YACE,OACA,SACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,2BAAwE,MAAM;AAAA,EACzF,YACE,OACA,SACO,QACA,SACA,MACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAJjB;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,oCAAoC,MAAM;AAAA,EACrD,YACE,OACA,SACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,4BAA4B,MAAM;AAAA,EAE7C,YACE,OACA,YACG,MACH;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
class OnCreateException extends Error {
|
|
2
|
+
constructor(cause, message, options) {
|
|
3
|
+
super(message, { cause });
|
|
4
|
+
this.options = options;
|
|
5
|
+
this.name = "OnCreateException";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
class OnAuthException extends Error {
|
|
9
|
+
constructor(cause, message, client, options) {
|
|
10
|
+
super(message, { cause });
|
|
11
|
+
this.client = client;
|
|
12
|
+
this.options = options;
|
|
13
|
+
this.name = "OnAuthException";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
class OnJoinException extends Error {
|
|
17
|
+
constructor(cause, message, client, options, auth) {
|
|
18
|
+
super(message, { cause });
|
|
19
|
+
this.client = client;
|
|
20
|
+
this.options = options;
|
|
21
|
+
this.auth = auth;
|
|
22
|
+
this.name = "OnJoinException";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
class OnLeaveException extends Error {
|
|
26
|
+
constructor(cause, message, client, consented) {
|
|
27
|
+
super(message, { cause });
|
|
28
|
+
this.client = client;
|
|
29
|
+
this.consented = consented;
|
|
30
|
+
this.name = "OnLeaveException";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
class OnDisposeException extends Error {
|
|
34
|
+
constructor(cause, message) {
|
|
35
|
+
super(message, { cause });
|
|
36
|
+
this.name = "OnDisposeException";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
class OnMessageException extends Error {
|
|
40
|
+
constructor(cause, message, client, payload, type) {
|
|
41
|
+
super(message, { cause });
|
|
42
|
+
this.client = client;
|
|
43
|
+
this.payload = payload;
|
|
44
|
+
this.type = type;
|
|
45
|
+
this.name = "OnMessageException";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
class SimulationIntervalException extends Error {
|
|
49
|
+
constructor(cause, message) {
|
|
50
|
+
super(message, { cause });
|
|
51
|
+
this.name = "SimulationIntervalException";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
class TimedEventException extends Error {
|
|
55
|
+
constructor(cause, message, ...args) {
|
|
56
|
+
super(message, { cause });
|
|
57
|
+
this.name = "TimedEventException";
|
|
58
|
+
this.args = args;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export {
|
|
62
|
+
OnAuthException,
|
|
63
|
+
OnCreateException,
|
|
64
|
+
OnDisposeException,
|
|
65
|
+
OnJoinException,
|
|
66
|
+
OnLeaveException,
|
|
67
|
+
OnMessageException,
|
|
68
|
+
SimulationIntervalException,
|
|
69
|
+
TimedEventException
|
|
70
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/errors/RoomExceptions.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Client } from '../Transport';\nimport type { ExtractAuthData, ExtractUserData, Room } from '../Room';\n\nexport type RoomException<R extends Room = Room> =\n OnCreateException<R> |\n OnAuthException<R> |\n OnJoinException<R> |\n OnLeaveException<R> |\n OnDisposeException |\n OnMessageException<R> |\n SimulationIntervalException |\n TimedEventException;\n\nexport class OnCreateException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public options: Parameters<R['onCreate']>[0],\n ) {\n super(message, { cause });\n this.name = 'OnCreateException';\n }\n}\n\nexport class OnAuthException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Parameters<R['onAuth']>[0],\n public options: Parameters<R['onAuth']>[1],\n ) {\n super(message, { cause });\n this.name = 'OnAuthException';\n }\n}\n\nexport class OnJoinException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Parameters<R['onJoin']>[0],\n public options: Parameters<R['onJoin']>[1],\n public auth: Parameters<R['onJoin']>[2],\n ) {\n super(message, { cause });\n this.name = 'OnJoinException';\n }\n}\n\nexport class OnLeaveException<R extends Room = Room> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Parameters<R['onLeave']>[0],\n public consented: Parameters<R['onLeave']>[1],\n ) {\n super(message, { cause });\n this.name = 'OnLeaveException';\n }\n}\n\nexport class OnDisposeException extends Error {\n constructor(\n cause: Error,\n message: string,\n ) {\n super(message, { cause });\n this.name = 'OnDisposeException';\n }\n}\n\nexport class OnMessageException<R extends Room = Room, MessagePayload = any> extends Error {\n constructor(\n cause: Error,\n message: string,\n public client: Client<ExtractUserData<R['clients']>, ExtractAuthData<R['clients']>>,\n public payload: MessagePayload,\n public type: string,\n ) {\n super(message, { cause });\n this.name = 'OnMessageException';\n }\n}\n\nexport class SimulationIntervalException extends Error {\n constructor(\n cause: Error,\n message: string,\n ) {\n super(message, { cause });\n this.name = 'SimulationIntervalException';\n }\n}\n\nexport class TimedEventException extends Error {\n public args: any[];\n constructor(\n cause: Error,\n message: string,\n ...args: any[]\n ) {\n super(message, { cause });\n this.name = 'TimedEventException';\n this.args = args;\n }\n}"],
|
|
5
|
+
"mappings": "AAaO,MAAM,0BAAiD,MAAM;AAAA,EAClE,YACE,OACA,SACO,SACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAFjB;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,wBAA+C,MAAM;AAAA,EAChE,YACE,OACA,SACO,QACA,SACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAHjB;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,wBAA+C,MAAM;AAAA,EAChE,YACE,OACA,SACO,QACA,SACA,MACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAJjB;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,yBAAgD,MAAM;AAAA,EACjE,YACE,OACA,SACO,QACA,WACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAHjB;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,2BAA2B,MAAM;AAAA,EAC5C,YACE,OACA,SACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,2BAAwE,MAAM;AAAA,EACzF,YACE,OACA,SACO,QACA,SACA,MACP;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAJjB;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,oCAAoC,MAAM;AAAA,EACrD,YACE,OACA,SACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,4BAA4B,MAAM;AAAA,EAE7C,YACE,OACA,YACG,MACH;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/build/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export { Room, RoomInternalState } from './Room';
|
|
|
4
4
|
export { Protocol, ErrorCode, getMessageBytes } from './Protocol';
|
|
5
5
|
export { RegisteredHandler } from './matchmaker/RegisteredHandler';
|
|
6
6
|
export { ServerError } from './errors/ServerError';
|
|
7
|
+
export { RoomException, OnCreateException, OnAuthException, OnJoinException, OnLeaveException, OnDisposeException, OnMessageException, SimulationIntervalException, TimedEventException, } from './errors/RoomExceptions';
|
|
7
8
|
import * as matchMaker from './MatchMaker';
|
|
8
9
|
export { matchMaker };
|
|
9
10
|
export { updateLobby, subscribeLobby } from './matchmaker/Lobby';
|
package/build/index.js
CHANGED
|
@@ -33,14 +33,23 @@ __export(src_exports, {
|
|
|
33
33
|
ErrorCode: () => import_Protocol.ErrorCode,
|
|
34
34
|
LobbyRoom: () => import_LobbyRoom.LobbyRoom,
|
|
35
35
|
LocalPresence: () => import_LocalPresence.LocalPresence,
|
|
36
|
+
OnAuthException: () => import_RoomExceptions.OnAuthException,
|
|
37
|
+
OnCreateException: () => import_RoomExceptions.OnCreateException,
|
|
38
|
+
OnDisposeException: () => import_RoomExceptions.OnDisposeException,
|
|
39
|
+
OnJoinException: () => import_RoomExceptions.OnJoinException,
|
|
40
|
+
OnLeaveException: () => import_RoomExceptions.OnLeaveException,
|
|
41
|
+
OnMessageException: () => import_RoomExceptions.OnMessageException,
|
|
36
42
|
Protocol: () => import_Protocol.Protocol,
|
|
37
43
|
RegisteredHandler: () => import_RegisteredHandler.RegisteredHandler,
|
|
38
44
|
RelayRoom: () => import_RelayRoom.RelayRoom,
|
|
39
45
|
Room: () => import_Room.Room,
|
|
46
|
+
RoomException: () => import_RoomExceptions.RoomException,
|
|
40
47
|
RoomInternalState: () => import_Room.RoomInternalState,
|
|
41
48
|
SchemaSerializer: () => import_SchemaSerializer.SchemaSerializer,
|
|
42
49
|
Server: () => import_Server.Server,
|
|
43
50
|
ServerError: () => import_ServerError.ServerError,
|
|
51
|
+
SimulationIntervalException: () => import_RoomExceptions.SimulationIntervalException,
|
|
52
|
+
TimedEventException: () => import_RoomExceptions.TimedEventException,
|
|
44
53
|
Transport: () => import_Transport.Transport,
|
|
45
54
|
debugAndPrintError: () => import_Debug.debugAndPrintError,
|
|
46
55
|
debugConnection: () => import_Debug.debugConnection,
|
|
@@ -67,6 +76,7 @@ var import_Room = require("./Room");
|
|
|
67
76
|
var import_Protocol = require("./Protocol");
|
|
68
77
|
var import_RegisteredHandler = require("./matchmaker/RegisteredHandler");
|
|
69
78
|
var import_ServerError = require("./errors/ServerError");
|
|
79
|
+
var import_RoomExceptions = require("./errors/RoomExceptions");
|
|
70
80
|
var matchMaker = __toESM(require("./MatchMaker"));
|
|
71
81
|
var import_Lobby = require("./matchmaker/Lobby");
|
|
72
82
|
__reExport(src_exports, require("./matchmaker/driver"), module.exports);
|
|
@@ -92,14 +102,23 @@ var import_Logger = require("./Logger");
|
|
|
92
102
|
ErrorCode,
|
|
93
103
|
LobbyRoom,
|
|
94
104
|
LocalPresence,
|
|
105
|
+
OnAuthException,
|
|
106
|
+
OnCreateException,
|
|
107
|
+
OnDisposeException,
|
|
108
|
+
OnJoinException,
|
|
109
|
+
OnLeaveException,
|
|
110
|
+
OnMessageException,
|
|
95
111
|
Protocol,
|
|
96
112
|
RegisteredHandler,
|
|
97
113
|
RelayRoom,
|
|
98
114
|
Room,
|
|
115
|
+
RoomException,
|
|
99
116
|
RoomInternalState,
|
|
100
117
|
SchemaSerializer,
|
|
101
118
|
Server,
|
|
102
119
|
ServerError,
|
|
120
|
+
SimulationIntervalException,
|
|
121
|
+
TimedEventException,
|
|
103
122
|
Transport,
|
|
104
123
|
debugAndPrintError,
|
|
105
124
|
debugConnection,
|
package/build/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["import Clock, { Delayed } from '@gamestdio/timer';\n\n// Core classes\nexport { Server, type ServerOptions } from './Server';\nexport { Room, RoomInternalState } from './Room';\nexport { Protocol, ErrorCode, getMessageBytes } from './Protocol';\nexport { RegisteredHandler } from './matchmaker/RegisteredHandler';\nexport { ServerError } from './errors/ServerError';\n\n// MatchMaker\nimport * as matchMaker from './MatchMaker';\nexport { matchMaker };\nexport { updateLobby, subscribeLobby } from './matchmaker/Lobby';\n\n// Driver\nexport * from './matchmaker/driver';\n\n// Transport\nexport { type Client, ClientState, ClientArray, Transport, type ISendOptions } from './Transport';\n\n// Presence\nexport { type Presence } from './presence/Presence';\nexport { LocalPresence } from './presence/LocalPresence';\n\n// Serializers\nexport { type Serializer } from './serializer/Serializer';\nexport { SchemaSerializer } from './serializer/SchemaSerializer';\n\n// Utilities\nexport { Clock, Delayed };\nexport { generateId, Deferred, DummyServer, spliceOne, getBearerToken } from './utils/Utils';\nexport { isDevMode } from './utils/DevMode';\n\n// Debug\nexport {\n debugMatchMaking,\n debugMessage,\n debugPatch,\n debugError,\n debugConnection,\n debugDriver,\n debugPresence,\n debugAndPrintError,\n} from './Debug';\n\n// Default rooms\nexport { LobbyRoom } from './rooms/LobbyRoom';\nexport { RelayRoom } from './rooms/RelayRoom';\n\n// Abstract logging support\nexport { logger } from './Logger'\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA+B;AAG/B,oBAA2C;AAC3C,kBAAwC;AACxC,sBAAqD;AACrD,+BAAkC;AAClC,yBAA4B;
|
|
4
|
+
"sourcesContent": ["import Clock, { Delayed } from '@gamestdio/timer';\n\n// Core classes\nexport { Server, type ServerOptions } from './Server';\nexport { Room, RoomInternalState } from './Room';\nexport { Protocol, ErrorCode, getMessageBytes } from './Protocol';\nexport { RegisteredHandler } from './matchmaker/RegisteredHandler';\nexport { ServerError } from './errors/ServerError';\n\nexport {\n RoomException,\n OnCreateException,\n OnAuthException,\n OnJoinException,\n OnLeaveException,\n OnDisposeException,\n OnMessageException,\n SimulationIntervalException,\n TimedEventException,\n} from './errors/RoomExceptions';\n\n// MatchMaker\nimport * as matchMaker from './MatchMaker';\nexport { matchMaker };\nexport { updateLobby, subscribeLobby } from './matchmaker/Lobby';\n\n// Driver\nexport * from './matchmaker/driver';\n\n// Transport\nexport { type Client, ClientState, ClientArray, Transport, type ISendOptions } from './Transport';\n\n// Presence\nexport { type Presence } from './presence/Presence';\nexport { LocalPresence } from './presence/LocalPresence';\n\n// Serializers\nexport { type Serializer } from './serializer/Serializer';\nexport { SchemaSerializer } from './serializer/SchemaSerializer';\n\n// Utilities\nexport { Clock, Delayed };\nexport { generateId, Deferred, DummyServer, spliceOne, getBearerToken } from './utils/Utils';\nexport { isDevMode } from './utils/DevMode';\n\n// Debug\nexport {\n debugMatchMaking,\n debugMessage,\n debugPatch,\n debugError,\n debugConnection,\n debugDriver,\n debugPresence,\n debugAndPrintError,\n} from './Debug';\n\n// Default rooms\nexport { LobbyRoom } from './rooms/LobbyRoom';\nexport { RelayRoom } from './rooms/RelayRoom';\n\n// Abstract logging support\nexport { logger } from './Logger'\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA+B;AAG/B,oBAA2C;AAC3C,kBAAwC;AACxC,sBAAqD;AACrD,+BAAkC;AAClC,yBAA4B;AAE5B,4BAUO;AAGP,iBAA4B;AAE5B,mBAA4C;AAG5C,wBAAc,gCA3Bd;AA8BA,uBAAoF;AAGpF,sBAA8B;AAC9B,2BAA8B;AAG9B,wBAAgC;AAChC,8BAAiC;AAIjC,mBAA6E;AAC7E,qBAA0B;AAG1B,mBASO;AAGP,uBAA0B;AAC1B,uBAA0B;AAG1B,oBAAuB;",
|
|
6
6
|
"names": ["Clock"]
|
|
7
7
|
}
|
package/build/index.mjs
CHANGED
|
@@ -4,6 +4,17 @@ import { Room, RoomInternalState } from "./Room";
|
|
|
4
4
|
import { Protocol, ErrorCode, getMessageBytes } from "./Protocol";
|
|
5
5
|
import { RegisteredHandler } from "./matchmaker/RegisteredHandler";
|
|
6
6
|
import { ServerError } from "./errors/ServerError";
|
|
7
|
+
import {
|
|
8
|
+
RoomException,
|
|
9
|
+
OnCreateException,
|
|
10
|
+
OnAuthException,
|
|
11
|
+
OnJoinException,
|
|
12
|
+
OnLeaveException,
|
|
13
|
+
OnDisposeException,
|
|
14
|
+
OnMessageException,
|
|
15
|
+
SimulationIntervalException,
|
|
16
|
+
TimedEventException
|
|
17
|
+
} from "./errors/RoomExceptions";
|
|
7
18
|
import * as matchMaker from "./MatchMaker";
|
|
8
19
|
import { updateLobby, subscribeLobby } from "./matchmaker/Lobby";
|
|
9
20
|
export * from "./matchmaker/driver";
|
|
@@ -37,14 +48,23 @@ export {
|
|
|
37
48
|
ErrorCode,
|
|
38
49
|
LobbyRoom,
|
|
39
50
|
LocalPresence,
|
|
51
|
+
OnAuthException,
|
|
52
|
+
OnCreateException,
|
|
53
|
+
OnDisposeException,
|
|
54
|
+
OnJoinException,
|
|
55
|
+
OnLeaveException,
|
|
56
|
+
OnMessageException,
|
|
40
57
|
Protocol,
|
|
41
58
|
RegisteredHandler,
|
|
42
59
|
RelayRoom,
|
|
43
60
|
Room,
|
|
61
|
+
RoomException,
|
|
44
62
|
RoomInternalState,
|
|
45
63
|
SchemaSerializer,
|
|
46
64
|
Server,
|
|
47
65
|
ServerError,
|
|
66
|
+
SimulationIntervalException,
|
|
67
|
+
TimedEventException,
|
|
48
68
|
Transport,
|
|
49
69
|
debugAndPrintError,
|
|
50
70
|
debugConnection,
|