@ughuuu/gamend 1.1.1325 → 1.1.1328
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 +15 -9
- package/dist/ApiClient.js +2 -2
- package/dist/api/AdminAnalyticsApi.js +2 -2
- package/dist/api/AdminChatApi.js +2 -2
- package/dist/api/AdminEconomyApi.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/AdminMatchmakingApi.js +2 -2
- package/dist/api/AdminNotificationsApi.js +2 -2
- package/dist/api/AdminPushApi.js +2 -2
- package/dist/api/AdminQuestsApi.js +2 -2
- package/dist/api/AdminReadyChecksApi.js +2 -2
- package/dist/api/AdminRetentionApi.js +2 -2
- package/dist/api/AdminSessionsApi.js +2 -2
- package/dist/api/AdminStorageApi.js +2 -2
- package/dist/api/AdminTournamentsApi.js +2 -2
- package/dist/api/AdminUsersApi.js +2 -2
- package/dist/api/AuthenticationApi.js +2 -2
- package/dist/api/ChatApi.js +2 -2
- package/dist/api/ClientLogsApi.js +2 -2
- package/dist/api/EconomyApi.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/MatchmakingApi.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/PushApi.js +2 -2
- package/dist/api/QuestsApi.js +2 -2
- package/dist/api/ReadyChecksApi.js +2 -2
- package/dist/api/ReportsApi.js +2 -2
- package/dist/api/SignalingApi.js +2 -2
- package/dist/api/StatsApi.js +2 -2
- package/dist/api/TimeApi.js +2 -2
- package/dist/api/TournamentsApi.js +2 -2
- package/dist/api/UsersApi.js +2 -2
- package/dist/index.js +20 -0
- package/dist/model/AcceptPartyInviteRequest.js +2 -2
- package/dist/model/AccountBan.js +125 -0
- package/dist/model/ActivityStats.js +2 -2
- package/dist/model/AdminChatMute.js +2 -2
- package/dist/model/AdminChatMutePage.js +2 -2
- package/dist/model/AdminChatMuteResponse.js +2 -2
- package/dist/model/AdminClaimQuestRequest.js +2 -2
- package/dist/model/AdminCreateChatFilterWordRequest.js +2 -2
- package/dist/model/AdminCreateChatMuteRequest.js +2 -2
- package/dist/model/AdminCreateKvEntryRequest.js +2 -2
- package/dist/model/AdminCreateLeaderboardRequest.js +2 -2
- package/dist/model/AdminCreateNotificationRequest.js +2 -2
- package/dist/model/AdminCreateQuestRequest.js +2 -2
- package/dist/model/AdminCreateQuestRequestObjectivesInner.js +2 -2
- package/dist/model/AdminCreateQuestRequestRewardsInner.js +2 -2
- package/dist/model/AdminCreateTournamentRequest.js +2 -2
- package/dist/model/AdminGrantCurrencyRequest.js +2 -2
- package/dist/model/AdminGrantItemRequest.js +2 -2
- package/dist/model/AdminGrantQuestRequest.js +2 -2
- package/dist/model/AdminImportChatFilterWordsRequest.js +2 -2
- package/dist/model/AdminInventoryItem.js +2 -2
- package/dist/model/AdminInventoryItemPage.js +2 -2
- package/dist/model/AdminKvEntry.js +2 -2
- package/dist/model/AdminKvEntryPage.js +2 -2
- package/dist/model/AdminKvEntryResponse.js +2 -2
- package/dist/model/AdminLeaderboardIconUploadUrlRequest.js +2 -2
- package/dist/model/AdminLeaderboardRecord.js +2 -2
- package/dist/model/AdminLeaderboardRecordResponse.js +2 -2
- package/dist/model/AdminLedgerEntry.js +2 -2
- package/dist/model/AdminLedgerEntryPage.js +2 -2
- package/dist/model/AdminMatchmakingStats.js +2 -2
- package/dist/model/AdminMatchmakingStatsResponse.js +2 -2
- package/dist/model/AdminMatchmakingTicket.js +2 -2
- package/dist/model/AdminMatchmakingTicketPage.js +2 -2
- package/dist/model/AdminMatchmakingTicketResponse.js +2 -2
- package/dist/model/AdminPushToken.js +2 -2
- package/dist/model/AdminPushTokenPage.js +2 -2
- package/dist/model/AdminQuest.js +2 -2
- package/dist/model/AdminQuestClaim.js +2 -2
- package/dist/model/AdminQuestClaimResponse.js +2 -2
- package/dist/model/AdminQuestIconUploadUrlRequest.js +2 -2
- package/dist/model/AdminQuestPage.js +2 -2
- package/dist/model/AdminQuestProgress.js +2 -2
- package/dist/model/AdminQuestProgressPage.js +2 -2
- package/dist/model/AdminQuestProgressResponse.js +2 -2
- package/dist/model/AdminQuestResponse.js +2 -2
- package/dist/model/AdminReadyCheck.js +2 -2
- package/dist/model/AdminReadyCheckPage.js +2 -2
- package/dist/model/AdminReadyCheckResponse.js +2 -2
- package/dist/model/AdminResetQuestRequest.js +2 -2
- package/dist/model/AdminResolveChatReportRequest.js +2 -2
- package/dist/model/AdminResolveTournamentMatchRequest.js +2 -2
- package/dist/model/AdminSendPushRequest.js +2 -2
- package/dist/model/AdminSession.js +2 -2
- package/dist/model/AdminSessionPage.js +2 -2
- package/dist/model/AdminSetLeaderboardIconRequest.js +2 -2
- package/dist/model/AdminSetQuestIconRequest.js +2 -2
- package/dist/model/AdminSetTournamentIconRequest.js +2 -2
- package/dist/model/AdminSpendCurrencyRequest.js +2 -2
- package/dist/model/AdminSubmitLeaderboardScoreRequest.js +2 -2
- package/dist/model/AdminTestChatPhraseRequest.js +2 -2
- package/dist/model/AdminTournament.js +2 -2
- package/dist/model/AdminTournamentIconUploadUrlRequest.js +2 -2
- package/dist/model/AdminTournamentResponse.js +2 -2
- package/dist/model/AdminUpdateChatFilterWordRequest.js +2 -2
- package/dist/model/AdminUpdateGroupRequest.js +2 -2
- package/dist/model/AdminUpdateKvEntryRequest.js +2 -2
- package/dist/model/AdminUpdateLeaderboardRecordRequest.js +2 -2
- package/dist/model/AdminUpdateLeaderboardRequest.js +2 -2
- package/dist/model/AdminUpdateLobbyRequest.js +2 -2
- package/dist/model/AdminUpdateQuestRequest.js +2 -2
- package/dist/model/AdminUpdateTournamentRequest.js +2 -2
- package/dist/model/AdminUpdateUserRequest.js +2 -2
- package/dist/model/AdminUpsertKvRequest.js +2 -2
- package/dist/model/AdminUser.js +2 -2
- package/dist/model/AdminUserResponse.js +2 -2
- package/dist/model/AdminWallet.js +2 -2
- package/dist/model/AdminWalletPage.js +2 -2
- package/dist/model/AnalyticsCounts.js +2 -2
- package/dist/model/AnalyticsCountsResponse.js +2 -2
- package/dist/model/AnalyticsDaily.js +2 -2
- package/dist/model/AnalyticsDailyResponse.js +2 -2
- package/dist/model/AnalyticsDay.js +2 -2
- package/dist/model/AnalyticsEconomy.js +2 -2
- package/dist/model/AnalyticsEconomyResponse.js +2 -2
- package/dist/model/AnalyticsSummary.js +2 -2
- package/dist/model/AnalyticsSummaryResponse.js +2 -2
- package/dist/model/AuthProvidersResponse.js +2 -2
- package/dist/model/BlockedFriendship.js +2 -2
- package/dist/model/BlockedFriendshipPage.js +2 -2
- package/dist/model/CallHookRequest.js +2 -2
- package/dist/model/CancelPartyInviteRequest.js +2 -2
- package/dist/model/CancelledCount.js +2 -2
- package/dist/model/CancelledCountResponse.js +2 -2
- package/dist/model/ChatFilterHit.js +2 -2
- package/dist/model/ChatFilterLanguages.js +2 -2
- package/dist/model/ChatFilterLanguagesResponse.js +2 -2
- package/dist/model/ChatFilterTest.js +2 -2
- package/dist/model/ChatFilterTestResponse.js +2 -2
- package/dist/model/ChatFilterWord.js +2 -2
- package/dist/model/ChatFilterWordPage.js +2 -2
- package/dist/model/ChatFilterWordResponse.js +2 -2
- package/dist/model/ChatMessage.js +2 -2
- package/dist/model/ChatMessagePage.js +2 -2
- package/dist/model/ChatMessageResponse.js +2 -2
- package/dist/model/ChatMuteRecord.js +2 -2
- package/dist/model/ChatMuteRecordPage.js +2 -2
- package/dist/model/ChatMuteRecordResponse.js +2 -2
- package/dist/model/ChatReadCursor.js +2 -2
- package/dist/model/ChatReadCursorResponse.js +2 -2
- package/dist/model/ChatReport.js +2 -2
- package/dist/model/ChatReportPage.js +2 -2
- package/dist/model/ChatReportResponse.js +2 -2
- package/dist/model/ChatUnread.js +2 -2
- package/dist/model/ChatUnreadResponse.js +2 -2
- package/dist/model/ClientLogBatch.js +2 -2
- package/dist/model/ClientLogEntry.js +2 -2
- package/dist/model/ClientLogPolicy.js +2 -2
- package/dist/model/ClientLogPolicyResponse.js +2 -2
- package/dist/model/ClientLogResult.js +2 -2
- package/dist/model/ClientLogResultResponse.js +2 -2
- package/dist/model/ClientLogSession.js +2 -2
- package/dist/model/ConfirmRegistrationRequest.js +2 -2
- package/dist/model/CounterTotal.js +2 -2
- package/dist/model/CreateCurrentUserAvatarUploadUrlRequest.js +2 -2
- package/dist/model/CreateFriendRequestRequest.js +2 -2
- package/dist/model/CreateGroupIconUploadUrlRequest.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/CurrentUser.js +24 -7
- package/dist/model/CurrentUserResponse.js +2 -2
- package/dist/model/DeclinePartyInviteRequest.js +2 -2
- package/dist/model/DeleteCurrentUserRequest.js +2 -2
- package/dist/model/DeleteNotificationsRequest.js +2 -2
- package/dist/model/DeletedCount.js +2 -2
- package/dist/model/DeletedCountResponse.js +2 -2
- package/dist/model/DemoteGroupMemberRequest.js +2 -2
- package/dist/model/DeviceLoginRequest.js +2 -2
- package/dist/model/EconomyFlowDay.js +2 -2
- package/dist/model/EconomyTotal.js +2 -2
- package/dist/model/Entitlement.js +2 -2
- package/dist/model/EntitlementPage.js +2 -2
- package/dist/model/ErrorResponse.js +2 -2
- package/dist/model/Friend.js +2 -2
- package/dist/model/FriendPage.js +2 -2
- package/dist/model/FriendRequest.js +2 -2
- package/dist/model/FriendRequestLists.js +2 -2
- package/dist/model/FriendRequestMeta.js +2 -2
- package/dist/model/FriendRequestResponse.js +2 -2
- package/dist/model/FriendRequestsResponse.js +2 -2
- package/dist/model/Group.js +2 -2
- package/dist/model/GroupInvite.js +2 -2
- package/dist/model/GroupInviteOutcome.js +2 -2
- package/dist/model/GroupInviteOutcomeResponse.js +2 -2
- package/dist/model/GroupInvitePage.js +2 -2
- package/dist/model/GroupJoinRequest.js +2 -2
- package/dist/model/GroupJoinRequestPage.js +2 -2
- package/dist/model/GroupJoinRequestResponse.js +2 -2
- package/dist/model/GroupMember.js +2 -2
- package/dist/model/GroupMemberPage.js +2 -2
- package/dist/model/GroupMemberResponse.js +2 -2
- package/dist/model/GroupPage.js +2 -2
- package/dist/model/GroupResponse.js +2 -2
- package/dist/model/Health.js +2 -2
- package/dist/model/HealthResponse.js +2 -2
- package/dist/model/HookCallResponse.js +2 -2
- package/dist/model/HookFunction.js +2 -2
- package/dist/model/HookFunctionPage.js +2 -2
- package/dist/model/HookSignature.js +2 -2
- package/dist/model/ImportedCount.js +2 -2
- package/dist/model/ImportedCountResponse.js +2 -2
- package/dist/model/InventoryResponse.js +2 -2
- package/dist/model/InviteToGroupRequest.js +2 -2
- package/dist/model/InviteToPartyRequest.js +2 -2
- package/dist/model/ItemQuantity.js +2 -2
- package/dist/model/ItemQuantityResponse.js +2 -2
- package/dist/model/JoinLobbyRequest.js +2 -2
- package/dist/model/KickGroupMemberRequest.js +2 -2
- package/dist/model/KickPartyMemberRequest.js +2 -2
- package/dist/model/KickUserRequest.js +2 -2
- package/dist/model/KvEntry.js +2 -2
- package/dist/model/KvEntryResponse.js +2 -2
- package/dist/model/Leaderboard.js +2 -2
- package/dist/model/LeaderboardPage.js +2 -2
- package/dist/model/LeaderboardRecord.js +2 -2
- package/dist/model/LeaderboardRecordPage.js +2 -2
- package/dist/model/LeaderboardRecordResponse.js +2 -2
- package/dist/model/LeaderboardResponse.js +2 -2
- package/dist/model/LeaderboardsBySlugResponse.js +2 -2
- package/dist/model/LedgerEntry.js +2 -2
- package/dist/model/LedgerEntryPage.js +2 -2
- package/dist/model/LinkAppleIosRequest.js +2 -2
- package/dist/model/LinkDeviceRequest.js +2 -2
- package/dist/model/LinkGoogleIdTokenRequest.js +2 -2
- package/dist/model/LinkProviderRequest.js +2 -2
- package/dist/model/LinkedProviders.js +2 -2
- package/dist/model/Lobby.js +2 -2
- package/dist/model/LobbyPage.js +2 -2
- package/dist/model/LobbyResponse.js +2 -2
- package/dist/model/LobbyStats.js +2 -2
- package/dist/model/LobbyStatsResponse.js +2 -2
- package/dist/model/LoginRequest.js +2 -2
- package/dist/model/MarkChatReadRequest.js +2 -2
- package/dist/model/MatchmakingJoinRequest.js +2 -2
- package/dist/model/MatchmakingQueue.js +2 -2
- package/dist/model/MatchmakingStats.js +2 -2
- package/dist/model/MatchmakingStatsResponse.js +2 -2
- package/dist/model/MatchmakingTicket.js +2 -2
- package/dist/model/MatchmakingTicketResponse.js +2 -2
- package/dist/model/MuteGroupMemberRequest.js +2 -2
- package/dist/model/MuteLobbyMemberRequest.js +2 -2
- package/dist/model/MutePartyMemberRequest.js +2 -2
- package/dist/model/MyReadyChecks.js +2 -2
- package/dist/model/MyReadyChecksResponse.js +2 -2
- package/dist/model/Notification.js +2 -2
- package/dist/model/NotificationPage.js +2 -2
- package/dist/model/NotificationResponse.js +2 -2
- package/dist/model/OAuthAuthorization.js +2 -2
- package/dist/model/OAuthAuthorizationResponse.js +2 -2
- package/dist/model/OAuthSessionStatus.js +2 -2
- package/dist/model/OAuthSessionStatusResponse.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/OkResponse.js +2 -2
- package/dist/model/OpenLobbyReadyCheckRequest.js +2 -2
- package/dist/model/OpenPartyReadyCheckRequest.js +2 -2
- package/dist/model/PageMeta.js +2 -2
- package/dist/model/Party.js +2 -2
- package/dist/model/PartyCreateLobbyRequest.js +2 -2
- package/dist/model/PartyInvite.js +2 -2
- package/dist/model/PartyInvitePage.js +2 -2
- package/dist/model/PartyJoinLobbyRequest.js +2 -2
- package/dist/model/PartyResponse.js +2 -2
- package/dist/model/PartyStats.js +2 -2
- package/dist/model/PartyStatsResponse.js +2 -2
- package/dist/model/PaymentCatalogEntry.js +2 -2
- package/dist/model/PaymentCatalogEntryPage.js +2 -2
- package/dist/model/PaymentProduct.js +2 -2
- package/dist/model/PaymentWebhookReceipt.js +2 -2
- package/dist/model/PaymentWebhookReceiptResponse.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/PlayerStats.js +2 -2
- package/dist/model/PlayerStatsResponse.js +2 -2
- package/dist/model/PromoteGroupMemberRequest.js +2 -2
- package/dist/model/ProviderLinkStatus.js +2 -2
- package/dist/model/ProviderLinkStatusResponse.js +2 -2
- package/dist/model/PublicUser.js +2 -2
- package/dist/model/PublicUserPage.js +2 -2
- package/dist/model/PublicUserResponse.js +2 -2
- package/dist/model/Purchase.js +2 -2
- package/dist/model/PurchaseResponse.js +2 -2
- package/dist/model/PurchaseValidation.js +2 -2
- package/dist/model/PurchaseValidationResponse.js +2 -2
- package/dist/model/PushToken.js +2 -2
- package/dist/model/PushTokenPage.js +2 -2
- package/dist/model/PushTokenResponse.js +2 -2
- package/dist/model/Quest.js +2 -2
- package/dist/model/QuestClaim.js +2 -2
- package/dist/model/QuestClaimResponse.js +2 -2
- package/dist/model/QuestFunnelResponse.js +2 -2
- package/dist/model/QuestObjective.js +2 -2
- package/dist/model/QuestPage.js +2 -2
- package/dist/model/QuestProgress.js +2 -2
- package/dist/model/QuestReward.js +2 -2
- package/dist/model/QuestStats.js +2 -2
- package/dist/model/QuestStatsResponse.js +2 -2
- package/dist/model/QuickJoinRequest.js +2 -2
- package/dist/model/ReadyCheckOutcomesResponse.js +2 -2
- package/dist/model/ReadyCheckParticipant.js +2 -2
- package/dist/model/ReadyCheckState.js +2 -2
- package/dist/model/ReadyCheckStateResponse.js +2 -2
- package/dist/model/RefreshTokenRequest.js +2 -2
- package/dist/model/RegisterPushTokenRequest.js +2 -2
- package/dist/model/RegisterRequest.js +2 -2
- package/dist/model/Registration.js +2 -2
- package/dist/model/RegistrationResponse.js +2 -2
- package/dist/model/ReportChatMessageRequest.js +2 -2
- package/dist/model/ReportKind.js +2 -2
- package/dist/model/ReportKinds.js +2 -2
- package/dist/model/ReportKindsResponse.js +2 -2
- package/dist/model/ReportReceipt.js +2 -2
- package/dist/model/ReportReceiptResponse.js +2 -2
- package/dist/model/ReportRequest.js +2 -2
- package/dist/model/ResendConfirmationRequest.js +2 -2
- package/dist/model/ResolveLeaderboardSlugsRequest.js +2 -2
- package/dist/model/RespondReadyCheckRequest.js +2 -2
- package/dist/model/RetentionStatus.js +2 -2
- package/dist/model/RetentionStatusResponse.js +2 -2
- package/dist/model/SendChatMessageRequest.js +2 -2
- package/dist/model/SendNotificationRequest.js +2 -2
- package/dist/model/ServerStats.js +2 -2
- package/dist/model/ServerStatsResponse.js +2 -2
- package/dist/model/ServerTime.js +2 -2
- package/dist/model/ServerTimeResponse.js +2 -2
- package/dist/model/Session.js +2 -2
- package/dist/model/SessionResponse.js +2 -2
- package/dist/model/SetCurrentUserAvatarRequest.js +2 -2
- package/dist/model/SetGroupIconRequest.js +2 -2
- package/dist/model/SetLobbyStateRequest.js +2 -2
- package/dist/model/SignalingStats.js +2 -2
- package/dist/model/SignalingStatsResponse.js +2 -2
- package/dist/model/SteamCheckout.js +2 -2
- package/dist/model/SteamCheckoutResponse.js +2 -2
- package/dist/model/StorageObject.js +2 -2
- package/dist/model/StorageObjectPage.js +2 -2
- package/dist/model/StorageObjectResponse.js +2 -2
- package/dist/model/StorageUsage.js +2 -2
- package/dist/model/StorageUsageResponse.js +2 -2
- package/dist/model/StripeCheckout.js +2 -2
- package/dist/model/StripeCheckoutResponse.js +2 -2
- package/dist/model/Tournament.js +2 -2
- package/dist/model/TournamentBracket.js +2 -2
- package/dist/model/TournamentBracketPage.js +2 -2
- package/dist/model/TournamentEntry.js +2 -2
- package/dist/model/TournamentEntryPage.js +2 -2
- package/dist/model/TournamentEntryResponse.js +2 -2
- package/dist/model/TournamentMatch.js +2 -2
- package/dist/model/TournamentMatchCounts.js +2 -2
- package/dist/model/TournamentMatchResponse.js +2 -2
- package/dist/model/TournamentPage.js +2 -2
- package/dist/model/TournamentPlacement.js +2 -2
- package/dist/model/TournamentResponse.js +2 -2
- package/dist/model/TournamentStandings.js +2 -2
- package/dist/model/TournamentStandingsResponse.js +2 -2
- package/dist/model/TournamentStats.js +2 -2
- package/dist/model/UnmuteGroupMemberRequest.js +2 -2
- package/dist/model/UnmuteLobbyMemberRequest.js +2 -2
- package/dist/model/UnmutePartyMemberRequest.js +2 -2
- package/dist/model/UpdateChatMessageRequest.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/model/UploadTicket.js +2 -2
- package/dist/model/UploadTicketResponse.js +2 -2
- package/dist/model/UserBrief.js +2 -2
- package/dist/model/UserBriefPage.js +2 -2
- package/dist/model/WalletBalance.js +2 -2
- package/dist/model/WalletBalanceResponse.js +2 -2
- package/dist/model/WalletBalancesResponse.js +2 -2
- package/dist/realtime.js +74 -22
- package/dist/session.js +496 -0
- package/dist/webrtc.js +3 -3
- package/package.json +2 -2
package/dist/session.js
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.GamendSession = void 0;
|
|
7
|
+
var _ApiClient2 = _interopRequireDefault(require("./ApiClient"));
|
|
8
|
+
var _AuthenticationApi = _interopRequireDefault(require("./api/AuthenticationApi"));
|
|
9
|
+
var _realtime = require("./realtime");
|
|
10
|
+
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
|
|
11
|
+
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); }
|
|
12
|
+
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
|
|
13
|
+
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
|
|
14
|
+
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
|
|
15
|
+
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
|
|
16
|
+
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
|
|
17
|
+
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
|
|
18
|
+
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
|
|
19
|
+
function _readOnlyError(r) { throw new TypeError('"' + r + '" is read-only'); }
|
|
20
|
+
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 }; })(); }
|
|
21
|
+
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); }
|
|
22
|
+
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
|
|
23
|
+
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
|
|
24
|
+
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
25
|
+
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
|
|
26
|
+
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
|
|
27
|
+
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
|
|
28
|
+
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); } }
|
|
29
|
+
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
|
|
30
|
+
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
|
|
31
|
+
function _toPrimitive(t, e) { if ("object" != _typeof(t) || !t) return t; var r; if ("undefined" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) { var i = r.call(t, e || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === e ? String : Number)(t); } /**
|
|
32
|
+
* GamendSession — keeps a player signed in.
|
|
33
|
+
*
|
|
34
|
+
* Holds the access and refresh tokens, sends the access token with every API
|
|
35
|
+
* call made through `session.client`, refreshes it shortly before it expires
|
|
36
|
+
* (and once after a 401), and gives GameRealtime a token function, so a socket
|
|
37
|
+
* that reconnects hours later still carries a valid token. The JS counterpart
|
|
38
|
+
* of the token handling in the Godot client's GamendApi.
|
|
39
|
+
*
|
|
40
|
+
* Usage:
|
|
41
|
+
*
|
|
42
|
+
* import { GamendSession, AuthenticationApi, UsersApi } from '@ughuuu/gamend'
|
|
43
|
+
*
|
|
44
|
+
* const gamend = new GamendSession('https://your-server.com')
|
|
45
|
+
* gamend.on('session', (session) => session ? save(session) : forget())
|
|
46
|
+
* gamend.on('authFailed', () => showLogin())
|
|
47
|
+
* gamend.restore(loadSaved()) // optional: a session saved earlier
|
|
48
|
+
*
|
|
49
|
+
* // Any sign-in made through gamend.client is picked up: email, device, a provider.
|
|
50
|
+
* await new AuthenticationApi(gamend.client).login({ loginRequest: { email, password } })
|
|
51
|
+
* const me = await new UsersApi(gamend.client).getCurrentUser()
|
|
52
|
+
*
|
|
53
|
+
* const realtime = gamend.realtime()
|
|
54
|
+
* realtime.joinUserChannel(gamend.userId)
|
|
55
|
+
*
|
|
56
|
+
* await gamend.signOut()
|
|
57
|
+
*/
|
|
58
|
+
// Refresh this long before the access token expires, so a request sent just
|
|
59
|
+
// before the deadline does not arrive just after it.
|
|
60
|
+
var REFRESH_MARGIN_MS = 60 * 1000;
|
|
61
|
+
var LOGOUT_PATH = '/api/v1/logout';
|
|
62
|
+
var GamendSession = exports.GamendSession = /*#__PURE__*/function () {
|
|
63
|
+
/**
|
|
64
|
+
* @param {string} serverUrl - Base HTTP(S) server URL, e.g. "https://game.example.com"
|
|
65
|
+
*/
|
|
66
|
+
function GamendSession(serverUrl) {
|
|
67
|
+
_classCallCheck(this, GamendSession);
|
|
68
|
+
this._serverUrl = serverUrl.replace(/\/$/, '');
|
|
69
|
+
this._session = null;
|
|
70
|
+
this._generation = 0;
|
|
71
|
+
this._refreshing = null;
|
|
72
|
+
this._listeners = {
|
|
73
|
+
session: new Set(),
|
|
74
|
+
authFailed: new Set()
|
|
75
|
+
};
|
|
76
|
+
this._realtimes = new Set();
|
|
77
|
+
/** The ApiClient to hand every generated API class: `new LobbiesApi(gamend.client)`. */
|
|
78
|
+
this.client = new SessionApiClient(this._serverUrl, this);
|
|
79
|
+
// Refreshes bypass `client`, so their answer is adopted only when no
|
|
80
|
+
// sign-in or sign-out happened while they were in flight.
|
|
81
|
+
this._plainClient = new _ApiClient2["default"](this._serverUrl);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Whether a session is held. */
|
|
85
|
+
return _createClass(GamendSession, [{
|
|
86
|
+
key: "signedIn",
|
|
87
|
+
get: function get() {
|
|
88
|
+
return this._session !== null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The signed-in user's id, or null. */
|
|
92
|
+
}, {
|
|
93
|
+
key: "userId",
|
|
94
|
+
get: function get() {
|
|
95
|
+
return this._session ? this._session.user_id : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The session to save for `restore`: `{access_token, refresh_token,
|
|
100
|
+
* expires_at, user_id}`, `expires_at` in unix ms; null when signed out. The
|
|
101
|
+
* refresh token signs in for 30 days, so store it as you would a password.
|
|
102
|
+
* @returns {Object|null}
|
|
103
|
+
*/
|
|
104
|
+
}, {
|
|
105
|
+
key: "session",
|
|
106
|
+
get: function get() {
|
|
107
|
+
return this._session ? _objectSpread({}, this._session) : null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Resumes a session saved from `session` or the 'session' event. A missing
|
|
112
|
+
* or past `expires_at` makes the first call refresh the access token.
|
|
113
|
+
* @param {Object|null} saved
|
|
114
|
+
*/
|
|
115
|
+
}, {
|
|
116
|
+
key: "restore",
|
|
117
|
+
value: function restore(saved) {
|
|
118
|
+
this._set(saved && saved.refresh_token ? saved : null);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Listens for 'session' (signed in, refreshed or signed out: the new
|
|
123
|
+
* `session`, or null) or 'authFailed' (the server refused the refresh token,
|
|
124
|
+
* as after a sign-out elsewhere or a password change; the session is gone).
|
|
125
|
+
* @param {'session'|'authFailed'} event
|
|
126
|
+
* @param {Function} listener
|
|
127
|
+
* @returns {Function} Call it to stop listening
|
|
128
|
+
*/
|
|
129
|
+
}, {
|
|
130
|
+
key: "on",
|
|
131
|
+
value: function on(event, listener) {
|
|
132
|
+
var listeners = this._listeners[event];
|
|
133
|
+
if (!listeners) throw new Error("GamendSession: unknown event \"".concat(event, "\""));
|
|
134
|
+
listeners.add(listener);
|
|
135
|
+
return function () {
|
|
136
|
+
return listeners["delete"](listener);
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* A valid access token, refreshed first when it expires within a minute;
|
|
142
|
+
* null when signed out. Sockets from `realtime()` call this.
|
|
143
|
+
* @returns {Promise<string|null>}
|
|
144
|
+
*/
|
|
145
|
+
}, {
|
|
146
|
+
key: "getAccessToken",
|
|
147
|
+
value: (function () {
|
|
148
|
+
var _getAccessToken = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
|
|
149
|
+
var session;
|
|
150
|
+
return _regenerator().w(function (_context) {
|
|
151
|
+
while (1) switch (_context.n) {
|
|
152
|
+
case 0:
|
|
153
|
+
session = this._session;
|
|
154
|
+
if (session) {
|
|
155
|
+
_context.n = 1;
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
return _context.a(2, null);
|
|
159
|
+
case 1:
|
|
160
|
+
if (!(Date.now() < session.expires_at - REFRESH_MARGIN_MS)) {
|
|
161
|
+
_context.n = 2;
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
return _context.a(2, session.access_token);
|
|
165
|
+
case 2:
|
|
166
|
+
_context.n = 3;
|
|
167
|
+
return this.refresh();
|
|
168
|
+
case 3:
|
|
169
|
+
return _context.a(2, this._session ? this._session.access_token : null);
|
|
170
|
+
}
|
|
171
|
+
}, _callee, this);
|
|
172
|
+
}));
|
|
173
|
+
function getAccessToken() {
|
|
174
|
+
return _getAccessToken.apply(this, arguments);
|
|
175
|
+
}
|
|
176
|
+
return getAccessToken;
|
|
177
|
+
}()
|
|
178
|
+
/**
|
|
179
|
+
* Exchanges the refresh token for a new access token now; concurrent calls
|
|
180
|
+
* share one request. Resolves true when refreshed, false when signed out,
|
|
181
|
+
* offline (the session is kept for the next try) or refused (the session is
|
|
182
|
+
* dropped and 'authFailed' fires).
|
|
183
|
+
* @returns {Promise<boolean>}
|
|
184
|
+
*/
|
|
185
|
+
)
|
|
186
|
+
}, {
|
|
187
|
+
key: "refresh",
|
|
188
|
+
value: function refresh() {
|
|
189
|
+
var _this = this;
|
|
190
|
+
if (!this._refreshing) {
|
|
191
|
+
this._refreshing = this._refresh()["finally"](function () {
|
|
192
|
+
_this._refreshing = null;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return this._refreshing;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* A GameRealtime socket that asks this session for its token, disconnected
|
|
200
|
+
* when the session ends or another user signs in.
|
|
201
|
+
* @param {Object} socketOpts - As for GameRealtime, e.g. `{ format: 'protobuf' }`
|
|
202
|
+
* @returns {GameRealtime}
|
|
203
|
+
*/
|
|
204
|
+
}, {
|
|
205
|
+
key: "realtime",
|
|
206
|
+
value: function realtime() {
|
|
207
|
+
var _this2 = this;
|
|
208
|
+
var socketOpts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
209
|
+
if (!this._session) throw new Error('GamendSession: sign in before opening a realtime socket');
|
|
210
|
+
var realtime = new _realtime.GameRealtime(this._serverUrl, function () {
|
|
211
|
+
return _this2.getAccessToken();
|
|
212
|
+
}, socketOpts);
|
|
213
|
+
this._realtimes.add(realtime);
|
|
214
|
+
return realtime;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Revokes the tokens on the server (on every device: revocation is per
|
|
219
|
+
* account) and drops the session here, even when the server cannot be reached.
|
|
220
|
+
*/
|
|
221
|
+
}, {
|
|
222
|
+
key: "signOut",
|
|
223
|
+
value: (function () {
|
|
224
|
+
var _signOut = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
|
|
225
|
+
var _t;
|
|
226
|
+
return _regenerator().w(function (_context2) {
|
|
227
|
+
while (1) switch (_context2.p = _context2.n) {
|
|
228
|
+
case 0:
|
|
229
|
+
if (this._session) {
|
|
230
|
+
_context2.n = 1;
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
return _context2.a(2);
|
|
234
|
+
case 1:
|
|
235
|
+
_context2.p = 1;
|
|
236
|
+
_context2.n = 2;
|
|
237
|
+
return new _AuthenticationApi["default"](this.client).logout();
|
|
238
|
+
case 2:
|
|
239
|
+
_context2.n = 4;
|
|
240
|
+
break;
|
|
241
|
+
case 3:
|
|
242
|
+
_context2.p = 3;
|
|
243
|
+
_t = _context2.v;
|
|
244
|
+
case 4:
|
|
245
|
+
return _context2.a(2);
|
|
246
|
+
}
|
|
247
|
+
}, _callee2, this, [[1, 3]]);
|
|
248
|
+
}));
|
|
249
|
+
function signOut() {
|
|
250
|
+
return _signOut.apply(this, arguments);
|
|
251
|
+
}
|
|
252
|
+
return signOut;
|
|
253
|
+
}() // ── Private ────────────────────────────────────────────────────────────────
|
|
254
|
+
)
|
|
255
|
+
}, {
|
|
256
|
+
key: "_refresh",
|
|
257
|
+
value: function () {
|
|
258
|
+
var _refresh2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
|
|
259
|
+
var session, generation, body, _yield$Authentication, response, _t2;
|
|
260
|
+
return _regenerator().w(function (_context3) {
|
|
261
|
+
while (1) switch (_context3.p = _context3.n) {
|
|
262
|
+
case 0:
|
|
263
|
+
session = this._session;
|
|
264
|
+
if (session) {
|
|
265
|
+
_context3.n = 1;
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
return _context3.a(2, false);
|
|
269
|
+
case 1:
|
|
270
|
+
generation = this._generation;
|
|
271
|
+
_context3.p = 2;
|
|
272
|
+
_context3.n = 3;
|
|
273
|
+
return new _AuthenticationApi["default"](this._plainClient).refreshTokenWithHttpInfo({
|
|
274
|
+
refreshTokenRequest: {
|
|
275
|
+
refresh_token: session.refresh_token
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
case 3:
|
|
279
|
+
_yield$Authentication = _context3.v;
|
|
280
|
+
response = _yield$Authentication.response;
|
|
281
|
+
body = response.body;
|
|
282
|
+
_context3.n = 5;
|
|
283
|
+
break;
|
|
284
|
+
case 4:
|
|
285
|
+
_context3.p = 4;
|
|
286
|
+
_t2 = _context3.v;
|
|
287
|
+
if (generation === this._generation && _t2.status === 401) {
|
|
288
|
+
this._set(null);
|
|
289
|
+
this._emit('authFailed');
|
|
290
|
+
}
|
|
291
|
+
return _context3.a(2, false);
|
|
292
|
+
case 5:
|
|
293
|
+
return _context3.a(2, generation === this._generation && this._adopt(body));
|
|
294
|
+
}
|
|
295
|
+
}, _callee3, this, [[2, 4]]);
|
|
296
|
+
}));
|
|
297
|
+
function _refresh() {
|
|
298
|
+
return _refresh2.apply(this, arguments);
|
|
299
|
+
}
|
|
300
|
+
return _refresh;
|
|
301
|
+
}() // After a 401 on a call that sent `sentToken`: true when there is a newer
|
|
302
|
+
// token to retry with.
|
|
303
|
+
}, {
|
|
304
|
+
key: "_recover",
|
|
305
|
+
value: function () {
|
|
306
|
+
var _recover2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(sentToken) {
|
|
307
|
+
return _regenerator().w(function (_context4) {
|
|
308
|
+
while (1) switch (_context4.n) {
|
|
309
|
+
case 0:
|
|
310
|
+
if (this._session) {
|
|
311
|
+
_context4.n = 1;
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
return _context4.a(2, false);
|
|
315
|
+
case 1:
|
|
316
|
+
if (!(this._session.access_token !== sentToken)) {
|
|
317
|
+
_context4.n = 2;
|
|
318
|
+
break;
|
|
319
|
+
}
|
|
320
|
+
return _context4.a(2, true);
|
|
321
|
+
case 2:
|
|
322
|
+
return _context4.a(2, this.refresh());
|
|
323
|
+
}
|
|
324
|
+
}, _callee4, this);
|
|
325
|
+
}));
|
|
326
|
+
function _recover(_x) {
|
|
327
|
+
return _recover2.apply(this, arguments);
|
|
328
|
+
}
|
|
329
|
+
return _recover;
|
|
330
|
+
}() // Takes the session from a sign-in or refresh answer: `data` is a Session,
|
|
331
|
+
// or, for a polled provider sign-in, holds one under `data.session`.
|
|
332
|
+
}, {
|
|
333
|
+
key: "_adopt",
|
|
334
|
+
value: function _adopt(body) {
|
|
335
|
+
var data = body && body.data;
|
|
336
|
+
var session = data && (data.access_token ? data : data.session);
|
|
337
|
+
if (!session || !session.access_token || !session.refresh_token) return false;
|
|
338
|
+
this._set({
|
|
339
|
+
access_token: session.access_token,
|
|
340
|
+
refresh_token: session.refresh_token,
|
|
341
|
+
expires_at: Date.now() + (session.expires_in || 0) * 1000,
|
|
342
|
+
user_id: session.user_id || this.userId
|
|
343
|
+
});
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
}, {
|
|
347
|
+
key: "_set",
|
|
348
|
+
value: function _set(saved) {
|
|
349
|
+
var previous = this._session;
|
|
350
|
+
this._generation++;
|
|
351
|
+
this._session = saved ? {
|
|
352
|
+
access_token: saved.access_token || null,
|
|
353
|
+
refresh_token: saved.refresh_token,
|
|
354
|
+
expires_at: saved.expires_at || 0,
|
|
355
|
+
user_id: saved.user_id || null
|
|
356
|
+
} : null;
|
|
357
|
+
this.client.authentications.authorization.accessToken = this._session ? this._session.access_token : null;
|
|
358
|
+
if (!this._session || previous && previous.user_id !== this._session.user_id) {
|
|
359
|
+
this._realtimes.forEach(function (realtime) {
|
|
360
|
+
return realtime.disconnect();
|
|
361
|
+
});
|
|
362
|
+
this._realtimes.clear();
|
|
363
|
+
}
|
|
364
|
+
this._emit('session', this.session);
|
|
365
|
+
}
|
|
366
|
+
}, {
|
|
367
|
+
key: "_emit",
|
|
368
|
+
value: function _emit(event, value) {
|
|
369
|
+
this._listeners[event].forEach(function (listener) {
|
|
370
|
+
try {
|
|
371
|
+
listener(value);
|
|
372
|
+
} catch (err) {
|
|
373
|
+
console.error("GamendSession: a '".concat(event, "' listener failed"), err);
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
}]);
|
|
378
|
+
}(); // The ApiClient behind `GamendSession.client`: sends the session's access
|
|
379
|
+
// token (refreshed first when due, and once more after a 401), adopts the
|
|
380
|
+
// session a sign-in answers, and signs out with the refresh token.
|
|
381
|
+
var SessionApiClient = /*#__PURE__*/function (_ApiClient) {
|
|
382
|
+
function SessionApiClient(basePath, gamendSession) {
|
|
383
|
+
var _this3;
|
|
384
|
+
_classCallCheck(this, SessionApiClient);
|
|
385
|
+
_this3 = _callSuper(this, SessionApiClient, [basePath]);
|
|
386
|
+
_this3._gamendSession = gamendSession;
|
|
387
|
+
return _this3;
|
|
388
|
+
}
|
|
389
|
+
_inherits(SessionApiClient, _ApiClient);
|
|
390
|
+
return _createClass(SessionApiClient, [{
|
|
391
|
+
key: "callApi",
|
|
392
|
+
value: function () {
|
|
393
|
+
var _callApi = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
|
|
394
|
+
var _this4 = this;
|
|
395
|
+
var _len,
|
|
396
|
+
args,
|
|
397
|
+
_key,
|
|
398
|
+
gamend,
|
|
399
|
+
path,
|
|
400
|
+
headerParams,
|
|
401
|
+
authNames,
|
|
402
|
+
call,
|
|
403
|
+
authed,
|
|
404
|
+
sentToken,
|
|
405
|
+
result,
|
|
406
|
+
_args5 = arguments,
|
|
407
|
+
_t3,
|
|
408
|
+
_t4;
|
|
409
|
+
return _regenerator().w(function (_context5) {
|
|
410
|
+
while (1) switch (_context5.p = _context5.n) {
|
|
411
|
+
case 0:
|
|
412
|
+
for (_len = _args5.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
413
|
+
args[_key] = _args5[_key];
|
|
414
|
+
}
|
|
415
|
+
gamend = this._gamendSession;
|
|
416
|
+
path = args[0], headerParams = args[4], authNames = args[7];
|
|
417
|
+
call = function call() {
|
|
418
|
+
return _ApiClient2["default"].prototype.callApi.apply(_this4, args);
|
|
419
|
+
}; // Logout reads the token itself, so that an expired one can still sign
|
|
420
|
+
// out, and its route is unauthenticated: the generated call sends no
|
|
421
|
+
// token. Send the refresh token, which outlives the access token.
|
|
422
|
+
if (!(path === LOGOUT_PATH)) {
|
|
423
|
+
_context5.n = 5;
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
if (gamend.signedIn) {
|
|
427
|
+
_context5.n = 1;
|
|
428
|
+
break;
|
|
429
|
+
}
|
|
430
|
+
return _context5.a(2, call());
|
|
431
|
+
case 1:
|
|
432
|
+
args[4] = _objectSpread({
|
|
433
|
+
Authorization: "Bearer ".concat(gamend._session.refresh_token)
|
|
434
|
+
}, headerParams);
|
|
435
|
+
_context5.p = 2;
|
|
436
|
+
_context5.n = 3;
|
|
437
|
+
return call();
|
|
438
|
+
case 3:
|
|
439
|
+
return _context5.a(2, _context5.v);
|
|
440
|
+
case 4:
|
|
441
|
+
_context5.p = 4;
|
|
442
|
+
gamend._set(null);
|
|
443
|
+
return _context5.f(4);
|
|
444
|
+
case 5:
|
|
445
|
+
authed = authNames.includes('authorization') && gamend.signedIn;
|
|
446
|
+
if (!authed) {
|
|
447
|
+
_context5.n = 6;
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
_context5.n = 6;
|
|
451
|
+
return gamend.getAccessToken();
|
|
452
|
+
case 6:
|
|
453
|
+
sentToken = this.authentications.authorization.accessToken;
|
|
454
|
+
_context5.p = 7;
|
|
455
|
+
_context5.n = 8;
|
|
456
|
+
return call();
|
|
457
|
+
case 8:
|
|
458
|
+
result = _context5.v;
|
|
459
|
+
_context5.n = 14;
|
|
460
|
+
break;
|
|
461
|
+
case 9:
|
|
462
|
+
_context5.p = 9;
|
|
463
|
+
_t3 = _context5.v;
|
|
464
|
+
_t4 = !authed || _t3.status !== 401;
|
|
465
|
+
if (_t4) {
|
|
466
|
+
_context5.n = 11;
|
|
467
|
+
break;
|
|
468
|
+
}
|
|
469
|
+
_context5.n = 10;
|
|
470
|
+
return gamend._recover(sentToken);
|
|
471
|
+
case 10:
|
|
472
|
+
_t4 = !_context5.v;
|
|
473
|
+
case 11:
|
|
474
|
+
if (!_t4) {
|
|
475
|
+
_context5.n = 12;
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
throw _t3;
|
|
479
|
+
case 12:
|
|
480
|
+
_context5.n = 13;
|
|
481
|
+
return call();
|
|
482
|
+
case 13:
|
|
483
|
+
result = _context5.v;
|
|
484
|
+
case 14:
|
|
485
|
+
gamend._adopt(result.response && result.response.body);
|
|
486
|
+
return _context5.a(2, result);
|
|
487
|
+
}
|
|
488
|
+
}, _callee5, this, [[7, 9], [2,, 4, 5]]);
|
|
489
|
+
}));
|
|
490
|
+
function callApi() {
|
|
491
|
+
return _callApi.apply(this, arguments);
|
|
492
|
+
}
|
|
493
|
+
return callApi;
|
|
494
|
+
}()
|
|
495
|
+
}]);
|
|
496
|
+
}(_ApiClient2["default"]);
|
package/dist/webrtc.js
CHANGED
|
@@ -29,10 +29,10 @@ function _toPrimitive(t, e) { if ("object" != _typeof(t) || !t) return t; var r;
|
|
|
29
29
|
*
|
|
30
30
|
* Usage:
|
|
31
31
|
*
|
|
32
|
-
* import {
|
|
32
|
+
* import { GameWebRTC } from '@ughuuu/gamend'
|
|
33
33
|
*
|
|
34
|
-
* const realtime =
|
|
35
|
-
* const userChannel = realtime.joinUserChannel(userId)
|
|
34
|
+
* const realtime = gamend.realtime() // gamend: a signed-in GamendSession
|
|
35
|
+
* const userChannel = realtime.joinUserChannel(gamend.userId)
|
|
36
36
|
*
|
|
37
37
|
* const webrtc = new GameWebRTC(userChannel, {
|
|
38
38
|
* dataChannels: [
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ughuuu/gamend",
|
|
3
|
-
"version": "1.1.
|
|
4
|
-
"description": "API for Gamend. 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, quests, 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 - **GitHub OAuth**: Use `/api/v1/auth/github` 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 by default), use for API requests; `expires_in` gives its lifetime in seconds - `refresh_token` - Long-lived (30 days by default), 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 - **Push delivery**: notifications also fan out to the recipient's registered mobile devices (see Push notifications) ## **5b. Push notifications** Mobile/web push delivery to registered devices (FCM for Android/Web, APNs-direct for iOS): - **Register device tokens** via `POST /me/push_tokens` (`token`, `platform`, optional `provider`/`device_id`); re-registering a `device_id` rotates its token in place - **List/remove own devices** via `GET /me/push_tokens` and `DELETE /me/push_tokens/:id` - **Server-authoritative sending** — no public send endpoint; pushes originate from server hooks (`Gamend.Push.send_to_user/2`) or the admin API - **Per-token routing**: each token's `provider` (\"fcm\" | \"apns\") selects the delivery backend; unconfigured backends log instead of sending (dev-friendly) - **Reliability**: delivery rides the durable job queue with retries; dead tokens reported by the provider are disabled automatically ## **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 is built in**: an admin-managed word filter (`block` / `mask` / `flag`, matched on a normalized form so leetspeak and padding do not slip through) and mutes are enforced before a message is stored or broadcast; the `before_chat_message` pipeline hook stays available for rules of your own - **Report a message**: `POST /chat/messages/:id/report` with an optional `reason` — one report per player per message, capped per day; reports the filter files itself have no reporter - **Scoped mutes** mirror kick: `POST /lobbies/mute` + `/lobbies/unmute` (lobby host), `POST /groups/:id/mute` + `/groups/:id/unmute` (group admin), `POST /parties/mute` + `/parties/unmute` (party leader), each with a paginated `.../mutes` listing for the same authority. Body is `{target_user_id, expires_at?, reason?}`; omitting `expires_at` mutes permanently - **Global mutes and the blocklist are server-authoritative** — no public endpoint; admin API (`/api/v1/admin/chat`) or a plugin calling `Gamend.Chat.mute_user/4` - **Real-time moderation events**: the muted player receives `chat_muted` / `chat_unmuted` on their user channel ## **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. Quests / Progression** One event-driven progression engine covering achievements, daily/weekly quests, time-boxed event quests, chains, and groups: - **Kinds**: `achievement` (permanent one-shot — the replacement for the old achievements system), `daily`/`weekly` (reset per UTC period), `event` (starts_at/ends_at window), `chain` (requires a prerequisite quest) - **Objectives**: each quest lists objectives `{event, target, params}`; server-side `report_event` advances every matching active quest — there is **no public endpoint to advance progress** (server-authoritative) - **Rewards**: currencies (Economy) and items (Inventory), paid **exactly once** per period via idempotent grants; `auto_claim` quests pay on completion, others via `POST /me/quests/:key/claim` - **My quests**: `GET /me/quests` returns active quests, per-period progress, and a claimable flag; hidden quests appear once completed - **Groups**: quests sharing a `group_key` collapse to one entry carrying `group_size`; `?group=<key>` lists that group's members in full - **Catalog**: `GET /quests` and per-user completions `GET /quests/user/:user_id` (gated by `GAMEND_FEATURES_LIST_QUESTS`) - **Admin management**: definitions CRUD plus per-user grant/reset/force-claim under `/api/v1/admin/quests` ## **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 `match_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. Ready checks** One primitive for \"everyone must answer before this proceeds\", with one client-facing surface: - **A player holds at most one check per lane** — the match lane (lobby ready-up or matchmaking accept) and the party lane (the party's standing board) — so answering needs no id: `GET /me/ready_check` returns `{\"lobby\": …, \"party\": …}` (each null when none) and `POST /me/ready_check` with `{\"ready\": true|false, \"scope\": \"lobby\"|\"party\"}` answers one (scope defaults to `lobby`) - **Two kinds.** `ready` (lobby/party board) is a toggle — a \"no\" just leaves the check open, and it lists every participant. `accept` (match confirmation) is final — one decline fails it for everyone — and returns counts plus your own state, so a pending match does not reveal who you were paired with - **Hosts open one** with `POST /lobbies/ready_check` (host-managed lobbies only; hostless matchmaking lobbies belong to the server), **party leaders** with `POST /parties/ready_check`; either call is a **reset** — it quietly replaces an already-open board with a fresh one over the current members, so the same endpoint serves \"ready check!\", \"force ready\" (with `timeout_ms`) and \"start over\". Call it off with `DELETE /lobbies/ready_check` / `DELETE /parties/ready_check`. The opener is pre-marked ready — clicking the button is their answer - **Failure does nothing on its own**: a declined or timed-out check kicks nobody, starts nothing, and moves no lobby state. It reports who did not answer, and the game (or the host, with the kick they already have) decides - **Live**: `ready_check_started` / `ready_check_updated` / `ready_check_passed` / `ready_check_failed` on the lobby channel, the party channel for a party board, or the user channel for an accept check - **Admin management** over HTTP: list/filter checks, force-cancel, and 24h outcome stats under `/api/v1/admin/ready_checks` ## **15. 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. ### **15.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() ``` ### **15.2 Available Channels** - **User channel** (`user:<user_id>`): notifications, friend events, quest progress/completions/claims, party/group invites, tournament events, chat mutes (`chat_muted` / `chat_unmuted`), 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 ### **15.3 JS SDK Helper** The `GameRealtime` class (included in this SDK) wraps Phoenix.Socket with convenient channel helpers: ```javascript import { GameRealtime } from '@ughuuu/gamend' const realtime = new GameRealtime('https://your-server.com', accessToken) const userChannel = realtime.joinUserChannel(userId) userChannel.on('notification', payload => console.log(payload)) ``` `phoenix` ships as a dependency of the package, so no extra install is needed. ## **16. 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). ### **16.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 ### **16.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **16.3 JS SDK Helper** The `GameWebRTC` class (included in this SDK, browser-only) handles signaling automatically: ```javascript import { GameRealtime, GameWebRTC } from '@ughuuu/gamend' 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.1.1328",
|
|
4
|
+
"description": "API for Gamend. 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, quests, 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 - **GitHub OAuth**: Use `/api/v1/auth/github` 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 by default), use for API requests; `expires_in` gives its lifetime in seconds - `refresh_token` - Long-lived (30 days by default), 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. ### **1.4 Banned Accounts** An admin or the game can ban an account for a while or for good. A banned account still signs in, refreshes and signs out, `GET /api/v1/me` answers with its `ban` (`expires_at`, null when permanent, and `reason`), and `DELETE /api/v1/me` deletes it. Every other authenticated call answers 403 `account_banned`. On the socket it joins only its own user channel, where `account_banned` and `account_unbanned` arrive, and a ban placed while it is connected closes the socket. ## **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 - **Push delivery**: notifications also fan out to the recipient's registered mobile devices (see Push notifications) ## **5b. Push notifications** Mobile/web push delivery to registered devices (FCM for Android/Web, APNs-direct for iOS): - **Register device tokens** via `POST /me/push_tokens` (`token`, `platform`, optional `provider`/`device_id`); re-registering a `device_id` rotates its token in place - **List/remove own devices** via `GET /me/push_tokens` and `DELETE /me/push_tokens/:id` - **Server-authoritative sending** — no public send endpoint; pushes originate from server hooks (`Gamend.Push.send_to_user/2`) or the admin API - **Per-token routing**: each token's `provider` (\"fcm\" | \"apns\") selects the delivery backend; unconfigured backends log instead of sending (dev-friendly) - **Reliability**: delivery rides the durable job queue with retries; dead tokens reported by the provider are disabled automatically ## **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 is built in**: an admin-managed word filter (`block` / `mask` / `flag`, matched on a normalized form so leetspeak and padding do not slip through) and mutes are enforced before a message is stored or broadcast; the `before_chat_message` pipeline hook stays available for rules of your own - **Report a message**: `POST /chat/messages/:id/report` with an optional `reason` — one report per player per message, capped per day; reports the filter files itself have no reporter - **Scoped mutes** mirror kick: `POST /lobbies/mute` + `/lobbies/unmute` (lobby host), `POST /groups/:id/mute` + `/groups/:id/unmute` (group admin), `POST /parties/mute` + `/parties/unmute` (party leader), each with a paginated `.../mutes` listing for the same authority. Body is `{target_user_id, expires_at?, reason?}`; omitting `expires_at` mutes permanently - **Global mutes and the blocklist are server-authoritative** — no public endpoint; admin API (`/api/v1/admin/chat`) or a plugin calling `Gamend.Chat.mute_user/4` - **Real-time moderation events**: the muted player receives `chat_muted` / `chat_unmuted` on their user channel ## **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. Quests / Progression** One event-driven progression engine covering achievements, daily/weekly quests, time-boxed event quests, chains, and groups: - **Kinds**: `achievement` (permanent one-shot — the replacement for the old achievements system), `daily`/`weekly` (reset per UTC period), `event` (starts_at/ends_at window), `chain` (requires a prerequisite quest) - **Objectives**: each quest lists objectives `{event, target, params}`; server-side `report_event` advances every matching active quest — there is **no public endpoint to advance progress** (server-authoritative) - **Rewards**: currencies (Economy) and items (Inventory), paid **exactly once** per period via idempotent grants; `auto_claim` quests pay on completion, others via `POST /me/quests/:key/claim` - **My quests**: `GET /me/quests` returns active quests, per-period progress, and a claimable flag; hidden quests appear once completed - **Groups**: quests sharing a `group_key` collapse to one entry carrying `group_size`; `?group=<key>` lists that group's members in full - **Catalog**: `GET /quests` and per-user completions `GET /quests/user/:user_id` (gated by `GAMEND_FEATURES_LIST_QUESTS`) - **Admin management**: definitions CRUD plus per-user grant/reset/force-claim under `/api/v1/admin/quests` ## **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 `match_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. Ready checks** One primitive for \"everyone must answer before this proceeds\", with one client-facing surface: - **A player holds at most one check per lane** — the match lane (lobby ready-up or matchmaking accept) and the party lane (the party's standing board) — so answering needs no id: `GET /me/ready_check` returns `{\"lobby\": …, \"party\": …}` (each null when none) and `POST /me/ready_check` with `{\"ready\": true|false, \"scope\": \"lobby\"|\"party\"}` answers one (scope defaults to `lobby`) - **Two kinds.** `ready` (lobby/party board) is a toggle — a \"no\" just leaves the check open, and it lists every participant. `accept` (match confirmation) is final — one decline fails it for everyone — and returns counts plus your own state, so a pending match does not reveal who you were paired with - **Hosts open one** with `POST /lobbies/ready_check` (host-managed lobbies only; hostless matchmaking lobbies belong to the server), **party leaders** with `POST /parties/ready_check`; either call is a **reset** — it quietly replaces an already-open board with a fresh one over the current members, so the same endpoint serves \"ready check!\", \"force ready\" (with `timeout_ms`) and \"start over\". Call it off with `DELETE /lobbies/ready_check` / `DELETE /parties/ready_check`. The opener is pre-marked ready — clicking the button is their answer - **Failure does nothing on its own**: a declined or timed-out check kicks nobody, starts nothing, and moves no lobby state. It reports who did not answer, and the game (or the host, with the kick they already have) decides - **Live**: `ready_check_started` / `ready_check_updated` / `ready_check_passed` / `ready_check_failed` on the lobby channel, the party channel for a party board, or the user channel for an accept check - **Admin management** over HTTP: list/filter checks, force-cancel, and 24h outcome stats under `/api/v1/admin/ready_checks` ## **15. 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. ### **15.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() ``` ### **15.2 Available Channels** - **User channel** (`user:<user_id>`): notifications, friend events, quest progress/completions/claims, party/group invites, tournament events, chat mutes (`chat_muted` / `chat_unmuted`), account bans (`account_banned` / `account_unbanned`), 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 ### **15.3 JS SDK Helper** The `GameRealtime` class (included in this SDK) wraps Phoenix.Socket with convenient channel helpers. Open it from a `GamendSession`, which keeps the player signed in and gives the socket a valid token whenever it reconnects: ```javascript import { GamendSession, AuthenticationApi } from '@ughuuu/gamend' const gamend = new GamendSession('https://your-server.com') await new AuthenticationApi(gamend.client).login({ loginRequest: { email, password } }) const realtime = gamend.realtime() const userChannel = realtime.joinUserChannel(gamend.userId) userChannel.on('notification', payload => console.log(payload)) ``` `phoenix` ships as a dependency of the package, so no extra install is needed. ## **16. 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). ### **16.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 ### **16.2 Default DataChannels** - **`events`** (reliable, ordered): important game events (player actions, state changes) - **`state`** (unreliable, unordered): high-frequency position/state sync ### **16.3 JS SDK Helper** The `GameWebRTC` class (included in this SDK, browser-only) handles signaling automatically: ```javascript import { GameWebRTC } from '@ughuuu/gamend' const realtime = gamend.realtime() // gamend: a signed-in GamendSession const userChannel = realtime.joinUserChannel(gamend.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": {
|