@ughuuu/game_server 1.0.1034 → 1.0.1039
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -11
- package/dist/ApiClient.js +2 -2
- package/dist/api/AchievementsApi.js +2 -2
- package/dist/api/AdminAchievementsApi.js +2 -2
- package/dist/api/AdminChatApi.js +2 -2
- package/dist/api/AdminGroupsApi.js +2 -2
- package/dist/api/AdminKVApi.js +2 -2
- package/dist/api/AdminLeaderboardsApi.js +2 -2
- package/dist/api/AdminLobbiesApi.js +2 -2
- package/dist/api/AdminNotificationsApi.js +2 -2
- package/dist/api/AdminSessionsApi.js +2 -2
- package/dist/api/AdminTournamentsApi.js +374 -0
- package/dist/api/AdminUsersApi.js +2 -2
- package/dist/api/AuthenticationApi.js +2 -2
- package/dist/api/ChatApi.js +2 -2
- package/dist/api/FriendsApi.js +2 -2
- package/dist/api/GroupsApi.js +2 -2
- package/dist/api/HealthApi.js +2 -2
- package/dist/api/HooksApi.js +2 -2
- package/dist/api/KVApi.js +2 -2
- package/dist/api/LeaderboardsApi.js +2 -2
- package/dist/api/LobbiesApi.js +2 -2
- package/dist/api/NotificationsApi.js +2 -2
- package/dist/api/PartiesApi.js +2 -2
- package/dist/api/PaymentsApi.js +2 -2
- package/dist/api/TournamentsApi.js +394 -0
- package/dist/api/UsersApi.js +2 -2
- package/dist/gamend_proto.js +389 -0
- package/dist/gamend_realtime.pb.js +6473 -0
- package/dist/index.js +63 -0
- package/dist/model/AcceptPartyInvite200Response.js +2 -2
- package/dist/model/AcceptPartyInvite200ResponseMembersInner.js +2 -2
- package/dist/model/AcceptPartyInviteRequest.js +2 -2
- package/dist/model/AdminCreateAchievementRequest.js +2 -2
- package/dist/model/AdminCreateLeaderboard200Response.js +2 -2
- package/dist/model/AdminCreateLeaderboard200ResponseData.js +2 -2
- package/dist/model/AdminCreateLeaderboardRequest.js +2 -2
- package/dist/model/AdminCreateNotificationRequest.js +2 -2
- package/dist/model/AdminDeleteChatConversation200Response.js +2 -2
- package/dist/model/AdminDrawTournament200Response.js +91 -0
- package/dist/model/AdminDrawTournament200ResponseData.js +297 -0
- package/dist/model/AdminGrantAchievementRequest.js +2 -2
- package/dist/model/AdminIncrementAchievementRequest.js +2 -2
- package/dist/model/AdminListAchievements200Response.js +2 -2
- package/dist/model/AdminListAchievements200ResponseDataInner.js +2 -2
- package/dist/model/AdminListChatMessages200Response.js +2 -2
- package/dist/model/AdminListChatMessages200ResponseDataInner.js +2 -2
- package/dist/model/AdminListGroups200Response.js +2 -2
- package/dist/model/AdminListKvEntries200Response.js +2 -2
- package/dist/model/AdminListLobbies200Response.js +2 -2
- package/dist/model/AdminListLobbies200ResponseDataInner.js +2 -2
- package/dist/model/AdminListNotifications200Response.js +2 -2
- package/dist/model/AdminListNotifications200ResponseDataInner.js +2 -2
- package/dist/model/AdminListSessions200Response.js +2 -2
- package/dist/model/AdminListSessions200ResponseDataInner.js +2 -2
- package/dist/model/AdminResolveTournamentMatchRequest.js +90 -0
- package/dist/model/AdminRevokeAchievementRequest.js +2 -2
- package/dist/model/AdminSubmitLeaderboardScoreRequest.js +2 -2
- package/dist/model/AdminUpdateAchievementRequest.js +2 -2
- package/dist/model/AdminUpdateGroup200Response.js +2 -2
- package/dist/model/AdminUpdateGroupRequest.js +2 -2
- package/dist/model/AdminUpdateKvEntryRequest.js +2 -2
- package/dist/model/AdminUpdateLeaderboardRecord200Response.js +2 -2
- package/dist/model/AdminUpdateLeaderboardRecord200ResponseData.js +2 -2
- package/dist/model/AdminUpdateLeaderboardRecordRequest.js +2 -2
- package/dist/model/AdminUpdateLeaderboardRequest.js +2 -2
- package/dist/model/AdminUpdateLobby200Response.js +2 -2
- package/dist/model/AdminUpdateTournamentRequest.js +253 -0
- package/dist/model/AdminUpdateUser200Response.js +2 -2
- package/dist/model/AdminUpdateUser200ResponseData.js +2 -2
- package/dist/model/AdminUpdateUserRequest.js +2 -2
- package/dist/model/AdminUpsertKv200Response.js +2 -2
- package/dist/model/AdminUpsertKv200ResponseData.js +2 -2
- package/dist/model/AdminUpsertKvRequest.js +2 -2
- package/dist/model/ApproveJoinRequest200Response.js +2 -2
- package/dist/model/CallHook200Response.js +2 -2
- package/dist/model/CallHookRequest.js +2 -2
- package/dist/model/CancelJoinRequest200Response.js +2 -2
- package/dist/model/ChatUnreadCount200Response.js +2 -2
- package/dist/model/CreateGroupRequest.js +2 -2
- package/dist/model/CreateLobbyRequest.js +2 -2
- package/dist/model/CreatePartyRequest.js +2 -2
- package/dist/model/DeclineGroupInvite200Response.js +2 -2
- package/dist/model/DeleteNotificationsRequest.js +2 -2
- package/dist/model/DeviceLoginRequest.js +2 -2
- package/dist/model/ErrorResponse.js +2 -2
- package/dist/model/GameServerWebApiV1TournamentControllerIndex200Response.js +110 -0
- package/dist/model/GameServerWebApiV1TournamentControllerIndex200ResponseDataInner.js +258 -0
- package/dist/model/GameServerWebApiV1TournamentControllerMyMatch200Response.js +173 -0
- package/dist/model/GetCurrentUser200Response.js +2 -2
- package/dist/model/GetCurrentUser200ResponseLinkedProviders.js +2 -2
- package/dist/model/GetKv200Response.js +2 -2
- package/dist/model/GetLobby200Response.js +2 -2
- package/dist/model/GetMyRecord200Response.js +2 -2
- package/dist/model/GetMyRecord200ResponseData.js +2 -2
- package/dist/model/HealthResponse.js +2 -2
- package/dist/model/InviteToPartyRequest.js +2 -2
- package/dist/model/ListBlockedFriends200Response.js +2 -2
- package/dist/model/ListBlockedFriends200ResponseDataInner.js +2 -2
- package/dist/model/ListBlockedFriends200ResponseDataInnerRequester.js +2 -2
- package/dist/model/ListChatMessages200Response.js +2 -2
- package/dist/model/ListChatMessages200ResponseDataInner.js +2 -2
- package/dist/model/ListFriendRequests200Response.js +2 -2
- package/dist/model/ListFriendRequests200ResponseIncomingInner.js +2 -2
- package/dist/model/ListFriendRequests200ResponseIncomingInnerRequester.js +2 -2
- package/dist/model/ListFriendRequests200ResponseMeta.js +2 -2
- package/dist/model/ListFriends200Response.js +2 -2
- package/dist/model/ListFriends200ResponseDataInner.js +2 -2
- package/dist/model/ListFriends200ResponseMeta.js +2 -2
- package/dist/model/ListGroupMembers200Response.js +2 -2
- package/dist/model/ListJoinRequests200Response.js +2 -2
- package/dist/model/ListLeaderboardRecords200Response.js +2 -2
- package/dist/model/ListLeaderboards200Response.js +2 -2
- package/dist/model/ListLobbies200Response.js +2 -2
- package/dist/model/ListLobbies200ResponseDataInner.js +2 -2
- package/dist/model/ListMyGroups200Response.js +2 -2
- package/dist/model/ListMyGroups200ResponseDataInner.js +2 -2
- package/dist/model/ListPartyInvitations200ResponseInner.js +2 -2
- package/dist/model/ListRecordsAroundUser200Response.js +2 -2
- package/dist/model/ListSentInvitations200Response.js +2 -2
- package/dist/model/ListSentInvitations200ResponseDataInner.js +2 -2
- package/dist/model/LoginRequest.js +2 -2
- package/dist/model/MarkChatReadRequest.js +2 -2
- package/dist/model/MyAchievements200Response.js +2 -2
- package/dist/model/MyAchievements200ResponseDataInner.js +2 -2
- package/dist/model/NotifyGroup200Response.js +2 -2
- package/dist/model/NotifyGroupRequest.js +2 -2
- package/dist/model/OAuthSessionData.js +2 -2
- package/dist/model/OAuthSessionDataDetails.js +2 -2
- package/dist/model/OAuthSessionStatus.js +2 -2
- package/dist/model/OauthApiCallback200Response.js +2 -2
- package/dist/model/OauthApiCallbackRequest.js +2 -2
- package/dist/model/OauthCallbackApiAppleIosRequest.js +2 -2
- package/dist/model/OauthGoogleIdTokenRequest.js +2 -2
- package/dist/model/OauthRequest200Response.js +2 -2
- package/dist/model/OauthSessionStatus404Response.js +2 -2
- package/dist/model/PartyCreateLobbyRequest.js +2 -2
- package/dist/model/PartyJoinLobbyRequest.js +2 -2
- package/dist/model/PaymentsEntitlements401Response.js +2 -2
- package/dist/model/PaymentsSteamCheckoutRequest.js +2 -2
- package/dist/model/PaymentsSteamFinalizeRequest.js +2 -2
- package/dist/model/PaymentsStripeCheckoutRequest.js +2 -2
- package/dist/model/QuickJoinRequest.js +2 -2
- package/dist/model/RefreshToken200Response.js +2 -2
- package/dist/model/RefreshToken200ResponseData.js +2 -2
- package/dist/model/RefreshTokenRequest.js +2 -2
- package/dist/model/ResolveLeaderboardSlugs200Response.js +2 -2
- package/dist/model/ResolveLeaderboardSlugs200ResponseDataValue.js +2 -2
- package/dist/model/ResolveLeaderboardSlugsRequest.js +2 -2
- package/dist/model/SearchUsers200Response.js +2 -2
- package/dist/model/SearchUsers200ResponseDataInner.js +2 -2
- package/dist/model/SendChatMessageRequest.js +2 -2
- package/dist/model/SendNotificationRequest.js +2 -2
- package/dist/model/UpdateChatMessageRequest.js +2 -2
- package/dist/model/UpdateCurrentUserDisplayName400Response.js +2 -2
- package/dist/model/UpdateCurrentUserDisplayNameRequest.js +2 -2
- package/dist/model/UpdateCurrentUserPasswordRequest.js +2 -2
- package/dist/model/UpdateCurrentUserUsernameRequest.js +2 -2
- package/dist/model/UpdateGroupRequest.js +2 -2
- package/dist/model/UpdateLobbyRequest.js +2 -2
- package/dist/model/UpdatePartyRequest.js +2 -2
- package/dist/realtime.js +75 -12
- package/dist/webrtc.js +187 -21
- package/package.json +2 -2
package/dist/webrtc.js
CHANGED
|
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
exports["default"] = exports.GameWebRTC = void 0;
|
|
7
|
+
var _gamend_proto = require("./gamend_proto.js");
|
|
7
8
|
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); }
|
|
8
9
|
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
|
|
9
10
|
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
|
|
@@ -16,8 +17,7 @@ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Can
|
|
|
16
17
|
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); } }
|
|
17
18
|
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
|
|
18
19
|
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
|
|
19
|
-
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); }
|
|
20
|
-
/**
|
|
20
|
+
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); } /**
|
|
21
21
|
* GameWebRTC — Browser WebRTC DataChannel client for game_server.
|
|
22
22
|
*
|
|
23
23
|
* Uses an existing Phoenix channel (e.g. from GameRealtime.joinUserChannel)
|
|
@@ -49,7 +49,6 @@ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e
|
|
|
49
49
|
* webrtc.send('events', JSON.stringify({ type: 'player_move', x: 10, y: 20 }))
|
|
50
50
|
* webrtc.close()
|
|
51
51
|
*/
|
|
52
|
-
|
|
53
52
|
/**
|
|
54
53
|
* Default DataChannel definitions.
|
|
55
54
|
* - "events": reliable, ordered — important game events
|
|
@@ -85,6 +84,12 @@ var GameWebRTC = exports.GameWebRTC = /*#__PURE__*/function () {
|
|
|
85
84
|
this.opts = opts;
|
|
86
85
|
this.iceServers = opts.iceServers || DEFAULT_ICE_SERVERS;
|
|
87
86
|
this.dataChannelDefs = opts.dataChannels || DEFAULT_DATA_CHANNELS;
|
|
87
|
+
// 'protobuf' negotiates the RtcEnvelope RPC protocol (with request ids)
|
|
88
|
+
// on the "events" DataChannel via the DataChannel protocol field.
|
|
89
|
+
this.format = opts.format === 'protobuf' ? 'protobuf' : 'json';
|
|
90
|
+
/** @type {Map<number|string, {resolve: Function, reject: Function, timer: any}>} */
|
|
91
|
+
this._pendingCalls = new Map();
|
|
92
|
+
this._nextCallId = 1;
|
|
88
93
|
|
|
89
94
|
/** @type {RTCPeerConnection|null} */
|
|
90
95
|
this.pc = null;
|
|
@@ -135,6 +140,7 @@ var GameWebRTC = exports.GameWebRTC = /*#__PURE__*/function () {
|
|
|
135
140
|
};
|
|
136
141
|
if (def.maxRetransmits !== undefined) dcOpts.maxRetransmits = def.maxRetransmits;
|
|
137
142
|
if (def.maxPacketLifeTime !== undefined) dcOpts.maxPacketLifeTime = def.maxPacketLifeTime;
|
|
143
|
+
if (this.format === 'protobuf') dcOpts.protocol = 'protobuf';
|
|
138
144
|
dc = this.pc.createDataChannel(def.label, dcOpts);
|
|
139
145
|
this._wireDataChannel(dc);
|
|
140
146
|
this.channels.set(def.label, dc);
|
|
@@ -196,6 +202,113 @@ var GameWebRTC = exports.GameWebRTC = /*#__PURE__*/function () {
|
|
|
196
202
|
return true;
|
|
197
203
|
}
|
|
198
204
|
|
|
205
|
+
/**
|
|
206
|
+
* Call a server-side plugin hook over the "events" DataChannel.
|
|
207
|
+
*
|
|
208
|
+
* In protobuf mode replies are correlated by request id, so concurrent
|
|
209
|
+
* calls (including to the same function) are safe. In JSON mode replies
|
|
210
|
+
* are matched by plugin+fn (legacy protocol), first pending call wins.
|
|
211
|
+
*
|
|
212
|
+
* @param {string} plugin
|
|
213
|
+
* @param {string} fn
|
|
214
|
+
* @param {Array} args
|
|
215
|
+
* @param {number} timeoutMs
|
|
216
|
+
* @returns {Promise<any>} the hook result
|
|
217
|
+
*/
|
|
218
|
+
}, {
|
|
219
|
+
key: "callHook",
|
|
220
|
+
value: function callHook(plugin, fn) {
|
|
221
|
+
var _this2 = this;
|
|
222
|
+
var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
|
|
223
|
+
var timeoutMs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10000;
|
|
224
|
+
var dc = this.channels.get('events');
|
|
225
|
+
if (!dc || dc.readyState !== 'open') {
|
|
226
|
+
return Promise.reject(new Error('events DataChannel is not open'));
|
|
227
|
+
}
|
|
228
|
+
return new Promise(function (resolve, reject) {
|
|
229
|
+
var key;
|
|
230
|
+
if (_this2.format === 'protobuf') {
|
|
231
|
+
var id = _this2._nextCallId++;
|
|
232
|
+
key = id;
|
|
233
|
+
var envelope = _gamend_proto.PB.RtcEnvelope.encode({
|
|
234
|
+
call_hook: {
|
|
235
|
+
id: id,
|
|
236
|
+
plugin: plugin,
|
|
237
|
+
fn: fn,
|
|
238
|
+
args_json: new TextEncoder().encode(JSON.stringify(args))
|
|
239
|
+
}
|
|
240
|
+
}).finish();
|
|
241
|
+
dc.send(envelope);
|
|
242
|
+
} else {
|
|
243
|
+
key = "".concat(plugin, " ").concat(fn);
|
|
244
|
+
dc.send(JSON.stringify({
|
|
245
|
+
type: 'call_hook',
|
|
246
|
+
plugin: plugin,
|
|
247
|
+
fn: fn,
|
|
248
|
+
args: args
|
|
249
|
+
}));
|
|
250
|
+
}
|
|
251
|
+
var timer = setTimeout(function () {
|
|
252
|
+
_this2._pendingCalls["delete"](key);
|
|
253
|
+
reject(new Error("callHook ".concat(plugin, ".").concat(fn, " timed out")));
|
|
254
|
+
}, timeoutMs);
|
|
255
|
+
_this2._pendingCalls.set(key, {
|
|
256
|
+
resolve: resolve,
|
|
257
|
+
reject: reject,
|
|
258
|
+
timer: timer
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Call a typed (protobuf) plugin hook over the "events" DataChannel.
|
|
265
|
+
*
|
|
266
|
+
* Encode the bytes with your game's schema (convention: <FnName>Request /
|
|
267
|
+
* <FnName>Reply, registered by the plugin) — the server decodes them into
|
|
268
|
+
* the request struct, so a hook without a registered schema errors with
|
|
269
|
+
* hook_schema_missing. Requires format: 'protobuf'.
|
|
270
|
+
*
|
|
271
|
+
* @param {string} plugin
|
|
272
|
+
* @param {string} fn
|
|
273
|
+
* @param {Uint8Array} bytes - encoded request message
|
|
274
|
+
* @param {number} timeoutMs
|
|
275
|
+
* @returns {Promise<Uint8Array>} the raw reply bytes
|
|
276
|
+
*/
|
|
277
|
+
}, {
|
|
278
|
+
key: "callHookRaw",
|
|
279
|
+
value: function callHookRaw(plugin, fn, bytes) {
|
|
280
|
+
var _this3 = this;
|
|
281
|
+
var timeoutMs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10000;
|
|
282
|
+
if (this.format !== 'protobuf') {
|
|
283
|
+
return Promise.reject(new Error('callHookRaw requires format: "protobuf"'));
|
|
284
|
+
}
|
|
285
|
+
var dc = this.channels.get('events');
|
|
286
|
+
if (!dc || dc.readyState !== 'open') {
|
|
287
|
+
return Promise.reject(new Error('events DataChannel is not open'));
|
|
288
|
+
}
|
|
289
|
+
return new Promise(function (resolve, reject) {
|
|
290
|
+
var id = _this3._nextCallId++;
|
|
291
|
+
var envelope = _gamend_proto.PB.RtcEnvelope.encode({
|
|
292
|
+
call_hook: {
|
|
293
|
+
id: id,
|
|
294
|
+
plugin: plugin,
|
|
295
|
+
fn: fn,
|
|
296
|
+
args_raw: bytes
|
|
297
|
+
}
|
|
298
|
+
}).finish();
|
|
299
|
+
dc.send(envelope);
|
|
300
|
+
var timer = setTimeout(function () {
|
|
301
|
+
_this3._pendingCalls["delete"](id);
|
|
302
|
+
reject(new Error("callHookRaw ".concat(plugin, ".").concat(fn, " timed out")));
|
|
303
|
+
}, timeoutMs);
|
|
304
|
+
_this3._pendingCalls.set(id, {
|
|
305
|
+
resolve: resolve,
|
|
306
|
+
reject: reject,
|
|
307
|
+
timer: timer
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
199
312
|
/**
|
|
200
313
|
* Check if a specific DataChannel is open.
|
|
201
314
|
* @param {string} label
|
|
@@ -261,11 +374,11 @@ var GameWebRTC = exports.GameWebRTC = /*#__PURE__*/function () {
|
|
|
261
374
|
}, {
|
|
262
375
|
key: "_setupChannelListeners",
|
|
263
376
|
value: function _setupChannelListeners() {
|
|
264
|
-
var
|
|
377
|
+
var _this4 = this;
|
|
265
378
|
// Server sends SDP answer
|
|
266
379
|
this._answerRef = this.channel.on('webrtc:answer', function (payload) {
|
|
267
|
-
if (
|
|
268
|
-
|
|
380
|
+
if (_this4.pc) {
|
|
381
|
+
_this4.pc.setRemoteDescription(new RTCSessionDescription({
|
|
269
382
|
sdp: payload.sdp,
|
|
270
383
|
type: payload.type
|
|
271
384
|
}));
|
|
@@ -274,28 +387,28 @@ var GameWebRTC = exports.GameWebRTC = /*#__PURE__*/function () {
|
|
|
274
387
|
|
|
275
388
|
// Server sends ICE candidate
|
|
276
389
|
this._iceRef = this.channel.on('webrtc:ice', function (payload) {
|
|
277
|
-
if (
|
|
278
|
-
|
|
279
|
-
return
|
|
390
|
+
if (_this4.pc && payload.candidate) {
|
|
391
|
+
_this4.pc.addIceCandidate(new RTCIceCandidate(payload))["catch"](function (err) {
|
|
392
|
+
return _this4._emitError(err);
|
|
280
393
|
});
|
|
281
394
|
}
|
|
282
395
|
});
|
|
283
396
|
|
|
284
397
|
// Server notifies about connection state changes
|
|
285
398
|
this._stateRef = this.channel.on('webrtc:state', function (payload) {
|
|
286
|
-
var cb =
|
|
399
|
+
var cb = _this4.opts.onStateChange;
|
|
287
400
|
if (cb) cb(payload.state);
|
|
288
401
|
});
|
|
289
402
|
|
|
290
403
|
// Server relays DataChannel data back via WebSocket (fallback)
|
|
291
404
|
this._dataRef = this.channel.on('webrtc:data', function (payload) {
|
|
292
|
-
var cb =
|
|
405
|
+
var cb = _this4.opts.onData;
|
|
293
406
|
if (cb) cb(payload.channel, payload.data);
|
|
294
407
|
});
|
|
295
408
|
|
|
296
409
|
// Server confirms channel open
|
|
297
410
|
this._openRef = this.channel.on('webrtc:channel_open', function (payload) {
|
|
298
|
-
var cb =
|
|
411
|
+
var cb = _this4.opts.onChannelOpen;
|
|
299
412
|
if (cb) cb(payload.channel);
|
|
300
413
|
});
|
|
301
414
|
}
|
|
@@ -340,30 +453,83 @@ var GameWebRTC = exports.GameWebRTC = /*#__PURE__*/function () {
|
|
|
340
453
|
}, {
|
|
341
454
|
key: "_wireDataChannel",
|
|
342
455
|
value: function _wireDataChannel(dc) {
|
|
343
|
-
var
|
|
456
|
+
var _this5 = this;
|
|
344
457
|
dc.onopen = function () {
|
|
345
|
-
var cb =
|
|
458
|
+
var cb = _this5.opts.onChannelOpen;
|
|
346
459
|
if (cb) cb(dc.label);
|
|
347
460
|
|
|
348
461
|
// Resolve connect() promise when the FIRST channel opens
|
|
349
|
-
if (
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
462
|
+
if (_this5._resolveConnect) {
|
|
463
|
+
_this5._resolveConnect();
|
|
464
|
+
_this5._resolveConnect = null;
|
|
465
|
+
_this5._rejectConnect = null;
|
|
353
466
|
}
|
|
354
467
|
};
|
|
355
468
|
dc.onclose = function () {
|
|
356
|
-
var cb =
|
|
469
|
+
var cb = _this5.opts.onChannelClose;
|
|
357
470
|
if (cb) cb(dc.label);
|
|
358
471
|
};
|
|
359
472
|
dc.onmessage = function (event) {
|
|
360
|
-
|
|
473
|
+
if (dc.label === 'events' && _this5._handleRpcReply(event.data)) return;
|
|
474
|
+
var cb = _this5.opts.onData;
|
|
361
475
|
if (cb) cb(dc.label, event.data);
|
|
362
476
|
};
|
|
363
477
|
dc.onerror = function (event) {
|
|
364
|
-
|
|
478
|
+
_this5._emitError(event.error || event);
|
|
365
479
|
};
|
|
366
480
|
}
|
|
481
|
+
|
|
482
|
+
// Routes hook replies to pending callHook promises. Returns true when the
|
|
483
|
+
// message was an RPC reply and has been consumed.
|
|
484
|
+
}, {
|
|
485
|
+
key: "_handleRpcReply",
|
|
486
|
+
value: function _handleRpcReply(data) {
|
|
487
|
+
try {
|
|
488
|
+
if (this.format === 'protobuf') {
|
|
489
|
+
if (typeof data === 'string') return false;
|
|
490
|
+
var bin = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
491
|
+
var env = _gamend_proto.PB.RtcEnvelope.decode(bin);
|
|
492
|
+
if (env.hook_reply) {
|
|
493
|
+
var _pending = this._takePending(env.hook_reply.id);
|
|
494
|
+
if (_pending) {
|
|
495
|
+
if (env.hook_reply.data === 'data_raw') {
|
|
496
|
+
_pending.resolve(env.hook_reply.data_raw);
|
|
497
|
+
} else {
|
|
498
|
+
var _env$hook_reply$data_;
|
|
499
|
+
var json = new TextDecoder().decode((_env$hook_reply$data_ = env.hook_reply.data_json) !== null && _env$hook_reply$data_ !== void 0 ? _env$hook_reply$data_ : new Uint8Array());
|
|
500
|
+
_pending.resolve(json.length ? JSON.parse(json) : null);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return true;
|
|
504
|
+
}
|
|
505
|
+
if (env.hook_error) {
|
|
506
|
+
var _pending2 = this._takePending(env.hook_error.id);
|
|
507
|
+
if (_pending2) _pending2.reject(new Error(env.hook_error.error));
|
|
508
|
+
return true;
|
|
509
|
+
}
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
if (typeof data !== 'string') return false;
|
|
513
|
+
var msg = JSON.parse(data);
|
|
514
|
+
if (msg.type !== 'hook_reply' && msg.type !== 'hook_error') return false;
|
|
515
|
+
var pending = this._takePending("".concat(msg.plugin, " ").concat(msg.fn));
|
|
516
|
+
if (!pending) return false;
|
|
517
|
+
if (msg.type === 'hook_reply') pending.resolve(msg.data);else pending.reject(new Error(msg.error));
|
|
518
|
+
return true;
|
|
519
|
+
} catch (_) {
|
|
520
|
+
return false;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}, {
|
|
524
|
+
key: "_takePending",
|
|
525
|
+
value: function _takePending(key) {
|
|
526
|
+
var pending = this._pendingCalls.get(key);
|
|
527
|
+
if (pending) {
|
|
528
|
+
clearTimeout(pending.timer);
|
|
529
|
+
this._pendingCalls["delete"](key);
|
|
530
|
+
}
|
|
531
|
+
return pending;
|
|
532
|
+
}
|
|
367
533
|
}, {
|
|
368
534
|
key: "_emitError",
|
|
369
535
|
value: function _emitError(error) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ughuuu/game_server",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "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, 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. 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. ### **12.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() ``` ### **12.2 Available Channels** - **User channel** (`user:<user_id>`): notifications, friend events, achievement unlocks, party/group invites - **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 ### **12.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` ## **13. 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). ### **13.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 ### **13.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **13.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 })) ``` ",
|
|
3
|
+
"version": "1.0.1039",
|
|
4
|
+
"description": "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, 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. 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. ### **13.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() ``` ### **13.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 ### **13.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` ## **14. 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). ### **14.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 ### **14.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **14.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 })) ``` ",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"scripts": {
|