@ughuuu/game_server 1.0.1039 → 1.0.1040

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.
Files changed (178) hide show
  1. package/README.md +45 -11
  2. package/dist/ApiClient.js +2 -2
  3. package/dist/api/AchievementsApi.js +2 -2
  4. package/dist/api/AdminAchievementsApi.js +2 -2
  5. package/dist/api/AdminChatApi.js +2 -2
  6. package/dist/api/AdminGroupsApi.js +2 -2
  7. package/dist/api/AdminKVApi.js +2 -2
  8. package/dist/api/AdminLeaderboardsApi.js +2 -2
  9. package/dist/api/AdminLobbiesApi.js +2 -2
  10. package/dist/api/AdminMatchmakingApi.js +165 -0
  11. package/dist/api/AdminNotificationsApi.js +2 -2
  12. package/dist/api/AdminSessionsApi.js +2 -2
  13. package/dist/api/AdminTournamentsApi.js +2 -2
  14. package/dist/api/AdminUsersApi.js +2 -2
  15. package/dist/api/AuthenticationApi.js +2 -2
  16. package/dist/api/ChatApi.js +2 -2
  17. package/dist/api/FriendsApi.js +126 -2
  18. package/dist/api/GroupsApi.js +2 -2
  19. package/dist/api/HealthApi.js +2 -2
  20. package/dist/api/HooksApi.js +2 -2
  21. package/dist/api/KVApi.js +2 -2
  22. package/dist/api/LeaderboardsApi.js +2 -2
  23. package/dist/api/LobbiesApi.js +2 -2
  24. package/dist/api/MatchmakingApi.js +187 -0
  25. package/dist/api/NotificationsApi.js +2 -2
  26. package/dist/api/PartiesApi.js +2 -2
  27. package/dist/api/PaymentsApi.js +2 -2
  28. package/dist/api/TournamentsApi.js +2 -2
  29. package/dist/api/UsersApi.js +2 -2
  30. package/dist/index.js +126 -7
  31. package/dist/model/AcceptPartyInvite200Response.js +2 -2
  32. package/dist/model/AcceptPartyInvite200ResponseMembersInner.js +2 -2
  33. package/dist/model/AcceptPartyInviteRequest.js +2 -2
  34. package/dist/model/AdminCancelMatchmakingTicket200Response.js +91 -0
  35. package/dist/model/AdminCreateAchievementRequest.js +2 -2
  36. package/dist/model/AdminCreateLeaderboard200Response.js +2 -2
  37. package/dist/model/AdminCreateLeaderboard200ResponseData.js +2 -2
  38. package/dist/model/AdminCreateLeaderboardRequest.js +2 -2
  39. package/dist/model/AdminCreateNotificationRequest.js +2 -2
  40. package/dist/model/AdminDeleteChatConversation200Response.js +2 -2
  41. package/dist/model/AdminDrawTournament200Response.js +2 -2
  42. package/dist/model/AdminDrawTournament200ResponseData.js +2 -2
  43. package/dist/model/AdminGrantAchievementRequest.js +2 -2
  44. package/dist/model/AdminIncrementAchievementRequest.js +2 -2
  45. package/dist/model/AdminListAchievements200Response.js +2 -2
  46. package/dist/model/AdminListAchievements200ResponseDataInner.js +2 -2
  47. package/dist/model/AdminListChatMessages200Response.js +2 -2
  48. package/dist/model/AdminListChatMessages200ResponseDataInner.js +2 -2
  49. package/dist/model/AdminListGroups200Response.js +2 -2
  50. package/dist/model/AdminListKvEntries200Response.js +2 -2
  51. package/dist/model/AdminListLobbies200Response.js +2 -2
  52. package/dist/model/AdminListLobbies200ResponseDataInner.js +2 -2
  53. package/dist/model/AdminListMatchmakingTickets200Response.js +124 -0
  54. package/dist/model/AdminListMatchmakingTickets200ResponseDataInner.js +196 -0
  55. package/dist/model/AdminListNotifications200Response.js +2 -2
  56. package/dist/model/AdminListNotifications200ResponseDataInner.js +2 -2
  57. package/dist/model/AdminListSessions200Response.js +2 -2
  58. package/dist/model/AdminListSessions200ResponseDataInner.js +2 -2
  59. package/dist/model/AdminMatchmakingStats200Response.js +91 -0
  60. package/dist/model/AdminMatchmakingStats200ResponseData.js +113 -0
  61. package/dist/model/AdminResolveTournamentMatchRequest.js +2 -2
  62. package/dist/model/AdminRevokeAchievementRequest.js +2 -2
  63. package/dist/model/AdminSubmitLeaderboardScoreRequest.js +2 -2
  64. package/dist/model/AdminUpdateAchievementRequest.js +2 -2
  65. package/dist/model/AdminUpdateGroup200Response.js +2 -2
  66. package/dist/model/AdminUpdateGroupRequest.js +2 -2
  67. package/dist/model/AdminUpdateKvEntryRequest.js +2 -2
  68. package/dist/model/AdminUpdateLeaderboardRecord200Response.js +2 -2
  69. package/dist/model/AdminUpdateLeaderboardRecord200ResponseData.js +2 -2
  70. package/dist/model/AdminUpdateLeaderboardRecordRequest.js +2 -2
  71. package/dist/model/AdminUpdateLeaderboardRequest.js +2 -2
  72. package/dist/model/AdminUpdateLobby200Response.js +2 -2
  73. package/dist/model/AdminUpdateTournamentRequest.js +2 -2
  74. package/dist/model/AdminUpdateUser200Response.js +2 -2
  75. package/dist/model/AdminUpdateUser200ResponseData.js +2 -2
  76. package/dist/model/AdminUpdateUserRequest.js +2 -2
  77. package/dist/model/AdminUpsertKv200Response.js +2 -2
  78. package/dist/model/AdminUpsertKv200ResponseData.js +2 -2
  79. package/dist/model/AdminUpsertKvRequest.js +2 -2
  80. package/dist/model/ApproveJoinRequest200Response.js +2 -2
  81. package/dist/model/CallHook200Response.js +2 -2
  82. package/dist/model/CallHookRequest.js +2 -2
  83. package/dist/model/CancelJoinRequest200Response.js +2 -2
  84. package/dist/model/ChatUnreadCount200Response.js +2 -2
  85. package/dist/model/CreateGroupRequest.js +2 -2
  86. package/dist/model/CreateLobbyRequest.js +2 -2
  87. package/dist/model/CreatePartyRequest.js +2 -2
  88. package/dist/model/DeclineGroupInvite200Response.js +2 -2
  89. package/dist/model/DeleteNotificationsRequest.js +2 -2
  90. package/dist/model/DeviceLoginRequest.js +2 -2
  91. package/dist/model/ErrorResponse.js +2 -2
  92. package/dist/model/GameServerWebApiV1TournamentControllerIndex200Response.js +2 -2
  93. package/dist/model/GameServerWebApiV1TournamentControllerIndex200ResponseDataInner.js +2 -2
  94. package/dist/model/GameServerWebApiV1TournamentControllerMyMatch200Response.js +2 -2
  95. package/dist/model/GetCurrentUser200Response.js +2 -2
  96. package/dist/model/GetCurrentUser200ResponseLinkedProviders.js +2 -2
  97. package/dist/model/GetKv200Response.js +2 -2
  98. package/dist/model/GetLobby200Response.js +2 -2
  99. package/dist/model/GetMyRecord200Response.js +2 -2
  100. package/dist/model/GetMyRecord200ResponseData.js +2 -2
  101. package/dist/model/HealthResponse.js +2 -2
  102. package/dist/model/InviteToPartyRequest.js +2 -2
  103. package/dist/model/ListBlacklistedUsers200Response.js +118 -0
  104. package/dist/model/ListBlacklistedUsers200ResponseDataInner.js +113 -0
  105. package/dist/model/ListBlockedFriends200Response.js +2 -2
  106. package/dist/model/ListBlockedFriends200ResponseDataInner.js +6 -6
  107. package/dist/model/ListChatMessages200Response.js +2 -2
  108. package/dist/model/ListChatMessages200ResponseDataInner.js +2 -2
  109. package/dist/model/ListFriendRequests200Response.js +2 -2
  110. package/dist/model/ListFriendRequests200ResponseIncomingInner.js +2 -2
  111. package/dist/model/ListFriendRequests200ResponseIncomingInnerRequester.js +2 -2
  112. package/dist/model/ListFriendRequests200ResponseMeta.js +2 -2
  113. package/dist/model/ListFriends200Response.js +2 -2
  114. package/dist/model/ListFriends200ResponseDataInner.js +2 -2
  115. package/dist/model/ListFriends200ResponseMeta.js +2 -2
  116. package/dist/model/ListGroupMembers200Response.js +2 -2
  117. package/dist/model/ListJoinRequests200Response.js +2 -2
  118. package/dist/model/ListLeaderboardRecords200Response.js +2 -2
  119. package/dist/model/ListLeaderboards200Response.js +2 -2
  120. package/dist/model/ListLobbies200Response.js +2 -2
  121. package/dist/model/ListLobbies200ResponseDataInner.js +2 -2
  122. package/dist/model/ListMyGroups200Response.js +2 -2
  123. package/dist/model/ListMyGroups200ResponseDataInner.js +2 -2
  124. package/dist/model/ListPartyInvitations200ResponseInner.js +2 -2
  125. package/dist/model/ListRecordsAroundUser200Response.js +2 -2
  126. package/dist/model/ListSentInvitations200Response.js +2 -2
  127. package/dist/model/ListSentInvitations200ResponseDataInner.js +2 -2
  128. package/dist/model/LoginRequest.js +2 -2
  129. package/dist/model/MarkChatReadRequest.js +2 -2
  130. package/dist/model/MatchmakingCancel200Response.js +85 -0
  131. package/dist/model/MatchmakingJoin201Response.js +91 -0
  132. package/dist/model/MatchmakingJoin201ResponseData.js +186 -0
  133. package/dist/model/MatchmakingJoinRequest.js +101 -0
  134. package/dist/model/MatchmakingMyTicket200Response.js +91 -0
  135. package/dist/model/MatchmakingMyTicket200ResponseData.js +186 -0
  136. package/dist/model/MatchmakingStats200Response.js +91 -0
  137. package/dist/model/MatchmakingStats200ResponseData.js +118 -0
  138. package/dist/model/MatchmakingStats200ResponseDataQueuesInner.js +93 -0
  139. package/dist/model/MyAchievements200Response.js +2 -2
  140. package/dist/model/MyAchievements200ResponseDataInner.js +2 -2
  141. package/dist/model/NotifyGroup200Response.js +2 -2
  142. package/dist/model/NotifyGroupRequest.js +2 -2
  143. package/dist/model/OAuthSessionData.js +2 -2
  144. package/dist/model/OAuthSessionDataDetails.js +2 -2
  145. package/dist/model/OAuthSessionStatus.js +2 -2
  146. package/dist/model/OauthApiCallback200Response.js +2 -2
  147. package/dist/model/OauthApiCallbackRequest.js +2 -2
  148. package/dist/model/OauthCallbackApiAppleIosRequest.js +2 -2
  149. package/dist/model/OauthGoogleIdTokenRequest.js +2 -2
  150. package/dist/model/OauthRequest200Response.js +2 -2
  151. package/dist/model/OauthSessionStatus404Response.js +2 -2
  152. package/dist/model/PartyCreateLobbyRequest.js +2 -2
  153. package/dist/model/PartyJoinLobbyRequest.js +2 -2
  154. package/dist/model/PaymentsEntitlements401Response.js +2 -2
  155. package/dist/model/PaymentsSteamCheckoutRequest.js +2 -2
  156. package/dist/model/PaymentsSteamFinalizeRequest.js +2 -2
  157. package/dist/model/PaymentsStripeCheckoutRequest.js +2 -2
  158. package/dist/model/QuickJoinRequest.js +2 -2
  159. package/dist/model/RefreshToken200Response.js +2 -2
  160. package/dist/model/RefreshToken200ResponseData.js +2 -2
  161. package/dist/model/RefreshTokenRequest.js +2 -2
  162. package/dist/model/ResolveLeaderboardSlugs200Response.js +2 -2
  163. package/dist/model/ResolveLeaderboardSlugs200ResponseDataValue.js +2 -2
  164. package/dist/model/ResolveLeaderboardSlugsRequest.js +2 -2
  165. package/dist/model/SearchUsers200Response.js +2 -2
  166. package/dist/model/SearchUsers200ResponseDataInner.js +2 -2
  167. package/dist/model/SendChatMessageRequest.js +2 -2
  168. package/dist/model/SendNotificationRequest.js +2 -2
  169. package/dist/model/UpdateChatMessageRequest.js +2 -2
  170. package/dist/model/UpdateCurrentUserDisplayName400Response.js +2 -2
  171. package/dist/model/UpdateCurrentUserDisplayNameRequest.js +2 -2
  172. package/dist/model/UpdateCurrentUserPasswordRequest.js +2 -2
  173. package/dist/model/UpdateCurrentUserUsernameRequest.js +2 -2
  174. package/dist/model/UpdateGroupRequest.js +2 -2
  175. package/dist/model/UpdateLobbyRequest.js +2 -2
  176. package/dist/model/UpdatePartyRequest.js +2 -2
  177. package/package.json +2 -2
  178. package/dist/model/ListBlockedFriends200ResponseDataInnerRequester.js +0 -113
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+ var _ApiClient = _interopRequireDefault(require("../ApiClient"));
8
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
9
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
10
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
11
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
12
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
13
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
14
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /**
15
+ * Game Server API
16
+ * API for the Gamend Game Server. Provides HTTP REST API, real-time WebSocket channels, and WebRTC DataChannels for low-latency game data. Features authentication, users, lobbies, groups, parties, friends, chat, notifications, achievements, leaderboards, tournaments, matchmaking, payments, server scripting, and admin portal. ## **1. Authentication** This API uses JWT (JSON Web Tokens) with access and refresh tokens: ### **1.1 Getting Tokens** - **Email/Password**: POST to `/api/v1/login` with email and password - **Device (SDK)**: POST to `/api/v1/login` with a `device_id` string (creates/returns a device user) - **Discord OAuth**: Use `/api/v1/auth/discord` flow - **Google OAuth**: Use `/api/v1/auth/google` flow - **Facebook OAuth**: Use `/api/v1/auth/facebook` flow - **Apple Sign In**: Use `/auth/apple` browser flow or apple sdk flow - **Steam (OpenID)**: Use `/api/v1/auth/steam` flow Both methods return: - `access_token` - Short-lived (15 min), use for API requests - `refresh_token` - Long-lived (30 days), use to get new access tokens ### **1.2 Using Tokens** Include the access token in the Authorization header: ``` Authorization: Bearer <access_token> ``` ### **1.3 Refreshing Tokens** When your access token expires, use POST `/api/v1/refresh` with your refresh token to get a new access token. ## **2. Users** Users endpoints cover the user lifecycle and profile features. Key highlights: - **Registration and login** (email/password, device token for SDKs, and OAuth providers) - **Profile metadata** (JSON blob per user) and editable profile fields - **Account lifecycle**: password reset, email confirmation, and account deletion - **Sessions & tokens**: both browser sessions and JWT-based API tokens are supported ## **3. Friends** The Friends domain offers lightweight social features: - **Friend requests** (send / accept / reject / block flows) - **Friend listing & pagination**, with basic privacy controls - **Domain helpers** to manage and query friend relationships from API or UI contexts ## **4. Lobbies** Lobbies provide matchmaking / room management primitives. Highlights: - **Create / list / update / delete** lobbies with rich metadata (mode, region, tags) - **Host-managed or hostless** modes (hostless allowed internally, not creatable via public API) - **Membership management**: join, leave, kick users, and automatic host transfer - **Controls & protection**: max users, hidden/locked states, and optional password protection - **Hidden lobbies** are excluded from public listings; public listing endpoints are paginated ## **5. Notifications** Persistent user-to-user notifications that survive across sessions: - **Send notifications** to accepted friends with a title, optional content, and optional metadata - **List own notifications** with pagination (ordered oldest-first) - **Delete notifications** by ID (single or batch) - **Real-time delivery** via the user WebSocket channel (`\"notification\"` events) - **Offline delivery**: undeleted notifications are replayed on WebSocket reconnect ## **6. Groups** Groups provide persistent community management for players: - **Three group types**: `public` (anyone joins directly), `private` (users request to join, admins approve), `hidden` (invite-only, never listed) - **Membership roles**: `admin` and `member`, with promote/demote capabilities - **Join requests**: for private groups, users submit requests that admins approve or reject - **Invitations**: admins can invite users directly (blocked users are rejected) - **CRUD operations**: create, update, delete groups with metadata support - **Group chat**: integrated via the Chat API with `chat_type: \"group\"` ## **7. Parties** Ephemeral groups of users for short-lived sessions (e.g., matchmaking squads): - **Invite-only joining**: the party leader sends invites by user ID to friends or shared-group members - **Invite flow**: `POST /parties/invite` → recipient accepts via `POST /parties/invite/accept` or declines via `POST /parties/invite/decline`; leader can cancel via `POST /parties/invite/cancel` - **Invite visibility**: leader can list sent invites (`GET /parties/invitations/sent`); recipient can list received invites (`GET /parties/invitations`) - **Connection requirement**: invites can only be sent to users who are friends or share at least one group with the leader - **One party at a time**: a user can only be in one party; accepting an invite while already in a party is rejected - **Leader management**: the creator is the leader; leadership can be transferred - **Lobby integration**: parties can create or join lobbies as a group - **Party chat**: integrated via the Chat API with `chat_type: \"party\"` - **Real-time events** via the party WebSocket channel ## **8. Chat** Real-time messaging across multiple conversation types: - **Chat types**: `lobby` (within a lobby), `group` (within a group), `party` (within a party), `friend` (DMs between friends) - **Send messages** with content, optional metadata, and automatic access validation - **List messages** with pagination (newest first) - **Read tracking**: mark messages as read and get unread counts per conversation - **Real-time delivery** via PubSub and WebSocket channels - **Moderation hooks**: `before_chat_message` pipeline hook for filtering/blocking ## **9. Leaderboards** Server-managed ranked scoreboards: - **Multiple leaderboards**: create named leaderboards with configurable sort order - **Score submission**: submit scores with optional metadata - **Rankings**: retrieve paginated rankings with user details - **Reset support**: leaderboards can be reset periodically ## **10. Key-Value Storage** Per-user persistent key-value storage for game state, preferences, and settings: - **Get/set/delete** key-value pairs scoped to the authenticated user - **List keys** with optional prefix filtering - **Metadata support**: values can include arbitrary JSON metadata ## **11. Achievements** Track player accomplishments with progress-based or instant-unlock achievements: - **Achievement definitions**: admin-created with slug, title, description, icon, sort order, and optional progress target - **Progress tracking**: increment progress toward a target; auto-unlocks when progress reaches the target - **Instant unlock**: directly unlock achievements without progress tracking - **Hidden achievements**: details obscured (\"???\") until unlocked by the user - **Public listings**: paginated, optionally filtered; authenticated users see their own progress - **Admin management**: create, update, delete, grant, revoke, unlock, and increment achievements ## **12. Tournaments** Single-elimination bracket tournaments, server-structured and game-judged: - **Registration window → seeded draw → timed rounds → champions**; recurring tournaments (cron) create one occurrence per cycle sharing a slug; a nil starts_at keeps registration open until an admin draws manually - **Join/leave** as an entry leader (`POST`/`DELETE /tournaments/:id/join`); team composition is game policy - **Browse**: list/filter tournaments, standings, full bracket view, and the caller's current match (`GET /tournaments/:id/my-match`) - **Match verdicts are server-side** (game hooks) — no public resolve endpoint; clients get `tournament_match_ready` / `tournament_match_resolved` / `tournament_updated` / `tournament_finished` on the user channel - **Admin management** over HTTP: create/update/delete, cancel, draw now, finish, and force match verdicts under `/api/v1/admin/tournaments` ## **13. Matchmaking** Ticket-based queueing that turns waiting players into hidden, locked lobbies: - **Join over HTTP** (`POST /matchmaking/tickets` with a `match_params` string map); only tickets with identical params match together — encode mode/map/skill band as parameter values - **A match forms** when a group reaches `max_players`, or has at least `min_players` and the oldest ticket outwaited the timeout; the server creates a hidden lobby, seats everyone and locks it - **The result is a push, not a poll**: matched players receive `matchmaking_found` (`lobby_id`, `match_params`) on their user channel; disconnecting cancels your tickets - **Inspect**: `GET /matchmaking/tickets/me` for your ticket, `GET /matchmaking/stats` for queue depths - **Admin management** over HTTP: list/filter tickets, force-cancel, and stats under `/api/v1/admin/matchmaking` ## **14. Real-time: WebSocket Channels** The server provides real-time communication via Phoenix WebSocket channels. Connect to the WebSocket endpoint and join topic-based channels for live updates. ### **14.1 Connection** Connect to `wss://your-server.com/socket` with your JWT token as a parameter: ``` const socket = new Socket(\"wss://your-server.com/socket\", { params: { token: \"<access_token>\" } }) socket.connect() ``` ### **14.2 Available Channels** - **User channel** (`user:<user_id>`): notifications, friend events, achievement unlocks, party/group invites, tournament events, KV subscriptions - **Lobby channel** (`lobby:<lobby_id>`): lobby member joins/leaves, lobby updates, lobby chat - **Lobbies channel** (`lobbies`): global lobby list changes (created, updated, deleted) - **Group channel** (`group:<group_id>`): group member changes, group updates, group chat - **Groups channel** (`groups`): global group list changes - **Party channel** (`party:<party_id>`): party member changes, party updates, party chat ### **14.3 JS SDK Helper** The `GameRealtime` class (included in this SDK) wraps Phoenix.Socket with convenient channel helpers: ```javascript import { GameRealtime } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', accessToken) const userChannel = realtime.joinUserChannel(userId) userChannel.on('notification', payload => console.log(payload)) ``` Requires the `phoenix` npm package as a peer dependency: `npm install phoenix` ## **15. Real-time: WebRTC DataChannels** For low-latency game data, the server supports WebRTC DataChannels alongside WebSocket. The server acts as a WebRTC peer (not P2P between clients). ### **15.1 How It Works** 1. Client connects via WebSocket and joins the **User channel** 2. Client sends an SDP offer over the channel (`webrtc:offer` event) 3. Server responds with an SDP answer (`webrtc:answer` event) 4. ICE candidates are exchanged (`webrtc:ice` events) 5. Once connected, named DataChannels carry game data at low latency ### **15.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **15.3 JS SDK Helper** The `GameWebRTC` class (included in this SDK, browser-only) handles signaling automatically: ```javascript import { GameRealtime, GameWebRTC } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', token) const userChannel = realtime.joinUserChannel(userId) const webrtc = new GameWebRTC(userChannel, { onData: (label, data) => console.log(label, data) }) await webrtc.connect() webrtc.send('events', JSON.stringify({ type: 'move', x: 10, y: 20 })) ```
17
+ *
18
+ * The version of the OpenAPI document: 1.0.1040
19
+ *
20
+ *
21
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
22
+ * https://openapi-generator.tech
23
+ * Do not edit the class manually.
24
+ *
25
+ */
26
+ /**
27
+ * The MatchmakingMyTicket200ResponseData model module.
28
+ * @module model/MatchmakingMyTicket200ResponseData
29
+ * @version 1.0.0
30
+ */
31
+ var MatchmakingMyTicket200ResponseData = /*#__PURE__*/function () {
32
+ /**
33
+ * Constructs a new <code>MatchmakingMyTicket200ResponseData</code>.
34
+ * @alias module:model/MatchmakingMyTicket200ResponseData
35
+ */
36
+ function MatchmakingMyTicket200ResponseData() {
37
+ _classCallCheck(this, MatchmakingMyTicket200ResponseData);
38
+ MatchmakingMyTicket200ResponseData.initialize(this);
39
+ }
40
+
41
+ /**
42
+ * Initializes the fields of this object.
43
+ * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
44
+ * Only for internal use.
45
+ */
46
+ return _createClass(MatchmakingMyTicket200ResponseData, null, [{
47
+ key: "initialize",
48
+ value: function initialize(obj) {}
49
+
50
+ /**
51
+ * Constructs a <code>MatchmakingMyTicket200ResponseData</code> from a plain JavaScript object, optionally creating a new instance.
52
+ * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
53
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
54
+ * @param {module:model/MatchmakingMyTicket200ResponseData} obj Optional instance to populate.
55
+ * @return {module:model/MatchmakingMyTicket200ResponseData} The populated <code>MatchmakingMyTicket200ResponseData</code> instance.
56
+ */
57
+ }, {
58
+ key: "constructFromObject",
59
+ value: function constructFromObject(data, obj) {
60
+ if (data) {
61
+ obj = obj || new MatchmakingMyTicket200ResponseData();
62
+ if (data.hasOwnProperty('id')) {
63
+ obj['id'] = _ApiClient["default"].convertToType(data['id'], 'String');
64
+ }
65
+ if (data.hasOwnProperty('match_id')) {
66
+ obj['match_id'] = _ApiClient["default"].convertToType(data['match_id'], 'String');
67
+ }
68
+ if (data.hasOwnProperty('match_params')) {
69
+ obj['match_params'] = _ApiClient["default"].convertToType(data['match_params'], Object);
70
+ }
71
+ if (data.hasOwnProperty('matched_at')) {
72
+ obj['matched_at'] = _ApiClient["default"].convertToType(data['matched_at'], 'Date');
73
+ }
74
+ if (data.hasOwnProperty('max_players')) {
75
+ obj['max_players'] = _ApiClient["default"].convertToType(data['max_players'], 'Number');
76
+ }
77
+ if (data.hasOwnProperty('min_players')) {
78
+ obj['min_players'] = _ApiClient["default"].convertToType(data['min_players'], 'Number');
79
+ }
80
+ if (data.hasOwnProperty('queued_at')) {
81
+ obj['queued_at'] = _ApiClient["default"].convertToType(data['queued_at'], 'Date');
82
+ }
83
+ if (data.hasOwnProperty('status')) {
84
+ obj['status'] = _ApiClient["default"].convertToType(data['status'], 'String');
85
+ }
86
+ if (data.hasOwnProperty('timeout_ms')) {
87
+ obj['timeout_ms'] = _ApiClient["default"].convertToType(data['timeout_ms'], 'Number');
88
+ }
89
+ }
90
+ return obj;
91
+ }
92
+
93
+ /**
94
+ * Validates the JSON data with respect to <code>MatchmakingMyTicket200ResponseData</code>.
95
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
96
+ * @return {boolean} to indicate whether the JSON data is valid with respect to <code>MatchmakingMyTicket200ResponseData</code>.
97
+ */
98
+ }, {
99
+ key: "validateJSON",
100
+ value: function validateJSON(data) {
101
+ // ensure the json data is a string
102
+ if (data['id'] && !(typeof data['id'] === 'string' || data['id'] instanceof String)) {
103
+ throw new Error("Expected the field `id` to be a primitive type in the JSON string but got " + data['id']);
104
+ }
105
+ // ensure the json data is a string
106
+ if (data['match_id'] && !(typeof data['match_id'] === 'string' || data['match_id'] instanceof String)) {
107
+ throw new Error("Expected the field `match_id` to be a primitive type in the JSON string but got " + data['match_id']);
108
+ }
109
+ // ensure the json data is a string
110
+ if (data['status'] && !(typeof data['status'] === 'string' || data['status'] instanceof String)) {
111
+ throw new Error("Expected the field `status` to be a primitive type in the JSON string but got " + data['status']);
112
+ }
113
+ return true;
114
+ }
115
+ }]);
116
+ }();
117
+ /**
118
+ * @member {String} id
119
+ */
120
+ MatchmakingMyTicket200ResponseData.prototype['id'] = undefined;
121
+
122
+ /**
123
+ * Lobby the ticket was matched into
124
+ * @member {String} match_id
125
+ */
126
+ MatchmakingMyTicket200ResponseData.prototype['match_id'] = undefined;
127
+
128
+ /**
129
+ * String key/value pairs; only identical params match together
130
+ * @member {Object} match_params
131
+ */
132
+ MatchmakingMyTicket200ResponseData.prototype['match_params'] = undefined;
133
+
134
+ /**
135
+ * @member {Date} matched_at
136
+ */
137
+ MatchmakingMyTicket200ResponseData.prototype['matched_at'] = undefined;
138
+
139
+ /**
140
+ * @member {Number} max_players
141
+ */
142
+ MatchmakingMyTicket200ResponseData.prototype['max_players'] = undefined;
143
+
144
+ /**
145
+ * @member {Number} min_players
146
+ */
147
+ MatchmakingMyTicket200ResponseData.prototype['min_players'] = undefined;
148
+
149
+ /**
150
+ * @member {Date} queued_at
151
+ */
152
+ MatchmakingMyTicket200ResponseData.prototype['queued_at'] = undefined;
153
+
154
+ /**
155
+ * @member {module:model/MatchmakingMyTicket200ResponseData.StatusEnum} status
156
+ */
157
+ MatchmakingMyTicket200ResponseData.prototype['status'] = undefined;
158
+
159
+ /**
160
+ * @member {Number} timeout_ms
161
+ */
162
+ MatchmakingMyTicket200ResponseData.prototype['timeout_ms'] = undefined;
163
+
164
+ /**
165
+ * Allowed values for the <code>status</code> property.
166
+ * @enum {String}
167
+ * @readonly
168
+ */
169
+ MatchmakingMyTicket200ResponseData['StatusEnum'] = {
170
+ /**
171
+ * value: "queued"
172
+ * @const
173
+ */
174
+ "queued": "queued",
175
+ /**
176
+ * value: "matched"
177
+ * @const
178
+ */
179
+ "matched": "matched",
180
+ /**
181
+ * value: "cancelled"
182
+ * @const
183
+ */
184
+ "cancelled": "cancelled"
185
+ };
186
+ var _default = exports["default"] = MatchmakingMyTicket200ResponseData;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+ var _ApiClient = _interopRequireDefault(require("../ApiClient"));
8
+ var _MatchmakingStats200ResponseData = _interopRequireDefault(require("./MatchmakingStats200ResponseData"));
9
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
10
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
11
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
12
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
13
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
14
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
15
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /**
16
+ * Game Server API
17
+ * API for the Gamend Game Server. Provides HTTP REST API, real-time WebSocket channels, and WebRTC DataChannels for low-latency game data. Features authentication, users, lobbies, groups, parties, friends, chat, notifications, achievements, leaderboards, tournaments, matchmaking, payments, server scripting, and admin portal. ## **1. Authentication** This API uses JWT (JSON Web Tokens) with access and refresh tokens: ### **1.1 Getting Tokens** - **Email/Password**: POST to `/api/v1/login` with email and password - **Device (SDK)**: POST to `/api/v1/login` with a `device_id` string (creates/returns a device user) - **Discord OAuth**: Use `/api/v1/auth/discord` flow - **Google OAuth**: Use `/api/v1/auth/google` flow - **Facebook OAuth**: Use `/api/v1/auth/facebook` flow - **Apple Sign In**: Use `/auth/apple` browser flow or apple sdk flow - **Steam (OpenID)**: Use `/api/v1/auth/steam` flow Both methods return: - `access_token` - Short-lived (15 min), use for API requests - `refresh_token` - Long-lived (30 days), use to get new access tokens ### **1.2 Using Tokens** Include the access token in the Authorization header: ``` Authorization: Bearer <access_token> ``` ### **1.3 Refreshing Tokens** When your access token expires, use POST `/api/v1/refresh` with your refresh token to get a new access token. ## **2. Users** Users endpoints cover the user lifecycle and profile features. Key highlights: - **Registration and login** (email/password, device token for SDKs, and OAuth providers) - **Profile metadata** (JSON blob per user) and editable profile fields - **Account lifecycle**: password reset, email confirmation, and account deletion - **Sessions & tokens**: both browser sessions and JWT-based API tokens are supported ## **3. Friends** The Friends domain offers lightweight social features: - **Friend requests** (send / accept / reject / block flows) - **Friend listing & pagination**, with basic privacy controls - **Domain helpers** to manage and query friend relationships from API or UI contexts ## **4. Lobbies** Lobbies provide matchmaking / room management primitives. Highlights: - **Create / list / update / delete** lobbies with rich metadata (mode, region, tags) - **Host-managed or hostless** modes (hostless allowed internally, not creatable via public API) - **Membership management**: join, leave, kick users, and automatic host transfer - **Controls & protection**: max users, hidden/locked states, and optional password protection - **Hidden lobbies** are excluded from public listings; public listing endpoints are paginated ## **5. Notifications** Persistent user-to-user notifications that survive across sessions: - **Send notifications** to accepted friends with a title, optional content, and optional metadata - **List own notifications** with pagination (ordered oldest-first) - **Delete notifications** by ID (single or batch) - **Real-time delivery** via the user WebSocket channel (`\"notification\"` events) - **Offline delivery**: undeleted notifications are replayed on WebSocket reconnect ## **6. Groups** Groups provide persistent community management for players: - **Three group types**: `public` (anyone joins directly), `private` (users request to join, admins approve), `hidden` (invite-only, never listed) - **Membership roles**: `admin` and `member`, with promote/demote capabilities - **Join requests**: for private groups, users submit requests that admins approve or reject - **Invitations**: admins can invite users directly (blocked users are rejected) - **CRUD operations**: create, update, delete groups with metadata support - **Group chat**: integrated via the Chat API with `chat_type: \"group\"` ## **7. Parties** Ephemeral groups of users for short-lived sessions (e.g., matchmaking squads): - **Invite-only joining**: the party leader sends invites by user ID to friends or shared-group members - **Invite flow**: `POST /parties/invite` → recipient accepts via `POST /parties/invite/accept` or declines via `POST /parties/invite/decline`; leader can cancel via `POST /parties/invite/cancel` - **Invite visibility**: leader can list sent invites (`GET /parties/invitations/sent`); recipient can list received invites (`GET /parties/invitations`) - **Connection requirement**: invites can only be sent to users who are friends or share at least one group with the leader - **One party at a time**: a user can only be in one party; accepting an invite while already in a party is rejected - **Leader management**: the creator is the leader; leadership can be transferred - **Lobby integration**: parties can create or join lobbies as a group - **Party chat**: integrated via the Chat API with `chat_type: \"party\"` - **Real-time events** via the party WebSocket channel ## **8. Chat** Real-time messaging across multiple conversation types: - **Chat types**: `lobby` (within a lobby), `group` (within a group), `party` (within a party), `friend` (DMs between friends) - **Send messages** with content, optional metadata, and automatic access validation - **List messages** with pagination (newest first) - **Read tracking**: mark messages as read and get unread counts per conversation - **Real-time delivery** via PubSub and WebSocket channels - **Moderation hooks**: `before_chat_message` pipeline hook for filtering/blocking ## **9. Leaderboards** Server-managed ranked scoreboards: - **Multiple leaderboards**: create named leaderboards with configurable sort order - **Score submission**: submit scores with optional metadata - **Rankings**: retrieve paginated rankings with user details - **Reset support**: leaderboards can be reset periodically ## **10. Key-Value Storage** Per-user persistent key-value storage for game state, preferences, and settings: - **Get/set/delete** key-value pairs scoped to the authenticated user - **List keys** with optional prefix filtering - **Metadata support**: values can include arbitrary JSON metadata ## **11. Achievements** Track player accomplishments with progress-based or instant-unlock achievements: - **Achievement definitions**: admin-created with slug, title, description, icon, sort order, and optional progress target - **Progress tracking**: increment progress toward a target; auto-unlocks when progress reaches the target - **Instant unlock**: directly unlock achievements without progress tracking - **Hidden achievements**: details obscured (\"???\") until unlocked by the user - **Public listings**: paginated, optionally filtered; authenticated users see their own progress - **Admin management**: create, update, delete, grant, revoke, unlock, and increment achievements ## **12. Tournaments** Single-elimination bracket tournaments, server-structured and game-judged: - **Registration window → seeded draw → timed rounds → champions**; recurring tournaments (cron) create one occurrence per cycle sharing a slug; a nil starts_at keeps registration open until an admin draws manually - **Join/leave** as an entry leader (`POST`/`DELETE /tournaments/:id/join`); team composition is game policy - **Browse**: list/filter tournaments, standings, full bracket view, and the caller's current match (`GET /tournaments/:id/my-match`) - **Match verdicts are server-side** (game hooks) — no public resolve endpoint; clients get `tournament_match_ready` / `tournament_match_resolved` / `tournament_updated` / `tournament_finished` on the user channel - **Admin management** over HTTP: create/update/delete, cancel, draw now, finish, and force match verdicts under `/api/v1/admin/tournaments` ## **13. Matchmaking** Ticket-based queueing that turns waiting players into hidden, locked lobbies: - **Join over HTTP** (`POST /matchmaking/tickets` with a `match_params` string map); only tickets with identical params match together — encode mode/map/skill band as parameter values - **A match forms** when a group reaches `max_players`, or has at least `min_players` and the oldest ticket outwaited the timeout; the server creates a hidden lobby, seats everyone and locks it - **The result is a push, not a poll**: matched players receive `matchmaking_found` (`lobby_id`, `match_params`) on their user channel; disconnecting cancels your tickets - **Inspect**: `GET /matchmaking/tickets/me` for your ticket, `GET /matchmaking/stats` for queue depths - **Admin management** over HTTP: list/filter tickets, force-cancel, and stats under `/api/v1/admin/matchmaking` ## **14. Real-time: WebSocket Channels** The server provides real-time communication via Phoenix WebSocket channels. Connect to the WebSocket endpoint and join topic-based channels for live updates. ### **14.1 Connection** Connect to `wss://your-server.com/socket` with your JWT token as a parameter: ``` const socket = new Socket(\"wss://your-server.com/socket\", { params: { token: \"<access_token>\" } }) socket.connect() ``` ### **14.2 Available Channels** - **User channel** (`user:<user_id>`): notifications, friend events, achievement unlocks, party/group invites, tournament events, KV subscriptions - **Lobby channel** (`lobby:<lobby_id>`): lobby member joins/leaves, lobby updates, lobby chat - **Lobbies channel** (`lobbies`): global lobby list changes (created, updated, deleted) - **Group channel** (`group:<group_id>`): group member changes, group updates, group chat - **Groups channel** (`groups`): global group list changes - **Party channel** (`party:<party_id>`): party member changes, party updates, party chat ### **14.3 JS SDK Helper** The `GameRealtime` class (included in this SDK) wraps Phoenix.Socket with convenient channel helpers: ```javascript import { GameRealtime } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', accessToken) const userChannel = realtime.joinUserChannel(userId) userChannel.on('notification', payload => console.log(payload)) ``` Requires the `phoenix` npm package as a peer dependency: `npm install phoenix` ## **15. Real-time: WebRTC DataChannels** For low-latency game data, the server supports WebRTC DataChannels alongside WebSocket. The server acts as a WebRTC peer (not P2P between clients). ### **15.1 How It Works** 1. Client connects via WebSocket and joins the **User channel** 2. Client sends an SDP offer over the channel (`webrtc:offer` event) 3. Server responds with an SDP answer (`webrtc:answer` event) 4. ICE candidates are exchanged (`webrtc:ice` events) 5. Once connected, named DataChannels carry game data at low latency ### **15.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **15.3 JS SDK Helper** The `GameWebRTC` class (included in this SDK, browser-only) handles signaling automatically: ```javascript import { GameRealtime, GameWebRTC } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', token) const userChannel = realtime.joinUserChannel(userId) const webrtc = new GameWebRTC(userChannel, { onData: (label, data) => console.log(label, data) }) await webrtc.connect() webrtc.send('events', JSON.stringify({ type: 'move', x: 10, y: 20 })) ```
18
+ *
19
+ * The version of the OpenAPI document: 1.0.1040
20
+ *
21
+ *
22
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
23
+ * https://openapi-generator.tech
24
+ * Do not edit the class manually.
25
+ *
26
+ */
27
+ /**
28
+ * The MatchmakingStats200Response model module.
29
+ * @module model/MatchmakingStats200Response
30
+ * @version 1.0.0
31
+ */
32
+ var MatchmakingStats200Response = /*#__PURE__*/function () {
33
+ /**
34
+ * Constructs a new <code>MatchmakingStats200Response</code>.
35
+ * @alias module:model/MatchmakingStats200Response
36
+ */
37
+ function MatchmakingStats200Response() {
38
+ _classCallCheck(this, MatchmakingStats200Response);
39
+ MatchmakingStats200Response.initialize(this);
40
+ }
41
+
42
+ /**
43
+ * Initializes the fields of this object.
44
+ * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
45
+ * Only for internal use.
46
+ */
47
+ return _createClass(MatchmakingStats200Response, null, [{
48
+ key: "initialize",
49
+ value: function initialize(obj) {}
50
+
51
+ /**
52
+ * Constructs a <code>MatchmakingStats200Response</code> from a plain JavaScript object, optionally creating a new instance.
53
+ * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
54
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
55
+ * @param {module:model/MatchmakingStats200Response} obj Optional instance to populate.
56
+ * @return {module:model/MatchmakingStats200Response} The populated <code>MatchmakingStats200Response</code> instance.
57
+ */
58
+ }, {
59
+ key: "constructFromObject",
60
+ value: function constructFromObject(data, obj) {
61
+ if (data) {
62
+ obj = obj || new MatchmakingStats200Response();
63
+ if (data.hasOwnProperty('data')) {
64
+ obj['data'] = _MatchmakingStats200ResponseData["default"].constructFromObject(data['data']);
65
+ }
66
+ }
67
+ return obj;
68
+ }
69
+
70
+ /**
71
+ * Validates the JSON data with respect to <code>MatchmakingStats200Response</code>.
72
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
73
+ * @return {boolean} to indicate whether the JSON data is valid with respect to <code>MatchmakingStats200Response</code>.
74
+ */
75
+ }, {
76
+ key: "validateJSON",
77
+ value: function validateJSON(data) {
78
+ // validate the optional field `data`
79
+ if (data['data']) {
80
+ // data not null
81
+ _MatchmakingStats200ResponseData["default"].validateJSON(data['data']);
82
+ }
83
+ return true;
84
+ }
85
+ }]);
86
+ }();
87
+ /**
88
+ * @member {module:model/MatchmakingStats200ResponseData} data
89
+ */
90
+ MatchmakingStats200Response.prototype['data'] = undefined;
91
+ var _default = exports["default"] = MatchmakingStats200Response;
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+ var _ApiClient = _interopRequireDefault(require("../ApiClient"));
8
+ var _MatchmakingStats200ResponseDataQueuesInner = _interopRequireDefault(require("./MatchmakingStats200ResponseDataQueuesInner"));
9
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
10
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
11
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
12
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
13
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
14
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
15
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
16
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
17
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
18
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /**
19
+ * Game Server API
20
+ * API for the Gamend Game Server. Provides HTTP REST API, real-time WebSocket channels, and WebRTC DataChannels for low-latency game data. Features authentication, users, lobbies, groups, parties, friends, chat, notifications, achievements, leaderboards, tournaments, matchmaking, payments, server scripting, and admin portal. ## **1. Authentication** This API uses JWT (JSON Web Tokens) with access and refresh tokens: ### **1.1 Getting Tokens** - **Email/Password**: POST to `/api/v1/login` with email and password - **Device (SDK)**: POST to `/api/v1/login` with a `device_id` string (creates/returns a device user) - **Discord OAuth**: Use `/api/v1/auth/discord` flow - **Google OAuth**: Use `/api/v1/auth/google` flow - **Facebook OAuth**: Use `/api/v1/auth/facebook` flow - **Apple Sign In**: Use `/auth/apple` browser flow or apple sdk flow - **Steam (OpenID)**: Use `/api/v1/auth/steam` flow Both methods return: - `access_token` - Short-lived (15 min), use for API requests - `refresh_token` - Long-lived (30 days), use to get new access tokens ### **1.2 Using Tokens** Include the access token in the Authorization header: ``` Authorization: Bearer <access_token> ``` ### **1.3 Refreshing Tokens** When your access token expires, use POST `/api/v1/refresh` with your refresh token to get a new access token. ## **2. Users** Users endpoints cover the user lifecycle and profile features. Key highlights: - **Registration and login** (email/password, device token for SDKs, and OAuth providers) - **Profile metadata** (JSON blob per user) and editable profile fields - **Account lifecycle**: password reset, email confirmation, and account deletion - **Sessions & tokens**: both browser sessions and JWT-based API tokens are supported ## **3. Friends** The Friends domain offers lightweight social features: - **Friend requests** (send / accept / reject / block flows) - **Friend listing & pagination**, with basic privacy controls - **Domain helpers** to manage and query friend relationships from API or UI contexts ## **4. Lobbies** Lobbies provide matchmaking / room management primitives. Highlights: - **Create / list / update / delete** lobbies with rich metadata (mode, region, tags) - **Host-managed or hostless** modes (hostless allowed internally, not creatable via public API) - **Membership management**: join, leave, kick users, and automatic host transfer - **Controls & protection**: max users, hidden/locked states, and optional password protection - **Hidden lobbies** are excluded from public listings; public listing endpoints are paginated ## **5. Notifications** Persistent user-to-user notifications that survive across sessions: - **Send notifications** to accepted friends with a title, optional content, and optional metadata - **List own notifications** with pagination (ordered oldest-first) - **Delete notifications** by ID (single or batch) - **Real-time delivery** via the user WebSocket channel (`\"notification\"` events) - **Offline delivery**: undeleted notifications are replayed on WebSocket reconnect ## **6. Groups** Groups provide persistent community management for players: - **Three group types**: `public` (anyone joins directly), `private` (users request to join, admins approve), `hidden` (invite-only, never listed) - **Membership roles**: `admin` and `member`, with promote/demote capabilities - **Join requests**: for private groups, users submit requests that admins approve or reject - **Invitations**: admins can invite users directly (blocked users are rejected) - **CRUD operations**: create, update, delete groups with metadata support - **Group chat**: integrated via the Chat API with `chat_type: \"group\"` ## **7. Parties** Ephemeral groups of users for short-lived sessions (e.g., matchmaking squads): - **Invite-only joining**: the party leader sends invites by user ID to friends or shared-group members - **Invite flow**: `POST /parties/invite` → recipient accepts via `POST /parties/invite/accept` or declines via `POST /parties/invite/decline`; leader can cancel via `POST /parties/invite/cancel` - **Invite visibility**: leader can list sent invites (`GET /parties/invitations/sent`); recipient can list received invites (`GET /parties/invitations`) - **Connection requirement**: invites can only be sent to users who are friends or share at least one group with the leader - **One party at a time**: a user can only be in one party; accepting an invite while already in a party is rejected - **Leader management**: the creator is the leader; leadership can be transferred - **Lobby integration**: parties can create or join lobbies as a group - **Party chat**: integrated via the Chat API with `chat_type: \"party\"` - **Real-time events** via the party WebSocket channel ## **8. Chat** Real-time messaging across multiple conversation types: - **Chat types**: `lobby` (within a lobby), `group` (within a group), `party` (within a party), `friend` (DMs between friends) - **Send messages** with content, optional metadata, and automatic access validation - **List messages** with pagination (newest first) - **Read tracking**: mark messages as read and get unread counts per conversation - **Real-time delivery** via PubSub and WebSocket channels - **Moderation hooks**: `before_chat_message` pipeline hook for filtering/blocking ## **9. Leaderboards** Server-managed ranked scoreboards: - **Multiple leaderboards**: create named leaderboards with configurable sort order - **Score submission**: submit scores with optional metadata - **Rankings**: retrieve paginated rankings with user details - **Reset support**: leaderboards can be reset periodically ## **10. Key-Value Storage** Per-user persistent key-value storage for game state, preferences, and settings: - **Get/set/delete** key-value pairs scoped to the authenticated user - **List keys** with optional prefix filtering - **Metadata support**: values can include arbitrary JSON metadata ## **11. Achievements** Track player accomplishments with progress-based or instant-unlock achievements: - **Achievement definitions**: admin-created with slug, title, description, icon, sort order, and optional progress target - **Progress tracking**: increment progress toward a target; auto-unlocks when progress reaches the target - **Instant unlock**: directly unlock achievements without progress tracking - **Hidden achievements**: details obscured (\"???\") until unlocked by the user - **Public listings**: paginated, optionally filtered; authenticated users see their own progress - **Admin management**: create, update, delete, grant, revoke, unlock, and increment achievements ## **12. Tournaments** Single-elimination bracket tournaments, server-structured and game-judged: - **Registration window → seeded draw → timed rounds → champions**; recurring tournaments (cron) create one occurrence per cycle sharing a slug; a nil starts_at keeps registration open until an admin draws manually - **Join/leave** as an entry leader (`POST`/`DELETE /tournaments/:id/join`); team composition is game policy - **Browse**: list/filter tournaments, standings, full bracket view, and the caller's current match (`GET /tournaments/:id/my-match`) - **Match verdicts are server-side** (game hooks) — no public resolve endpoint; clients get `tournament_match_ready` / `tournament_match_resolved` / `tournament_updated` / `tournament_finished` on the user channel - **Admin management** over HTTP: create/update/delete, cancel, draw now, finish, and force match verdicts under `/api/v1/admin/tournaments` ## **13. Matchmaking** Ticket-based queueing that turns waiting players into hidden, locked lobbies: - **Join over HTTP** (`POST /matchmaking/tickets` with a `match_params` string map); only tickets with identical params match together — encode mode/map/skill band as parameter values - **A match forms** when a group reaches `max_players`, or has at least `min_players` and the oldest ticket outwaited the timeout; the server creates a hidden lobby, seats everyone and locks it - **The result is a push, not a poll**: matched players receive `matchmaking_found` (`lobby_id`, `match_params`) on their user channel; disconnecting cancels your tickets - **Inspect**: `GET /matchmaking/tickets/me` for your ticket, `GET /matchmaking/stats` for queue depths - **Admin management** over HTTP: list/filter tickets, force-cancel, and stats under `/api/v1/admin/matchmaking` ## **14. Real-time: WebSocket Channels** The server provides real-time communication via Phoenix WebSocket channels. Connect to the WebSocket endpoint and join topic-based channels for live updates. ### **14.1 Connection** Connect to `wss://your-server.com/socket` with your JWT token as a parameter: ``` const socket = new Socket(\"wss://your-server.com/socket\", { params: { token: \"<access_token>\" } }) socket.connect() ``` ### **14.2 Available Channels** - **User channel** (`user:<user_id>`): notifications, friend events, achievement unlocks, party/group invites, tournament events, KV subscriptions - **Lobby channel** (`lobby:<lobby_id>`): lobby member joins/leaves, lobby updates, lobby chat - **Lobbies channel** (`lobbies`): global lobby list changes (created, updated, deleted) - **Group channel** (`group:<group_id>`): group member changes, group updates, group chat - **Groups channel** (`groups`): global group list changes - **Party channel** (`party:<party_id>`): party member changes, party updates, party chat ### **14.3 JS SDK Helper** The `GameRealtime` class (included in this SDK) wraps Phoenix.Socket with convenient channel helpers: ```javascript import { GameRealtime } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', accessToken) const userChannel = realtime.joinUserChannel(userId) userChannel.on('notification', payload => console.log(payload)) ``` Requires the `phoenix` npm package as a peer dependency: `npm install phoenix` ## **15. Real-time: WebRTC DataChannels** For low-latency game data, the server supports WebRTC DataChannels alongside WebSocket. The server acts as a WebRTC peer (not P2P between clients). ### **15.1 How It Works** 1. Client connects via WebSocket and joins the **User channel** 2. Client sends an SDP offer over the channel (`webrtc:offer` event) 3. Server responds with an SDP answer (`webrtc:answer` event) 4. ICE candidates are exchanged (`webrtc:ice` events) 5. Once connected, named DataChannels carry game data at low latency ### **15.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **15.3 JS SDK Helper** The `GameWebRTC` class (included in this SDK, browser-only) handles signaling automatically: ```javascript import { GameRealtime, GameWebRTC } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', token) const userChannel = realtime.joinUserChannel(userId) const webrtc = new GameWebRTC(userChannel, { onData: (label, data) => console.log(label, data) }) await webrtc.connect() webrtc.send('events', JSON.stringify({ type: 'move', x: 10, y: 20 })) ```
21
+ *
22
+ * The version of the OpenAPI document: 1.0.1040
23
+ *
24
+ *
25
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
26
+ * https://openapi-generator.tech
27
+ * Do not edit the class manually.
28
+ *
29
+ */
30
+ /**
31
+ * The MatchmakingStats200ResponseData model module.
32
+ * @module model/MatchmakingStats200ResponseData
33
+ * @version 1.0.0
34
+ */
35
+ var MatchmakingStats200ResponseData = /*#__PURE__*/function () {
36
+ /**
37
+ * Constructs a new <code>MatchmakingStats200ResponseData</code>.
38
+ * @alias module:model/MatchmakingStats200ResponseData
39
+ */
40
+ function MatchmakingStats200ResponseData() {
41
+ _classCallCheck(this, MatchmakingStats200ResponseData);
42
+ MatchmakingStats200ResponseData.initialize(this);
43
+ }
44
+
45
+ /**
46
+ * Initializes the fields of this object.
47
+ * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
48
+ * Only for internal use.
49
+ */
50
+ return _createClass(MatchmakingStats200ResponseData, null, [{
51
+ key: "initialize",
52
+ value: function initialize(obj) {}
53
+
54
+ /**
55
+ * Constructs a <code>MatchmakingStats200ResponseData</code> from a plain JavaScript object, optionally creating a new instance.
56
+ * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
57
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
58
+ * @param {module:model/MatchmakingStats200ResponseData} obj Optional instance to populate.
59
+ * @return {module:model/MatchmakingStats200ResponseData} The populated <code>MatchmakingStats200ResponseData</code> instance.
60
+ */
61
+ }, {
62
+ key: "constructFromObject",
63
+ value: function constructFromObject(data, obj) {
64
+ if (data) {
65
+ obj = obj || new MatchmakingStats200ResponseData();
66
+ if (data.hasOwnProperty('queued')) {
67
+ obj['queued'] = _ApiClient["default"].convertToType(data['queued'], 'Number');
68
+ }
69
+ if (data.hasOwnProperty('queues')) {
70
+ obj['queues'] = _ApiClient["default"].convertToType(data['queues'], [_MatchmakingStats200ResponseDataQueuesInner["default"]]);
71
+ }
72
+ }
73
+ return obj;
74
+ }
75
+
76
+ /**
77
+ * Validates the JSON data with respect to <code>MatchmakingStats200ResponseData</code>.
78
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
79
+ * @return {boolean} to indicate whether the JSON data is valid with respect to <code>MatchmakingStats200ResponseData</code>.
80
+ */
81
+ }, {
82
+ key: "validateJSON",
83
+ value: function validateJSON(data) {
84
+ if (data['queues']) {
85
+ // data not null
86
+ // ensure the json data is an array
87
+ if (!Array.isArray(data['queues'])) {
88
+ throw new Error("Expected the field `queues` to be an array in the JSON data but got " + data['queues']);
89
+ }
90
+ // validate the optional field `queues` (array)
91
+ var _iterator = _createForOfIteratorHelper(data['queues']),
92
+ _step;
93
+ try {
94
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
95
+ var item = _step.value;
96
+ _MatchmakingStats200ResponseDataQueuesInner["default"].validateJSON(item);
97
+ }
98
+ } catch (err) {
99
+ _iterator.e(err);
100
+ } finally {
101
+ _iterator.f();
102
+ }
103
+ ;
104
+ }
105
+ return true;
106
+ }
107
+ }]);
108
+ }();
109
+ /**
110
+ * @member {Number} queued
111
+ */
112
+ MatchmakingStats200ResponseData.prototype['queued'] = undefined;
113
+
114
+ /**
115
+ * @member {Array.<module:model/MatchmakingStats200ResponseDataQueuesInner>} queues
116
+ */
117
+ MatchmakingStats200ResponseData.prototype['queues'] = undefined;
118
+ var _default = exports["default"] = MatchmakingStats200ResponseData;
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+ var _ApiClient = _interopRequireDefault(require("../ApiClient"));
8
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
9
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
10
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
11
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
12
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
13
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
14
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /**
15
+ * Game Server API
16
+ * API for the Gamend Game Server. Provides HTTP REST API, real-time WebSocket channels, and WebRTC DataChannels for low-latency game data. Features authentication, users, lobbies, groups, parties, friends, chat, notifications, achievements, leaderboards, tournaments, matchmaking, payments, server scripting, and admin portal. ## **1. Authentication** This API uses JWT (JSON Web Tokens) with access and refresh tokens: ### **1.1 Getting Tokens** - **Email/Password**: POST to `/api/v1/login` with email and password - **Device (SDK)**: POST to `/api/v1/login` with a `device_id` string (creates/returns a device user) - **Discord OAuth**: Use `/api/v1/auth/discord` flow - **Google OAuth**: Use `/api/v1/auth/google` flow - **Facebook OAuth**: Use `/api/v1/auth/facebook` flow - **Apple Sign In**: Use `/auth/apple` browser flow or apple sdk flow - **Steam (OpenID)**: Use `/api/v1/auth/steam` flow Both methods return: - `access_token` - Short-lived (15 min), use for API requests - `refresh_token` - Long-lived (30 days), use to get new access tokens ### **1.2 Using Tokens** Include the access token in the Authorization header: ``` Authorization: Bearer <access_token> ``` ### **1.3 Refreshing Tokens** When your access token expires, use POST `/api/v1/refresh` with your refresh token to get a new access token. ## **2. Users** Users endpoints cover the user lifecycle and profile features. Key highlights: - **Registration and login** (email/password, device token for SDKs, and OAuth providers) - **Profile metadata** (JSON blob per user) and editable profile fields - **Account lifecycle**: password reset, email confirmation, and account deletion - **Sessions & tokens**: both browser sessions and JWT-based API tokens are supported ## **3. Friends** The Friends domain offers lightweight social features: - **Friend requests** (send / accept / reject / block flows) - **Friend listing & pagination**, with basic privacy controls - **Domain helpers** to manage and query friend relationships from API or UI contexts ## **4. Lobbies** Lobbies provide matchmaking / room management primitives. Highlights: - **Create / list / update / delete** lobbies with rich metadata (mode, region, tags) - **Host-managed or hostless** modes (hostless allowed internally, not creatable via public API) - **Membership management**: join, leave, kick users, and automatic host transfer - **Controls & protection**: max users, hidden/locked states, and optional password protection - **Hidden lobbies** are excluded from public listings; public listing endpoints are paginated ## **5. Notifications** Persistent user-to-user notifications that survive across sessions: - **Send notifications** to accepted friends with a title, optional content, and optional metadata - **List own notifications** with pagination (ordered oldest-first) - **Delete notifications** by ID (single or batch) - **Real-time delivery** via the user WebSocket channel (`\"notification\"` events) - **Offline delivery**: undeleted notifications are replayed on WebSocket reconnect ## **6. Groups** Groups provide persistent community management for players: - **Three group types**: `public` (anyone joins directly), `private` (users request to join, admins approve), `hidden` (invite-only, never listed) - **Membership roles**: `admin` and `member`, with promote/demote capabilities - **Join requests**: for private groups, users submit requests that admins approve or reject - **Invitations**: admins can invite users directly (blocked users are rejected) - **CRUD operations**: create, update, delete groups with metadata support - **Group chat**: integrated via the Chat API with `chat_type: \"group\"` ## **7. Parties** Ephemeral groups of users for short-lived sessions (e.g., matchmaking squads): - **Invite-only joining**: the party leader sends invites by user ID to friends or shared-group members - **Invite flow**: `POST /parties/invite` → recipient accepts via `POST /parties/invite/accept` or declines via `POST /parties/invite/decline`; leader can cancel via `POST /parties/invite/cancel` - **Invite visibility**: leader can list sent invites (`GET /parties/invitations/sent`); recipient can list received invites (`GET /parties/invitations`) - **Connection requirement**: invites can only be sent to users who are friends or share at least one group with the leader - **One party at a time**: a user can only be in one party; accepting an invite while already in a party is rejected - **Leader management**: the creator is the leader; leadership can be transferred - **Lobby integration**: parties can create or join lobbies as a group - **Party chat**: integrated via the Chat API with `chat_type: \"party\"` - **Real-time events** via the party WebSocket channel ## **8. Chat** Real-time messaging across multiple conversation types: - **Chat types**: `lobby` (within a lobby), `group` (within a group), `party` (within a party), `friend` (DMs between friends) - **Send messages** with content, optional metadata, and automatic access validation - **List messages** with pagination (newest first) - **Read tracking**: mark messages as read and get unread counts per conversation - **Real-time delivery** via PubSub and WebSocket channels - **Moderation hooks**: `before_chat_message` pipeline hook for filtering/blocking ## **9. Leaderboards** Server-managed ranked scoreboards: - **Multiple leaderboards**: create named leaderboards with configurable sort order - **Score submission**: submit scores with optional metadata - **Rankings**: retrieve paginated rankings with user details - **Reset support**: leaderboards can be reset periodically ## **10. Key-Value Storage** Per-user persistent key-value storage for game state, preferences, and settings: - **Get/set/delete** key-value pairs scoped to the authenticated user - **List keys** with optional prefix filtering - **Metadata support**: values can include arbitrary JSON metadata ## **11. Achievements** Track player accomplishments with progress-based or instant-unlock achievements: - **Achievement definitions**: admin-created with slug, title, description, icon, sort order, and optional progress target - **Progress tracking**: increment progress toward a target; auto-unlocks when progress reaches the target - **Instant unlock**: directly unlock achievements without progress tracking - **Hidden achievements**: details obscured (\"???\") until unlocked by the user - **Public listings**: paginated, optionally filtered; authenticated users see their own progress - **Admin management**: create, update, delete, grant, revoke, unlock, and increment achievements ## **12. Tournaments** Single-elimination bracket tournaments, server-structured and game-judged: - **Registration window → seeded draw → timed rounds → champions**; recurring tournaments (cron) create one occurrence per cycle sharing a slug; a nil starts_at keeps registration open until an admin draws manually - **Join/leave** as an entry leader (`POST`/`DELETE /tournaments/:id/join`); team composition is game policy - **Browse**: list/filter tournaments, standings, full bracket view, and the caller's current match (`GET /tournaments/:id/my-match`) - **Match verdicts are server-side** (game hooks) — no public resolve endpoint; clients get `tournament_match_ready` / `tournament_match_resolved` / `tournament_updated` / `tournament_finished` on the user channel - **Admin management** over HTTP: create/update/delete, cancel, draw now, finish, and force match verdicts under `/api/v1/admin/tournaments` ## **13. Matchmaking** Ticket-based queueing that turns waiting players into hidden, locked lobbies: - **Join over HTTP** (`POST /matchmaking/tickets` with a `match_params` string map); only tickets with identical params match together — encode mode/map/skill band as parameter values - **A match forms** when a group reaches `max_players`, or has at least `min_players` and the oldest ticket outwaited the timeout; the server creates a hidden lobby, seats everyone and locks it - **The result is a push, not a poll**: matched players receive `matchmaking_found` (`lobby_id`, `match_params`) on their user channel; disconnecting cancels your tickets - **Inspect**: `GET /matchmaking/tickets/me` for your ticket, `GET /matchmaking/stats` for queue depths - **Admin management** over HTTP: list/filter tickets, force-cancel, and stats under `/api/v1/admin/matchmaking` ## **14. Real-time: WebSocket Channels** The server provides real-time communication via Phoenix WebSocket channels. Connect to the WebSocket endpoint and join topic-based channels for live updates. ### **14.1 Connection** Connect to `wss://your-server.com/socket` with your JWT token as a parameter: ``` const socket = new Socket(\"wss://your-server.com/socket\", { params: { token: \"<access_token>\" } }) socket.connect() ``` ### **14.2 Available Channels** - **User channel** (`user:<user_id>`): notifications, friend events, achievement unlocks, party/group invites, tournament events, KV subscriptions - **Lobby channel** (`lobby:<lobby_id>`): lobby member joins/leaves, lobby updates, lobby chat - **Lobbies channel** (`lobbies`): global lobby list changes (created, updated, deleted) - **Group channel** (`group:<group_id>`): group member changes, group updates, group chat - **Groups channel** (`groups`): global group list changes - **Party channel** (`party:<party_id>`): party member changes, party updates, party chat ### **14.3 JS SDK Helper** The `GameRealtime` class (included in this SDK) wraps Phoenix.Socket with convenient channel helpers: ```javascript import { GameRealtime } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', accessToken) const userChannel = realtime.joinUserChannel(userId) userChannel.on('notification', payload => console.log(payload)) ``` Requires the `phoenix` npm package as a peer dependency: `npm install phoenix` ## **15. Real-time: WebRTC DataChannels** For low-latency game data, the server supports WebRTC DataChannels alongside WebSocket. The server acts as a WebRTC peer (not P2P between clients). ### **15.1 How It Works** 1. Client connects via WebSocket and joins the **User channel** 2. Client sends an SDP offer over the channel (`webrtc:offer` event) 3. Server responds with an SDP answer (`webrtc:answer` event) 4. ICE candidates are exchanged (`webrtc:ice` events) 5. Once connected, named DataChannels carry game data at low latency ### **15.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **15.3 JS SDK Helper** The `GameWebRTC` class (included in this SDK, browser-only) handles signaling automatically: ```javascript import { GameRealtime, GameWebRTC } from '@ughuuu/game_server' const realtime = new GameRealtime('https://your-server.com', token) const userChannel = realtime.joinUserChannel(userId) const webrtc = new GameWebRTC(userChannel, { onData: (label, data) => console.log(label, data) }) await webrtc.connect() webrtc.send('events', JSON.stringify({ type: 'move', x: 10, y: 20 })) ```
17
+ *
18
+ * The version of the OpenAPI document: 1.0.1040
19
+ *
20
+ *
21
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
22
+ * https://openapi-generator.tech
23
+ * Do not edit the class manually.
24
+ *
25
+ */
26
+ /**
27
+ * The MatchmakingStats200ResponseDataQueuesInner model module.
28
+ * @module model/MatchmakingStats200ResponseDataQueuesInner
29
+ * @version 1.0.0
30
+ */
31
+ var MatchmakingStats200ResponseDataQueuesInner = /*#__PURE__*/function () {
32
+ /**
33
+ * Constructs a new <code>MatchmakingStats200ResponseDataQueuesInner</code>.
34
+ * @alias module:model/MatchmakingStats200ResponseDataQueuesInner
35
+ */
36
+ function MatchmakingStats200ResponseDataQueuesInner() {
37
+ _classCallCheck(this, MatchmakingStats200ResponseDataQueuesInner);
38
+ MatchmakingStats200ResponseDataQueuesInner.initialize(this);
39
+ }
40
+
41
+ /**
42
+ * Initializes the fields of this object.
43
+ * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
44
+ * Only for internal use.
45
+ */
46
+ return _createClass(MatchmakingStats200ResponseDataQueuesInner, null, [{
47
+ key: "initialize",
48
+ value: function initialize(obj) {}
49
+
50
+ /**
51
+ * Constructs a <code>MatchmakingStats200ResponseDataQueuesInner</code> from a plain JavaScript object, optionally creating a new instance.
52
+ * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
53
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
54
+ * @param {module:model/MatchmakingStats200ResponseDataQueuesInner} obj Optional instance to populate.
55
+ * @return {module:model/MatchmakingStats200ResponseDataQueuesInner} The populated <code>MatchmakingStats200ResponseDataQueuesInner</code> instance.
56
+ */
57
+ }, {
58
+ key: "constructFromObject",
59
+ value: function constructFromObject(data, obj) {
60
+ if (data) {
61
+ obj = obj || new MatchmakingStats200ResponseDataQueuesInner();
62
+ if (data.hasOwnProperty('params')) {
63
+ obj['params'] = _ApiClient["default"].convertToType(data['params'], Object);
64
+ }
65
+ if (data.hasOwnProperty('waiting')) {
66
+ obj['waiting'] = _ApiClient["default"].convertToType(data['waiting'], 'Number');
67
+ }
68
+ }
69
+ return obj;
70
+ }
71
+
72
+ /**
73
+ * Validates the JSON data with respect to <code>MatchmakingStats200ResponseDataQueuesInner</code>.
74
+ * @param {Object} data The plain JavaScript object bearing properties of interest.
75
+ * @return {boolean} to indicate whether the JSON data is valid with respect to <code>MatchmakingStats200ResponseDataQueuesInner</code>.
76
+ */
77
+ }, {
78
+ key: "validateJSON",
79
+ value: function validateJSON(data) {
80
+ return true;
81
+ }
82
+ }]);
83
+ }();
84
+ /**
85
+ * @member {Object} params
86
+ */
87
+ MatchmakingStats200ResponseDataQueuesInner.prototype['params'] = undefined;
88
+
89
+ /**
90
+ * @member {Number} waiting
91
+ */
92
+ MatchmakingStats200ResponseDataQueuesInner.prototype['waiting'] = undefined;
93
+ var _default = exports["default"] = MatchmakingStats200ResponseDataQueuesInner;