mezon-sdk 2.7.1 → 2.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build.mjs CHANGED
@@ -1,45 +1,45 @@
1
- // Copyright 2020 The Nakama Authors
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import esbuild from 'esbuild';
16
-
17
- // Shared esbuild config
18
- const config = {
19
- logLevel: 'info',
20
- entryPoints: ['index.ts'],
21
- bundle: true,
22
- target: 'es6',
23
- globalName: 'satorijs'
24
- };
25
-
26
- // Build CommonJS
27
- await esbuild.build({
28
- ...config,
29
- format: 'cjs',
30
- outfile: 'dist/satori-js.cjs.js'
31
- });
32
-
33
- // Build ESM
34
- await esbuild.build({
35
- ...config,
36
- format: 'esm',
37
- outfile: 'dist/satori-js.esm.mjs'
38
- });
39
-
40
- // Build IIFE
41
- await esbuild.build({
42
- ...config,
43
- format: 'iife',
44
- outfile: 'dist/satori-js.iife.js'
1
+ // Copyright 2020 The Nakama Authors
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ import esbuild from 'esbuild';
16
+
17
+ // Shared esbuild config
18
+ const config = {
19
+ logLevel: 'info',
20
+ entryPoints: ['index.ts'],
21
+ bundle: true,
22
+ target: 'es6',
23
+ globalName: 'satorijs'
24
+ };
25
+
26
+ // Build CommonJS
27
+ await esbuild.build({
28
+ ...config,
29
+ format: 'cjs',
30
+ outfile: 'dist/mezon-sdk.cjs.js'
31
+ });
32
+
33
+ // Build ESM
34
+ await esbuild.build({
35
+ ...config,
36
+ format: 'esm',
37
+ outfile: 'dist/mezon-sdk.esm.mjs'
38
+ });
39
+
40
+ // Build IIFE
41
+ await esbuild.build({
42
+ ...config,
43
+ format: 'iife',
44
+ outfile: 'dist/mezon-sdk.iife.js'
45
45
  });
package/client.ts CHANGED
@@ -1,327 +1,198 @@
1
- /**
2
- * Copyright 2020 The Nakama Authors
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- import { SatoriApi, ApiSession, ApiAuthenticateRequest, ApiEventRequest, ApiAuthenticateLogoutRequest, ApiAuthenticateRefreshRequest, ApiIdentifyRequest, ApiUpdatePropertiesRequest, ApiEvent, ApiUpdateMessageRequest } from "./api.gen";
18
-
19
- import { Session } from "./session";
20
-
21
- const DEFAULT_HOST = "127.0.0.1";
22
- const DEFAULT_PORT = "7450";
23
- const DEFAULT_API_KEY = "defaultkey";
24
- const DEFAULT_TIMEOUT_MS = 7000;
25
- const DEFAULT_EXPIRED_TIMESPAN_MS = 5 * 60 * 1000;
26
-
27
- /** A client for Satori server. */
28
- export class Client {
29
-
30
- /** The expired timespan used to check session lifetime. */
31
- public expiredTimespanMs = DEFAULT_EXPIRED_TIMESPAN_MS;
32
-
33
- /** The low level API client for Nakama server. */
34
- private readonly apiClient: SatoriApi;
35
-
36
- constructor(
37
- readonly apiKey = DEFAULT_API_KEY,
38
- readonly host = DEFAULT_HOST,
39
- readonly port = DEFAULT_PORT,
40
- readonly useSSL = false,
41
- readonly timeout = DEFAULT_TIMEOUT_MS,
42
- readonly autoRefreshSession = true) {
43
- const scheme = (useSSL) ? "https://" : "http://";
44
- const basePath = `${scheme}${host}:${port}`;
45
-
46
- this.apiClient = new SatoriApi(apiKey, basePath, timeout);
47
- }
48
-
49
- /** Authenticate a user with an ID against the server. */
50
- async authenticate(id: string, customProperties?: Record<string, string>, defaultProperties?: Record<string, string>) {
51
-
52
- const request : ApiAuthenticateRequest = {
53
- "id": id,
54
- custom: customProperties,
55
- default: defaultProperties
56
- };
57
-
58
- return this.apiClient.satoriAuthenticate(this.apiKey, "", request).then((apiSession : ApiSession) => {
59
- return Promise.resolve(new Session(apiSession.token || "", apiSession.refresh_token || ""));
60
- });
61
- }
62
-
63
- /** Refresh a user's session using a refresh token retrieved from a previous authentication request. */
64
- async sessionRefresh(session: Session) {
65
-
66
- const request : ApiAuthenticateRefreshRequest = {
67
- "refresh_token": session.refresh_token,
68
- };
69
-
70
- return this.apiClient.satoriAuthenticateRefresh(this.apiKey, "", request).then((apiSession : ApiSession) => {
71
- return Promise.resolve(new Session(apiSession.token || "", apiSession.refresh_token || ""));
72
- });
73
- }
74
-
75
- /** Log out a session, invalidate a refresh token, or log out all sessions/refresh tokens for a user. */
76
- async logout(session: Session) {
77
-
78
- const request : ApiAuthenticateLogoutRequest = {
79
- "token": session.token,
80
- "refresh_token": session.refresh_token
81
- };
82
-
83
- return this.apiClient.satoriAuthenticateLogout(session.token, request).then((response) => {
84
- return Promise.resolve(response !== undefined);
85
- });
86
- }
87
-
88
- /** Publish an event for this session. */
89
- async event(session: Session, event: ApiEvent) {
90
- if (this.autoRefreshSession && session.refresh_token &&
91
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
92
- await this.sessionRefresh(session);
93
- }
94
-
95
- const request : ApiEventRequest = {
96
- events: [event]
97
- };
98
-
99
- return this.apiClient.satoriEvent(session.token, request).then((response) => {
100
- return Promise.resolve(response !== undefined);
101
- });
102
- }
103
-
104
- /** Publish multiple events for this session */
105
- async events(session: Session, events: Array<ApiEvent>) {
106
- if (this.autoRefreshSession && session.refresh_token &&
107
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
108
- await this.sessionRefresh(session);
109
- }
110
-
111
- const request : ApiEventRequest = {
112
- events
113
- };
114
-
115
- return this.apiClient.satoriEvent(session.token, request).then((response) => {
116
- return Promise.resolve(response !== undefined);
117
- });
118
- }
119
-
120
- /** Get or list all available experiments for this identity. */
121
- async getExperiments(session: Session, names?: Array<string>) {
122
- if (this.autoRefreshSession && session.refresh_token &&
123
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
124
- await this.sessionRefresh(session);
125
- }
126
-
127
- return this.apiClient.satoriGetExperiments(session.token, names);
128
- }
129
-
130
- /** Get a single flag for this identity. Throws an error when the flag does not exist. */
131
- async getFlag(session: Session, name: string) {
132
- if (this.autoRefreshSession && session.refresh_token &&
133
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
134
- await this.sessionRefresh(session);
135
- }
136
-
137
- return this.apiClient.satoriGetFlags(session.token, "", "", [name]).then((flagList) => {
138
- let flag = null;
139
-
140
- flagList.flags?.forEach((f) => {
141
- if (f.name === name) {
142
- flag = f;
143
- }
144
- });
145
-
146
- if (flag === null) {
147
- return Promise.reject("Flag does not exist.");
148
- }
149
-
150
- return Promise.resolve(flag);
151
- });
152
- }
153
-
154
-
155
- /** Get a single flag for this identity. */
156
- async getFlagWithFallback(session: Session, name: string, fallbackValue?: string) {
157
- return this.getFlag(session, name)
158
- .then((flag) => {
159
- return flag;
160
- })
161
- .catch(() => {
162
- const flag = {
163
- name,
164
- value: fallbackValue
165
- };
166
-
167
- return Promise.resolve(flag)
168
- });
169
- }
170
-
171
- /** Get a single flag with its configured default value. Throws an error when the flag does not exist. */
172
- async getFlagDefault(name: string) {
173
- return this.apiClient.satoriGetFlags("", this.apiKey, "", [name]).then((flagList) => {
174
- let flag = null;
175
-
176
- flagList.flags?.forEach((f) => {
177
- if (f.name === name) {
178
- flag = f;
179
- }
180
- });
181
-
182
- if (flag === null) {
183
- return Promise.reject("Flag does not exist.");
184
- }
185
-
186
- return Promise.resolve(flag);
187
- });
188
- }
189
-
190
- /** Get a single flag with its configured default value. */
191
- async getFlagDefaultWithFallback(name: string, fallbackValue?: string) {
192
- return this.getFlagDefault(name)
193
- .then((flag) => {
194
- return flag;
195
- })
196
- .catch(() => {
197
- const flag = {
198
- name,
199
- value: fallbackValue
200
- };
201
-
202
- return Promise.resolve(flag)
203
- });
204
- }
205
-
206
- /** List all available flags for this identity. */
207
- async getFlags(session: Session, names?: Array<string>) {
208
- if (this.autoRefreshSession && session.refresh_token &&
209
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
210
- await this.sessionRefresh(session);
211
- }
212
-
213
- return this.apiClient.satoriGetFlags(session.token, "", "", names);
214
- }
215
-
216
- /** List all available default flags. */
217
- async getFlagsDefault(names?: Array<string>) {
218
- return this.apiClient.satoriGetFlags("", this.apiKey, "", names);
219
- }
220
-
221
- /** Enrich/replace the current session with new identifier. */
222
- async identify(session: Session, id: string, defaultProperties?: Record<string, string>, customProperties?: Record<string, string>) {
223
- if (this.autoRefreshSession && session.refresh_token &&
224
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
225
- await this.sessionRefresh(session);
226
- }
227
-
228
- const request : ApiIdentifyRequest = {
229
- id: id,
230
- default: defaultProperties,
231
- custom: customProperties
232
- };
233
-
234
- return this.apiClient.satoriIdentify(session.token, request).then((apiSession: ApiSession) => {
235
- return Promise.resolve(new Session(apiSession.token || "", apiSession.refresh_token || ""));
236
- });
237
- }
238
-
239
- /** List available live events. */
240
- async getLiveEvents(session: Session, names?: Array<string>) {
241
- if (this.autoRefreshSession && session.refresh_token &&
242
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
243
- await this.sessionRefresh(session);
244
- }
245
-
246
- return this.apiClient.satoriGetLiveEvents(session.token, names);
247
- }
248
-
249
- /** List properties associated with this identity. */
250
- async listProperties(session: Session) {
251
- if (this.autoRefreshSession && session.refresh_token &&
252
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
253
- await this.sessionRefresh(session);
254
- }
255
-
256
- return this.apiClient.satoriListProperties(session.token);
257
- }
258
-
259
- /** Update identity properties. */
260
- async updateProperties(session: Session, defaultProperties?: Record<string, string>, customProperties?: Record<string, string>, recompute?: boolean) {
261
- if (this.autoRefreshSession && session.refresh_token &&
262
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
263
- await this.sessionRefresh(session);
264
- }
265
-
266
- const request : ApiUpdatePropertiesRequest = {
267
- default: defaultProperties,
268
- custom: customProperties,
269
- recompute: recompute,
270
- };
271
-
272
- return this.apiClient.satoriUpdateProperties(session.token, request).then((response) => {
273
- return Promise.resolve(response !== undefined);
274
- });
275
- }
276
-
277
- /** Delete the caller's identity and associated data. */
278
- async deleteIdentity(session: Session) {
279
- if (this.autoRefreshSession && session.refresh_token &&
280
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
281
- await this.sessionRefresh(session);
282
- }
283
-
284
- return this.apiClient.satoriDeleteIdentity(session.token).then((response) => {
285
- return Promise.resolve(response !== undefined);
286
- });
287
- }
288
-
289
- async getMessageList(session : Session) {
290
- if (this.autoRefreshSession && session.refresh_token &&
291
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
292
- await this.sessionRefresh(session);
293
- }
294
-
295
- return this.apiClient.satoriGetMessageList(session.token).then((response) => {
296
- return Promise.resolve(response !== undefined);
297
- });
298
- }
299
-
300
- async deleteMessage(session : Session, id : string) {
301
- if (this.autoRefreshSession && session.refresh_token &&
302
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
303
- await this.sessionRefresh(session);
304
- }
305
-
306
- return this.apiClient.satoriDeleteMessage(session.token, id).then((response) => {
307
- return Promise.resolve(response !== undefined);
308
- });
309
- }
310
-
311
- async updateMessage(session : Session, id : string, consume_time? : string, read_time? : string) {
312
- if (this.autoRefreshSession && session.refresh_token &&
313
- session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
314
- await this.sessionRefresh(session);
315
- }
316
-
317
- const request : ApiUpdateMessageRequest = {
318
- id: id,
319
- consume_time: consume_time,
320
- read_time: read_time
321
- };
322
-
323
- return this.apiClient.satoriUpdateMessage(session.token, id, request).then((response) => {
324
- return Promise.resolve(response !== undefined);
325
- });
326
- }
327
- };
1
+ /**
2
+ * Copyright 2020 The Nakama Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { MezonApi, ApiAuthenticateLogoutRequest, ApiAuthenticateRefreshRequest, ApiUpdateMessageRequest, ApiSession } from "./api";
18
+ import { Session } from "./session";
19
+ import { ApiMessageReaction, ChannelCreatedEvent, ChannelDeletedEvent, ChannelMessage, ChannelUpdatedEvent, DefaultSocket, Socket, UserChannelAddedEvent, UserChannelRemovedEvent, UserClanRemovedEvent, VoiceJoinedEvent } from "./socket";
20
+ import { WebSocketAdapter } from "./web_socket_adapter";
21
+ import { WebSocketAdapterPb } from 'mezon-js-protobuf';
22
+
23
+ const DEFAULT_HOST = "127.0.0.1";
24
+ const DEFAULT_PORT = "7350";
25
+ const DEFAULT_API_KEY = "defaultkey";
26
+ const DEFAULT_TIMEOUT_MS = 7000;
27
+ const DEFAULT_EXPIRED_TIMESPAN_MS = 5 * 60 * 1000;
28
+
29
+ /** A client for Mezon server. */
30
+ export class Client {
31
+
32
+ /** The expired timespan used to check session lifetime. */
33
+ public expiredTimespanMs = DEFAULT_EXPIRED_TIMESPAN_MS;
34
+
35
+ /** The low level API client for Nakama server. */
36
+ private readonly apiClient: MezonApi;
37
+
38
+ constructor(
39
+ readonly apiKey = DEFAULT_API_KEY,
40
+ readonly host = DEFAULT_HOST,
41
+ readonly port = DEFAULT_PORT,
42
+ readonly useSSL = false,
43
+ readonly timeout = DEFAULT_TIMEOUT_MS,
44
+ readonly autoRefreshSession = true) {
45
+ const scheme = (useSSL) ? "https://" : "http://";
46
+ const basePath = `${scheme}${host}:${port}`;
47
+
48
+ this.apiClient = new MezonApi(apiKey, basePath, timeout);
49
+ }
50
+
51
+ /** Authenticate a user with an ID against the server. */
52
+ async authenticate() {
53
+ return this.apiClient.mezonAuthenticate(this.apiKey, "", {
54
+ account: {
55
+ token: this.apiKey,
56
+ }
57
+ }).then(async (apiSession : ApiSession) => {
58
+ const sockSession = new Session(apiSession.token || "", apiSession.refresh_token || "");
59
+ const socket = this.createSocket(false, true, new WebSocketAdapterPb());
60
+ const session = await socket.connect(sockSession, false);
61
+
62
+ if (!session) {
63
+ console.log("error authenticate");
64
+ return;
65
+ }
66
+
67
+ socket.onchannelmessage = this.onchannelmessage;
68
+ socket.ondisconnect = this.ondisconnect;
69
+ socket.onerror = this.onerror;
70
+ socket.onmessagereaction = this.onmessagereaction;
71
+ socket.onuserchannelremoved = this.onuserchannelremoved;
72
+ socket.onuserclanremoved = this.onuserclanremoved;
73
+ socket.onuserchanneladded = this.onuserchanneladded;
74
+ socket.onchannelcreated = this.onchannelcreated;
75
+ socket.onchanneldeleted = this.onchanneldeleted;
76
+ socket.onchannelupdated = this.onchannelupdated;
77
+ socket.onheartbeattimeout = this.onheartbeattimeout;
78
+
79
+ return Promise.resolve("connect successful");
80
+ });
81
+ }
82
+
83
+ /** Refresh a user's session using a refresh token retrieved from a previous authentication request. */
84
+ async sessionRefresh(session: Session) {
85
+
86
+ const request : ApiAuthenticateRefreshRequest = {
87
+ "refresh_token": session.refresh_token,
88
+ };
89
+
90
+ return this.apiClient.mezonAuthenticateRefresh(this.apiKey, "", request).then((apiSession : ApiSession) => {
91
+ return Promise.resolve(new Session(apiSession.token || "", apiSession.refresh_token || ""));
92
+ });
93
+ }
94
+
95
+ /** Log out a session, invalidate a refresh token, or log out all sessions/refresh tokens for a user. */
96
+ async logout(session: Session) {
97
+
98
+ const request : ApiAuthenticateLogoutRequest = {
99
+ "token": session.token,
100
+ "refresh_token": session.refresh_token
101
+ };
102
+
103
+ return this.apiClient.mezonAuthenticateLogout(session.token, request).then((response) => {
104
+ return Promise.resolve(response !== undefined);
105
+ });
106
+ }
107
+
108
+ async deleteMessage(session : Session, id : string) {
109
+ if (this.autoRefreshSession && session.refresh_token &&
110
+ session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
111
+ await this.sessionRefresh(session);
112
+ }
113
+
114
+ return this.apiClient.mezonDeleteMessage(session.token, id).then((response) => {
115
+ return Promise.resolve(response !== undefined);
116
+ });
117
+ }
118
+
119
+ async updateMessage(session : Session, id : string, consume_time? : string, read_time? : string) {
120
+ if (this.autoRefreshSession && session.refresh_token &&
121
+ session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
122
+ await this.sessionRefresh(session);
123
+ }
124
+
125
+ const request : ApiUpdateMessageRequest = {
126
+ id: id,
127
+ consume_time: consume_time,
128
+ read_time: read_time
129
+ };
130
+
131
+ return this.apiClient.mezonUpdateMessage(session.token, id, request).then((response) => {
132
+ return Promise.resolve(response !== undefined);
133
+ });
134
+ }
135
+
136
+ /** A socket created with the client's configuration. */
137
+ createSocket(useSSL = false, verbose: boolean = false, adapter : WebSocketAdapter = new WebSocketAdapterPb(), sendTimeoutMs : number = DefaultSocket.DefaultSendTimeoutMs): Socket {
138
+ return new DefaultSocket(this.host, this.port, useSSL, verbose, adapter, sendTimeoutMs);
139
+ }
140
+
141
+ onerror(evt: Event) {
142
+ console.log(evt);
143
+ }
144
+
145
+ onmessagereaction(messagereaction: ApiMessageReaction) {
146
+ console.log(messagereaction);
147
+ if (messagereaction.action) {
148
+ this.onMessageReactionRemove(messagereaction);
149
+ } else {
150
+ this.onMessageReactionAdd(messagereaction);
151
+ }
152
+ }
153
+
154
+ onchannelmessage(channelMessage: ChannelMessage) {
155
+ this.onMessage(channelMessage);
156
+ }
157
+
158
+ ondisconnect(e: Event) {
159
+ console.log(e);
160
+ }
161
+
162
+ onuserchanneladded(user: UserChannelAddedEvent) {
163
+ console.log(user);
164
+ }
165
+
166
+ onuserchannelremoved(user: UserChannelRemovedEvent) {
167
+ console.log(user);
168
+ }
169
+
170
+ onuserclanremoved(user: UserClanRemovedEvent) {
171
+ this.onClanMemberUpdate(user.user_ids, true);
172
+ }
173
+
174
+ onchannelcreated(channelCreated: ChannelCreatedEvent) {
175
+ console.log(channelCreated);
176
+ }
177
+
178
+ onchanneldeleted(channelDeleted: ChannelDeletedEvent) {
179
+ console.log(channelDeleted);
180
+ }
181
+
182
+ onchannelupdated(channelUpdated: ChannelUpdatedEvent) {
183
+ console.log(channelUpdated);
184
+ }
185
+
186
+ onheartbeattimeout() {
187
+ console.log("Heartbeat timeout.");
188
+ }
189
+
190
+ /** Receive clan evnet. */
191
+ onMessage!: (channelMessage: ChannelMessage) => void;
192
+ onClanMemberUpdate!: (member_id: Array<string>, leave: boolean) => void;
193
+ onMessageDelete!: (channelMessage: ChannelMessage) => void;
194
+ onMessageReactionAdd!: (messageReactionEvent: ApiMessageReaction) => void;
195
+ onVoiceStateUpdate!: (voiceState: VoiceJoinedEvent) => void;
196
+ onMessageReactionRemove!: (messageReactionEvent: ApiMessageReaction) => void;
197
+
198
+ };