@tenxyte/core 0.1.5 → 0.9.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/dist/index.cjs CHANGED
@@ -1,497 +1,1882 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- AuthModule: () => AuthModule,
24
- RbacModule: () => RbacModule,
25
- SecurityModule: () => SecurityModule,
26
- TenxyteClient: () => TenxyteClient,
27
- TenxyteHttpClient: () => TenxyteHttpClient,
28
- UserModule: () => UserModule
29
- });
30
- module.exports = __toCommonJS(index_exports);
31
-
32
- // src/http/client.ts
33
- var TenxyteHttpClient = class {
34
- baseUrl;
35
- defaultHeaders;
36
- // Interceptors
37
- requestInterceptors = [];
38
- responseInterceptors = [];
39
- constructor(options) {
40
- this.baseUrl = options.baseUrl.replace(/\/$/, "");
41
- this.defaultHeaders = {
42
- "Content-Type": "application/json",
43
- Accept: "application/json",
44
- ...options.headers
45
- };
46
- }
47
- // Interceptor Registration
48
- addRequestInterceptor(interceptor) {
49
- this.requestInterceptors.push(interceptor);
50
- }
51
- addResponseInterceptor(interceptor) {
52
- this.responseInterceptors.push(interceptor);
53
- }
54
- /**
55
- * Main request method wrapping fetch
56
- */
57
- async request(endpoint, config = {}) {
58
- const urlStr = endpoint.startsWith("http") ? endpoint : `${this.baseUrl}${endpoint.startsWith("/") ? "" : "/"}${endpoint}`;
59
- let urlObj = new URL(urlStr);
60
- if (config.params) {
61
- Object.entries(config.params).forEach(([key, value]) => {
62
- if (value !== void 0 && value !== null) {
63
- urlObj.searchParams.append(key, String(value));
64
- }
65
- });
66
- }
67
- let requestContext = {
68
- url: urlObj.toString(),
69
- ...config,
70
- headers: { ...this.defaultHeaders, ...config.headers || {} }
71
- };
72
- if (typeof FormData !== "undefined" && requestContext.body instanceof FormData) {
73
- const headers = requestContext.headers;
74
- delete headers["Content-Type"];
75
- delete headers["content-type"];
76
- } else if (requestContext.body && typeof requestContext.body === "object") {
77
- const contentType = requestContext.headers["Content-Type"] || "";
78
- if (contentType.toLowerCase().includes("application/json")) {
79
- requestContext.body = JSON.stringify(requestContext.body);
80
- }
81
- }
82
- for (const interceptor of this.requestInterceptors) {
83
- requestContext = await interceptor(requestContext);
84
- }
85
- const { url, ...fetchConfig } = requestContext;
86
- try {
87
- let response = await fetch(url, fetchConfig);
88
- for (const interceptor of this.responseInterceptors) {
89
- response = await interceptor(response, { url, config: fetchConfig });
90
- }
91
- if (!response.ok) {
92
- throw await this.normalizeError(response);
93
- }
94
- if (response.status === 204) {
95
- return {};
96
- }
97
- const contentType = response.headers.get("content-type");
98
- if (contentType && contentType.includes("application/json")) {
99
- return await response.json();
100
- }
101
- return await response.text();
102
- } catch (error) {
103
- if (error && error.code) {
104
- throw error;
105
- }
106
- throw {
107
- error: error.message || "Network request failed",
108
- code: "NETWORK_ERROR",
109
- details: String(error)
110
- };
111
- }
112
- }
113
- async normalizeError(response) {
114
- try {
115
- const body = await response.json();
116
- return {
117
- error: body.error || body.detail || "API request failed",
118
- code: body.code || `HTTP_${response.status}`,
119
- details: body.details || body,
120
- retry_after: response.headers.has("Retry-After") ? parseInt(response.headers.get("Retry-After"), 10) : void 0
121
- };
122
- } catch (e) {
123
- return {
124
- error: `HTTP Error ${response.status}: ${response.statusText}`,
125
- code: `HTTP_${response.status}`
126
- };
127
- }
128
- }
129
- // Convenience methods
130
- get(endpoint, config) {
131
- return this.request(endpoint, { ...config, method: "GET" });
132
- }
133
- post(endpoint, data, config) {
134
- return this.request(endpoint, { ...config, method: "POST", body: data });
135
- }
136
- put(endpoint, data, config) {
137
- return this.request(endpoint, { ...config, method: "PUT", body: data });
138
- }
139
- patch(endpoint, data, config) {
140
- return this.request(endpoint, { ...config, method: "PATCH", body: data });
141
- }
142
- delete(endpoint, config) {
143
- return this.request(endpoint, { ...config, method: "DELETE" });
144
- }
145
- };
146
-
147
- // src/modules/auth.ts
148
- var AuthModule = class {
149
- constructor(client) {
150
- this.client = client;
151
- }
152
- /**
153
- * Authenticate user with email and password
154
- */
155
- async loginWithEmail(data) {
156
- return this.client.post("/api/v1/auth/login/email/", data);
157
- }
158
- /**
159
- * Authenticate user with international phone number and password
160
- */
161
- async loginWithPhone(data) {
162
- return this.client.post("/api/v1/auth/login/phone/", data);
163
- }
164
- /**
165
- * Register a new user
166
- */
167
- async register(data) {
168
- return this.client.post("/api/v1/auth/register/", data);
169
- }
170
- /**
171
- * Logout from the current session
172
- */
173
- async logout(refreshToken) {
174
- return this.client.post("/api/v1/auth/logout/", { refresh_token: refreshToken });
175
- }
176
- /**
177
- * Logout from all sessions (revokes all refresh tokens)
178
- */
179
- async logoutAll() {
180
- return this.client.post("/api/v1/auth/logout/all/");
181
- }
182
- /**
183
- * Request a magic link for sign-in
184
- */
185
- async requestMagicLink(data) {
186
- return this.client.post("/api/v1/auth/magic-link/request/", data);
187
- }
188
- /**
189
- * Verify a magic link token
190
- */
191
- async verifyMagicLink(token) {
192
- return this.client.get(`/api/v1/auth/magic-link/verify/`, { params: { token } });
193
- }
194
- /**
195
- * Perform OAuth2 Social Authentication (e.g. Google, GitHub)
196
- */
197
- async loginWithSocial(provider, data) {
198
- return this.client.post(`/api/v1/auth/social/${provider}/`, data);
199
- }
200
- /**
201
- * Handle Social Auth Callback (authorization code flow)
202
- */
203
- async handleSocialCallback(provider, code, redirectUri) {
204
- return this.client.get(`/api/v1/auth/social/${provider}/callback/`, {
205
- params: { code, redirect_uri: redirectUri }
206
- });
207
- }
208
- };
209
-
210
- // src/modules/security.ts
211
- var SecurityModule = class {
212
- constructor(client) {
213
- this.client = client;
214
- }
215
- // --- OTP Verification --- //
216
- async requestOtp(data) {
217
- return this.client.post("/api/v1/auth/otp/request/", data);
218
- }
219
- async verifyOtpEmail(data) {
220
- return this.client.post("/api/v1/auth/otp/verify/email/", data);
221
- }
222
- async verifyOtpPhone(data) {
223
- return this.client.post("/api/v1/auth/otp/verify/phone/", data);
224
- }
225
- // --- TOTP / 2FA --- //
226
- async get2FAStatus() {
227
- return this.client.get("/api/v1/auth/2fa/status/");
228
- }
229
- async setup2FA() {
230
- return this.client.post("/api/v1/auth/2fa/setup/");
231
- }
232
- async confirm2FA(totp_code) {
233
- return this.client.post("/api/v1/auth/2fa/confirm/", { totp_code });
234
- }
235
- async disable2FA(totp_code, password) {
236
- return this.client.post("/api/v1/auth/2fa/disable/", { totp_code, password });
237
- }
238
- async regenerateBackupCodes(totp_code) {
239
- return this.client.post("/api/v1/auth/2fa/backup-codes/", { totp_code });
240
- }
241
- // --- Password Management --- //
242
- async resetPasswordRequest(data) {
243
- return this.client.post("/api/v1/auth/password/reset/request/", data);
244
- }
245
- async resetPasswordConfirm(data) {
246
- return this.client.post("/api/v1/auth/password/reset/confirm/", data);
247
- }
248
- async changePassword(data) {
249
- return this.client.post("/api/v1/auth/password/change/", data);
250
- }
251
- async checkPasswordStrength(data) {
252
- return this.client.post("/api/v1/auth/password/strength/", data);
253
- }
254
- async getPasswordRequirements() {
255
- return this.client.get("/api/v1/auth/password/requirements/");
256
- }
257
- // --- WebAuthn / Passkeys --- //
258
- async registerWebAuthnBegin() {
259
- return this.client.post("/api/v1/auth/webauthn/register/begin/");
260
- }
261
- async registerWebAuthnComplete(data) {
262
- return this.client.post("/api/v1/auth/webauthn/register/complete/", data);
263
- }
264
- async authenticateWebAuthnBegin(data) {
265
- return this.client.post("/api/v1/auth/webauthn/authenticate/begin/", data || {});
266
- }
267
- async authenticateWebAuthnComplete(data) {
268
- return this.client.post("/api/v1/auth/webauthn/authenticate/complete/", data);
269
- }
270
- async listWebAuthnCredentials() {
271
- return this.client.get("/api/v1/auth/webauthn/credentials/");
272
- }
273
- async deleteWebAuthnCredential(credentialId) {
274
- return this.client.delete(`/api/v1/auth/webauthn/credentials/${credentialId}/`);
275
- }
276
- };
277
-
278
- // src/utils/jwt.ts
279
- function decodeJwt(token) {
280
- try {
281
- const parts = token.split(".");
282
- if (parts.length !== 3) {
283
- return null;
284
- }
285
- let base64Url = parts[1];
286
- if (!base64Url) return null;
287
- let base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
288
- while (base64.length % 4) {
289
- base64 += "=";
290
- }
291
- const isBrowser = typeof window !== "undefined" && typeof window.atob === "function";
292
- let jsonPayload;
293
- if (isBrowser) {
294
- jsonPayload = decodeURIComponent(
295
- window.atob(base64).split("").map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)).join("")
296
- );
297
- } else {
298
- jsonPayload = Buffer.from(base64, "base64").toString("utf8");
299
- }
300
- return JSON.parse(jsonPayload);
301
- } catch (e) {
302
- return null;
303
- }
304
- }
305
-
306
- // src/modules/rbac.ts
307
- var RbacModule = class {
308
- constructor(client) {
309
- this.client = client;
310
- }
311
- cachedToken = null;
312
- /**
313
- * Cache a token to use for parameter-less synchronous checks.
314
- */
315
- setToken(token) {
316
- this.cachedToken = token;
317
- }
318
- getDecodedToken(token) {
319
- const t = token || this.cachedToken;
320
- if (!t) return null;
321
- return decodeJwt(t);
322
- }
323
- // --- Synchronous Checks --- //
324
- hasRole(role, token) {
325
- const decoded = this.getDecodedToken(token);
326
- if (!decoded?.roles) return false;
327
- return decoded.roles.includes(role);
328
- }
329
- hasAnyRole(roles, token) {
330
- const decoded = this.getDecodedToken(token);
331
- if (!decoded?.roles) return false;
332
- return roles.some((r) => decoded.roles.includes(r));
333
- }
334
- hasAllRoles(roles, token) {
335
- const decoded = this.getDecodedToken(token);
336
- if (!decoded?.roles) return false;
337
- return roles.every((r) => decoded.roles.includes(r));
338
- }
339
- hasPermission(permission, token) {
340
- const decoded = this.getDecodedToken(token);
341
- if (!decoded?.permissions) return false;
342
- return decoded.permissions.includes(permission);
343
- }
344
- hasAnyPermission(permissions, token) {
345
- const decoded = this.getDecodedToken(token);
346
- if (!decoded?.permissions) return false;
347
- return permissions.some((p) => decoded.permissions.includes(p));
348
- }
349
- hasAllPermissions(permissions, token) {
350
- const decoded = this.getDecodedToken(token);
351
- if (!decoded?.permissions) return false;
352
- return permissions.every((p) => decoded.permissions.includes(p));
353
- }
354
- // --- Roles CRUD --- //
355
- async listRoles() {
356
- return this.client.get("/api/v1/auth/roles/");
357
- }
358
- async createRole(data) {
359
- return this.client.post("/api/v1/auth/roles/", data);
360
- }
361
- async getRole(roleId) {
362
- return this.client.get(`/api/v1/auth/roles/${roleId}/`);
363
- }
364
- async updateRole(roleId, data) {
365
- return this.client.put(`/api/v1/auth/roles/${roleId}/`, data);
366
- }
367
- async deleteRole(roleId) {
368
- return this.client.delete(`/api/v1/auth/roles/${roleId}/`);
369
- }
370
- // --- Role Permissions Management --- //
371
- async getRolePermissions(roleId) {
372
- return this.client.get(`/api/v1/auth/roles/${roleId}/permissions/`);
373
- }
374
- async addPermissionsToRole(roleId, permission_codes) {
375
- return this.client.post(`/api/v1/auth/roles/${roleId}/permissions/`, { permission_codes });
376
- }
377
- async removePermissionsFromRole(roleId, permission_codes) {
378
- return this.client.delete(`/api/v1/auth/roles/${roleId}/permissions/`, {
379
- // Note: DELETE request with body is supported via our fetch wrapper if enabled,
380
- // or we might need to rely on query strings. The schema specifies body or query.
381
- // Let's pass it in body via a custom config or URL params.
382
- body: { permission_codes }
383
- });
384
- }
385
- // --- Permissions CRUD --- //
386
- async listPermissions() {
387
- return this.client.get("/api/v1/auth/permissions/");
388
- }
389
- async createPermission(data) {
390
- return this.client.post("/api/v1/auth/permissions/", data);
391
- }
392
- async getPermission(permissionId) {
393
- return this.client.get(`/api/v1/auth/permissions/${permissionId}/`);
394
- }
395
- async updatePermission(permissionId, data) {
396
- return this.client.put(`/api/v1/auth/permissions/${permissionId}/`, data);
397
- }
398
- async deletePermission(permissionId) {
399
- return this.client.delete(`/api/v1/auth/permissions/${permissionId}/`);
400
- }
401
- // --- Direct Assignment (Users) --- //
402
- async assignRoleToUser(userId, roleCode) {
403
- return this.client.post(`/api/v1/auth/users/${userId}/roles/`, { role_code: roleCode });
404
- }
405
- async removeRoleFromUser(userId, roleCode) {
406
- return this.client.delete(`/api/v1/auth/users/${userId}/roles/`, {
407
- params: { role_code: roleCode }
408
- });
409
- }
410
- async assignPermissionsToUser(userId, permissionCodes) {
411
- return this.client.post(`/api/v1/auth/users/${userId}/permissions/`, { permission_codes: permissionCodes });
412
- }
413
- async removePermissionsFromUser(userId, permissionCodes) {
414
- return this.client.delete(`/api/v1/auth/users/${userId}/permissions/`, {
415
- body: { permission_codes: permissionCodes }
416
- });
417
- }
418
- };
419
-
420
- // src/modules/user.ts
421
- var UserModule = class {
422
- constructor(client) {
423
- this.client = client;
424
- }
425
- // --- Standard Profile Actions --- //
426
- async getProfile() {
427
- return this.client.get("/api/v1/auth/me/");
428
- }
429
- async updateProfile(data) {
430
- return this.client.patch("/api/v1/auth/me/", data);
431
- }
432
- /**
433
- * Upload an avatar using FormData.
434
- * Ensure the environment supports FormData (browser or Node.js v18+).
435
- * @param formData The FormData object containing the 'avatar' field.
436
- */
437
- async uploadAvatar(formData) {
438
- return this.client.patch("/api/v1/auth/me/", formData);
439
- }
440
- async deleteAccount(password, otpCode) {
441
- return this.client.post("/api/v1/auth/request-account-deletion/", {
442
- password,
443
- otp_code: otpCode
444
- });
445
- }
446
- // --- Admin Actions Mapping --- //
447
- async listUsers(params) {
448
- return this.client.get("/api/v1/auth/admin/users/", { params });
449
- }
450
- async getUser(userId) {
451
- return this.client.get(`/api/v1/auth/admin/users/${userId}/`);
452
- }
453
- async adminUpdateUser(userId, data) {
454
- return this.client.patch(`/api/v1/auth/admin/users/${userId}/`, data);
455
- }
456
- async adminDeleteUser(userId) {
457
- return this.client.delete(`/api/v1/auth/admin/users/${userId}/`);
458
- }
459
- async banUser(userId, reason = "") {
460
- return this.client.post(`/api/v1/auth/admin/users/${userId}/ban/`, { reason });
461
- }
462
- async unbanUser(userId) {
463
- return this.client.post(`/api/v1/auth/admin/users/${userId}/unban/`);
464
- }
465
- async lockUser(userId, durationMinutes = 30, reason = "") {
466
- return this.client.post(`/api/v1/auth/admin/users/${userId}/lock/`, { duration_minutes: durationMinutes, reason });
467
- }
468
- async unlockUser(userId) {
469
- return this.client.post(`/api/v1/auth/admin/users/${userId}/unlock/`);
470
- }
471
- };
472
-
473
- // src/client.ts
474
- var TenxyteClient = class {
475
- http;
476
- auth;
477
- security;
478
- rbac;
479
- user;
480
- constructor(options) {
481
- this.http = new TenxyteHttpClient(options);
482
- this.auth = new AuthModule(this.http);
483
- this.security = new SecurityModule(this.http);
484
- this.rbac = new RbacModule(this.http);
485
- this.user = new UserModule(this.http);
486
- }
487
- };
488
- // Annotate the CommonJS export names for ESM import in node:
489
- 0 && (module.exports = {
490
- AuthModule,
491
- RbacModule,
492
- SecurityModule,
493
- TenxyteClient,
494
- TenxyteHttpClient,
495
- UserModule
496
- });
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AdminModule: () => AdminModule,
24
+ AiModule: () => AiModule,
25
+ ApplicationsModule: () => ApplicationsModule,
26
+ AuthModule: () => AuthModule,
27
+ B2bModule: () => B2bModule,
28
+ CookieStorage: () => CookieStorage,
29
+ DashboardModule: () => DashboardModule,
30
+ EventEmitter: () => EventEmitter,
31
+ GdprModule: () => GdprModule,
32
+ LocalStorage: () => LocalStorage,
33
+ MemoryStorage: () => MemoryStorage,
34
+ NOOP_LOGGER: () => NOOP_LOGGER,
35
+ RbacModule: () => RbacModule,
36
+ SDK_VERSION: () => SDK_VERSION,
37
+ SecurityModule: () => SecurityModule,
38
+ TenxyteClient: () => TenxyteClient,
39
+ TenxyteHttpClient: () => TenxyteHttpClient,
40
+ UserModule: () => UserModule,
41
+ buildDeviceInfo: () => buildDeviceInfo,
42
+ createAuthInterceptor: () => createAuthInterceptor,
43
+ createDeviceInfoInterceptor: () => createDeviceInfoInterceptor,
44
+ createRefreshInterceptor: () => createRefreshInterceptor,
45
+ createRetryInterceptor: () => createRetryInterceptor,
46
+ decodeJwt: () => decodeJwt,
47
+ resolveConfig: () => resolveConfig
48
+ });
49
+ module.exports = __toCommonJS(index_exports);
50
+
51
+ // src/storage/memory.ts
52
+ var MemoryStorage = class {
53
+ store;
54
+ constructor() {
55
+ this.store = /* @__PURE__ */ new Map();
56
+ }
57
+ getItem(key) {
58
+ const value = this.store.get(key);
59
+ return value !== void 0 ? value : null;
60
+ }
61
+ setItem(key, value) {
62
+ this.store.set(key, value);
63
+ }
64
+ removeItem(key) {
65
+ this.store.delete(key);
66
+ }
67
+ clear() {
68
+ this.store.clear();
69
+ }
70
+ };
71
+
72
+ // src/storage/localStorage.ts
73
+ var LocalStorage = class {
74
+ fallbackMemoryStore = null;
75
+ isAvailable;
76
+ constructor() {
77
+ this.isAvailable = this.checkAvailability();
78
+ if (!this.isAvailable) {
79
+ this.fallbackMemoryStore = new MemoryStorage();
80
+ }
81
+ }
82
+ checkAvailability() {
83
+ try {
84
+ if (typeof window === "undefined" || !window.localStorage) {
85
+ return false;
86
+ }
87
+ const testKey = "__tenxyte_test__";
88
+ window.localStorage.setItem(testKey, "1");
89
+ window.localStorage.removeItem(testKey);
90
+ return true;
91
+ } catch (_e) {
92
+ return false;
93
+ }
94
+ }
95
+ getItem(key) {
96
+ if (!this.isAvailable && this.fallbackMemoryStore) {
97
+ return this.fallbackMemoryStore.getItem(key);
98
+ }
99
+ return window.localStorage.getItem(key);
100
+ }
101
+ setItem(key, value) {
102
+ if (!this.isAvailable && this.fallbackMemoryStore) {
103
+ this.fallbackMemoryStore.setItem(key, value);
104
+ return;
105
+ }
106
+ try {
107
+ window.localStorage.setItem(key, value);
108
+ } catch (_e) {
109
+ console.warn(`[Tenxyte SDK] Warning: failed to write to localStorage for key ${key}`);
110
+ }
111
+ }
112
+ removeItem(key) {
113
+ if (!this.isAvailable && this.fallbackMemoryStore) {
114
+ this.fallbackMemoryStore.removeItem(key);
115
+ return;
116
+ }
117
+ window.localStorage.removeItem(key);
118
+ }
119
+ clear() {
120
+ if (!this.isAvailable && this.fallbackMemoryStore) {
121
+ this.fallbackMemoryStore.clear();
122
+ return;
123
+ }
124
+ window.localStorage.clear();
125
+ }
126
+ };
127
+
128
+ // src/storage/cookie.ts
129
+ var CookieStorage = class {
130
+ defaultOptions;
131
+ constructor(options = {}) {
132
+ const secure = options.secure ?? true;
133
+ const sameSite = options.sameSite ?? "Lax";
134
+ this.defaultOptions = `path=/; SameSite=${sameSite}${secure ? "; Secure" : ""}`;
135
+ }
136
+ getItem(key) {
137
+ if (typeof document === "undefined") return null;
138
+ const match = document.cookie.match(new RegExp(`(^| )${key}=([^;]+)`));
139
+ return match ? decodeURIComponent(match[2]) : null;
140
+ }
141
+ setItem(key, value) {
142
+ if (typeof document === "undefined") return;
143
+ document.cookie = `${key}=${encodeURIComponent(value)}; ${this.defaultOptions}`;
144
+ }
145
+ removeItem(key) {
146
+ if (typeof document === "undefined") return;
147
+ document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
148
+ }
149
+ clear() {
150
+ this.removeItem("tx_access");
151
+ this.removeItem("tx_refresh");
152
+ }
153
+ };
154
+
155
+ // src/config.ts
156
+ var SDK_VERSION = "0.9.0";
157
+ var NOOP_LOGGER = {
158
+ debug() {
159
+ },
160
+ warn() {
161
+ },
162
+ error() {
163
+ }
164
+ };
165
+ function resolveConfig(config) {
166
+ return {
167
+ baseUrl: config.baseUrl,
168
+ headers: config.headers ?? {},
169
+ storage: config.storage ?? new MemoryStorage(),
170
+ autoRefresh: config.autoRefresh ?? true,
171
+ autoDeviceInfo: config.autoDeviceInfo ?? true,
172
+ timeoutMs: config.timeoutMs,
173
+ onSessionExpired: config.onSessionExpired,
174
+ logger: config.logger ?? NOOP_LOGGER,
175
+ logLevel: config.logLevel ?? "silent",
176
+ deviceInfoOverride: config.deviceInfoOverride,
177
+ retryConfig: config.retryConfig
178
+ };
179
+ }
180
+
181
+ // src/http/client.ts
182
+ var TenxyteHttpClient = class {
183
+ baseUrl;
184
+ defaultHeaders;
185
+ timeoutMs;
186
+ // Interceptors
187
+ requestInterceptors = [];
188
+ responseInterceptors = [];
189
+ constructor(options) {
190
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
191
+ this.timeoutMs = options.timeoutMs;
192
+ this.defaultHeaders = {
193
+ "Content-Type": "application/json",
194
+ Accept: "application/json",
195
+ ...options.headers
196
+ };
197
+ }
198
+ // Interceptor Registration
199
+ addRequestInterceptor(interceptor) {
200
+ this.requestInterceptors.push(interceptor);
201
+ }
202
+ addResponseInterceptor(interceptor) {
203
+ this.responseInterceptors.push(interceptor);
204
+ }
205
+ /**
206
+ * Main request method wrapping fetch
207
+ */
208
+ async request(endpoint, config = {}) {
209
+ const urlStr = endpoint.startsWith("http") ? endpoint : `${this.baseUrl}${endpoint.startsWith("/") ? "" : "/"}${endpoint}`;
210
+ const urlObj = new URL(urlStr);
211
+ if (config.params) {
212
+ Object.entries(config.params).forEach(([key, value]) => {
213
+ if (value !== void 0 && value !== null) {
214
+ urlObj.searchParams.append(key, String(value));
215
+ }
216
+ });
217
+ }
218
+ let requestContext = {
219
+ url: urlObj.toString(),
220
+ ...config,
221
+ headers: { ...this.defaultHeaders, ...config.headers || {} }
222
+ };
223
+ if (typeof FormData !== "undefined" && requestContext.body instanceof FormData) {
224
+ const headers = requestContext.headers;
225
+ delete headers["Content-Type"];
226
+ delete headers["content-type"];
227
+ } else if (requestContext.body && typeof requestContext.body === "object") {
228
+ const contentType = requestContext.headers["Content-Type"] || "";
229
+ if (contentType.toLowerCase().includes("application/json")) {
230
+ requestContext.body = JSON.stringify(requestContext.body);
231
+ }
232
+ }
233
+ for (const interceptor of this.requestInterceptors) {
234
+ requestContext = await interceptor(requestContext);
235
+ }
236
+ const { url, ...fetchConfig } = requestContext;
237
+ let controller;
238
+ let timeoutId;
239
+ if (this.timeoutMs) {
240
+ controller = new AbortController();
241
+ fetchConfig.signal = controller.signal;
242
+ timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
243
+ }
244
+ try {
245
+ let response = await fetch(url, fetchConfig);
246
+ for (const interceptor of this.responseInterceptors) {
247
+ response = await interceptor(response, { url, config: fetchConfig });
248
+ }
249
+ if (!response.ok) {
250
+ throw await this.normalizeError(response);
251
+ }
252
+ if (response.status === 204) {
253
+ return {};
254
+ }
255
+ const contentType = response.headers.get("content-type");
256
+ if (contentType && contentType.includes("application/json")) {
257
+ return await response.json();
258
+ }
259
+ return await response.text();
260
+ } catch (error) {
261
+ if (error?.name === "AbortError") {
262
+ throw {
263
+ error: `Request timed out after ${this.timeoutMs}ms`,
264
+ code: "TIMEOUT",
265
+ details: url
266
+ };
267
+ }
268
+ if (error && error.code) {
269
+ throw error;
270
+ }
271
+ throw {
272
+ error: error.message || "Network request failed",
273
+ code: "NETWORK_ERROR",
274
+ details: String(error)
275
+ };
276
+ } finally {
277
+ if (timeoutId !== void 0) {
278
+ clearTimeout(timeoutId);
279
+ }
280
+ }
281
+ }
282
+ async normalizeError(response) {
283
+ try {
284
+ const body = await response.json();
285
+ return {
286
+ error: body.error || body.detail || "API request failed",
287
+ code: body.code || `HTTP_${response.status}`,
288
+ details: body.details || body,
289
+ retry_after: response.headers.has("Retry-After") ? parseInt(response.headers.get("Retry-After"), 10) : void 0
290
+ };
291
+ } catch (_e) {
292
+ return {
293
+ error: `HTTP Error ${response.status}: ${response.statusText}`,
294
+ code: `HTTP_${response.status}`
295
+ };
296
+ }
297
+ }
298
+ // Convenience methods
299
+ get(endpoint, config) {
300
+ return this.request(endpoint, { ...config, method: "GET" });
301
+ }
302
+ post(endpoint, data, config) {
303
+ return this.request(endpoint, { ...config, method: "POST", body: data });
304
+ }
305
+ put(endpoint, data, config) {
306
+ return this.request(endpoint, { ...config, method: "PUT", body: data });
307
+ }
308
+ patch(endpoint, data, config) {
309
+ return this.request(endpoint, { ...config, method: "PATCH", body: data });
310
+ }
311
+ delete(endpoint, data, config) {
312
+ return this.request(endpoint, { ...config, method: "DELETE", body: data });
313
+ }
314
+ };
315
+
316
+ // src/utils/device_info.ts
317
+ function buildDeviceInfo(customInfo = {}) {
318
+ const autoInfo = getAutoInfo();
319
+ const v = "1";
320
+ const os = customInfo.os || autoInfo.os;
321
+ const osv = customInfo.osVersion || autoInfo.osVersion;
322
+ const device = customInfo.device || autoInfo.device;
323
+ const arch = customInfo.arch || autoInfo.arch;
324
+ const app = customInfo.app || autoInfo.app;
325
+ const appv = customInfo.appVersion || autoInfo.appVersion;
326
+ const runtime = customInfo.runtime || autoInfo.runtime;
327
+ const rtv = customInfo.runtimeVersion || autoInfo.runtimeVersion;
328
+ const tz = customInfo.timezone || autoInfo.timezone;
329
+ const parts = [
330
+ `v=${v}`,
331
+ `os=${os}` + (osv ? `;osv=${osv}` : ""),
332
+ `device=${device}`,
333
+ arch ? `arch=${arch}` : "",
334
+ app ? `app=${app}${appv ? `;appv=${appv}` : ""}` : "",
335
+ `runtime=${runtime}` + (rtv ? `;rtv=${rtv}` : ""),
336
+ tz ? `tz=${tz}` : ""
337
+ ];
338
+ return parts.filter(Boolean).join("|");
339
+ }
340
+ function getAutoInfo() {
341
+ const info = {
342
+ os: "unknown",
343
+ osVersion: "",
344
+ device: "desktop",
345
+ // default
346
+ arch: "",
347
+ app: "sdk",
348
+ appVersion: "0.1.0",
349
+ runtime: "unknown",
350
+ runtimeVersion: "",
351
+ timezone: ""
352
+ };
353
+ try {
354
+ if (typeof Intl !== "undefined") {
355
+ info.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
356
+ }
357
+ if (typeof process !== "undefined" && process.version) {
358
+ info.runtime = "node";
359
+ info.runtimeVersion = process.version;
360
+ info.os = process.platform;
361
+ info.arch = process.arch;
362
+ info.device = "server";
363
+ } else if (typeof window !== "undefined" && window.navigator) {
364
+ const ua = window.navigator.userAgent.toLowerCase();
365
+ if (ua.includes("windows")) info.os = "windows";
366
+ else if (ua.includes("mac")) info.os = "macos";
367
+ else if (ua.includes("linux")) info.os = "linux";
368
+ else if (ua.includes("android")) info.os = "android";
369
+ else if (ua.includes("ios") || ua.includes("iphone") || ua.includes("ipad")) info.os = "ios";
370
+ if (/mobi|android|touch|mini/i.test(ua)) info.device = "mobile";
371
+ if (/tablet|ipad/i.test(ua)) info.device = "tablet";
372
+ if (ua.includes("firefox")) info.runtime = "firefox";
373
+ else if (ua.includes("edg/")) info.runtime = "edge";
374
+ else if (ua.includes("chrome")) info.runtime = "chrome";
375
+ else if (ua.includes("safari")) info.runtime = "safari";
376
+ }
377
+ } catch (_e) {
378
+ }
379
+ return info;
380
+ }
381
+
382
+ // src/http/interceptors.ts
383
+ function createAuthInterceptor(storage, context) {
384
+ return async (request) => {
385
+ const token = await storage.getItem("tx_access");
386
+ const headers = { ...request.headers || {} };
387
+ if (token && !headers["Authorization"]) {
388
+ headers["Authorization"] = `Bearer ${token}`;
389
+ }
390
+ if (context.activeOrgSlug && !headers["X-Org-Slug"]) {
391
+ headers["X-Org-Slug"] = context.activeOrgSlug;
392
+ }
393
+ if (context.agentTraceId && !headers["X-Prompt-Trace-ID"]) {
394
+ headers["X-Prompt-Trace-ID"] = context.agentTraceId;
395
+ }
396
+ return { ...request, headers };
397
+ };
398
+ }
399
+ function createRefreshInterceptor(client, storage, onSessionExpired, onTokenRefreshed) {
400
+ let isRefreshing = false;
401
+ let refreshQueue = [];
402
+ const processQueue = (error, token = null) => {
403
+ refreshQueue.forEach((prom) => prom(token));
404
+ refreshQueue = [];
405
+ };
406
+ return async (response, request) => {
407
+ if (response.status === 401 && !request.url.includes("/auth/refresh") && !request.url.includes("/auth/login")) {
408
+ const refreshToken = await storage.getItem("tx_refresh");
409
+ if (!refreshToken) {
410
+ onSessionExpired();
411
+ return response;
412
+ }
413
+ if (isRefreshing) {
414
+ return new Promise((resolve) => {
415
+ refreshQueue.push((newToken) => {
416
+ if (newToken) {
417
+ const retryHeaders = { ...request.config.headers, Authorization: `Bearer ${newToken}` };
418
+ resolve(fetch(request.url, { ...request.config, headers: retryHeaders }));
419
+ } else {
420
+ resolve(response);
421
+ }
422
+ });
423
+ });
424
+ }
425
+ isRefreshing = true;
426
+ try {
427
+ const refreshResponse = await fetch(`${client["baseUrl"]}/auth/refresh/`, {
428
+ method: "POST",
429
+ headers: { "Content-Type": "application/json" },
430
+ body: JSON.stringify({ refresh_token: refreshToken })
431
+ });
432
+ if (!refreshResponse.ok) {
433
+ throw new Error("Refresh failed");
434
+ }
435
+ const data = await refreshResponse.json();
436
+ await storage.setItem("tx_access", data.access);
437
+ if (data.refresh) {
438
+ await storage.setItem("tx_refresh", data.refresh);
439
+ }
440
+ isRefreshing = false;
441
+ onTokenRefreshed?.(data.access, data.refresh);
442
+ processQueue(null, data.access);
443
+ const retryHeaders = { ...request.config.headers, Authorization: `Bearer ${data.access}` };
444
+ const r = await fetch(request.url, { ...request.config, headers: retryHeaders });
445
+ return r;
446
+ } catch (err) {
447
+ isRefreshing = false;
448
+ await storage.removeItem("tx_access");
449
+ await storage.removeItem("tx_refresh");
450
+ processQueue(err, null);
451
+ onSessionExpired();
452
+ return response;
453
+ }
454
+ }
455
+ return response;
456
+ };
457
+ }
458
+ var DEVICE_INFO_ENDPOINTS = [
459
+ "/login/email/",
460
+ "/login/phone/",
461
+ "/register/",
462
+ "/social/"
463
+ ];
464
+ var DEFAULT_RETRY = {
465
+ maxRetries: 3,
466
+ retryOn429: true,
467
+ retryOnNetworkError: true,
468
+ baseDelayMs: 1e3
469
+ };
470
+ function sleep(ms) {
471
+ return new Promise((resolve) => setTimeout(resolve, ms));
472
+ }
473
+ function createRetryInterceptor(config = {}, logger) {
474
+ const opts = { ...DEFAULT_RETRY, ...config };
475
+ return async (response, request) => {
476
+ const shouldRetry429 = opts.retryOn429 && response.status === 429;
477
+ const shouldRetryServer = response.status >= 500;
478
+ if (!shouldRetry429 && !shouldRetryServer) {
479
+ return response;
480
+ }
481
+ let lastResponse = response;
482
+ for (let attempt = 1; attempt <= opts.maxRetries; attempt++) {
483
+ let delayMs = opts.baseDelayMs * Math.pow(2, attempt - 1);
484
+ const retryAfter = lastResponse.headers.get("Retry-After");
485
+ if (retryAfter) {
486
+ const parsed = Number(retryAfter);
487
+ if (!isNaN(parsed)) {
488
+ delayMs = parsed * 1e3;
489
+ }
490
+ }
491
+ logger?.debug(`[Tenxyte Retry] Attempt ${attempt}/${opts.maxRetries} after ${delayMs}ms for ${request.url}`);
492
+ await sleep(delayMs);
493
+ try {
494
+ const retryResponse = await fetch(request.url, request.config);
495
+ if (retryResponse.status === 429 && opts.retryOn429 && attempt < opts.maxRetries) {
496
+ lastResponse = retryResponse;
497
+ continue;
498
+ }
499
+ if (retryResponse.status >= 500 && attempt < opts.maxRetries) {
500
+ lastResponse = retryResponse;
501
+ continue;
502
+ }
503
+ return retryResponse;
504
+ } catch (err) {
505
+ if (!opts.retryOnNetworkError || attempt >= opts.maxRetries) {
506
+ throw err;
507
+ }
508
+ logger?.warn(`[Tenxyte Retry] Network error on attempt ${attempt}/${opts.maxRetries}`, err);
509
+ }
510
+ }
511
+ return lastResponse;
512
+ };
513
+ }
514
+ function createDeviceInfoInterceptor(override) {
515
+ const fingerprint = buildDeviceInfo(override);
516
+ return (request) => {
517
+ const isPost = !request.method || request.method === "POST";
518
+ const matchesEndpoint = DEVICE_INFO_ENDPOINTS.some((ep) => request.url.includes(ep));
519
+ if (isPost && matchesEndpoint && request.body && typeof request.body === "object") {
520
+ const body = request.body;
521
+ if (!body.device_info) {
522
+ return { ...request, body: { ...body, device_info: fingerprint } };
523
+ }
524
+ }
525
+ return request;
526
+ };
527
+ }
528
+
529
+ // src/modules/auth.ts
530
+ var AuthModule = class {
531
+ constructor(client, storage, onTokens, onLogout) {
532
+ this.client = client;
533
+ this.storage = storage;
534
+ this.onTokens = onTokens;
535
+ this.onLogout = onLogout;
536
+ }
537
+ async clearTokens() {
538
+ if (this.storage) {
539
+ await this.storage.removeItem("tx_access");
540
+ await this.storage.removeItem("tx_refresh");
541
+ this.onLogout?.();
542
+ }
543
+ }
544
+ async persistTokens(tokens) {
545
+ if (this.storage) {
546
+ await this.storage.setItem("tx_access", tokens.access_token);
547
+ if (tokens.refresh_token) {
548
+ await this.storage.setItem("tx_refresh", tokens.refresh_token);
549
+ }
550
+ this.onTokens?.(tokens.access_token, tokens.refresh_token);
551
+ }
552
+ return tokens;
553
+ }
554
+ /**
555
+ * Authenticate a user with their email and password.
556
+ * @param data - The login credentials and optional TOTP code if 2FA is required.
557
+ * @returns A pair of Access and Refresh tokens upon successful authentication.
558
+ * @throws {TenxyteError} If credentials are invalid, or if `2FA_REQUIRED` without a valid `totp_code`.
559
+ */
560
+ async loginWithEmail(data) {
561
+ const tokens = await this.client.post("/api/v1/auth/login/email/", data);
562
+ return this.persistTokens(tokens);
563
+ }
564
+ /**
565
+ * Authenticate a user with an international phone number and password.
566
+ * @param data - The login credentials and optional TOTP code if 2FA is required.
567
+ * @returns A pair of Access and Refresh tokens.
568
+ */
569
+ async loginWithPhone(data) {
570
+ const tokens = await this.client.post("/api/v1/auth/login/phone/", data);
571
+ return this.persistTokens(tokens);
572
+ }
573
+ /**
574
+ * Registers a new user account.
575
+ * @param data - The registration details (email, password, etc.).
576
+ * @returns The registered user data or a confirmation message.
577
+ */
578
+ async register(data) {
579
+ const result = await this.client.post("/api/v1/auth/register/", data);
580
+ if (result?.access_token) {
581
+ await this.persistTokens(result);
582
+ }
583
+ return result;
584
+ }
585
+ /**
586
+ * Logout from the current session.
587
+ * Informs the backend to immediately revoke the specified refresh token.
588
+ * @param refreshToken - The refresh token to revoke.
589
+ */
590
+ async logout(refreshToken) {
591
+ await this.client.post("/api/v1/auth/logout/", { refresh_token: refreshToken });
592
+ await this.clearTokens();
593
+ }
594
+ /**
595
+ * Logout from all sessions across all devices.
596
+ * Revokes all refresh tokens currently assigned to the user.
597
+ */
598
+ async logoutAll() {
599
+ await this.client.post("/api/v1/auth/logout/all/");
600
+ await this.clearTokens();
601
+ }
602
+ /**
603
+ * Manually refresh the access token using a valid refresh token.
604
+ * The refresh token is automatically rotated for improved security.
605
+ * @param refreshToken - The current refresh token.
606
+ * @returns A new token pair (access + rotated refresh).
607
+ */
608
+ async refreshToken(refreshToken) {
609
+ const tokens = await this.client.post("/api/v1/auth/refresh/", { refresh_token: refreshToken });
610
+ return this.persistTokens(tokens);
611
+ }
612
+ /**
613
+ * Request a Magic Link for passwordless sign-in.
614
+ * @param data - The email to send the logic link to.
615
+ */
616
+ async requestMagicLink(data) {
617
+ return this.client.post("/api/v1/auth/magic-link/request/", data);
618
+ }
619
+ /**
620
+ * Verifies a magic link token extracted from the URL.
621
+ * @param token - The cryptographic token received via email.
622
+ * @returns A session token pair if the token is valid and unexpired.
623
+ */
624
+ async verifyMagicLink(token) {
625
+ const tokens = await this.client.get(`/api/v1/auth/magic-link/verify/`, { params: { token } });
626
+ return this.persistTokens(tokens);
627
+ }
628
+ /**
629
+ * Submits OAuth2 Social Authentication payloads to the backend.
630
+ * Can be used with native mobile SDK tokens (like Apple Sign-In JWTs).
631
+ * @param provider - The OAuth provider ('google', 'github', etc.)
632
+ * @param data - The OAuth tokens (access_token, id_token, etc.)
633
+ * @returns An active session token pair.
634
+ */
635
+ async loginWithSocial(provider, data) {
636
+ const tokens = await this.client.post(`/api/v1/auth/social/${provider}/`, data);
637
+ return this.persistTokens(tokens);
638
+ }
639
+ /**
640
+ * Handle Social Auth Callbacks (Authorization Code flow).
641
+ * @param provider - The OAuth provider ('google', 'github', etc.)
642
+ * @param code - The authorization code retrieved from the query string parameters.
643
+ * @param redirectUri - The original redirect URI that was requested.
644
+ * @returns An active session token pair after successful code exchange.
645
+ */
646
+ async handleSocialCallback(provider, code, redirectUri) {
647
+ const tokens = await this.client.get(`/api/v1/auth/social/${provider}/callback/`, {
648
+ params: { code, redirect_uri: redirectUri }
649
+ });
650
+ return this.persistTokens(tokens);
651
+ }
652
+ };
653
+
654
+ // src/utils/base64url.ts
655
+ function bufferToBase64url(buffer) {
656
+ const bytes = new Uint8Array(buffer);
657
+ let binary = "";
658
+ for (let i = 0; i < bytes.byteLength; i++) {
659
+ binary += String.fromCharCode(bytes[i]);
660
+ }
661
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
662
+ }
663
+ function base64urlToBuffer(base64url) {
664
+ const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
665
+ const padLen = (4 - base64.length % 4) % 4;
666
+ const padded = base64 + "=".repeat(padLen);
667
+ const binary = atob(padded);
668
+ const bytes = new Uint8Array(binary.length);
669
+ for (let i = 0; i < binary.length; i++) {
670
+ bytes[i] = binary.charCodeAt(i);
671
+ }
672
+ return bytes;
673
+ }
674
+
675
+ // src/modules/security.ts
676
+ var SecurityModule = class {
677
+ constructor(client) {
678
+ this.client = client;
679
+ }
680
+ // ─── 2FA (TOTP) Management ───
681
+ /**
682
+ * Get the current 2FA status for the authenticated user.
683
+ * @returns Information about whether 2FA is enabled and how many backup codes remain.
684
+ */
685
+ async get2FAStatus() {
686
+ return this.client.get("/api/v1/auth/2fa/status/");
687
+ }
688
+ /**
689
+ * Start the 2FA enrollment process.
690
+ * @returns The secret key and QR code URL to be scanned by an Authenticator app.
691
+ */
692
+ async setup2FA() {
693
+ return this.client.post("/api/v1/auth/2fa/setup/");
694
+ }
695
+ /**
696
+ * Confirm the 2FA setup by providing the first TOTP code generated by the Authenticator app.
697
+ * @param totpCode - The 6-digit code.
698
+ */
699
+ async confirm2FA(totpCode) {
700
+ return this.client.post("/api/v1/auth/2fa/confirm/", { totp_code: totpCode });
701
+ }
702
+ /**
703
+ * Disable 2FA for the current user.
704
+ * Usually requires re-authentication or providing the active password/totp code.
705
+ * @param totpCode - The current 6-digit code to verify intent.
706
+ * @param password - (Optional) The user's password if required by backend policy.
707
+ */
708
+ async disable2FA(totpCode, password) {
709
+ return this.client.post("/api/v1/auth/2fa/disable/", { totp_code: totpCode, password });
710
+ }
711
+ /**
712
+ * Invalidate old backup codes and explicitly generate a new batch.
713
+ * @param totpCode - An active TOTP code to verify intent.
714
+ */
715
+ async regenerateBackupCodes(totpCode) {
716
+ return this.client.post("/api/v1/auth/2fa/backup-codes/", { totp_code: totpCode });
717
+ }
718
+ // ─── Verification OTP (Email / Phone) ───
719
+ /**
720
+ * Request an OTP code to be dispatched to the user's primary contact method.
721
+ * @param type - The channel type ('email' or 'phone').
722
+ */
723
+ async requestOtp(type) {
724
+ return this.client.post("/api/v1/auth/otp/request/", { type: type === "email" ? "email_verification" : "phone_verification" });
725
+ }
726
+ /**
727
+ * Verify an email confirmation OTP.
728
+ * @param code - The numeric code received via email.
729
+ */
730
+ async verifyOtpEmail(code) {
731
+ return this.client.post("/api/v1/auth/otp/verify/email/", { code });
732
+ }
733
+ /**
734
+ * Verify a phone confirmation OTP (SMS dispatch).
735
+ * @param code - The numeric code received via SMS.
736
+ */
737
+ async verifyOtpPhone(code) {
738
+ return this.client.post("/api/v1/auth/otp/verify/phone/", { code });
739
+ }
740
+ // ─── Password Sub-module ───
741
+ /**
742
+ * Triggers a password reset flow, dispatching an OTP to the target.
743
+ * @param target - Either an email address or a phone configuration payload.
744
+ */
745
+ async resetPasswordRequest(target) {
746
+ return this.client.post("/api/v1/auth/password/reset/request/", target);
747
+ }
748
+ /**
749
+ * Confirm a password reset using the OTP dispatched by `resetPasswordRequest`.
750
+ * @param data - The OTP code and the new matching password fields.
751
+ */
752
+ async resetPasswordConfirm(data) {
753
+ return this.client.post("/api/v1/auth/password/reset/confirm/", data);
754
+ }
755
+ /**
756
+ * Change password for an already authenticated user.
757
+ * @param currentPassword - The existing password to verify intent.
758
+ * @param newPassword - The distinct new password.
759
+ */
760
+ async changePassword(currentPassword, newPassword) {
761
+ return this.client.post("/api/v1/auth/password/change/", {
762
+ current_password: currentPassword,
763
+ new_password: newPassword
764
+ });
765
+ }
766
+ /**
767
+ * Evaluate the strength of a potential password against backend policies.
768
+ * @param password - The password string to test.
769
+ * @param email - (Optional) The user's email to ensure the password doesn't contain it.
770
+ */
771
+ async checkPasswordStrength(password, email) {
772
+ return this.client.post("/api/v1/auth/password/strength/", { password, email });
773
+ }
774
+ /**
775
+ * Fetch the password complexity requirements enforced by the Tenxyte backend.
776
+ */
777
+ async getPasswordRequirements() {
778
+ return this.client.get("/api/v1/auth/password/requirements/");
779
+ }
780
+ // ─── WebAuthn / Passkeys (FIDO2) ───
781
+ /**
782
+ * Register a new WebAuthn device (Passkey/Biometrics/Security Key) for the authenticated user.
783
+ * Integrates transparently with the browser `navigator.credentials` API.
784
+ * @param deviceName - Optional human-readable name for the device being registered.
785
+ */
786
+ async registerWebAuthn(deviceName) {
787
+ const optionsResponse = await this.client.post("/api/v1/auth/webauthn/register/begin/");
788
+ const publicKeyOpts = optionsResponse.publicKey;
789
+ publicKeyOpts.challenge = base64urlToBuffer(publicKeyOpts.challenge);
790
+ publicKeyOpts.user.id = base64urlToBuffer(publicKeyOpts.user.id);
791
+ if (publicKeyOpts.excludeCredentials) {
792
+ publicKeyOpts.excludeCredentials.forEach((cred2) => {
793
+ cred2.id = base64urlToBuffer(cred2.id);
794
+ });
795
+ }
796
+ const cred = await navigator.credentials.create({ publicKey: publicKeyOpts });
797
+ if (!cred) {
798
+ throw new Error("WebAuthn registration was aborted or failed.");
799
+ }
800
+ const response = cred.response;
801
+ const completionPayload = {
802
+ device_name: deviceName,
803
+ credential: {
804
+ id: cred.id,
805
+ type: cred.type,
806
+ rawId: bufferToBase64url(cred.rawId),
807
+ response: {
808
+ attestationObject: bufferToBase64url(response.attestationObject),
809
+ clientDataJSON: bufferToBase64url(response.clientDataJSON)
810
+ }
811
+ }
812
+ };
813
+ return this.client.post("/api/v1/auth/webauthn/register/complete/", completionPayload);
814
+ }
815
+ /**
816
+ * Authenticate via WebAuthn (Passkey) without requiring a password.
817
+ * Integrates transparently with the browser `navigator.credentials` API.
818
+ * @param email - The email address identifying the user account (optional if discoverable credentials are used).
819
+ * @returns A session token pair and the user context upon successful cryptographic challenge verification.
820
+ */
821
+ async authenticateWebAuthn(email) {
822
+ const optionsResponse = await this.client.post("/api/v1/auth/webauthn/authenticate/begin/", email ? { email } : {});
823
+ const publicKeyOpts = optionsResponse.publicKey;
824
+ publicKeyOpts.challenge = base64urlToBuffer(publicKeyOpts.challenge);
825
+ if (publicKeyOpts.allowCredentials) {
826
+ publicKeyOpts.allowCredentials.forEach((cred2) => {
827
+ cred2.id = base64urlToBuffer(cred2.id);
828
+ });
829
+ }
830
+ const cred = await navigator.credentials.get({ publicKey: publicKeyOpts });
831
+ if (!cred) {
832
+ throw new Error("WebAuthn authentication was aborted or failed.");
833
+ }
834
+ const response = cred.response;
835
+ const completionPayload = {
836
+ credential: {
837
+ id: cred.id,
838
+ type: cred.type,
839
+ rawId: bufferToBase64url(cred.rawId),
840
+ response: {
841
+ authenticatorData: bufferToBase64url(response.authenticatorData),
842
+ clientDataJSON: bufferToBase64url(response.clientDataJSON),
843
+ signature: bufferToBase64url(response.signature),
844
+ userHandle: response.userHandle ? bufferToBase64url(response.userHandle) : null
845
+ }
846
+ }
847
+ };
848
+ return this.client.post("/api/v1/auth/webauthn/authenticate/complete/", completionPayload);
849
+ }
850
+ /**
851
+ * List all registered WebAuthn credentials for the active user.
852
+ */
853
+ async listWebAuthnCredentials() {
854
+ return this.client.get("/api/v1/auth/webauthn/credentials/");
855
+ }
856
+ /**
857
+ * Delete a specific WebAuthn credential, removing its capability to sign in.
858
+ * @param credentialId - The internal ID of the credential to delete.
859
+ */
860
+ async deleteWebAuthnCredential(credentialId) {
861
+ return this.client.delete(`/api/v1/auth/webauthn/credentials/${credentialId}/`);
862
+ }
863
+ };
864
+
865
+ // src/utils/jwt.ts
866
+ function decodeJwt(token) {
867
+ try {
868
+ const parts = token.split(".");
869
+ if (parts.length !== 3) {
870
+ return null;
871
+ }
872
+ const base64Url = parts[1];
873
+ if (!base64Url) return null;
874
+ let base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
875
+ while (base64.length % 4) {
876
+ base64 += "=";
877
+ }
878
+ const isBrowser = typeof window !== "undefined" && typeof window.atob === "function";
879
+ let jsonPayload;
880
+ if (isBrowser) {
881
+ jsonPayload = decodeURIComponent(
882
+ window.atob(base64).split("").map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)).join("")
883
+ );
884
+ } else {
885
+ jsonPayload = Buffer.from(base64, "base64").toString("utf8");
886
+ }
887
+ return JSON.parse(jsonPayload);
888
+ } catch (_e) {
889
+ return null;
890
+ }
891
+ }
892
+
893
+ // src/modules/rbac.ts
894
+ var RbacModule = class {
895
+ constructor(client) {
896
+ this.client = client;
897
+ }
898
+ cachedToken = null;
899
+ /**
900
+ * Cache a decoded JWT payload locally to perform parameter-less synchronous permission checks.
901
+ * Usually invoked automatically by the system upon login or token refresh.
902
+ * @param token - The raw JWT access token encoded string.
903
+ */
904
+ setToken(token) {
905
+ this.cachedToken = token;
906
+ }
907
+ getDecodedToken(token) {
908
+ const t = token || this.cachedToken;
909
+ if (!t) return null;
910
+ return decodeJwt(t);
911
+ }
912
+ // --- Synchronous Checks --- //
913
+ /**
914
+ * Synchronously deeply inspects the cached (or provided) JWT to determine if the user has a specific Role.
915
+ * @param role - The exact code name of the Role.
916
+ * @param token - (Optional) Provide a specific token overriding the cached one.
917
+ */
918
+ hasRole(role, token) {
919
+ const decoded = this.getDecodedToken(token);
920
+ if (!decoded?.roles) return false;
921
+ return decoded.roles.includes(role);
922
+ }
923
+ /**
924
+ * Evaluates if the active session holds AT LEAST ONE of the listed Roles.
925
+ * @param roles - An array of Role codes.
926
+ */
927
+ hasAnyRole(roles, token) {
928
+ const decoded = this.getDecodedToken(token);
929
+ if (!decoded?.roles) return false;
930
+ return roles.some((r) => decoded.roles.includes(r));
931
+ }
932
+ /**
933
+ * Evaluates if the active session holds ALL of the listed Roles concurrently.
934
+ * @param roles - An array of Role codes.
935
+ */
936
+ hasAllRoles(roles, token) {
937
+ const decoded = this.getDecodedToken(token);
938
+ if (!decoded?.roles) return false;
939
+ return roles.every((r) => decoded.roles.includes(r));
940
+ }
941
+ /**
942
+ * Synchronously deeply inspects the cached (or provided) JWT to determine if the user has a specific granular Permission.
943
+ * @param permission - The exact code name of the Permission (e.g., 'invoices.read').
944
+ */
945
+ hasPermission(permission, token) {
946
+ const decoded = this.getDecodedToken(token);
947
+ if (!decoded?.permissions) return false;
948
+ return decoded.permissions.includes(permission);
949
+ }
950
+ /**
951
+ * Evaluates if the active session holds AT LEAST ONE of the listed Permissions.
952
+ */
953
+ hasAnyPermission(permissions, token) {
954
+ const decoded = this.getDecodedToken(token);
955
+ if (!decoded?.permissions) return false;
956
+ return permissions.some((p) => decoded.permissions.includes(p));
957
+ }
958
+ /**
959
+ * Evaluates if the active session holds ALL of the listed Permissions concurrently.
960
+ */
961
+ hasAllPermissions(permissions, token) {
962
+ const decoded = this.getDecodedToken(token);
963
+ if (!decoded?.permissions) return false;
964
+ return permissions.every((p) => decoded.permissions.includes(p));
965
+ }
966
+ // --- Roles CRUD --- //
967
+ /** Fetch all application global Roles structure */
968
+ async listRoles() {
969
+ return this.client.get("/api/v1/auth/roles/");
970
+ }
971
+ /** Create a new architectural Role inside Tenxyte */
972
+ async createRole(data) {
973
+ return this.client.post("/api/v1/auth/roles/", data);
974
+ }
975
+ /** Get detailed metadata defining a single bounded Role */
976
+ async getRole(roleId) {
977
+ return this.client.get(`/api/v1/auth/roles/${roleId}/`);
978
+ }
979
+ /** Modify properties bounding a Role */
980
+ async updateRole(roleId, data) {
981
+ return this.client.put(`/api/v1/auth/roles/${roleId}/`, data);
982
+ }
983
+ /** Unbind and destruct a Role from the global Tenant. (Dangerous, implies cascading permission unbindings) */
984
+ async deleteRole(roleId) {
985
+ return this.client.delete(`/api/v1/auth/roles/${roleId}/`);
986
+ }
987
+ // --- Role Permissions Management --- //
988
+ async getRolePermissions(roleId) {
989
+ return this.client.get(`/api/v1/auth/roles/${roleId}/permissions/`);
990
+ }
991
+ async addPermissionsToRole(roleId, permission_codes) {
992
+ return this.client.post(`/api/v1/auth/roles/${roleId}/permissions/`, { permission_codes });
993
+ }
994
+ async removePermissionsFromRole(roleId, permission_codes) {
995
+ return this.client.delete(`/api/v1/auth/roles/${roleId}/permissions/`, { permission_codes });
996
+ }
997
+ // --- Permissions CRUD --- //
998
+ /** Enumerates all available fine-grained Permissions inside this Tenant scope. */
999
+ async listPermissions() {
1000
+ return this.client.get("/api/v1/auth/permissions/");
1001
+ }
1002
+ /** Bootstraps a new granular Permission flag (e.g. `billing.refund`). */
1003
+ async createPermission(data) {
1004
+ return this.client.post("/api/v1/auth/permissions/", data);
1005
+ }
1006
+ /** Retrieves an existing atomic Permission construct. */
1007
+ async getPermission(permissionId) {
1008
+ return this.client.get(`/api/v1/auth/permissions/${permissionId}/`);
1009
+ }
1010
+ /** Edits the human readable description or structural dependencies of a Permission. */
1011
+ async updatePermission(permissionId, data) {
1012
+ return this.client.put(`/api/v1/auth/permissions/${permissionId}/`, data);
1013
+ }
1014
+ /** Destroys an atomic Permission permanently. Any Roles referencing it will be stripped of this grant automatically. */
1015
+ async deletePermission(permissionId) {
1016
+ return this.client.delete(`/api/v1/auth/permissions/${permissionId}/`);
1017
+ }
1018
+ // --- Direct Assignment (Users) --- //
1019
+ /**
1020
+ * Retrieve all roles assigned to a specific user.
1021
+ * @param userId - The target user ID.
1022
+ */
1023
+ async getUserRoles(userId) {
1024
+ return this.client.get(`/api/v1/auth/users/${userId}/roles/`);
1025
+ }
1026
+ /**
1027
+ * Retrieve all permissions directly assigned to a specific user (excluding role-based permissions).
1028
+ * @param userId - The target user ID.
1029
+ */
1030
+ async getUserPermissions(userId) {
1031
+ return this.client.get(`/api/v1/auth/users/${userId}/permissions/`);
1032
+ }
1033
+ /**
1034
+ * Attach a given Role globally to a user entity.
1035
+ * Use sparingly if B2B multi-tenancy contexts are preferred.
1036
+ */
1037
+ async assignRoleToUser(userId, roleCode) {
1038
+ return this.client.post(`/api/v1/auth/users/${userId}/roles/`, { role_code: roleCode });
1039
+ }
1040
+ /**
1041
+ * Unbind a global Role from a user entity.
1042
+ */
1043
+ async removeRoleFromUser(userId, roleCode) {
1044
+ return this.client.delete(`/api/v1/auth/users/${userId}/roles/`, void 0, {
1045
+ params: { role_code: roleCode }
1046
+ });
1047
+ }
1048
+ /**
1049
+ * Ad-Hoc directly attach specific granular Permissions to a single User, bypassing Role boundaries.
1050
+ */
1051
+ async assignPermissionsToUser(userId, permissionCodes) {
1052
+ return this.client.post(`/api/v1/auth/users/${userId}/permissions/`, { permission_codes: permissionCodes });
1053
+ }
1054
+ /**
1055
+ * Ad-Hoc strip direct granular Permissions bindings from a specific User.
1056
+ */
1057
+ async removePermissionsFromUser(userId, permissionCodes) {
1058
+ return this.client.delete(`/api/v1/auth/users/${userId}/permissions/`, { permission_codes: permissionCodes });
1059
+ }
1060
+ };
1061
+
1062
+ // src/modules/user.ts
1063
+ var UserModule = class {
1064
+ constructor(client) {
1065
+ this.client = client;
1066
+ }
1067
+ // --- Standard Profile Actions --- //
1068
+ /** Retrieve your current comprehensive Profile metadata matching the active network bearer token. */
1069
+ async getProfile() {
1070
+ return this.client.get("/api/v1/auth/me/");
1071
+ }
1072
+ /** Modify your active profile core details or injected application metadata. */
1073
+ async updateProfile(data) {
1074
+ return this.client.patch("/api/v1/auth/me/", data);
1075
+ }
1076
+ /**
1077
+ * Upload an avatar using FormData.
1078
+ * Ensure the environment supports FormData (browser or Node.js v18+).
1079
+ * @param formData The FormData object containing the 'avatar' field.
1080
+ */
1081
+ async uploadAvatar(formData) {
1082
+ return this.client.patch("/api/v1/auth/me/", formData);
1083
+ }
1084
+ /**
1085
+ * @deprecated Use `gdpr.requestAccountDeletion()` instead. This proxy will be removed in a future release.
1086
+ * Trigger self-deletion of an entire account data boundary.
1087
+ * @param password - Requires the active system password as destructive proof of intent.
1088
+ * @param otpCode - (Optional) If an OTP was queried prior to attempting account deletion.
1089
+ */
1090
+ async deleteAccount(password, otpCode) {
1091
+ return this.client.post("/api/v1/auth/request-account-deletion/", {
1092
+ password,
1093
+ otp_code: otpCode
1094
+ });
1095
+ }
1096
+ /**
1097
+ * Retrieve the roles and permissions of the currently authenticated user.
1098
+ * @returns An object containing `roles[]` and `permissions[]`.
1099
+ */
1100
+ async getMyRoles() {
1101
+ return this.client.get("/api/v1/auth/me/roles/");
1102
+ }
1103
+ // --- Admin Actions Mapping --- //
1104
+ /** (Admin only) Lists users paginated matching criteria. */
1105
+ async listUsers(params) {
1106
+ return this.client.get("/api/v1/auth/admin/users/", { params });
1107
+ }
1108
+ /** (Admin only) Gets deterministic data related to a remote unassociated user. */
1109
+ async getUser(userId) {
1110
+ return this.client.get(`/api/v1/auth/admin/users/${userId}/`);
1111
+ }
1112
+ /** (Admin only) Modifies configuration/details or capacity bounds related to a remote unassociated user. */
1113
+ async adminUpdateUser(userId, data) {
1114
+ return this.client.patch(`/api/v1/auth/admin/users/${userId}/`, data);
1115
+ }
1116
+ /** (Admin only) Force obliterate a User boundary. Can affect relational database stability if not bound carefully. */
1117
+ async adminDeleteUser(userId) {
1118
+ return this.client.delete(`/api/v1/auth/admin/users/${userId}/`);
1119
+ }
1120
+ /** (Admin only) Apply a permanent suspension / ban state globally on a user token footprint. */
1121
+ async banUser(userId, reason = "") {
1122
+ return this.client.post(`/api/v1/auth/admin/users/${userId}/ban/`, { reason });
1123
+ }
1124
+ /** (Admin only) Recover a user footprint from a global ban state. */
1125
+ async unbanUser(userId) {
1126
+ return this.client.post(`/api/v1/auth/admin/users/${userId}/unban/`);
1127
+ }
1128
+ /** (Admin only) Apply a temporary lock bounding block on a user interaction footprint. */
1129
+ async lockUser(userId, durationMinutes = 30, reason = "") {
1130
+ return this.client.post(`/api/v1/auth/admin/users/${userId}/lock/`, { duration_minutes: durationMinutes, reason });
1131
+ }
1132
+ /** (Admin only) Releases an arbitrary temporary system lock placed on a user bounds. */
1133
+ async unlockUser(userId) {
1134
+ return this.client.post(`/api/v1/auth/admin/users/${userId}/unlock/`);
1135
+ }
1136
+ };
1137
+
1138
+ // src/modules/b2b.ts
1139
+ var B2bModule = class {
1140
+ constructor(client) {
1141
+ this.client = client;
1142
+ this.client.addRequestInterceptor((config) => {
1143
+ if (this.currentOrgSlug) {
1144
+ config.headers = {
1145
+ ...config.headers,
1146
+ "X-Org-Slug": this.currentOrgSlug
1147
+ };
1148
+ }
1149
+ return config;
1150
+ });
1151
+ }
1152
+ currentOrgSlug = null;
1153
+ // ─── Context Management ───
1154
+ /**
1155
+ * Set the active Organization context.
1156
+ * Subsequent API requests will automatically include the `X-Org-Slug` header.
1157
+ * @param slug - The unique string identifier of the organization.
1158
+ */
1159
+ switchOrganization(slug) {
1160
+ this.currentOrgSlug = slug;
1161
+ }
1162
+ /**
1163
+ * Clear the active Organization context, dropping the `X-Org-Slug` header for standard User operations.
1164
+ */
1165
+ clearOrganization() {
1166
+ this.currentOrgSlug = null;
1167
+ }
1168
+ /** Get the currently active Organization slug context if set. */
1169
+ getCurrentOrganizationSlug() {
1170
+ return this.currentOrgSlug;
1171
+ }
1172
+ // ─── Organizations CRUD ───
1173
+ /** Create a new top-level or child Organization in the backend. */
1174
+ async createOrganization(data) {
1175
+ return this.client.post("/api/v1/auth/organizations/", data);
1176
+ }
1177
+ /** List organizations the currently authenticated user belongs to. */
1178
+ async listMyOrganizations(params) {
1179
+ return this.client.get("/api/v1/auth/organizations/", { params });
1180
+ }
1181
+ /** Retrieve details about a specific organization by slug. */
1182
+ async getOrganization(slug) {
1183
+ return this.client.get(`/api/v1/auth/organizations/${slug}/`);
1184
+ }
1185
+ /** Update configuration and metadata of an Organization. */
1186
+ async updateOrganization(slug, data) {
1187
+ return this.client.patch(`/api/v1/auth/organizations/${slug}/`, data);
1188
+ }
1189
+ /** Permanently delete an Organization. */
1190
+ async deleteOrganization(slug) {
1191
+ return this.client.delete(`/api/v1/auth/organizations/${slug}/`);
1192
+ }
1193
+ /** Retrieve the topology subtree extending downward from this point. */
1194
+ async getOrganizationTree(slug) {
1195
+ return this.client.get(`/api/v1/auth/organizations/${slug}/tree/`);
1196
+ }
1197
+ // ─── Member Management ───
1198
+ /** List users bound to a specific Organization. */
1199
+ async listMembers(slug, params) {
1200
+ return this.client.get(`/api/v1/auth/organizations/${slug}/members/`, { params });
1201
+ }
1202
+ /** Add a user directly into an Organization with a designated role. */
1203
+ async addMember(slug, data) {
1204
+ return this.client.post(`/api/v1/auth/organizations/${slug}/members/`, data);
1205
+ }
1206
+ /** Evolve or demote an existing member's role within the Organization. */
1207
+ async updateMemberRole(slug, userId, roleCode) {
1208
+ return this.client.patch(`/api/v1/auth/organizations/${slug}/members/${userId}/`, { role_code: roleCode });
1209
+ }
1210
+ /** Kick a user out of the Organization. */
1211
+ async removeMember(slug, userId) {
1212
+ return this.client.delete(`/api/v1/auth/organizations/${slug}/members/${userId}/`);
1213
+ }
1214
+ // ─── Invitations ───
1215
+ /** Send an onboarding email invitation to join an Organization. */
1216
+ async inviteMember(slug, data) {
1217
+ return this.client.post(`/api/v1/auth/organizations/${slug}/invitations/`, data);
1218
+ }
1219
+ /** Fetch a definition matrix of what Organization-level roles can be assigned. */
1220
+ async listOrgRoles() {
1221
+ return this.client.get("/api/v1/auth/organizations/roles/");
1222
+ }
1223
+ };
1224
+
1225
+ // src/modules/ai.ts
1226
+ var AiModule = class {
1227
+ constructor(client, logger) {
1228
+ this.client = client;
1229
+ this.logger = logger;
1230
+ this.client.addRequestInterceptor((config) => {
1231
+ const headers = { ...config.headers };
1232
+ if (this.agentToken) {
1233
+ headers["Authorization"] = `AgentBearer ${this.agentToken}`;
1234
+ }
1235
+ if (this.traceId) {
1236
+ headers["X-Prompt-Trace-ID"] = this.traceId;
1237
+ }
1238
+ return { ...config, headers };
1239
+ });
1240
+ this.client.addResponseInterceptor(async (response, _request) => {
1241
+ if (response.status === 202) {
1242
+ const cloned = response.clone();
1243
+ try {
1244
+ const data = await cloned.json();
1245
+ this.logger?.debug("[Tenxyte AI] Received 202 Awaiting Approval:", data);
1246
+ } catch {
1247
+ }
1248
+ } else if (response.status === 403) {
1249
+ const cloned = response.clone();
1250
+ try {
1251
+ const data = await cloned.json();
1252
+ if (data.code === "BUDGET_EXCEEDED") {
1253
+ this.logger?.warn("[Tenxyte AI] Network responded with Budget Exceeded for Agent.");
1254
+ } else if (data.status === "suspended") {
1255
+ this.logger?.warn("[Tenxyte AI] Circuit breaker open for Agent.");
1256
+ }
1257
+ } catch {
1258
+ }
1259
+ }
1260
+ return response;
1261
+ });
1262
+ }
1263
+ agentToken = null;
1264
+ traceId = null;
1265
+ logger;
1266
+ // ─── AgentToken Lifecycle ───
1267
+ /**
1268
+ * Create an AgentToken granting specific deterministic limits to an AI Agent.
1269
+ */
1270
+ async createAgentToken(data) {
1271
+ return this.client.post("/api/v1/auth/ai/tokens/", data);
1272
+ }
1273
+ /**
1274
+ * Set the SDK to operate on behalf of an Agent using the generated Agent Token payload.
1275
+ * Overrides standard `Authorization` headers with `AgentBearer`.
1276
+ */
1277
+ setAgentToken(token) {
1278
+ this.agentToken = token;
1279
+ }
1280
+ /** Disables the active Agent override and reverts to standard User session requests. */
1281
+ clearAgentToken() {
1282
+ this.agentToken = null;
1283
+ }
1284
+ /** Check if the SDK is currently mocking requests as an AI Agent. */
1285
+ isAgentMode() {
1286
+ return this.agentToken !== null;
1287
+ }
1288
+ /** List previously provisioned active Agent tokens. */
1289
+ async listAgentTokens() {
1290
+ return this.client.get("/api/v1/auth/ai/tokens/");
1291
+ }
1292
+ /** Fetch the status and configuration of a specific AgentToken. */
1293
+ async getAgentToken(tokenId) {
1294
+ return this.client.get(`/api/v1/auth/ai/tokens/${tokenId}/`);
1295
+ }
1296
+ /** Irreversibly revoke a targeted AgentToken from acting upon the Tenant. */
1297
+ async revokeAgentToken(tokenId) {
1298
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/revoke/`);
1299
+ }
1300
+ /** Temporarily freeze an AgentToken by forcibly closing its Circuit Breaker. */
1301
+ async suspendAgentToken(tokenId) {
1302
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/suspend/`);
1303
+ }
1304
+ /** Emergency kill-switch to wipe all operational Agent Tokens. */
1305
+ async revokeAllAgentTokens() {
1306
+ return this.client.post("/api/v1/auth/ai/tokens/revoke-all/");
1307
+ }
1308
+ // ─── Circuit Breaker ───
1309
+ /** Satisfy an Agent's Dead-Man's switch heartbeat requirement to prevent suspension. */
1310
+ async sendHeartbeat(tokenId) {
1311
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/heartbeat/`);
1312
+ }
1313
+ // ─── Human in the Loop (HITL) ───
1314
+ /** List intercepted HTTP 202 actions waiting for Human interaction / approval. */
1315
+ async listPendingActions() {
1316
+ return this.client.get("/api/v1/auth/ai/pending-actions/");
1317
+ }
1318
+ /** Complete a pending HITL authorization to finally flush the Agent action to backend systems. */
1319
+ async confirmPendingAction(confirmationToken) {
1320
+ return this.client.post("/api/v1/auth/ai/pending-actions/confirm/", { token: confirmationToken });
1321
+ }
1322
+ /** Block an Agent action permanently. */
1323
+ async denyPendingAction(confirmationToken) {
1324
+ return this.client.post("/api/v1/auth/ai/pending-actions/deny/", { token: confirmationToken });
1325
+ }
1326
+ // ─── Traceability and Budget ───
1327
+ /** Start piping the `X-Prompt-Trace-ID` custom header outwards for tracing logs against LLM inputs. */
1328
+ setTraceId(traceId) {
1329
+ this.traceId = traceId;
1330
+ }
1331
+ /** Disable trace forwarding context. */
1332
+ clearTraceId() {
1333
+ this.traceId = null;
1334
+ }
1335
+ /**
1336
+ * Report consumption costs associated with a backend invocation back to Tenxyte for strict circuit budgeting.
1337
+ * @param tokenId - AgentToken evaluating ID.
1338
+ * @param usage - Sunk token costs or explicit USD derivations.
1339
+ */
1340
+ async reportUsage(tokenId, usage) {
1341
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/report-usage/`, usage);
1342
+ }
1343
+ };
1344
+
1345
+ // src/modules/applications.ts
1346
+ var ApplicationsModule = class {
1347
+ constructor(client) {
1348
+ this.client = client;
1349
+ }
1350
+ /**
1351
+ * List all registered applications (paginated).
1352
+ * @param params - Optional filters: `search`, `is_active`, `ordering`, `page`, `page_size`.
1353
+ * @returns A paginated list of applications.
1354
+ */
1355
+ async listApplications(params) {
1356
+ return this.client.get("/api/v1/auth/applications/", {
1357
+ params
1358
+ });
1359
+ }
1360
+ /**
1361
+ * Create a new application.
1362
+ * @param data - The application name and optional description.
1363
+ * @returns The created application including one-time `client_secret`.
1364
+ */
1365
+ async createApplication(data) {
1366
+ return this.client.post("/api/v1/auth/applications/", data);
1367
+ }
1368
+ /**
1369
+ * Get a single application by its ID.
1370
+ * @param appId - The application ID.
1371
+ * @returns The application details (secret is never included).
1372
+ */
1373
+ async getApplication(appId) {
1374
+ return this.client.get(`/api/v1/auth/applications/${appId}/`);
1375
+ }
1376
+ /**
1377
+ * Fully update an application (PUT — all fields replaced).
1378
+ * @param appId - The application ID.
1379
+ * @param data - The full updated application data.
1380
+ * @returns The updated application.
1381
+ */
1382
+ async updateApplication(appId, data) {
1383
+ return this.client.put(`/api/v1/auth/applications/${appId}/`, data);
1384
+ }
1385
+ /**
1386
+ * Partially update an application (PATCH — only provided fields are changed).
1387
+ * @param appId - The application ID.
1388
+ * @param data - The fields to update.
1389
+ * @returns The updated application.
1390
+ */
1391
+ async patchApplication(appId, data) {
1392
+ return this.client.patch(`/api/v1/auth/applications/${appId}/`, data);
1393
+ }
1394
+ /**
1395
+ * Delete an application permanently.
1396
+ * @param appId - The application ID.
1397
+ */
1398
+ async deleteApplication(appId) {
1399
+ return this.client.delete(`/api/v1/auth/applications/${appId}/`);
1400
+ }
1401
+ /**
1402
+ * Regenerate credentials for an application.
1403
+ * **Warning:** Old credentials are immediately invalidated. The new secret is shown only once.
1404
+ * @param appId - The application ID.
1405
+ * @param confirmation - Must be the string `"REGENERATE"` to confirm the irreversible action.
1406
+ * @returns The new credentials (access_key + access_secret shown once).
1407
+ */
1408
+ async regenerateCredentials(appId, confirmation = "REGENERATE") {
1409
+ return this.client.post(`/api/v1/auth/applications/${appId}/regenerate/`, { confirmation });
1410
+ }
1411
+ };
1412
+
1413
+ // src/modules/admin.ts
1414
+ var AdminModule = class {
1415
+ constructor(client) {
1416
+ this.client = client;
1417
+ }
1418
+ // ─── Audit Logs ───
1419
+ /**
1420
+ * List audit log entries (paginated).
1421
+ * @param params - Optional filters and pagination.
1422
+ */
1423
+ async listAuditLogs(params) {
1424
+ return this.client.get("/api/v1/auth/admin/audit-logs/", {
1425
+ params
1426
+ });
1427
+ }
1428
+ /**
1429
+ * Get a single audit log entry by ID.
1430
+ * @param logId - The audit log entry ID.
1431
+ */
1432
+ async getAuditLog(logId) {
1433
+ return this.client.get(`/api/v1/auth/admin/audit-logs/${logId}/`);
1434
+ }
1435
+ // ─── Login Attempts ───
1436
+ /**
1437
+ * List login attempt records (paginated).
1438
+ * @param params - Optional filters and pagination.
1439
+ */
1440
+ async listLoginAttempts(params) {
1441
+ return this.client.get("/api/v1/auth/admin/login-attempts/", {
1442
+ params
1443
+ });
1444
+ }
1445
+ // ─── Blacklisted Tokens ───
1446
+ /**
1447
+ * List blacklisted (revoked) JWT tokens (paginated).
1448
+ * @param params - Optional filters and pagination.
1449
+ */
1450
+ async listBlacklistedTokens(params) {
1451
+ return this.client.get("/api/v1/auth/admin/blacklisted-tokens/", {
1452
+ params
1453
+ });
1454
+ }
1455
+ /**
1456
+ * Remove expired blacklisted tokens.
1457
+ * @returns A summary object with cleanup results.
1458
+ */
1459
+ async cleanupBlacklistedTokens() {
1460
+ return this.client.post("/api/v1/auth/admin/blacklisted-tokens/cleanup/");
1461
+ }
1462
+ // ─── Refresh Tokens ───
1463
+ /**
1464
+ * List refresh tokens (admin view — token values are hidden).
1465
+ * @param params - Optional filters and pagination.
1466
+ */
1467
+ async listRefreshTokens(params) {
1468
+ return this.client.get("/api/v1/auth/admin/refresh-tokens/", {
1469
+ params
1470
+ });
1471
+ }
1472
+ /**
1473
+ * Revoke a specific refresh token.
1474
+ * @param tokenId - The refresh token ID.
1475
+ * @returns The updated refresh token record.
1476
+ */
1477
+ async revokeRefreshToken(tokenId) {
1478
+ return this.client.post(`/api/v1/auth/admin/refresh-tokens/${tokenId}/revoke/`);
1479
+ }
1480
+ };
1481
+
1482
+ // src/modules/gdpr.ts
1483
+ var GdprModule = class {
1484
+ constructor(client) {
1485
+ this.client = client;
1486
+ }
1487
+ // ─── User-facing ───
1488
+ /**
1489
+ * Request account deletion (GDPR-compliant).
1490
+ * Initiates a 30-day grace period during which the user can cancel.
1491
+ * @param data - Password (+ optional OTP code and reason).
1492
+ */
1493
+ async requestAccountDeletion(data) {
1494
+ return this.client.post("/api/v1/auth/request-account-deletion/", data);
1495
+ }
1496
+ /**
1497
+ * Confirm the account deletion using the token received by email.
1498
+ * The token is valid for 24 hours. After confirmation the account enters the 30-day grace period.
1499
+ * @param token - The confirmation token from the email.
1500
+ */
1501
+ async confirmAccountDeletion(token) {
1502
+ return this.client.post("/api/v1/auth/confirm-account-deletion/", { token });
1503
+ }
1504
+ /**
1505
+ * Cancel a pending account deletion during the grace period.
1506
+ * The account is immediately reactivated.
1507
+ * @param password - The current password for security.
1508
+ */
1509
+ async cancelAccountDeletion(password) {
1510
+ return this.client.post("/api/v1/auth/cancel-account-deletion/", { password });
1511
+ }
1512
+ /**
1513
+ * Get the deletion status for the current user.
1514
+ * Includes pending, confirmed, or cancelled requests.
1515
+ */
1516
+ async getAccountDeletionStatus() {
1517
+ return this.client.get("/api/v1/auth/account-deletion-status/");
1518
+ }
1519
+ /**
1520
+ * Export all personal data (GDPR right to data portability).
1521
+ * @param password - The current password for security.
1522
+ */
1523
+ async exportUserData(password) {
1524
+ return this.client.post("/api/v1/auth/export-user-data/", { password });
1525
+ }
1526
+ // ─── Admin-facing ───
1527
+ /**
1528
+ * List deletion requests (admin, paginated).
1529
+ * @param params - Optional filters and pagination.
1530
+ */
1531
+ async listDeletionRequests(params) {
1532
+ return this.client.get("/api/v1/auth/admin/deletion-requests/", {
1533
+ params
1534
+ });
1535
+ }
1536
+ /**
1537
+ * Get a single deletion request by ID.
1538
+ * @param requestId - The deletion request ID.
1539
+ */
1540
+ async getDeletionRequest(requestId) {
1541
+ return this.client.get(`/api/v1/auth/admin/deletion-requests/${requestId}/`);
1542
+ }
1543
+ /**
1544
+ * Process (execute) a confirmed deletion request.
1545
+ * **WARNING:** This is irreversible and permanently destroys all user data.
1546
+ * @param requestId - The deletion request ID.
1547
+ * @param data - Must include `{ confirmation: "PERMANENTLY DELETE" }`.
1548
+ */
1549
+ async processDeletionRequest(requestId, data) {
1550
+ return this.client.post(`/api/v1/auth/admin/deletion-requests/${requestId}/process/`, data);
1551
+ }
1552
+ /**
1553
+ * Batch-process all confirmed deletion requests whose 30-day grace period has expired.
1554
+ * Typically run by a daily cron job.
1555
+ */
1556
+ async processExpiredDeletions() {
1557
+ return this.client.post("/api/v1/auth/admin/deletion-requests/process-expired/");
1558
+ }
1559
+ };
1560
+
1561
+ // src/modules/dashboard.ts
1562
+ var DashboardModule = class {
1563
+ constructor(client) {
1564
+ this.client = client;
1565
+ }
1566
+ /**
1567
+ * Get global cross-module dashboard statistics.
1568
+ * Data varies based on the organizational context (`X-Org-Slug`) and permissions.
1569
+ * Covers users, authentication, applications, security, and GDPR metrics.
1570
+ * Charts span the last 7 days with previous-period comparisons.
1571
+ * @param params - Optional period and comparison flag.
1572
+ */
1573
+ async getStats(params) {
1574
+ return this.client.get("/api/v1/auth/dashboard/stats/", {
1575
+ params
1576
+ });
1577
+ }
1578
+ /**
1579
+ * Get authentication-specific statistics.
1580
+ * Includes login stats, methods breakdown, registrations, tokens, top failure reasons, and 7-day graphs.
1581
+ */
1582
+ async getAuthStats() {
1583
+ return this.client.get("/api/v1/auth/dashboard/auth/");
1584
+ }
1585
+ /**
1586
+ * Get security-specific statistics.
1587
+ * Includes audit summary, blacklisted tokens, suspicious activity, and 2FA adoption.
1588
+ */
1589
+ async getSecurityStats() {
1590
+ return this.client.get("/api/v1/auth/dashboard/security/");
1591
+ }
1592
+ /**
1593
+ * Get GDPR-specific statistics.
1594
+ * Includes deletion requests by status and data export metrics.
1595
+ */
1596
+ async getGdprStats() {
1597
+ return this.client.get("/api/v1/auth/dashboard/gdpr/");
1598
+ }
1599
+ /**
1600
+ * Get organization-specific statistics.
1601
+ * Includes organizations, members, roles, and top organizations.
1602
+ */
1603
+ async getOrganizationStats() {
1604
+ return this.client.get("/api/v1/auth/dashboard/organizations/");
1605
+ }
1606
+ };
1607
+
1608
+ // src/utils/events.ts
1609
+ var EventEmitter = class {
1610
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
1611
+ events;
1612
+ constructor() {
1613
+ this.events = /* @__PURE__ */ new Map();
1614
+ }
1615
+ /**
1616
+ * Subscribe to an event.
1617
+ * @param event The event name
1618
+ * @param callback The callback function
1619
+ * @returns Unsubscribe function
1620
+ */
1621
+ on(event, callback) {
1622
+ if (!this.events.has(event)) {
1623
+ this.events.set(event, []);
1624
+ }
1625
+ this.events.get(event).push(callback);
1626
+ return () => this.off(event, callback);
1627
+ }
1628
+ /**
1629
+ * Unsubscribe from an event.
1630
+ * @param event The event name
1631
+ * @param callback The exact callback function that was passed to .on()
1632
+ */
1633
+ off(event, callback) {
1634
+ const callbacks = this.events.get(event);
1635
+ if (!callbacks) return;
1636
+ const index = callbacks.indexOf(callback);
1637
+ if (index !== -1) {
1638
+ callbacks.splice(index, 1);
1639
+ }
1640
+ }
1641
+ /**
1642
+ * Subscribe to an event exactly once.
1643
+ */
1644
+ once(event, callback) {
1645
+ const wrapped = (payload) => {
1646
+ this.off(event, wrapped);
1647
+ callback(payload);
1648
+ };
1649
+ return this.on(event, wrapped);
1650
+ }
1651
+ /**
1652
+ * Emit an event internally.
1653
+ */
1654
+ emit(event, payload) {
1655
+ const callbacks = this.events.get(event);
1656
+ if (!callbacks) return;
1657
+ const copy = [...callbacks];
1658
+ for (const callback of copy) {
1659
+ try {
1660
+ callback(payload);
1661
+ } catch (err) {
1662
+ console.error(`[Tenxyte EventEmitter] Error executing callback for event ${String(event)}`, err);
1663
+ }
1664
+ }
1665
+ }
1666
+ removeAllListeners() {
1667
+ this.events.clear();
1668
+ }
1669
+ };
1670
+
1671
+ // src/client.ts
1672
+ var TenxyteClient = class {
1673
+ /** Fully resolved configuration (all defaults applied). */
1674
+ config;
1675
+ /** Persistent token storage back-end (defaults to MemoryStorage). */
1676
+ storage;
1677
+ /** Shared mutable context used by interceptors (org slug, agent trace ID). */
1678
+ context;
1679
+ /** The core HTTP wrapper handling network interception and parsing */
1680
+ http;
1681
+ /** Authentication module (Login, Signup, Magic link, session handling) */
1682
+ auth;
1683
+ /** Security module (2FA, WebAuthn, Passwords, OTPs) */
1684
+ security;
1685
+ /** Role-Based Access Control and permission checking module */
1686
+ rbac;
1687
+ /** Connected user's profile and management module */
1688
+ user;
1689
+ /** Business-to-Business organizations module (multi-tenant environments) */
1690
+ b2b;
1691
+ /** AIRS - AI Responsibility & Security module (Agent tokens, Circuit breakers, HITL) */
1692
+ ai;
1693
+ /** Applications module (API client CRUD, credential management) */
1694
+ applications;
1695
+ /** Admin module (audit logs, login attempts, blacklisted tokens, refresh tokens) */
1696
+ admin;
1697
+ /** GDPR module (account deletion, data export, deletion request management) */
1698
+ gdpr;
1699
+ /** Dashboard module (global, auth, security, GDPR, organization statistics) */
1700
+ dashboard;
1701
+ /** Internal event emitter used via composition. */
1702
+ emitter;
1703
+ /**
1704
+ * Initializes the SDK with connection details for your Tenxyte-powered API.
1705
+ *
1706
+ * Accepts the full TenxyteClientConfig. Minimal usage with just { baseUrl }
1707
+ * is still supported for backward compatibility.
1708
+ *
1709
+ * @param options Configuration options including `baseUrl` and custom headers like `X-Access-Key`
1710
+ *
1711
+ * @example
1712
+ * ```typescript
1713
+ * const tx = new TenxyteClient({
1714
+ * baseUrl: 'https://api.my-service.com',
1715
+ * headers: { 'X-Access-Key': 'pkg_abc123' }
1716
+ * });
1717
+ * ```
1718
+ */
1719
+ constructor(options) {
1720
+ this.config = resolveConfig(options);
1721
+ this.storage = this.config.storage;
1722
+ this.emitter = new EventEmitter();
1723
+ this.context = { activeOrgSlug: null, agentTraceId: null };
1724
+ this.http = new TenxyteHttpClient({
1725
+ baseUrl: this.config.baseUrl,
1726
+ headers: this.config.headers,
1727
+ timeoutMs: this.config.timeoutMs
1728
+ });
1729
+ this.http.addRequestInterceptor(createAuthInterceptor(this.storage, this.context));
1730
+ if (this.config.autoDeviceInfo) {
1731
+ this.http.addRequestInterceptor(createDeviceInfoInterceptor(this.config.deviceInfoOverride));
1732
+ }
1733
+ if (this.config.retryConfig) {
1734
+ this.http.addResponseInterceptor(
1735
+ createRetryInterceptor(this.config.retryConfig, this.config.logger)
1736
+ );
1737
+ }
1738
+ if (this.config.autoRefresh) {
1739
+ this.http.addResponseInterceptor(
1740
+ createRefreshInterceptor(
1741
+ this.http,
1742
+ this.storage,
1743
+ () => {
1744
+ this.emit("session:expired", void 0);
1745
+ this.config.onSessionExpired?.();
1746
+ },
1747
+ (accessToken, refreshToken) => {
1748
+ this.rbac.setToken(accessToken);
1749
+ this.emit("token:refreshed", { accessToken });
1750
+ this.emit("token:stored", { accessToken, refreshToken });
1751
+ }
1752
+ )
1753
+ );
1754
+ }
1755
+ this.rbac = new RbacModule(this.http);
1756
+ this.auth = new AuthModule(
1757
+ this.http,
1758
+ this.storage,
1759
+ (accessToken, refreshToken) => {
1760
+ this.rbac.setToken(accessToken);
1761
+ this.emit("token:stored", { accessToken, refreshToken });
1762
+ },
1763
+ () => {
1764
+ this.rbac.setToken(null);
1765
+ this.emit("session:expired", void 0);
1766
+ }
1767
+ );
1768
+ this.security = new SecurityModule(this.http);
1769
+ this.user = new UserModule(this.http);
1770
+ this.b2b = new B2bModule(this.http);
1771
+ this.ai = new AiModule(this.http, this.config.logger);
1772
+ this.applications = new ApplicationsModule(this.http);
1773
+ this.admin = new AdminModule(this.http);
1774
+ this.gdpr = new GdprModule(this.http);
1775
+ this.dashboard = new DashboardModule(this.http);
1776
+ }
1777
+ // ─── Event delegation ───
1778
+ /** Subscribe to an SDK event. Returns an unsubscribe function. */
1779
+ on(event, callback) {
1780
+ return this.emitter.on(event, callback);
1781
+ }
1782
+ /** Subscribe to an SDK event exactly once. Returns an unsubscribe function. */
1783
+ once(event, callback) {
1784
+ return this.emitter.once(event, callback);
1785
+ }
1786
+ /** Unsubscribe a previously registered callback from an SDK event. */
1787
+ off(event, callback) {
1788
+ this.emitter.off(event, callback);
1789
+ }
1790
+ /** Emit an SDK event (internal use). */
1791
+ emit(event, payload) {
1792
+ this.emitter.emit(event, payload);
1793
+ }
1794
+ // ─── High-level helpers ───
1795
+ /**
1796
+ * Check whether a valid (non-expired) access token exists in storage.
1797
+ * Performs a synchronous JWT expiry check — no network call.
1798
+ */
1799
+ async isAuthenticated() {
1800
+ const token = await this.storage.getItem("tx_access");
1801
+ if (!token) return false;
1802
+ return !this.isTokenExpiredSync(token);
1803
+ }
1804
+ /**
1805
+ * Return the current access token from storage, or `null` if absent.
1806
+ */
1807
+ async getAccessToken() {
1808
+ return this.storage.getItem("tx_access");
1809
+ }
1810
+ /**
1811
+ * Decode the current access token and return the JWT payload.
1812
+ * Returns `null` if no token is stored or if decoding fails.
1813
+ * No network call is made — this reads from the cached JWT.
1814
+ */
1815
+ async getCurrentUser() {
1816
+ const token = await this.storage.getItem("tx_access");
1817
+ if (!token) return null;
1818
+ return decodeJwt(token);
1819
+ }
1820
+ /**
1821
+ * Check whether the stored access token is expired without making a network call.
1822
+ * Returns `true` if expired or if no token is present.
1823
+ */
1824
+ async isTokenExpired() {
1825
+ const token = await this.storage.getItem("tx_access");
1826
+ if (!token) return true;
1827
+ return this.isTokenExpiredSync(token);
1828
+ }
1829
+ /** Synchronous helper: checks JWT `exp` claim against current time. */
1830
+ isTokenExpiredSync(token) {
1831
+ const decoded = decodeJwt(token);
1832
+ if (!decoded?.exp) return true;
1833
+ return decoded.exp * 1e3 < Date.now() - 3e4;
1834
+ }
1835
+ // ─── Framework wrapper interface ───
1836
+ /**
1837
+ * Returns a synchronous snapshot of the SDK state.
1838
+ * Designed for consumption by framework wrappers (React, Vue, etc.).
1839
+ * Note: This is async because storage access may be async.
1840
+ */
1841
+ async getState() {
1842
+ const token = await this.storage.getItem("tx_access");
1843
+ const isAuthenticated = token ? !this.isTokenExpiredSync(token) : false;
1844
+ const user = token ? decodeJwt(token) : null;
1845
+ return {
1846
+ isAuthenticated,
1847
+ user,
1848
+ accessToken: token,
1849
+ activeOrg: this.context.activeOrgSlug,
1850
+ isAgentMode: this.ai.isAgentMode()
1851
+ };
1852
+ }
1853
+ };
1854
+ // Annotate the CommonJS export names for ESM import in node:
1855
+ 0 && (module.exports = {
1856
+ AdminModule,
1857
+ AiModule,
1858
+ ApplicationsModule,
1859
+ AuthModule,
1860
+ B2bModule,
1861
+ CookieStorage,
1862
+ DashboardModule,
1863
+ EventEmitter,
1864
+ GdprModule,
1865
+ LocalStorage,
1866
+ MemoryStorage,
1867
+ NOOP_LOGGER,
1868
+ RbacModule,
1869
+ SDK_VERSION,
1870
+ SecurityModule,
1871
+ TenxyteClient,
1872
+ TenxyteHttpClient,
1873
+ UserModule,
1874
+ buildDeviceInfo,
1875
+ createAuthInterceptor,
1876
+ createDeviceInfoInterceptor,
1877
+ createRefreshInterceptor,
1878
+ createRetryInterceptor,
1879
+ decodeJwt,
1880
+ resolveConfig
1881
+ });
497
1882
  //# sourceMappingURL=index.cjs.map