Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@heroiclabs/nakama-js

Package Overview
Dependencies
Maintainers
3
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@heroiclabs/nakama-js - npm Package Compare versions

Comparing version 2.1.7 to 2.2.0

16

build.js

@@ -14,15 +14,15 @@ // Copyright 2020 The Nakama Authors

// limitations under the License.
const { exec } = require("child_process");
const { execSync } = require("child_process");
function build(args) {
exec("npx esbuild --bundle index.ts --target=es6 --global-name=nakamajs " + args)
function esbuild(args) {
execSync("npx esbuild --bundle index.ts --target=es6 --global-name=nakamajs " + args)
}
// emit .d.ts files and perform type checking
exec("npx typescript --project packages/nakama-js/tsconfig.json")
execSync("npx typescript --project tsconfig.json", {stdio: 'inherit'})
build(" --format=cjs --outfile=dist/nakama-js.cjs.js")
build(" --format=esm --outfile=dist/nakama-js.esm.js")
build(" --format=iife --outfile=dist/nakama-js.iife.js")
esbuild(" --format=cjs --outfile=dist/nakama-js.cjs.js")
esbuild(" --format=esm --outfile=dist/nakama-js.esm.js")
esbuild(" --format=iife --outfile=dist/nakama-js.iife.js")
exec("npx rollup -c")
execSync("npx rollup -c")

@@ -1,8 +0,1 @@

export interface ConfigurationParameters {
basePath?: string;
username?: string;
password?: string;
bearerToken?: string;
timeoutMs?: number;
}
export interface GroupUserListGroupUser {

@@ -16,4 +9,15 @@ state?: number;

}
export declare enum ValidatedPurchaseEnvironment {
UNKNOWN = 0,
SANDBOX = 1,
PRODUCTION = 2
}
export declare enum ValidatedPurchaseStore {
APPLE_APP_STORE = 0,
GOOGLE_PLAY_STORE = 1,
HUAWEI_APP_GALLERY = 2
}
export interface WriteLeaderboardRecordRequestLeaderboardRecordWrite {
metadata?: string;
operator?: ApiOverrideOperator;
score?: string;

@@ -24,2 +28,3 @@ subscore?: string;

metadata?: string;
operator?: ApiOverrideOperator;
score?: string;

@@ -173,2 +178,6 @@ subscore?: string;

}
export interface ApiLinkSteamRequest {
account?: ApiAccountSteam;
sync?: boolean;
}
export interface ApiMatch {

@@ -198,2 +207,9 @@ authoritative?: boolean;

}
export declare enum ApiOverrideOperator {
NO_OVERRIDE = 0,
BEST = 1,
SET = 2,
INCREMENT = 3,
DECREMENT = 4
}
export interface ApiReadStorageObjectId {

@@ -217,2 +233,6 @@ collection?: string;

}
export interface ApiSessionLogoutRequest {
refresh_token?: string;
token?: string;
}
export interface ApiSessionRefreshRequest {

@@ -321,2 +341,25 @@ token?: string;

}
export interface ApiValidatePurchaseAppleRequest {
receipt?: string;
}
export interface ApiValidatePurchaseGoogleRequest {
purchase?: string;
}
export interface ApiValidatePurchaseHuaweiRequest {
purchase?: string;
signature?: string;
}
export interface ApiValidatePurchaseResponse {
validated_purchases?: Array<ApiValidatedPurchase>;
}
export interface ApiValidatedPurchase {
create_time?: string;
environment?: ValidatedPurchaseEnvironment;
product_id?: string;
provider_response?: string;
purchase_time?: string;
store?: ValidatedPurchaseStore;
transaction_id?: string;
update_time?: string;
}
export interface ApiWriteStorageObject {

@@ -343,76 +386,84 @@ collection?: string;

export declare class NakamaApi {
configuration: ConfigurationParameters;
constructor(configuration: ConfigurationParameters);
doFetch(urlPath: string, method: string, queryParams: any, body?: any, options?: any): Promise<any>;
healthcheck(options?: any): Promise<any>;
getAccount(options?: any): Promise<ApiAccount>;
updateAccount(body: ApiUpdateAccountRequest, options?: any): Promise<any>;
authenticateApple(body: ApiAccountApple, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateCustom(body: ApiAccountCustom, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateDevice(body: ApiAccountDevice, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateEmail(body: ApiAccountEmail, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateFacebook(body: ApiAccountFacebook, create?: boolean, username?: string, sync?: boolean, options?: any): Promise<ApiSession>;
authenticateFacebookInstantGame(body: ApiAccountFacebookInstantGame, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateGameCenter(body: ApiAccountGameCenter, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateGoogle(body: ApiAccountGoogle, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateSteam(body: ApiAccountSteam, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
linkApple(body: ApiAccountApple, options?: any): Promise<any>;
linkCustom(body: ApiAccountCustom, options?: any): Promise<any>;
linkDevice(body: ApiAccountDevice, options?: any): Promise<any>;
linkEmail(body: ApiAccountEmail, options?: any): Promise<any>;
linkFacebook(body: ApiAccountFacebook, sync?: boolean, options?: any): Promise<any>;
linkFacebookInstantGame(body: ApiAccountFacebookInstantGame, options?: any): Promise<any>;
linkGameCenter(body: ApiAccountGameCenter, options?: any): Promise<any>;
linkGoogle(body: ApiAccountGoogle, options?: any): Promise<any>;
linkSteam(body: ApiAccountSteam, options?: any): Promise<any>;
sessionRefresh(body: ApiSessionRefreshRequest, options?: any): Promise<ApiSession>;
unlinkApple(body: ApiAccountApple, options?: any): Promise<any>;
unlinkCustom(body: ApiAccountCustom, options?: any): Promise<any>;
unlinkDevice(body: ApiAccountDevice, options?: any): Promise<any>;
unlinkEmail(body: ApiAccountEmail, options?: any): Promise<any>;
unlinkFacebook(body: ApiAccountFacebook, options?: any): Promise<any>;
unlinkFacebookInstantGame(body: ApiAccountFacebookInstantGame, options?: any): Promise<any>;
unlinkGameCenter(body: ApiAccountGameCenter, options?: any): Promise<any>;
unlinkGoogle(body: ApiAccountGoogle, options?: any): Promise<any>;
unlinkSteam(body: ApiAccountSteam, options?: any): Promise<any>;
listChannelMessages(channelId: string, limit?: number, forward?: boolean, cursor?: string, options?: any): Promise<ApiChannelMessageList>;
event(body: ApiEvent, options?: any): Promise<any>;
deleteFriends(ids?: Array<string>, usernames?: Array<string>, options?: any): Promise<any>;
listFriends(limit?: number, state?: number, cursor?: string, options?: any): Promise<ApiFriendList>;
addFriends(ids?: Array<string>, usernames?: Array<string>, options?: any): Promise<any>;
blockFriends(ids?: Array<string>, usernames?: Array<string>, options?: any): Promise<any>;
importFacebookFriends(body: ApiAccountFacebook, reset?: boolean, options?: any): Promise<any>;
listGroups(name?: string, cursor?: string, limit?: number, options?: any): Promise<ApiGroupList>;
createGroup(body: ApiCreateGroupRequest, options?: any): Promise<ApiGroup>;
deleteGroup(groupId: string, options?: any): Promise<any>;
updateGroup(groupId: string, body: ApiUpdateGroupRequest, options?: any): Promise<any>;
addGroupUsers(groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
banGroupUsers(groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
demoteGroupUsers(groupId: string, userIds: Array<string>, options?: any): Promise<any>;
joinGroup(groupId: string, options?: any): Promise<any>;
kickGroupUsers(groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
leaveGroup(groupId: string, options?: any): Promise<any>;
promoteGroupUsers(groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
listGroupUsers(groupId: string, limit?: number, state?: number, cursor?: string, options?: any): Promise<ApiGroupUserList>;
deleteLeaderboardRecord(leaderboardId: string, options?: any): Promise<any>;
listLeaderboardRecords(leaderboardId: string, ownerIds?: Array<string>, limit?: number, cursor?: string, expiry?: string, options?: any): Promise<ApiLeaderboardRecordList>;
writeLeaderboardRecord(leaderboardId: string, body: WriteLeaderboardRecordRequestLeaderboardRecordWrite, options?: any): Promise<ApiLeaderboardRecord>;
listLeaderboardRecordsAroundOwner(leaderboardId: string, ownerId: string, limit?: number, expiry?: string, options?: any): Promise<ApiLeaderboardRecordList>;
listMatches(limit?: number, authoritative?: boolean, label?: string, minSize?: number, maxSize?: number, query?: string, options?: any): Promise<ApiMatchList>;
deleteNotifications(ids?: Array<string>, options?: any): Promise<any>;
listNotifications(limit?: number, cacheableCursor?: string, options?: any): Promise<ApiNotificationList>;
rpcFunc2(id: string, payload?: string, httpKey?: string, options?: any): Promise<ApiRpc>;
rpcFunc(id: string, body: string, httpKey?: string, options?: any): Promise<ApiRpc>;
readStorageObjects(body: ApiReadStorageObjectsRequest, options?: any): Promise<ApiStorageObjects>;
writeStorageObjects(body: ApiWriteStorageObjectsRequest, options?: any): Promise<ApiStorageObjectAcks>;
deleteStorageObjects(body: ApiDeleteStorageObjectsRequest, options?: any): Promise<any>;
listStorageObjects(collection: string, userId?: string, limit?: number, cursor?: string, options?: any): Promise<ApiStorageObjectList>;
listStorageObjects2(collection: string, userId: string, limit?: number, cursor?: string, options?: any): Promise<ApiStorageObjectList>;
listTournaments(categoryStart?: number, categoryEnd?: number, startTime?: number, endTime?: number, limit?: number, cursor?: string, options?: any): Promise<ApiTournamentList>;
listTournamentRecords(tournamentId: string, ownerIds?: Array<string>, limit?: number, cursor?: string, expiry?: string, options?: any): Promise<ApiTournamentRecordList>;
writeTournamentRecord(tournamentId: string, body: WriteTournamentRecordRequestTournamentRecordWrite, options?: any): Promise<ApiLeaderboardRecord>;
joinTournament(tournamentId: string, options?: any): Promise<any>;
listTournamentRecordsAroundOwner(tournamentId: string, ownerId: string, limit?: number, expiry?: string, options?: any): Promise<ApiTournamentRecordList>;
getUsers(ids?: Array<string>, usernames?: Array<string>, facebookIds?: Array<string>, options?: any): Promise<ApiUsers>;
listUserGroups(userId: string, limit?: number, state?: number, cursor?: string, options?: any): Promise<ApiUserGroupList>;
readonly serverKey: string;
readonly basePath: string;
readonly timeoutMs: number;
constructor(serverKey: string, basePath: string, timeoutMs: number);
healthcheck(bearerToken: string, options?: any): Promise<any>;
getAccount(bearerToken: string, options?: any): Promise<ApiAccount>;
updateAccount(bearerToken: string, body: ApiUpdateAccountRequest, options?: any): Promise<any>;
authenticateApple(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountApple, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateCustom(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountCustom, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateDevice(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountDevice, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateEmail(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountEmail, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateFacebook(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountFacebook, create?: boolean, username?: string, sync?: boolean, options?: any): Promise<ApiSession>;
authenticateFacebookInstantGame(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountFacebookInstantGame, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateGameCenter(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountGameCenter, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateGoogle(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountGoogle, create?: boolean, username?: string, options?: any): Promise<ApiSession>;
authenticateSteam(basicAuthUsername: string, basicAuthPassword: string, body: ApiAccountSteam, create?: boolean, username?: string, sync?: boolean, options?: any): Promise<ApiSession>;
linkApple(bearerToken: string, body: ApiAccountApple, options?: any): Promise<any>;
linkCustom(bearerToken: string, body: ApiAccountCustom, options?: any): Promise<any>;
linkDevice(bearerToken: string, body: ApiAccountDevice, options?: any): Promise<any>;
linkEmail(bearerToken: string, body: ApiAccountEmail, options?: any): Promise<any>;
linkFacebook(bearerToken: string, body: ApiAccountFacebook, sync?: boolean, options?: any): Promise<any>;
linkFacebookInstantGame(bearerToken: string, body: ApiAccountFacebookInstantGame, options?: any): Promise<any>;
linkGameCenter(bearerToken: string, body: ApiAccountGameCenter, options?: any): Promise<any>;
linkGoogle(bearerToken: string, body: ApiAccountGoogle, options?: any): Promise<any>;
linkSteam(bearerToken: string, body: ApiLinkSteamRequest, options?: any): Promise<any>;
sessionRefresh(basicAuthUsername: string, basicAuthPassword: string, body: ApiSessionRefreshRequest, options?: any): Promise<ApiSession>;
unlinkApple(bearerToken: string, body: ApiAccountApple, options?: any): Promise<any>;
unlinkCustom(bearerToken: string, body: ApiAccountCustom, options?: any): Promise<any>;
unlinkDevice(bearerToken: string, body: ApiAccountDevice, options?: any): Promise<any>;
unlinkEmail(bearerToken: string, body: ApiAccountEmail, options?: any): Promise<any>;
unlinkFacebook(bearerToken: string, body: ApiAccountFacebook, options?: any): Promise<any>;
unlinkFacebookInstantGame(bearerToken: string, body: ApiAccountFacebookInstantGame, options?: any): Promise<any>;
unlinkGameCenter(bearerToken: string, body: ApiAccountGameCenter, options?: any): Promise<any>;
unlinkGoogle(bearerToken: string, body: ApiAccountGoogle, options?: any): Promise<any>;
unlinkSteam(bearerToken: string, body: ApiAccountSteam, options?: any): Promise<any>;
listChannelMessages(bearerToken: string, channelId: string, limit?: number, forward?: boolean, cursor?: string, options?: any): Promise<ApiChannelMessageList>;
event(bearerToken: string, body: ApiEvent, options?: any): Promise<any>;
deleteFriends(bearerToken: string, ids?: Array<string>, usernames?: Array<string>, options?: any): Promise<any>;
listFriends(bearerToken: string, limit?: number, state?: number, cursor?: string, options?: any): Promise<ApiFriendList>;
addFriends(bearerToken: string, ids?: Array<string>, usernames?: Array<string>, options?: any): Promise<any>;
blockFriends(bearerToken: string, ids?: Array<string>, usernames?: Array<string>, options?: any): Promise<any>;
importFacebookFriends(bearerToken: string, body: ApiAccountFacebook, reset?: boolean, options?: any): Promise<any>;
importSteamFriends(bearerToken: string, body: ApiAccountSteam, reset?: boolean, options?: any): Promise<any>;
listGroups(bearerToken: string, name?: string, cursor?: string, limit?: number, options?: any): Promise<ApiGroupList>;
createGroup(bearerToken: string, body: ApiCreateGroupRequest, options?: any): Promise<ApiGroup>;
deleteGroup(bearerToken: string, groupId: string, options?: any): Promise<any>;
updateGroup(bearerToken: string, groupId: string, body: ApiUpdateGroupRequest, options?: any): Promise<any>;
addGroupUsers(bearerToken: string, groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
banGroupUsers(bearerToken: string, groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
demoteGroupUsers(bearerToken: string, groupId: string, userIds: Array<string>, options?: any): Promise<any>;
joinGroup(bearerToken: string, groupId: string, options?: any): Promise<any>;
kickGroupUsers(bearerToken: string, groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
leaveGroup(bearerToken: string, groupId: string, options?: any): Promise<any>;
promoteGroupUsers(bearerToken: string, groupId: string, userIds?: Array<string>, options?: any): Promise<any>;
listGroupUsers(bearerToken: string, groupId: string, limit?: number, state?: number, cursor?: string, options?: any): Promise<ApiGroupUserList>;
validatePurchaseApple(bearerToken: string, body: ApiValidatePurchaseAppleRequest, options?: any): Promise<ApiValidatePurchaseResponse>;
validatePurchaseGoogle(bearerToken: string, body: ApiValidatePurchaseGoogleRequest, options?: any): Promise<ApiValidatePurchaseResponse>;
validatePurchaseHuawei(bearerToken: string, body: ApiValidatePurchaseHuaweiRequest, options?: any): Promise<ApiValidatePurchaseResponse>;
deleteLeaderboardRecord(bearerToken: string, leaderboardId: string, options?: any): Promise<any>;
listLeaderboardRecords(bearerToken: string, leaderboardId: string, ownerIds?: Array<string>, limit?: number, cursor?: string, expiry?: string, options?: any): Promise<ApiLeaderboardRecordList>;
writeLeaderboardRecord(bearerToken: string, leaderboardId: string, body: WriteLeaderboardRecordRequestLeaderboardRecordWrite, options?: any): Promise<ApiLeaderboardRecord>;
listLeaderboardRecordsAroundOwner(bearerToken: string, leaderboardId: string, ownerId: string, limit?: number, expiry?: string, options?: any): Promise<ApiLeaderboardRecordList>;
listMatches(bearerToken: string, limit?: number, authoritative?: boolean, label?: string, minSize?: number, maxSize?: number, query?: string, options?: any): Promise<ApiMatchList>;
deleteNotifications(bearerToken: string, ids?: Array<string>, options?: any): Promise<any>;
listNotifications(bearerToken: string, limit?: number, cacheableCursor?: string, options?: any): Promise<ApiNotificationList>;
rpcFunc2(bearerToken: string, id: string, payload?: string, httpKey?: string, options?: any): Promise<ApiRpc>;
rpcFunc(bearerToken: string, id: string, body: string, httpKey?: string, options?: any): Promise<ApiRpc>;
sessionLogout(bearerToken: string, body: ApiSessionLogoutRequest, options?: any): Promise<any>;
readStorageObjects(bearerToken: string, body: ApiReadStorageObjectsRequest, options?: any): Promise<ApiStorageObjects>;
writeStorageObjects(bearerToken: string, body: ApiWriteStorageObjectsRequest, options?: any): Promise<ApiStorageObjectAcks>;
deleteStorageObjects(bearerToken: string, body: ApiDeleteStorageObjectsRequest, options?: any): Promise<any>;
listStorageObjects(bearerToken: string, collection: string, userId?: string, limit?: number, cursor?: string, options?: any): Promise<ApiStorageObjectList>;
listStorageObjects2(bearerToken: string, collection: string, userId: string, limit?: number, cursor?: string, options?: any): Promise<ApiStorageObjectList>;
listTournaments(bearerToken: string, categoryStart?: number, categoryEnd?: number, startTime?: number, endTime?: number, limit?: number, cursor?: string, options?: any): Promise<ApiTournamentList>;
listTournamentRecords(bearerToken: string, tournamentId: string, ownerIds?: Array<string>, limit?: number, cursor?: string, expiry?: string, options?: any): Promise<ApiTournamentRecordList>;
writeTournamentRecord2(bearerToken: string, tournamentId: string, body: WriteTournamentRecordRequestTournamentRecordWrite, options?: any): Promise<ApiLeaderboardRecord>;
writeTournamentRecord(bearerToken: string, tournamentId: string, body: WriteTournamentRecordRequestTournamentRecordWrite, options?: any): Promise<ApiLeaderboardRecord>;
joinTournament(bearerToken: string, tournamentId: string, options?: any): Promise<any>;
listTournamentRecordsAroundOwner(bearerToken: string, tournamentId: string, ownerId: string, limit?: number, expiry?: string, options?: any): Promise<ApiTournamentRecordList>;
getUsers(bearerToken: string, ids?: Array<string>, usernames?: Array<string>, facebookIds?: Array<string>, options?: any): Promise<ApiUsers>;
listUserGroups(bearerToken: string, userId: string, limit?: number, state?: number, cursor?: string, options?: any): Promise<ApiUserGroupList>;
buildFullUrl(basePath: string, fragment: string, queryParams: Map<string, any>): string;
}

@@ -1,2 +0,2 @@

import { ApiAccount, ApiAccountCustom, ApiAccountDevice, ApiAccountEmail, ApiAccountFacebook, ApiAccountFacebookInstantGame, ApiAccountGoogle, ApiAccountGameCenter, ApiAccountSteam, ApiCreateGroupRequest, ApiDeleteStorageObjectsRequest, ApiEvent, ApiMatchList, ApiReadStorageObjectsRequest, ApiStorageObjectAcks, ApiUpdateAccountRequest, ApiUpdateGroupRequest, ApiAccountApple } from "./api.gen";
import { ApiAccount, ApiAccountCustom, ApiAccountDevice, ApiAccountEmail, ApiAccountFacebook, ApiAccountFacebookInstantGame, ApiAccountGoogle, ApiAccountGameCenter, ApiAccountSteam, ApiCreateGroupRequest, ApiDeleteStorageObjectsRequest, ApiEvent, ApiMatchList, ApiReadStorageObjectsRequest, ApiStorageObjectAcks, ApiUpdateAccountRequest, ApiUpdateGroupRequest, ApiAccountApple, ApiLinkSteamRequest, ApiValidatePurchaseResponse } from "./api.gen";
import { Session } from "./session";

@@ -199,5 +199,6 @@ import { Socket } from "./socket";

readonly timeout: number;
readonly autoRefreshSession: boolean;
expiredTimespanMs: number;
private readonly apiClient;
private readonly configuration;
constructor(serverkey?: string, host?: string, port?: string, useSSL?: boolean, timeout?: number);
constructor(serverkey?: string, host?: string, port?: string, useSSL?: boolean, timeout?: number, autoRefreshSession?: boolean);
addGroupUsers(session: Session, groupId: string, ids?: Array<string>): Promise<boolean>;

@@ -213,3 +214,3 @@ addFriends(session: Session, ids?: Array<string>, usernames?: Array<string>): Promise<boolean>;

authenticateGameCenter(token: string, create?: boolean, username?: string, vars?: Map<string, string>): Promise<Session>;
authenticateSteam(token: string, create?: boolean, username?: string, vars?: Map<string, string>): Promise<Session>;
authenticateSteam(token: string, create?: boolean, username?: string, sync?: boolean, vars?: Map<string, string>): Promise<Session>;
banGroupUsers(session: Session, groupId: string, ids?: Array<string>): Promise<boolean>;

@@ -227,2 +228,3 @@ blockFriends(session: Session, ids?: Array<string>, usernames?: Array<string>): Promise<boolean>;

importFacebookFriends(session: Session, request: ApiAccountFacebook): Promise<boolean>;
importSteamFriends(session: Session, request: ApiAccountSteam, reset: boolean): Promise<boolean>;
getUsers(session: Session, ids?: Array<string>, usernames?: Array<string>, facebookIds?: Array<string>): Promise<Users>;

@@ -245,3 +247,3 @@ joinGroup(session: Session, groupId: string): Promise<boolean>;

linkGameCenter(session: Session, request: ApiAccountGameCenter): Promise<boolean>;
linkSteam(session: Session, request: ApiAccountSteam): Promise<boolean>;
linkSteam(session: Session, request: ApiLinkSteamRequest): Promise<boolean>;
listFriends(session: Session, state?: number, limit?: number, cursor?: string): Promise<Friends>;

@@ -259,3 +261,5 @@ listLeaderboardRecords(session: Session, leaderboardId: string, ownerIds?: Array<string>, limit?: number, cursor?: string, expiry?: string): Promise<LeaderboardRecordList>;

rpc(session: Session, id: string, input: object): Promise<RpcResponse>;
rpcGet(id: string, session?: Session, httpKey?: string, input?: object): Promise<RpcResponse>;
rpcHttpKey(id: string, httpKey?: string, input?: object): Promise<RpcResponse>;
sessionLogout(session: Session, token: string, refreshToken: string): Promise<boolean>;
sessionRefresh(session: Session, vars?: Map<string, string>): Promise<Session>;
unlinkApple(session: Session, request: ApiAccountApple): Promise<boolean>;

@@ -272,2 +276,5 @@ unlinkCustom(session: Session, request: ApiAccountCustom): Promise<boolean>;

updateGroup(session: Session, groupId: string, request: ApiUpdateGroupRequest): Promise<boolean>;
validatePurchaseApple(session: Session, receipt?: string): Promise<ApiValidatePurchaseResponse>;
validatePurchaseGoogle(session: Session, purchase?: string): Promise<ApiValidatePurchaseResponse>;
validatePurchaseHuawei(session: Session, purchase?: string, signature?: string): Promise<ApiValidatePurchaseResponse>;
writeLeaderboardRecord(session: Session, leaderboardId: string, request: WriteLeaderboardRecord): Promise<LeaderboardRecord>;

@@ -274,0 +281,0 @@ writeStorageObjects(session: Session, objects: Array<WriteStorageObject>): Promise<ApiStorageObjectAcks>;

export interface ISession {
readonly token: string;
token: string;
created: boolean;
readonly created_at: number;
readonly expires_at: number;
readonly username: string;
readonly user_id: string;
readonly vars: object;
expires_at?: number;
refresh_expires_at?: number;
refresh_token: string;
username?: string;
user_id?: string;
vars?: object;
isexpired(currenttime: number): boolean;
isrefreshexpired(currenttime: number): boolean;
}
export declare class Session {
readonly token: string;
export declare class Session implements ISession {
readonly created: boolean;
token: string;
readonly created_at: number;
readonly expires_at: number;
readonly username: string;
readonly user_id: string;
readonly vars: object;
constructor(token: string, created_at: number, expires_at: number, username: string, user_id: string, vars: object);
expires_at?: number;
refresh_expires_at?: number;
refresh_token: string;
username?: string;
user_id?: string;
vars?: object;
constructor(token: string, refresh_token: string, created: boolean);
isexpired(currenttime: number): boolean;
static restore(jwt: string): Session;
isrefreshexpired(currenttime: number): boolean;
update(token: string, refreshToken: string): void;
static restore(token: string, refreshToken: string): Session;
}

@@ -17,3 +17,3 @@ import { ApiRpc } from "./api.gen";

}
export interface ChannelJoin {
interface ChannelJoin {
channel_join: {

@@ -26,3 +26,3 @@ target: string;

}
export interface ChannelLeave {
interface ChannelLeave {
channel_leave: {

@@ -56,3 +56,3 @@ channel_id: string;

}
export interface ChannelMessageSend {
interface ChannelMessageSend {
channel_message_send: {

@@ -63,3 +63,3 @@ channel_id: string;

}
export interface ChannelMessageUpdate {
interface ChannelMessageUpdate {
channel_message_update: {

@@ -71,3 +71,3 @@ channel_id: string;

}
export interface ChannelMessageRemove {
interface ChannelMessageRemove {
channel_message_remove: {

@@ -104,3 +104,3 @@ channel_id: string;

}
export interface MatchmakerAdd {
interface MatchmakerAdd {
matchmaker_add: {

@@ -114,3 +114,6 @@ min_count: number;

}
export interface MatchmakerRemove {
export interface MatchmakerTicket {
ticket: string;
}
interface MatchmakerRemove {
matchmaker_remove: {

@@ -122,2 +125,3 @@ ticket: string;

presence: Presence;
party_id: string;
string_properties?: Record<string, string>;

@@ -141,6 +145,6 @@ numeric_properties?: Record<string, number>;

}
export interface CreateMatch {
interface CreateMatch {
match_create: {};
}
export interface JoinMatch {
interface JoinMatch {
match_join: {

@@ -152,3 +156,3 @@ match_id?: string;

}
export interface LeaveMatch {
interface LeaveMatch {
match_leave: {

@@ -164,6 +168,104 @@ match_id: string;

}
export interface MatchDataSend {
interface MatchDataSend {
match_data_send: RequireKeys<MatchData, "match_id" | "op_code" | "data">;
}
export interface Rpc {
export interface Party {
party_id: string;
open: boolean;
max_size: number;
self: Presence;
leader: Presence;
presences: Presence[];
}
export interface PartyCreate {
party_create: {
open: boolean;
max_size: number;
};
}
interface PartyJoin {
party_join: {
party_id: string;
};
}
interface PartyLeave {
party_leave: {
party_id: string;
};
}
interface PartyPromote {
party_promote: {
party_id: string;
presence: Presence;
};
}
export interface PartyLeader {
party_id: string;
presence: Presence;
}
interface PartyAccept {
party_accept: {
party_id: string;
presence: Presence;
};
}
interface PartyClose {
party_close: {
party_id: string;
};
}
export interface PartyData {
party_id: string;
presence: Presence;
op_code: number;
data: any;
}
interface PartyDataSend {
party_data_send: {
party_id: string;
op_code: number;
data: any;
};
}
export interface PartyJoinRequest {
party_id: string;
presences: Presence[];
}
export interface PartyJoinRequestList {
party_join_request_list: {
party_id: string;
};
}
interface PartyMatchmakerAdd {
party_matchmaker_add: {
party_id: string;
min_count: number;
max_count: number;
query: string;
string_properties?: Record<string, string>;
numeric_properties?: Record<string, number>;
};
}
interface PartyMatchmakerRemove {
party_matchmaker_remove: {
party_id: string;
ticket: string;
};
}
export interface PartyMatchmakerTicket {
party_id: string;
ticket: string;
}
export interface PartyPresenceEvent {
party_id: string;
joins: Presence[];
leaves: Presence[];
}
interface PartyRemove {
party_remove: {
party_id: string;
presence: Presence;
};
}
interface Rpc {
rpc: ApiRpc;

@@ -174,3 +276,3 @@ }

}
export interface StatusFollow {
interface StatusFollow {
status_follow: {

@@ -184,3 +286,3 @@ user_ids: string[];

}
export interface StatusUnfollow {
interface StatusUnfollow {
status_unfollow: {

@@ -190,3 +292,3 @@ user_ids: string[];

}
export interface StatusUpdate {
interface StatusUpdate {
status_update: {

@@ -199,14 +301,24 @@ status?: string;

disconnect(fireDisconnectEvent: boolean): void;
send(message: ChannelJoin | ChannelLeave | ChannelMessageSend | ChannelMessageUpdate | ChannelMessageRemove | CreateMatch | JoinMatch | LeaveMatch | MatchDataSend | MatchmakerAdd | MatchmakerRemove | Rpc | StatusFollow | StatusUnfollow | StatusUpdate): Promise<any>;
addMatchmaker(query: string, minCount: number, maxCount: number, stringProperties?: Record<string, string>, numericProperties?: Record<string, number>): Promise<MatchmakerMatched>;
acceptPartyMember(party_id: string, presence: Presence): Promise<void>;
addMatchmaker(query: string, minCount: number, maxCount: number, stringProperties?: Record<string, string>, numericProperties?: Record<string, number>): Promise<MatchmakerTicket>;
addMatchmakerParty(party_id: string, query: string, min_count: number, max_count: number, string_properties?: Record<string, string>, numericProperties?: Record<string, number>): Promise<PartyMatchmakerTicket>;
closeParty(party_id: string): Promise<void>;
createMatch(): Promise<Match>;
createParty(open: boolean, max_size: number): Promise<Party>;
followUsers(user_ids: string[]): Promise<Status>;
joinChat(target: string, type: number, persistence: boolean, hidden: boolean): Promise<Channel>;
joinParty(party_id: string): Promise<void>;
joinMatch(match_id?: string, token?: string, metadata?: {}): Promise<Match>;
leaveChat(channel_id: string): Promise<void>;
leaveMatch(matchId: string): Promise<void>;
leaveParty(party_id: string): Promise<void>;
listPartyJoinRequests(party_id: string): Promise<PartyJoinRequest>;
promotePartyMember(party_id: string, party_member: Presence): Promise<PartyLeader>;
removeChatMessage(channel_id: string, message_id: string): Promise<ChannelMessageAck>;
removeMatchmaker(ticket: string): Promise<void>;
removeMatchmakerParty(party_id: string, ticket: string): Promise<void>;
removePartyMember(party_id: string, presence: Presence): Promise<void>;
rpc(id?: string, payload?: string, http_key?: string): Promise<ApiRpc>;
sendMatchState(matchId: string, opCode: number, data: any, presence?: Presence[]): Promise<void>;
sendPartyData(party_id: string, opcode: number, data: any): Promise<void>;
unfollowUsers(user_ids: string[]): Promise<void>;

@@ -221,3 +333,11 @@ updateChatMessage(channel_id: string, message_id: string, content: any): Promise<ChannelMessageAck>;

onmatchpresence: (matchPresence: MatchPresenceEvent) => void;
onmatchmakerticket: (matchmakerTicket: MatchmakerTicket) => void;
onmatchmakermatched: (matchmakerMatched: MatchmakerMatched) => void;
onparty: (party: Party) => void;
onpartyclose: (partyClose: PartyClose) => void;
onpartydata: (partyData: PartyData) => void;
onpartyjoinrequest: (partyJoinRequest: PartyJoinRequest) => void;
onpartyleader: (partyLeader: PartyLeader) => void;
onpartypresence: (partyPresence: PartyPresenceEvent) => void;
onpartymatchmakerticket: (partyMatchmakerMatched: PartyMatchmakerTicket) => void;
onstatuspresence: (statusPresence: StatusPresenceEvent) => void;

@@ -252,18 +372,37 @@ onstreampresence: (streamPresence: StreamPresenceEvent) => void;

onmatchpresence(matchPresence: MatchPresenceEvent): void;
onmatchmakerticket(matchmakerTicket: MatchmakerTicket): void;
onmatchmakermatched(matchmakerMatched: MatchmakerMatched): void;
onparty(party: Party): void;
onpartyclose(): void;
onpartyjoinrequest(partyJoinRequest: PartyJoinRequest): void;
onpartydata(partyData: PartyData): void;
onpartyleader(partyLeader: PartyLeader): void;
onpartymatchmakerticket(partyMatched: PartyMatchmakerTicket): void;
onpartypresence(partyPresence: PartyPresenceEvent): void;
onstatuspresence(statusPresence: StatusPresenceEvent): void;
onstreampresence(streamPresence: StreamPresenceEvent): void;
onstreamdata(streamData: StreamData): void;
send(message: ChannelJoin | ChannelLeave | ChannelMessageSend | ChannelMessageUpdate | ChannelMessageRemove | CreateMatch | JoinMatch | LeaveMatch | MatchDataSend | MatchmakerAdd | MatchmakerRemove | Rpc | StatusFollow | StatusUnfollow | StatusUpdate): Promise<any>;
addMatchmaker(query: string, minCount: number, maxCount: number, stringProperties?: Record<string, string>, numericProperties?: Record<string, number>): Promise<MatchmakerMatched>;
send(message: ChannelJoin | ChannelLeave | ChannelMessageSend | ChannelMessageUpdate | ChannelMessageRemove | CreateMatch | JoinMatch | LeaveMatch | MatchDataSend | MatchmakerAdd | MatchmakerRemove | PartyAccept | PartyClose | PartyCreate | PartyDataSend | PartyJoin | PartyJoinRequestList | PartyLeave | PartyMatchmakerAdd | PartyMatchmakerRemove | PartyPromote | PartyRemove | Rpc | StatusFollow | StatusUnfollow | StatusUpdate): Promise<any>;
acceptPartyMember(party_id: string, presence: Presence): Promise<void>;
addMatchmaker(query: string, min_count: number, max_count: number, string_properties?: Record<string, string>, numeric_properties?: Record<string, number>): Promise<MatchmakerTicket>;
addMatchmakerParty(party_id: string, query: string, min_count: number, max_count: number, string_properties?: Record<string, string>, numeric_properties?: Record<string, number>): Promise<PartyMatchmakerTicket>;
closeParty(party_id: string): Promise<void>;
createMatch(): Promise<Match>;
createParty(open: boolean, max_size: number): Promise<Party>;
followUsers(userIds: string[]): Promise<Status>;
joinChat(target: string, type: number, persistence: boolean, hidden: boolean): Promise<Channel>;
joinMatch(match_id?: string, token?: string, metadata?: {}): Promise<Match>;
joinParty(party_id: string): Promise<void>;
leaveChat(channel_id: string): Promise<void>;
leaveMatch(matchId: string): Promise<void>;
leaveParty(party_id: string): Promise<void>;
listPartyJoinRequests(party_id: string): Promise<PartyJoinRequest>;
promotePartyMember(party_id: string, party_member: Presence): Promise<PartyLeader>;
removeChatMessage(channel_id: string, message_id: string): Promise<ChannelMessageAck>;
removeMatchmaker(ticket: string): Promise<void>;
removeMatchmakerParty(party_id: string, ticket: string): Promise<void>;
removePartyMember(party_id: string, member: Presence): Promise<void>;
rpc(id?: string, payload?: string, http_key?: string): Promise<ApiRpc>;
sendMatchState(matchId: string, opCode: number, data: any, presences?: Presence[]): Promise<void>;
sendPartyData(party_id: string, op_code: number, data: any): Promise<void>;
unfollowUsers(user_ids: string[]): Promise<void>;

@@ -270,0 +409,0 @@ updateChatMessage(channel_id: string, message_id: string, content: any): Promise<ChannelMessageAck>;

@@ -0,2 +1,3 @@

export declare function buildFetchOptions(method: string, options: any, bodyJson: string): any;
export declare function b64EncodeUnicode(str: string): string;
export declare function b64DecodeUnicode(str: string): string;

@@ -9,3 +9,3 @@ export interface WebSocketAdapter {

connect(scheme: string, host: string, port: string, createStatus: boolean, token: string): void;
send(msg: any): void;
send(message: any): void;
}

@@ -12,0 +12,0 @@ export interface SocketCloseHandler {

{
"name": "@heroiclabs/nakama-js",
"version": "2.1.7",
"version": "2.2.0",
"scripts": {

@@ -5,0 +5,0 @@ "build": "node build.js"

@@ -62,2 +62,3 @@ Nakama JavaScript client

console.info(session.token); // raw JWT token
console.info(session.refreshToken); // refresh token
console.info(session.userId);

@@ -75,5 +76,19 @@ console.info(session.username);

const authtoken = window.localStorage.getItem("nkauthtoken");
const session = nakamajs.Session.restore(authtoken);
if (session.isexpired(Date.now() / 1000)) {
console.warn("Session has expired. Must reauthenticate.");
const refreshtoken = window.localStorage.getItem("nkrefreshtoken");
let session = nakamajs.Session.restore(authtoken, refreshtoken);
// Check whether a session is close to expiry.
const unixTimeInFuture = Date.now() + 8.64e+7; // one day from now
if (session.isexpired(unixTimeInFuture / 1000)) {
try
{
session = await client.sessionRefresh(session);
}
catch (e)
{
console.info("Session can no longer be refreshed. Must reauthenticate!");
}
}

@@ -170,5 +185,11 @@ ```

Note on Yarn workspaces and testing particular versions of `nakama-js` from the `nakama-js-test` workspace:
Yarn will first look at the remote NPM registry for the `nakama-js` version specified. If that is not found,
it will symlink the local `nakama-js` workspace into `node_modules` which is necessary for running tests
against local changes.
### Protocol Buffer Web Socket Adapter
To update the generated Typescript required for using the protocol buffer adapter, run the following:
To update the generated Typescript required for using the protocol buffer adapter, `cd` into
`packages/nakama-js-protobuf` and run the following:

@@ -178,9 +199,10 @@ ```shell

--plugin="./node_modules/.bin/protoc-gen-ts_proto" \
--proto_path=$GOPATH/src \
--ts_proto_out=packages/nakama-js-protobuf \
--proto_path=$GOPATH/src/github.com/heroiclabs/nakama-common \
--ts_proto_out=. \
--ts_proto_opt=snakeToCamel=false \
--ts_proto_opt=useOptionals=true \
--ts_proto_opt=oneof=unions \
$GOPATH/src/github.com/heroiclabs/nakama-common/api/api.proto \
$GOPATH/src/github.com/heroiclabs/nakama-common/rtapi/realtime.proto
--ts_proto_opt=esModuleInterop=true \
$GOPATH/src/github.com/heroiclabs/nakama-common/rtapi/realtime.proto \
$GOPATH/src/github.com/heroiclabs/nakama-common/api/api.proto
```

@@ -187,0 +209,0 @@

@@ -20,37 +20,82 @@ /**

// Claims
readonly token: string;
token: string;
created: boolean
readonly created_at: number;
readonly expires_at: number;
readonly username: string;
readonly user_id: string;
readonly vars: object;
expires_at?: number;
refresh_expires_at?: number;
refresh_token: string;
username?: string;
user_id?: string;
vars?: object;
// Validate token
isexpired(currenttime: number): boolean;
isrefreshexpired(currenttime: number): boolean;
}
export class Session {
public constructor(
readonly token: string,
readonly created_at: number,
readonly expires_at: number,
readonly username: string,
readonly user_id: string,
readonly vars: object) {
export class Session implements ISession {
token : string;
readonly created_at: number;
expires_at?: number;
refresh_expires_at?: number;
refresh_token: string;
username?: string;
user_id?: string;
vars?: object;
constructor(
token: string,
refresh_token: string,
readonly created: boolean) {
this.token = token;
this.refresh_token = refresh_token;
this.created_at = Math.floor(new Date().getTime() / 1000);
this.update(token, refresh_token);
}
isexpired(currenttime: number): boolean {
return (this.expires_at - currenttime) < 0;
return (this.expires_at! - currenttime) < 0;
}
static restore(jwt: string): Session {
const createdAt = Math.floor(new Date().getTime() / 1000);
const parts = jwt.split('.');
if (parts.length != 3) {
isrefreshexpired(currenttime: number): boolean {
return (this.refresh_expires_at! - currenttime) < 0;
}
update(token: string, refreshToken: string) {
const tokenParts = token.split('.');
if (tokenParts.length != 3) {
throw 'jwt is not valid.';
}
const decoded = JSON.parse(atob(parts[1])); // FIXME: use base64 polyfill for React Native.
const expiresAt = Math.floor(parseInt(decoded['exp']));
return new Session(jwt, createdAt, expiresAt, decoded['usn'], decoded['uid'], decoded['vrs']);
const tokenDecoded = JSON.parse(atob(tokenParts[1])); // FIXME: use base64 polyfill for React Native.
const tokenExpiresAt = Math.floor(parseInt(tokenDecoded['exp']));
// clients that have just updated to the refresh tokens
// client release will not have a cached refresh token
if (refreshToken) {
const refreshTokenParts = refreshToken.split('.');
if (refreshTokenParts.length != 3) {
throw 'refresh jwt is not valid.';
}
const refreshTokenDecoded = JSON.parse(atob(refreshTokenParts[1])); // FIXME: use base64 polyfill for React Native.
const refreshTokenExpiresAt = Math.floor(parseInt(refreshTokenDecoded['exp']));
this.refresh_expires_at = refreshTokenExpiresAt;
this.refresh_token = refreshToken;
}
this.token = token;
this.expires_at = tokenExpiresAt;
this.username = tokenDecoded['usn'];
this.user_id = tokenDecoded['uid'];
this.vars = tokenDecoded['vrs'];
}
static restore(token: string, refreshToken: string): Session {
return new Session(token, refreshToken, false);
}
}

@@ -23,3 +23,2 @@ /**

/** Requires the set of keys K to exist in type T. */

@@ -49,3 +48,3 @@ type RequireKeys<T, K extends keyof T> = Omit<Partial<T>, K> & Pick<T, K>;

/** Join a realtime chat channel. */
export interface ChannelJoin {
interface ChannelJoin {
channel_join: {

@@ -60,3 +59,3 @@ target: string;

/** Leave a realtime chat channel. */
export interface ChannelLeave {
interface ChannelLeave {
channel_leave: {

@@ -96,3 +95,3 @@ channel_id: string;

/** Send a message to a realtime chat channel. */
export interface ChannelMessageSend {
interface ChannelMessageSend {
channel_message_send: {

@@ -105,3 +104,3 @@ channel_id: string;

/** Update a message previously sent to a realtime chat channel. */
export interface ChannelMessageUpdate {
interface ChannelMessageUpdate {
channel_message_update: {

@@ -115,3 +114,3 @@ channel_id: string,

/** Remove a message previously sent to a realtime chat channel. */
export interface ChannelMessageRemove {
interface ChannelMessageRemove {
channel_message_remove: {

@@ -160,3 +159,3 @@ channel_id: string;

/** Start a matchmaking process. */
export interface MatchmakerAdd {
interface MatchmakerAdd {
matchmaker_add: {

@@ -171,4 +170,9 @@ min_count: number;

/** The matchmaker ticket received from the server. */
export interface MatchmakerTicket {
ticket : string;
}
/** Cancel a matchmaking process. */
export interface MatchmakerRemove {
interface MatchmakerRemove {
matchmaker_remove: {

@@ -182,2 +186,3 @@ ticket: string;

presence: Presence;
party_id : string;
string_properties?: Record<string, string>;

@@ -207,3 +212,3 @@ numeric_properties?: Record<string, number>;

/** Create a multiplayer match. */
export interface CreateMatch {
interface CreateMatch {
match_create: {};

@@ -213,3 +218,3 @@ }

/** Join a multiplayer match. */
export interface JoinMatch {
interface JoinMatch {
match_join: {

@@ -223,3 +228,3 @@ match_id?: string;

/** Leave a multiplayer match. */
export interface LeaveMatch {
interface LeaveMatch {
match_leave: {

@@ -239,8 +244,140 @@ match_id: string;

/** Send a message contains match data. */
export interface MatchDataSend {
interface MatchDataSend {
match_data_send: RequireKeys<MatchData, "match_id" | "op_code" | "data">;
}
// Incoming information about a party.
export interface Party {
party_id : string;
open : boolean;
max_size : number;
self : Presence;
leader : Presence;
presences : Presence[];
}
// Create a party.
export interface PartyCreate {
party_create: {
open : boolean;
max_size : number;
}
}
// Join a party.
interface PartyJoin {
party_join: {
party_id : string;
}
}
// Leave a party.
interface PartyLeave {
party_leave: {
party_id : string;
}
}
// Promote a new party leader.
interface PartyPromote {
party_promote: {
party_id : string;
presence : Presence;
}
}
// Announcement of a new party leader.
export interface PartyLeader {
party_id : string;
presence : Presence;
}
// Accept a request to join.
interface PartyAccept {
party_accept: {
party_id : string;
presence : Presence;
}
}
// End a party, kicking all party members and closing it.
interface PartyClose {
party_close: {
party_id : string;
}
}
// Incoming party data delivered from the server.
export interface PartyData {
party_id: string;
presence: Presence;
op_code: number;
data: any;
}
// A client to server request to send data to a party.
interface PartyDataSend {
party_data_send: {
party_id : string;
op_code : number;
data : any;
}
}
// Incoming notification for one or more new presences attempting to join the party.
export interface PartyJoinRequest {
party_id : string;
presences : Presence[];
}
// Request a list of pending join requests for a party.
export interface PartyJoinRequestList {
party_join_request_list: {
party_id : string;
}
}
// Begin matchmaking as a party.
interface PartyMatchmakerAdd {
party_matchmaker_add: {
party_id : string;
min_count : number;
max_count : number;
query : string;
string_properties? : Record<string, string>;
numeric_properties? : Record<string, number>;
}
}
// Cancel a party matchmaking process using a ticket.
interface PartyMatchmakerRemove {
party_matchmaker_remove: {
party_id : string;
ticket : string;
}
}
// A response from starting a new party matchmaking process.
export interface PartyMatchmakerTicket {
party_id: string;
ticket: string;
}
// Presence update for a particular party.
export interface PartyPresenceEvent {
party_id : string;
joins : Presence[];
leaves : Presence[];
}
// Kick a party member, or decline a request to join.
interface PartyRemove {
party_remove: {
party_id : string;
presence : Presence;
}
}
/** Execute an Lua function on the server. */
export interface Rpc {
interface Rpc {
rpc: ApiRpc;

@@ -255,3 +392,3 @@ }

/** Start receiving status updates for some set of users. */
export interface StatusFollow {
interface StatusFollow {
status_follow: {user_ids: string[];}

@@ -267,3 +404,3 @@ }

/** Stop receiving status updates for some set of users. */
export interface StatusUnfollow {
interface StatusUnfollow {
status_unfollow: {user_ids: string[];};

@@ -273,3 +410,3 @@ }

/** Set the user's own status. */
export interface StatusUpdate {
interface StatusUpdate {
status_update: {status?: string;};

@@ -282,20 +419,28 @@ }

connect(session: Session, createStatus: boolean): Promise<Session>;
// Disconnect from the server.
disconnect(fireDisconnectEvent: boolean): void;
// Send message to the server. This method remains in the API for backwards compatibility.
// We recommend that you use the other socket-based methods below for improved
// type checking and code readability.
send(message: ChannelJoin | ChannelLeave | ChannelMessageSend |
ChannelMessageUpdate | ChannelMessageRemove | CreateMatch | JoinMatch |
LeaveMatch | MatchDataSend | MatchmakerAdd | MatchmakerRemove | Rpc |
StatusFollow | StatusUnfollow | StatusUpdate): Promise<any>;
// Accept a request to join.
acceptPartyMember(party_id : string, presence : Presence) : Promise<void>;
/// Join the matchmaker pool and search for opponents on the server.
addMatchmaker(query : string, minCount : number, maxCount : number,
stringProperties? : Record<string, string>, numericProperties? : Record<string, number>)
: Promise<MatchmakerMatched>;
: Promise<MatchmakerTicket>;
// Begin matchmaking as a party.
addMatchmakerParty(party_id: string, query : string, min_count : number, max_count : number,
string_properties? : Record<string, string>, numericProperties? : Record<string, number>)
: Promise<PartyMatchmakerTicket>;
// End a party, kicking all party members and closing it.
closeParty(party_id : string) : Promise<void>;
// Create a multiplayer match on the server.
createMatch() : Promise<Match>;
// Create a party.
createParty(open : boolean, max_size : number) : Promise<Party>;
// Subscribe to one or more users for their status updates.

@@ -307,2 +452,5 @@ followUsers(user_ids: string[]) : Promise<Status>;

// Join a party.
joinParty(party_id: string) : Promise<void>;
// Join a multiplayer match.

@@ -317,2 +465,11 @@ joinMatch(match_id?: string, token?: string, metadata?: {}) : Promise<Match>;

// Leave a party.
leaveParty(party_id: string) : Promise<void>;
// Request a list of pending join requests for a party.
listPartyJoinRequests(party_id : string) : Promise<PartyJoinRequest>;
// Promote a new party leader.
promotePartyMember(party_id : string, party_member : Presence) : Promise<PartyLeader>;
// Remove a chat message from a chat channel on the server.

@@ -324,2 +481,8 @@ removeChatMessage(channel_id: string, message_id: string) : Promise<ChannelMessageAck>;

// Cancel a party matchmaking process using a ticket.
removeMatchmakerParty(party_id : string, ticket : string) : Promise<void>;
// Kick a party member, or decline a request to join.
removePartyMember(party_id : string, presence : Presence) : Promise<void>;
// Execute an RPC function to the server.

@@ -332,2 +495,5 @@ rpc(id?: string, payload?: string, http_key?: string) : Promise<ApiRpc>

// Send data to a party.
sendPartyData(party_id : string, opcode : number, data : any) : Promise<void>;
// Unfollow one or more users from their status updates.

@@ -347,20 +513,54 @@ unfollowUsers(user_ids : string[]) : Promise<void>;

ondisconnect: (evt: Event) => void;
// Handle error events received from the socket.
onerror: (evt: Event) => void;
// Receive notifications from the socket.
onnotification: (notification: Notification) => void;
// Receive match data updates.
onmatchdata: (matchData: MatchData) => void;
// Receive match presence updates.
onmatchpresence: (matchPresence: MatchPresenceEvent) => void;
// Receive a matchmaker ticket.
onmatchmakerticket: (matchmakerTicket: MatchmakerTicket) => void;
// Receive matchmaking results.
onmatchmakermatched: (matchmakerMatched: MatchmakerMatched) => void;
// Receive party events.
onparty: (party : Party) => void;
// Receive party close events.
onpartyclose: (partyClose : PartyClose) => void;
// Receive party data updates.
onpartydata: (partyData: PartyData) => void;
// Receive party join requests, if party leader.
onpartyjoinrequest: (partyJoinRequest: PartyJoinRequest) => void;
// Receive announcements of a new party leader.
onpartyleader: (partyLeader : PartyLeader) => void;
// Receive a presence update for a party.
onpartypresence: (partyPresence : PartyPresenceEvent) => void;
// Receive matchmaking results.
onpartymatchmakerticket: (partyMatchmakerMatched: PartyMatchmakerTicket) => void;
// Receive status presence updates.
onstatuspresence: (statusPresence: StatusPresenceEvent) => void;
// Receive stream presence updates.
onstreampresence: (streamPresence: StreamPresenceEvent) => void;
// Receive stream data.
onstreamdata: (streamData: StreamData) => void;
// Receive channel message.
onchannelmessage: (channelMessage: ChannelMessage) => void;
// Receive channel presence updates.

@@ -418,3 +618,3 @@ onchannelpresence: (channelPresence: ChannelPresenceEvent) => void;

if (this.verbose && window && window.console) {
console.log("Response: %o", message);
console.log("Response: %o", JSON.stringify(message));
}

@@ -435,2 +635,4 @@

this.onmatchpresence(<MatchPresenceEvent>message.match_presence_event);
} else if (message.matchmaker_ticket) {
this.onmatchmakerticket(<MatchmakerTicket> message.matchmaker_ticket);
} else if (message.matchmaker_matched) {

@@ -449,2 +651,18 @@ this.onmatchmakermatched(<MatchmakerMatched>message.matchmaker_matched);

this.onchannelpresence(<ChannelPresenceEvent>message.channel_presence_event);
} else if (message.party_data) {
message.party_data.data = message.party_data.data != null ? JSON.parse(b64DecodeUnicode(message.party_data.data)) : null;
message.party_data.op_code = parseInt(message.party_data.op_code);
this.onpartydata(<PartyData>message.party_data);
} else if (message.on_party_close) {
this.onpartyclose();
} else if (message.party_join_request) {
this.onpartyjoinrequest(message.party_join_request);
} else if (message.party_leader) {
this.onpartyleader(<PartyLeader> message.party_leader);
} else if (message.party_matchmaker_ticket) {
this.onpartymatchmakerticket(message.party_matchmaker_ticket);
} else if (message.party_presence_event) {
this.onpartypresence(<PartyPresenceEvent> message.party_presence_event);
} else if (message.party) {
this.onparty(<Party> message.party);
} else {

@@ -538,2 +756,8 @@ if (this.verbose && window && window.console) {

onmatchmakerticket(matchmakerTicket: MatchmakerTicket) {
if (this.verbose && window && window.console) {
console.log(matchmakerTicket);
}
}
onmatchmakermatched(matchmakerMatched: MatchmakerMatched) {

@@ -545,2 +769,45 @@ if (this.verbose && window && window.console) {

onparty(party : Party) {
if (this.verbose && window && window.console) {
console.log(party);
}
}
onpartyclose() {
if (this.verbose && window && window.console) {
console.log("Party closed.");
}
}
onpartyjoinrequest(partyJoinRequest : PartyJoinRequest) {
if (this.verbose && window && window.console) {
console.log(partyJoinRequest);
}
}
onpartydata(partyData: PartyData) {
if (this.verbose && window && window.console) {
console.log(partyData);
}
}
onpartyleader(partyLeader: PartyLeader) {
if (this.verbose && window && window.console) {
console.log(partyLeader);
}
}
onpartymatchmakerticket(partyMatched: PartyMatchmakerTicket) {
if (this.verbose && window && window.console) {
console.log(partyMatched);
}
}
onpartypresence(partyPresence: PartyPresenceEvent) {
if (this.verbose && window && window.console) {
console.log(partyPresence);
}
}
onstatuspresence(statusPresence: StatusPresenceEvent) {

@@ -564,6 +831,7 @@ if (this.verbose && window && window.console) {

send(message: ChannelJoin | ChannelLeave | ChannelMessageSend |
ChannelMessageUpdate | ChannelMessageRemove | CreateMatch |
JoinMatch | LeaveMatch | MatchDataSend | MatchmakerAdd | MatchmakerRemove |
Rpc | StatusFollow | StatusUnfollow | StatusUpdate): Promise<any> {
send(message: ChannelJoin | ChannelLeave | ChannelMessageSend | ChannelMessageUpdate |
ChannelMessageRemove | CreateMatch | JoinMatch | LeaveMatch | MatchDataSend | MatchmakerAdd |
MatchmakerRemove | PartyAccept | PartyClose | PartyCreate | PartyDataSend | PartyJoin |
PartyJoinRequestList | PartyLeave | PartyMatchmakerAdd | PartyMatchmakerRemove | PartyPromote |
PartyRemove | Rpc | StatusFollow | StatusUnfollow | StatusUpdate): Promise<any> {
const untypedMessage = message as any;

@@ -581,2 +849,7 @@

}
else if (untypedMessage.party_data_send) {
untypedMessage.party_data_send.data = b64EncodeUnicode(JSON.stringify(untypedMessage.party_data_send.data));
this.adapter.send(untypedMessage);
resolve();
}
else {

@@ -600,3 +873,3 @@

if (this.verbose && window && window.console) {
console.log("Sent message: %o", untypedMessage);
console.log("Sent message: %o", JSON.stringify(untypedMessage));
}

@@ -606,23 +879,42 @@ });

acceptPartyMember(party_id: string, presence: Presence): Promise<void> {
return this.send({party_accept: {party_id: party_id, presence: presence}});
}
async addMatchmaker(query : string, minCount : number, maxCount : number,
stringProperties? : Record<string, string>, numericProperties? : Record<string, number>)
: Promise<MatchmakerMatched> {
async addMatchmaker(query : string, min_count : number, max_count : number,
string_properties? : Record<string, string>, numeric_properties? : Record<string, number>)
: Promise<MatchmakerTicket> {
const matchMakerAdd : MatchmakerAdd =
{
const response = await this.send({
"matchmaker_add": {
min_count: minCount,
max_count: maxCount,
min_count: min_count,
max_count: max_count,
query: query,
string_properties: stringProperties,
numeric_properties: numericProperties
string_properties: string_properties,
numeric_properties: numeric_properties
}
};
});
const response = await this.send(matchMakerAdd);
return response.matchmaker_ticket;
}
}
async addMatchmakerParty(party_id: string, query: string, min_count: number, max_count: number, string_properties?: Record<string, string>, numeric_properties?: Record<string, number>): Promise<PartyMatchmakerTicket> {
const response = await this.send({
party_matchmaker_add: {
party_id : party_id,
min_count: min_count,
max_count: max_count,
query: query,
string_properties: string_properties,
numeric_properties: numeric_properties
}});
return response.party_matchmaker_ticket;
}
async closeParty(party_id: string): Promise<void> {
return await this.send({party_close: {party_id: party_id}});
}
async createMatch(): Promise<Match> {

@@ -633,2 +925,7 @@ const response = await this.send({match_create: {}});

async createParty(open: boolean, max_size: number): Promise<Party> {
const response = await this.send({party_create: {open: open, max_size: max_size}});
return response.party;
}
async followUsers(userIds : string[]): Promise<Status> {

@@ -671,2 +968,6 @@ const response = await this.send({status_follow: {user_ids: userIds}});

async joinParty(party_id: string): Promise<void> {
return await this.send({party_join: {party_id: party_id}});
}
leaveChat(channel_id: string): Promise<void> {

@@ -680,5 +981,18 @@ return this.send({channel_leave: {channel_id: channel_id}});

leaveParty(party_id: string): Promise<void> {
return this.send({party_leave: {party_id: party_id}});
}
async listPartyJoinRequests(party_id: string): Promise<PartyJoinRequest> {
const response = await this.send({party_join_request_list: {party_id: party_id}});
return response.party_join_request;
}
async promotePartyMember(party_id: string, party_member: Presence): Promise<PartyLeader> {
const response = await this.send({party_promote: {party_id: party_id, presence: party_member}});
return response.party_leader;
}
async removeChatMessage(channel_id: string, message_id: string): Promise<ChannelMessageAck> {
const response = await this.send
(
const response = await this.send(
{

@@ -699,2 +1013,19 @@ channel_message_remove: {

removeMatchmakerParty(party_id: string, ticket: string): Promise<void> {
return this.send(
{
party_matchmaker_remove: {
party_id: party_id,
ticket: ticket
}
})
}
async removePartyMember(party_id: string, member: Presence): Promise<void> {
return this.send({party_remove: {
party_id: party_id,
presence: member
}});
}
async rpc(id?: string, payload?: string, http_key?: string) : Promise<ApiRpc> {

@@ -725,2 +1056,6 @@ const response = await this.send(

sendPartyData(party_id: string, op_code: number, data: any): Promise<void> {
return this.send({party_data_send: {party_id: party_id, op_code: op_code, data: data}})
}
unfollowUsers(user_ids : string[]): Promise<void> {

@@ -727,0 +1062,0 @@ return this.send({status_unfollow: {user_ids: user_ids}});

import {encode, decode} from "js-base64"
export function buildFetchOptions(method: string, options: any, bodyJson: string) {
const fetchOptions = {...{ method: method }, ...options};
fetchOptions.headers = {...options.headers};
const descriptor = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, "withCredentials");
// in Cocos Creator, XMLHttpRequest.withCredentials is not writable, so make the fetch
// polyfill avoid writing to it.
if (!descriptor?.set) {
fetchOptions.credentials = 'cocos-ignore'; // string value is arbitrary, cannot be 'omit' or 'include
}
if(!Object.keys(fetchOptions.headers).includes("Accept")) {
fetchOptions.headers["Accept"] = "application/json";
}
if(!Object.keys(fetchOptions.headers).includes("Content-Type")) {
fetchOptions.headers["Content-Type"] = "application/json";
}
Object.keys(fetchOptions.headers).forEach((key: string) => {
if (!fetchOptions.headers[key]) {
delete fetchOptions.headers[key];
}
});
if (bodyJson) {
fetchOptions.body = bodyJson;
}
return fetchOptions;
}
export function b64EncodeUnicode(str:string) {

@@ -4,0 +37,0 @@ return encode(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,

@@ -45,3 +45,3 @@ /**

connect(scheme: string, host: string, port : string, createStatus: boolean, token : string) : void;
send(msg : any) : void;
send(message: any) : void;
}

@@ -144,6 +144,7 @@

send(msg: any): void {
if (msg.match_data_send)
{
if (msg.match_data_send) {
// according to protobuf docs, int64 is encoded to JSON as string.
msg.match_data_send.op_code = msg.match_data_send.op_code.toString();
} else if (msg.party_data_send) {
msg.party_data_send.op_code = msg.party_data_send.op_code.toString();
}

@@ -150,0 +151,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc