mezon-light-sdk 1.0.3 → 1.0.4

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/dist/client.js DELETED
@@ -1,267 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LightClient = exports.SessionError = exports.AuthenticationError = void 0;
4
- const session_1 = require("./session");
5
- const api_gen_1 = require("./api.gen");
6
- const constants_1 = require("./constants");
7
- const web_socket_adapter_pb_1 = require("./web_socket_adapter_pb");
8
- const socket_gen_1 = require("./socket.gen");
9
- /**
10
- * Error thrown when authentication fails.
11
- */
12
- class AuthenticationError extends Error {
13
- constructor(message, statusCode) {
14
- super(message ?? "Authentication failed.");
15
- this.statusCode = statusCode;
16
- this.name = "AuthenticationError";
17
- }
18
- }
19
- exports.AuthenticationError = AuthenticationError;
20
- /**
21
- * Error thrown when session-related operations fail.
22
- */
23
- class SessionError extends Error {
24
- constructor(message) {
25
- super(message ?? "Session error.");
26
- this.name = "SessionError";
27
- }
28
- }
29
- exports.SessionError = SessionError;
30
- /**
31
- * Parses a URL and extracts client connection parameters.
32
- */
33
- function parseBaseUrl(apiUrl) {
34
- const url = new URL(apiUrl);
35
- const scheme = url.protocol === "https:" ? "https://" : "http://";
36
- return `${scheme}${url.hostname}:${url.port}`;
37
- }
38
- /**
39
- * LightClient provides a simplified interface for Mezon authentication and channel management.
40
- *
41
- * @example
42
- * ```typescript
43
- * // Initialize from existing tokens
44
- * const client = LightClient.initClient({
45
- * token: 'your-token',
46
- * refresh_token: 'your-refresh-token',
47
- * api_url: 'https://api.mezon.ai',
48
- * user_id: 'user-123'
49
- * });
50
- *
51
- * // Or authenticate with ID token
52
- * const client = await LightClient.authenticate({
53
- * id_token: 'id-token-from-provider',
54
- * user_id: 'user-123',
55
- * username: 'johndoe'
56
- * });
57
- * ```
58
- */
59
- class LightClient {
60
- constructor(session, client, userId) {
61
- /** Promise that resolves when the refresh token operation completes */
62
- this.refreshTokenPromise = null;
63
- this._session = session;
64
- this._client = client;
65
- this._userId = userId;
66
- }
67
- /**
68
- * Gets the current user ID.
69
- */
70
- get userId() {
71
- return this._userId;
72
- }
73
- /**
74
- * Gets the underlying Mezon session.
75
- */
76
- get session() {
77
- return this._session;
78
- }
79
- /**
80
- * Gets the underlying Mezon client.
81
- */
82
- get client() {
83
- return this._client;
84
- }
85
- /**
86
- * Initializes a LightClient from existing session tokens.
87
- * Use this when you have stored tokens from a previous authentication.
88
- *
89
- * @param config - Configuration containing tokens and connection details
90
- * @returns A new LightClient instance
91
- * @throws {SessionError} If required fields are missing
92
- */
93
- static initClient(config) {
94
- const { token, refresh_token, api_url, user_id, serverkey } = config;
95
- if (!token || !refresh_token || !api_url || !user_id) {
96
- throw new SessionError("Missing required fields: token, refresh_token, api_url, and user_id are all required");
97
- }
98
- const session = session_1.Session.restore(token, refresh_token, api_url, true);
99
- const client = new api_gen_1.MezonApi(serverkey || constants_1.DEFAULT_SERVER_KEY, 7000, parseBaseUrl(api_url));
100
- return new LightClient(session, client, user_id);
101
- }
102
- /**
103
- * Authenticates a user with an ID token from an identity provider.
104
- *
105
- * @param config - Authentication configuration
106
- * @returns A promise that resolves to a new LightClient instance
107
- * @throws {AuthenticationError} If authentication fails or response is invalid
108
- */
109
- static async authenticate(config) {
110
- const { id_token, user_id, username, serverkey = constants_1.DEFAULT_SERVER_KEY, gateway_url = constants_1.MEZON_GW_URL } = config;
111
- const client = new api_gen_1.MezonApi(serverkey || constants_1.DEFAULT_SERVER_KEY, 7000, parseBaseUrl(gateway_url));
112
- const body = {
113
- id_token,
114
- user_id,
115
- username,
116
- };
117
- const response = await client.authenticateIdToken(serverkey, "", body);
118
- if (!response) {
119
- throw new AuthenticationError("Authentication failed: No response from server.");
120
- }
121
- if (!response.token || !response.refresh_token || !response.api_url || !response.user_id) {
122
- throw new AuthenticationError("Invalid authentication response: missing required fields");
123
- }
124
- const session = session_1.Session.restore(response.token, response.refresh_token, response.api_url, true);
125
- client.setBasePath(parseBaseUrl(response.api_url));
126
- return new LightClient(session, client, response.user_id);
127
- }
128
- /**
129
- * Creates a direct message channel with a single user.
130
- *
131
- * @param peerId - The user ID to create a DM channel with
132
- * @returns A promise that resolves to the created channel descriptor
133
- */
134
- async createDM(peerId) {
135
- const request = {
136
- type: constants_1.CHANNEL_TYPE_DM,
137
- channel_private: 1,
138
- user_ids: [peerId],
139
- };
140
- return this._client.createChannelDesc(this._session.token, request);
141
- }
142
- /**
143
- * Creates a group direct message channel with multiple users.
144
- *
145
- * @param userIds - Array of user IDs to include in the group DM
146
- * @returns A promise that resolves to the created channel descriptor
147
- */
148
- async createGroupDM(userIds) {
149
- if (userIds.length === 0) {
150
- throw new Error("At least one user ID is required for a group DM");
151
- }
152
- const request = {
153
- type: constants_1.CHANNEL_TYPE_GROUP,
154
- channel_private: 1,
155
- user_ids: userIds,
156
- };
157
- return this._client.createChannelDesc(this._session.token, request);
158
- }
159
- /**
160
- * Refreshes the current session using the refresh token.
161
- * Call this before the session expires to maintain connectivity.
162
- *
163
- * @returns A promise that resolves when the session is refreshed
164
- */
165
- async refreshSession() {
166
- if (!this._session) {
167
- console.error("Cannot refresh a null session.");
168
- return this._session;
169
- }
170
- if (this._session.created && this._session.expires_at - this._session.created_at < 70) {
171
- console.warn("Session lifetime too short, please set '--session.token_expiry_sec' option. See the documentation for more info: https://mezon.vn/docs/mezon/getting-started/configuration/#session");
172
- }
173
- if (this._session.created && this._session.refresh_expires_at - this._session.created_at < 3700) {
174
- console.warn("Session refresh lifetime too short, please set '--session.refresh_token_expiry_sec' option. See the documentation for more info: https://mezon.vn/docs/mezon/getting-started/configuration/#session");
175
- }
176
- if (this.refreshTokenPromise) {
177
- return this.refreshTokenPromise;
178
- }
179
- this.refreshTokenPromise = new Promise(async (resolve, reject) => {
180
- try {
181
- const apiSession = await this.client.sessionRefresh(this._client.serverKey || constants_1.DEFAULT_SERVER_KEY, "", {
182
- token: this._session.refresh_token,
183
- vars: this._session.vars,
184
- is_remember: this._session.is_remember,
185
- });
186
- this._session.update(apiSession.token, apiSession.refresh_token, apiSession.is_remember || false);
187
- this.onRefreshSession(apiSession);
188
- resolve(this._session);
189
- }
190
- catch (error) {
191
- console.error("Session refresh failed:", error);
192
- reject(error);
193
- }
194
- finally {
195
- this.refreshTokenPromise = null;
196
- }
197
- });
198
- return this.refreshTokenPromise;
199
- }
200
- /** A socket created with the client's configuration. */
201
- createSocket(verbose = false, adapter = new web_socket_adapter_pb_1.WebSocketAdapterPb(), sendTimeoutMs = socket_gen_1.DefaultSocket.DefaultSendTimeoutMs) {
202
- const url = new URL(this._client.basePath);
203
- const { host, port, useSSL } = {
204
- host: url.hostname,
205
- port: url.port || (url.protocol === "https:" ? "443" : "80"),
206
- useSSL: url.protocol === "https:",
207
- };
208
- return new socket_gen_1.DefaultSocket(host, port, useSSL, verbose, adapter, sendTimeoutMs);
209
- }
210
- /**
211
- * Called when a token refresh is initiated.
212
- * This is a placeholder method that subclasses or instances can override
213
- * to perform actions before or after the refresh logic.
214
- */
215
- onRefreshSession(session) {
216
- console.log(`Token refresh occurred. Token: ${session.token}`);
217
- }
218
- /**
219
- * Checks if the current session token has expired.
220
- *
221
- * @returns True if the session is expired, false otherwise
222
- */
223
- isSessionExpired() {
224
- return this._session.isexpired(Date.now() / 1000);
225
- }
226
- /**
227
- * Checks if the refresh token has expired.
228
- * If this returns true, the user needs to re-authenticate.
229
- *
230
- * @returns True if the refresh token is expired, false otherwise
231
- */
232
- isRefreshSessionExpired() {
233
- return this._session.isrefreshexpired(Date.now() / 1000);
234
- }
235
- /**
236
- * Gets the authentication token for external use.
237
- */
238
- getToken() {
239
- return this._session.token;
240
- }
241
- /**
242
- * Gets the refresh token for storage.
243
- */
244
- getRefreshToken() {
245
- return this._session.refresh_token;
246
- }
247
- /**
248
- * Gets the current session.
249
- */
250
- getSession() {
251
- return this.session;
252
- }
253
- /**
254
- * Exports session data for storage and later restoration.
255
- *
256
- * @returns Object containing all data needed to restore the session
257
- */
258
- exportSession() {
259
- return {
260
- token: this._session.token,
261
- refresh_token: this._session.refresh_token,
262
- api_url: this._session.api_url || "",
263
- user_id: this._userId,
264
- };
265
- }
266
- }
267
- exports.LightClient = LightClient;
@@ -1,16 +0,0 @@
1
- /** Default Mezon Gateway URL */
2
- export declare const MEZON_GW_URL = "https://gw.mezon.ai";
3
- /** Maximum number of retries when waiting for socket to be ready */
4
- export declare const SOCKET_READY_MAX_RETRY = 20;
5
- /** Initial delay in milliseconds between socket ready retries (uses exponential backoff) */
6
- export declare const SOCKET_READY_RETRY_DELAY = 100;
7
- /** Clan ID used for Direct Messages */
8
- export declare const CLAN_DM = "0";
9
- /** Channel type for Direct Messages */
10
- export declare const CHANNEL_TYPE_DM = 3;
11
- export declare const CHANNEL_TYPE_GROUP = 2;
12
- /** Stream mode for Direct Messages */
13
- export declare const STREAM_MODE_DM = 4;
14
- export declare const STREAM_MODE_GROUP = 3;
15
- /** Default server key if none is provided */
16
- export declare const DEFAULT_SERVER_KEY = "DefaultServerKey";
package/dist/constants.js DELETED
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEFAULT_SERVER_KEY = exports.STREAM_MODE_GROUP = exports.STREAM_MODE_DM = exports.CHANNEL_TYPE_GROUP = exports.CHANNEL_TYPE_DM = exports.CLAN_DM = exports.SOCKET_READY_RETRY_DELAY = exports.SOCKET_READY_MAX_RETRY = exports.MEZON_GW_URL = void 0;
4
- /** Default Mezon Gateway URL */
5
- exports.MEZON_GW_URL = 'https://gw.mezon.ai';
6
- /** Maximum number of retries when waiting for socket to be ready */
7
- exports.SOCKET_READY_MAX_RETRY = 20;
8
- /** Initial delay in milliseconds between socket ready retries (uses exponential backoff) */
9
- exports.SOCKET_READY_RETRY_DELAY = 100;
10
- /** Clan ID used for Direct Messages */
11
- exports.CLAN_DM = '0';
12
- /** Channel type for Direct Messages */
13
- exports.CHANNEL_TYPE_DM = 3;
14
- exports.CHANNEL_TYPE_GROUP = 2;
15
- /** Stream mode for Direct Messages */
16
- exports.STREAM_MODE_DM = 4;
17
- exports.STREAM_MODE_GROUP = 3;
18
- /** Default server key if none is provided */
19
- exports.DEFAULT_SERVER_KEY = 'DefaultServerKey';
@@ -1,201 +0,0 @@
1
- import _m0 from "protobufjs/minimal";
2
- export declare const protobufPackage = "google.protobuf";
3
- /**
4
- * `NullValue` is a singleton enumeration to represent the null value for the
5
- * `Value` type union.
6
- *
7
- * The JSON representation for `NullValue` is JSON `null`.
8
- */
9
- export declare enum NullValue {
10
- /** NULL_VALUE - Null value. */
11
- NULL_VALUE = 0,
12
- UNRECOGNIZED = -1
13
- }
14
- export declare function nullValueFromJSON(object: any): NullValue;
15
- export declare function nullValueToJSON(object: NullValue): string;
16
- /**
17
- * `Struct` represents a structured data value, consisting of fields
18
- * which map to dynamically typed values. In some languages, `Struct`
19
- * might be supported by a native representation. For example, in
20
- * scripting languages like JS a struct is represented as an
21
- * object. The details of that representation are described together
22
- * with the proto support for the language.
23
- *
24
- * The JSON representation for `Struct` is JSON object.
25
- */
26
- export interface Struct {
27
- /** Unordered map of dynamically typed values. */
28
- fields: {
29
- [key: string]: any | undefined;
30
- };
31
- }
32
- export interface Struct_FieldsEntry {
33
- key: string;
34
- value: any | undefined;
35
- }
36
- /**
37
- * `Value` represents a dynamically typed value which can be either
38
- * null, a number, a string, a boolean, a recursive struct value, or a
39
- * list of values. A producer of value is expected to set one of these
40
- * variants. Absence of any variant indicates an error.
41
- *
42
- * The JSON representation for `Value` is JSON value.
43
- */
44
- export interface Value {
45
- /** Represents a null value. */
46
- null_value?: NullValue | undefined;
47
- /** Represents a double value. */
48
- number_value?: number | undefined;
49
- /** Represents a string value. */
50
- string_value?: string | undefined;
51
- /** Represents a boolean value. */
52
- bool_value?: boolean | undefined;
53
- /** Represents a structured value. */
54
- struct_value?: {
55
- [key: string]: any;
56
- } | undefined;
57
- /** Represents a repeated `Value`. */
58
- list_value?: Array<any> | undefined;
59
- }
60
- /**
61
- * `ListValue` is a wrapper around a repeated field of values.
62
- *
63
- * The JSON representation for `ListValue` is JSON array.
64
- */
65
- export interface ListValue {
66
- /** Repeated field of dynamically typed values. */
67
- values: any[];
68
- }
69
- export declare const Struct: {
70
- encode(message: Struct, writer?: _m0.Writer): _m0.Writer;
71
- decode(input: _m0.Reader | Uint8Array, length?: number): Struct;
72
- fromJSON(object: any): Struct;
73
- toJSON(message: Struct): unknown;
74
- create<I extends {
75
- fields?: {
76
- [x: string]: any;
77
- } | undefined;
78
- } & {
79
- fields?: ({
80
- [x: string]: any;
81
- } & {
82
- [x: string]: any;
83
- } & { [K in Exclude<keyof I["fields"], string | number>]: never; }) | undefined;
84
- } & { [K_1 in Exclude<keyof I, "fields">]: never; }>(base?: I | undefined): Struct;
85
- fromPartial<I_1 extends {
86
- fields?: {
87
- [x: string]: any;
88
- } | undefined;
89
- } & {
90
- fields?: ({
91
- [x: string]: any;
92
- } & {
93
- [x: string]: any;
94
- } & { [K_2 in Exclude<keyof I_1["fields"], string | number>]: never; }) | undefined;
95
- } & { [K_3 in Exclude<keyof I_1, "fields">]: never; }>(object: I_1): Struct;
96
- wrap(object: {
97
- [key: string]: any;
98
- } | undefined): Struct;
99
- unwrap(message: Struct): {
100
- [key: string]: any;
101
- };
102
- };
103
- export declare const Struct_FieldsEntry: {
104
- encode(message: Struct_FieldsEntry, writer?: _m0.Writer): _m0.Writer;
105
- decode(input: _m0.Reader | Uint8Array, length?: number): Struct_FieldsEntry;
106
- fromJSON(object: any): Struct_FieldsEntry;
107
- toJSON(message: Struct_FieldsEntry): unknown;
108
- create<I extends {
109
- key?: string | undefined;
110
- value?: any | undefined;
111
- } & {
112
- key?: string | undefined;
113
- value?: any | undefined;
114
- } & { [K in Exclude<keyof I, keyof Struct_FieldsEntry>]: never; }>(base?: I | undefined): Struct_FieldsEntry;
115
- fromPartial<I_1 extends {
116
- key?: string | undefined;
117
- value?: any | undefined;
118
- } & {
119
- key?: string | undefined;
120
- value?: any | undefined;
121
- } & { [K_1 in Exclude<keyof I_1, keyof Struct_FieldsEntry>]: never; }>(object: I_1): Struct_FieldsEntry;
122
- };
123
- export declare const Value: {
124
- encode(message: Value, writer?: _m0.Writer): _m0.Writer;
125
- decode(input: _m0.Reader | Uint8Array, length?: number): Value;
126
- fromJSON(object: any): Value;
127
- toJSON(message: Value): unknown;
128
- create<I extends {
129
- null_value?: NullValue | undefined;
130
- number_value?: number | undefined;
131
- string_value?: string | undefined;
132
- bool_value?: boolean | undefined;
133
- struct_value?: {
134
- [x: string]: any;
135
- } | undefined;
136
- list_value?: any[] | undefined;
137
- } & {
138
- null_value?: NullValue | undefined;
139
- number_value?: number | undefined;
140
- string_value?: string | undefined;
141
- bool_value?: boolean | undefined;
142
- struct_value?: ({
143
- [x: string]: any;
144
- } & {
145
- [x: string]: any;
146
- } & { [K in Exclude<keyof I["struct_value"], string | number>]: never; }) | undefined;
147
- list_value?: (any[] & any[] & { [K_1 in Exclude<keyof I["list_value"], keyof any[]>]: never; }) | undefined;
148
- } & { [K_2 in Exclude<keyof I, keyof Value>]: never; }>(base?: I | undefined): Value;
149
- fromPartial<I_1 extends {
150
- null_value?: NullValue | undefined;
151
- number_value?: number | undefined;
152
- string_value?: string | undefined;
153
- bool_value?: boolean | undefined;
154
- struct_value?: {
155
- [x: string]: any;
156
- } | undefined;
157
- list_value?: any[] | undefined;
158
- } & {
159
- null_value?: NullValue | undefined;
160
- number_value?: number | undefined;
161
- string_value?: string | undefined;
162
- bool_value?: boolean | undefined;
163
- struct_value?: ({
164
- [x: string]: any;
165
- } & {
166
- [x: string]: any;
167
- } & { [K_3 in Exclude<keyof I_1["struct_value"], string | number>]: never; }) | undefined;
168
- list_value?: (any[] & any[] & { [K_4 in Exclude<keyof I_1["list_value"], keyof any[]>]: never; }) | undefined;
169
- } & { [K_5 in Exclude<keyof I_1, keyof Value>]: never; }>(object: I_1): Value;
170
- wrap(value: any): Value;
171
- unwrap(message: any): string | number | boolean | Object | null | Array<any> | undefined;
172
- };
173
- export declare const ListValue: {
174
- encode(message: ListValue, writer?: _m0.Writer): _m0.Writer;
175
- decode(input: _m0.Reader | Uint8Array, length?: number): ListValue;
176
- fromJSON(object: any): ListValue;
177
- toJSON(message: ListValue): unknown;
178
- create<I extends {
179
- values?: any[] | undefined;
180
- } & {
181
- values?: (any[] & any[] & { [K in Exclude<keyof I["values"], keyof any[]>]: never; }) | undefined;
182
- } & { [K_1 in Exclude<keyof I, "values">]: never; }>(base?: I | undefined): ListValue;
183
- fromPartial<I_1 extends {
184
- values?: any[] | undefined;
185
- } & {
186
- values?: (any[] & any[] & { [K_2 in Exclude<keyof I_1["values"], keyof any[]>]: never; }) | undefined;
187
- } & { [K_3 in Exclude<keyof I_1, "values">]: never; }>(object: I_1): ListValue;
188
- wrap(array: Array<any> | undefined): ListValue;
189
- unwrap(message: ListValue): Array<any>;
190
- };
191
- type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
192
- export type DeepPartial<T> = T extends Builtin ? T : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? {
193
- [K in keyof T]?: DeepPartial<T[K]>;
194
- } : Partial<T>;
195
- type KeysOfUnion<T> = T extends T ? keyof T : never;
196
- export type Exact<P, I extends P> = P extends Builtin ? P : P & {
197
- [K in keyof P]: Exact<P[K], I[K]>;
198
- } & {
199
- [K in Exclude<keyof I, KeysOfUnion<P>>]: never;
200
- };
201
- export {};