@lidia.poet/sdk 0.2.0

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.
Files changed (92) hide show
  1. package/README.md +605 -0
  2. package/dist/LidiaSDK.d.ts +62 -0
  3. package/dist/LidiaSDK.d.ts.map +1 -0
  4. package/dist/client/LidiaClient.d.ts +24 -0
  5. package/dist/client/LidiaClient.d.ts.map +1 -0
  6. package/dist/errors/LidiaError.d.ts +31 -0
  7. package/dist/errors/LidiaError.d.ts.map +1 -0
  8. package/dist/errors/NetworkError.d.ts +17 -0
  9. package/dist/errors/NetworkError.d.ts.map +1 -0
  10. package/dist/errors/ValidationError.d.ts +26 -0
  11. package/dist/errors/ValidationError.d.ts.map +1 -0
  12. package/dist/index.d.ts +48 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.esm.js +1463 -0
  15. package/dist/index.js +1524 -0
  16. package/dist/services/AuthorizationService.d.ts +87 -0
  17. package/dist/services/AuthorizationService.d.ts.map +1 -0
  18. package/dist/services/CaseService.d.ts +24 -0
  19. package/dist/services/CaseService.d.ts.map +1 -0
  20. package/dist/services/ConversationService.d.ts +43 -0
  21. package/dist/services/ConversationService.d.ts.map +1 -0
  22. package/dist/services/ConversationTemplateService.d.ts +17 -0
  23. package/dist/services/ConversationTemplateService.d.ts.map +1 -0
  24. package/dist/services/DocumentService.d.ts +37 -0
  25. package/dist/services/DocumentService.d.ts.map +1 -0
  26. package/dist/services/FavoritesService.d.ts +15 -0
  27. package/dist/services/FavoritesService.d.ts.map +1 -0
  28. package/dist/services/FolderService.d.ts +15 -0
  29. package/dist/services/FolderService.d.ts.map +1 -0
  30. package/dist/services/HealthService.d.ts +8 -0
  31. package/dist/services/HealthService.d.ts.map +1 -0
  32. package/dist/services/LegisratioService.d.ts +11 -0
  33. package/dist/services/LegisratioService.d.ts.map +1 -0
  34. package/dist/services/MessageService.d.ts +27 -0
  35. package/dist/services/MessageService.d.ts.map +1 -0
  36. package/dist/services/NotificationService.d.ts +15 -0
  37. package/dist/services/NotificationService.d.ts.map +1 -0
  38. package/dist/services/OrganizationService.d.ts +23 -0
  39. package/dist/services/OrganizationService.d.ts.map +1 -0
  40. package/dist/services/SmartAnswerService.d.ts +13 -0
  41. package/dist/services/SmartAnswerService.d.ts.map +1 -0
  42. package/dist/services/TagService.d.ts +13 -0
  43. package/dist/services/TagService.d.ts.map +1 -0
  44. package/dist/services/UserService.d.ts +21 -0
  45. package/dist/services/UserService.d.ts.map +1 -0
  46. package/dist/services/WebSearchService.d.ts +13 -0
  47. package/dist/services/WebSearchService.d.ts.map +1 -0
  48. package/dist/services/WorkflowService.d.ts +21 -0
  49. package/dist/services/WorkflowService.d.ts.map +1 -0
  50. package/dist/types/auth.d.ts +22 -0
  51. package/dist/types/auth.d.ts.map +1 -0
  52. package/dist/types/case.d.ts +50 -0
  53. package/dist/types/case.d.ts.map +1 -0
  54. package/dist/types/common.d.ts +43 -0
  55. package/dist/types/common.d.ts.map +1 -0
  56. package/dist/types/config.d.ts +41 -0
  57. package/dist/types/config.d.ts.map +1 -0
  58. package/dist/types/conversation.d.ts +107 -0
  59. package/dist/types/conversation.d.ts.map +1 -0
  60. package/dist/types/conversationTemplate.d.ts +31 -0
  61. package/dist/types/conversationTemplate.d.ts.map +1 -0
  62. package/dist/types/document.d.ts +163 -0
  63. package/dist/types/document.d.ts.map +1 -0
  64. package/dist/types/favorites.d.ts +21 -0
  65. package/dist/types/favorites.d.ts.map +1 -0
  66. package/dist/types/folder.d.ts +53 -0
  67. package/dist/types/folder.d.ts.map +1 -0
  68. package/dist/types/legisratio.d.ts +18 -0
  69. package/dist/types/legisratio.d.ts.map +1 -0
  70. package/dist/types/message.d.ts +117 -0
  71. package/dist/types/message.d.ts.map +1 -0
  72. package/dist/types/notification.d.ts +19 -0
  73. package/dist/types/notification.d.ts.map +1 -0
  74. package/dist/types/organization.d.ts +94 -0
  75. package/dist/types/organization.d.ts.map +1 -0
  76. package/dist/types/smartAnswer.d.ts +30 -0
  77. package/dist/types/smartAnswer.d.ts.map +1 -0
  78. package/dist/types/user.d.ts +74 -0
  79. package/dist/types/user.d.ts.map +1 -0
  80. package/dist/types/webSearch.d.ts +28 -0
  81. package/dist/types/webSearch.d.ts.map +1 -0
  82. package/dist/types/workflow.d.ts +82 -0
  83. package/dist/types/workflow.d.ts.map +1 -0
  84. package/dist/utils/env.d.ts +14 -0
  85. package/dist/utils/env.d.ts.map +1 -0
  86. package/dist/utils/helpers.d.ts +9 -0
  87. package/dist/utils/helpers.d.ts.map +1 -0
  88. package/dist/utils/query.d.ts +7 -0
  89. package/dist/utils/query.d.ts.map +1 -0
  90. package/dist/utils/validation.d.ts +10 -0
  91. package/dist/utils/validation.d.ts.map +1 -0
  92. package/package.json +63 -0
package/dist/index.js ADDED
@@ -0,0 +1,1524 @@
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
+ AuthorizationService: () => AuthorizationService,
24
+ CaseParticipationType: () => CaseParticipationType,
25
+ CaseRole: () => CaseRole,
26
+ CaseService: () => CaseService,
27
+ ConversationService: () => ConversationService,
28
+ ConversationTemplateService: () => ConversationTemplateService,
29
+ ConversationType: () => ConversationType,
30
+ DocumentService: () => DocumentService,
31
+ DocumentSmartAnswerStatus: () => DocumentSmartAnswerStatus,
32
+ DocumentStatus: () => DocumentStatus,
33
+ DocumentType: () => DocumentType,
34
+ DocumentVisibility: () => DocumentVisibility,
35
+ FavoriteType: () => FavoriteType,
36
+ FavoritesService: () => FavoritesService,
37
+ FolderService: () => FolderService,
38
+ HealthService: () => HealthService,
39
+ Language: () => Language,
40
+ LegisratioService: () => LegisratioService,
41
+ LidiaClient: () => LidiaClient,
42
+ LidiaError: () => LidiaError,
43
+ LidiaSDK: () => LidiaSDK,
44
+ MessageSenderType: () => MessageSenderType,
45
+ MessageService: () => MessageService,
46
+ MessageStatus: () => MessageStatus,
47
+ NetworkError: () => NetworkError,
48
+ NotificationService: () => NotificationService,
49
+ OrganizationService: () => OrganizationService,
50
+ SmartAnswerService: () => SmartAnswerService,
51
+ TagService: () => TagService,
52
+ UserRole: () => UserRole,
53
+ UserService: () => UserService,
54
+ ValidationError: () => ValidationError,
55
+ WebSearchService: () => WebSearchService,
56
+ WorkflowService: () => WorkflowService,
57
+ buildQueryString: () => buildQueryString
58
+ });
59
+ module.exports = __toCommonJS(index_exports);
60
+
61
+ // src/errors/LidiaError.ts
62
+ var LidiaError = class _LidiaError extends Error {
63
+ constructor(message, code, status, details) {
64
+ super(message);
65
+ this.name = "LidiaError";
66
+ this.code = code;
67
+ this.status = status;
68
+ this.details = details;
69
+ if (Error.captureStackTrace) {
70
+ Error.captureStackTrace(this, _LidiaError);
71
+ }
72
+ }
73
+ /**
74
+ * Check if this is a validation error
75
+ */
76
+ isValidationError() {
77
+ return this.status === 400 && this.code.includes("validation");
78
+ }
79
+ /**
80
+ * Check if this is an authentication error
81
+ */
82
+ isAuthError() {
83
+ return this.status === 401;
84
+ }
85
+ /**
86
+ * Check if this is an authorization error
87
+ */
88
+ isForbiddenError() {
89
+ return this.status === 403;
90
+ }
91
+ /**
92
+ * Check if this is a not found error
93
+ */
94
+ isNotFoundError() {
95
+ return this.status === 404;
96
+ }
97
+ /**
98
+ * Check if this is a server error
99
+ */
100
+ isServerError() {
101
+ return this.status >= 500;
102
+ }
103
+ /**
104
+ * Get a user-friendly error message
105
+ */
106
+ getUserMessage() {
107
+ switch (this.status) {
108
+ case 400:
109
+ return "Invalid request. Please check your input.";
110
+ case 401:
111
+ return "Authentication required. Please check your API key.";
112
+ case 403:
113
+ return "Access denied. You do not have permission to perform this action.";
114
+ case 404:
115
+ return "The requested resource was not found.";
116
+ case 429:
117
+ return "Too many requests. Please try again later.";
118
+ case 500:
119
+ return "Internal server error. Please try again later.";
120
+ default:
121
+ return this.message || "An unexpected error occurred.";
122
+ }
123
+ }
124
+ };
125
+
126
+ // src/errors/NetworkError.ts
127
+ var NetworkError = class _NetworkError extends Error {
128
+ constructor(message, originalError) {
129
+ super(message);
130
+ this.name = "NetworkError";
131
+ this.originalError = originalError;
132
+ if (Error.captureStackTrace) {
133
+ Error.captureStackTrace(this, _NetworkError);
134
+ }
135
+ }
136
+ /**
137
+ * Check if this is a timeout error
138
+ */
139
+ isTimeoutError() {
140
+ var _a, _b, _c;
141
+ return ((_a = this.originalError) == null ? void 0 : _a.code) === "ECONNABORTED" || ((_c = (_b = this.originalError) == null ? void 0 : _b.message) == null ? void 0 : _c.includes("timeout"));
142
+ }
143
+ /**
144
+ * Check if this is a connection error
145
+ */
146
+ isConnectionError() {
147
+ var _a, _b, _c;
148
+ return ((_a = this.originalError) == null ? void 0 : _a.code) === "ECONNREFUSED" || ((_b = this.originalError) == null ? void 0 : _b.code) === "ENOTFOUND" || ((_c = this.originalError) == null ? void 0 : _c.code) === "ECONNRESET";
149
+ }
150
+ /**
151
+ * Get a user-friendly error message
152
+ */
153
+ getUserMessage() {
154
+ if (this.isTimeoutError()) {
155
+ return "Request timed out. Please check your connection and try again.";
156
+ }
157
+ if (this.isConnectionError()) {
158
+ return "Unable to connect to the server. Please check your internet connection.";
159
+ }
160
+ return "Network error occurred. Please check your connection and try again.";
161
+ }
162
+ };
163
+
164
+ // src/client/LidiaClient.ts
165
+ var LidiaClient = class {
166
+ constructor(config) {
167
+ this.config = {
168
+ timeout: 3e4,
169
+ debug: false,
170
+ retry: {
171
+ attempts: 3,
172
+ delay: 1e3,
173
+ backoff: 2
174
+ },
175
+ ...config
176
+ };
177
+ }
178
+ getAuthHeader() {
179
+ if (this.config.accessToken) {
180
+ return { Authorization: `Bearer ${this.config.accessToken}` };
181
+ }
182
+ return {};
183
+ }
184
+ async makeRequest(url, options = {}) {
185
+ const fullUrl = url.startsWith("http") ? url : `${this.config.baseUrl}${url}`;
186
+ const headers = {
187
+ "Content-Type": "application/json",
188
+ ...this.getAuthHeader(),
189
+ ...this.config.headers,
190
+ ...options.headers
191
+ };
192
+ if (this.config.debug) {
193
+ console.log(`[Lidia SDK] ${options.method || "GET"} ${fullUrl}`);
194
+ }
195
+ const retryConfig = this.config.retry ?? { attempts: 1, delay: 1e3, backoff: 2 };
196
+ let lastError;
197
+ for (let attempt = 0; attempt < retryConfig.attempts; attempt++) {
198
+ if (attempt > 0) {
199
+ const waitTime = retryConfig.delay * Math.pow(retryConfig.backoff ?? 2, attempt - 1);
200
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
201
+ if (this.config.debug) {
202
+ console.log(`[Lidia SDK] Retry attempt ${attempt + 1}/${retryConfig.attempts}`);
203
+ }
204
+ }
205
+ const controller = new AbortController();
206
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
207
+ try {
208
+ const response = await fetch(fullUrl, {
209
+ ...options,
210
+ headers,
211
+ signal: controller.signal
212
+ });
213
+ clearTimeout(timeoutId);
214
+ if (this.config.debug) {
215
+ console.log(`[Lidia SDK] Response: ${response.status}`);
216
+ }
217
+ if (!response.ok) {
218
+ let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
219
+ let errorCode = String(response.status);
220
+ let errorDetails;
221
+ try {
222
+ const errorData = await response.json();
223
+ if (errorData["message"]) errorMessage = String(errorData["message"]);
224
+ if (errorData["error"]) errorCode = String(errorData["error"]);
225
+ errorDetails = errorData;
226
+ } catch {
227
+ }
228
+ const err = new LidiaError(errorMessage, errorCode, response.status, errorDetails);
229
+ if (response.status >= 500 || response.status === 429) {
230
+ lastError = err;
231
+ continue;
232
+ }
233
+ throw err;
234
+ }
235
+ if (response.status === 204) {
236
+ return void 0;
237
+ }
238
+ const contentType = response.headers.get("content-type") ?? "";
239
+ if (contentType.includes("application/json")) {
240
+ return await response.json();
241
+ }
242
+ return await response.text();
243
+ } catch (error) {
244
+ clearTimeout(timeoutId);
245
+ if (error instanceof LidiaError) {
246
+ throw error;
247
+ }
248
+ if (error instanceof Error && error.name === "AbortError") {
249
+ lastError = new NetworkError("Request timeout");
250
+ continue;
251
+ }
252
+ lastError = new NetworkError("Network error occurred", error);
253
+ continue;
254
+ }
255
+ }
256
+ if (this.config.debug && lastError) {
257
+ console.error(`[Lidia SDK] All retry attempts exhausted:`, lastError);
258
+ }
259
+ throw lastError;
260
+ }
261
+ async get(url, config) {
262
+ return this.makeRequest(url, { ...config, method: "GET" });
263
+ }
264
+ async post(url, data, config) {
265
+ const requestConfig = { ...config, method: "POST" };
266
+ if (data !== void 0) {
267
+ requestConfig.body = JSON.stringify(data);
268
+ }
269
+ return this.makeRequest(url, requestConfig);
270
+ }
271
+ async put(url, data, config) {
272
+ const requestConfig = { ...config, method: "PUT" };
273
+ if (data !== void 0) {
274
+ requestConfig.body = JSON.stringify(data);
275
+ }
276
+ return this.makeRequest(url, requestConfig);
277
+ }
278
+ async patch(url, data, config) {
279
+ const requestConfig = { ...config, method: "PATCH" };
280
+ if (data !== void 0) {
281
+ requestConfig.body = JSON.stringify(data);
282
+ }
283
+ return this.makeRequest(url, requestConfig);
284
+ }
285
+ async delete(url, data, config) {
286
+ const requestConfig = { ...config, method: "DELETE" };
287
+ if (data !== void 0) {
288
+ requestConfig.body = JSON.stringify(data);
289
+ }
290
+ return this.makeRequest(url, requestConfig);
291
+ }
292
+ /**
293
+ * Download a blob (for file downloads)
294
+ */
295
+ async downloadBlob(url) {
296
+ const fullUrl = url.startsWith("http") ? url : `${this.config.baseUrl}${url}`;
297
+ const headers = {
298
+ ...this.getAuthHeader(),
299
+ ...this.config.headers
300
+ };
301
+ if (this.config.debug) {
302
+ console.log(`[Lidia SDK] GET ${fullUrl} (blob download)`);
303
+ }
304
+ const controller = new AbortController();
305
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
306
+ try {
307
+ const response = await fetch(fullUrl, {
308
+ method: "GET",
309
+ headers,
310
+ signal: controller.signal
311
+ });
312
+ clearTimeout(timeoutId);
313
+ if (!response.ok) {
314
+ throw new NetworkError(`HTTP ${response.status}: ${response.statusText}`);
315
+ }
316
+ return response.blob();
317
+ } catch (error) {
318
+ clearTimeout(timeoutId);
319
+ if (error instanceof NetworkError) throw error;
320
+ if (error instanceof Error && error.name === "AbortError") {
321
+ throw new NetworkError("Download timeout");
322
+ }
323
+ throw new NetworkError("Download failed", error);
324
+ }
325
+ }
326
+ setAuthTokens(tokens) {
327
+ this.authTokens = tokens;
328
+ this.config.accessToken = tokens.accessToken;
329
+ }
330
+ getAuthTokens() {
331
+ return this.authTokens;
332
+ }
333
+ clearAuthTokens() {
334
+ this.authTokens = void 0;
335
+ delete this.config.accessToken;
336
+ }
337
+ isAuthenticated() {
338
+ return !!(this.authTokens && this.config.accessToken);
339
+ }
340
+ updateConfig(newConfig) {
341
+ this.config = { ...this.config, ...newConfig };
342
+ }
343
+ };
344
+
345
+ // src/services/AuthorizationService.ts
346
+ var AuthorizationService = class {
347
+ // Refresh 5 minutes before expiry
348
+ constructor(client, config) {
349
+ this.autoRefreshInterval = null;
350
+ this.refreshBufferMinutes = 5;
351
+ var _a, _b;
352
+ this.client = client;
353
+ this.config = config;
354
+ if (!((_a = config.cognito) == null ? void 0 : _a.region) || !((_b = config.cognito) == null ? void 0 : _b.clientId)) {
355
+ throw new Error("Cognito configuration (region and clientId) is required for authentication");
356
+ }
357
+ }
358
+ /**
359
+ * Get the Cognito endpoint URL based on the configured region
360
+ */
361
+ getCognitoEndpoint() {
362
+ return `https://cognito-idp.${this.config.cognito.region}.amazonaws.com/`;
363
+ }
364
+ /**
365
+ * Get the Cognito client ID from config
366
+ */
367
+ getClientId() {
368
+ return this.config.cognito.clientId;
369
+ }
370
+ /**
371
+ * Login with email/username and password using AWS Cognito
372
+ */
373
+ async login(credentials) {
374
+ const username = credentials.username || credentials.email;
375
+ if (!username) {
376
+ throw new LidiaError("Username or email is required", "INVALID_CREDENTIALS", 400);
377
+ }
378
+ try {
379
+ const response = await fetch(this.getCognitoEndpoint(), {
380
+ method: "POST",
381
+ headers: {
382
+ "Content-Type": "application/x-amz-json-1.1",
383
+ "X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth"
384
+ },
385
+ body: JSON.stringify({
386
+ AuthParameters: {
387
+ USERNAME: username,
388
+ PASSWORD: credentials.password
389
+ },
390
+ AuthFlow: "USER_PASSWORD_AUTH",
391
+ ClientId: this.getClientId()
392
+ })
393
+ });
394
+ if (!response.ok) {
395
+ const errorData = await response.json();
396
+ throw new LidiaError(
397
+ errorData.message || `Login failed with status ${response.status}`,
398
+ "LOGIN_FAILED",
399
+ response.status
400
+ );
401
+ }
402
+ const cognitoResponse = await response.json();
403
+ const authResult = cognitoResponse.AuthenticationResult;
404
+ const expiresAt = new Date(Date.now() + authResult.ExpiresIn * 1e3);
405
+ const tokens = {
406
+ accessToken: authResult.AccessToken,
407
+ refreshToken: authResult.RefreshToken,
408
+ tokenType: authResult.TokenType,
409
+ expiresIn: authResult.ExpiresIn,
410
+ expiresAt
411
+ };
412
+ this.client.setAuthTokens(tokens);
413
+ this.startAutoRefresh();
414
+ return tokens;
415
+ } catch (error) {
416
+ if (error instanceof LidiaError) {
417
+ throw error;
418
+ }
419
+ throw new LidiaError(`Login failed: ${error.message}`, "LOGIN_ERROR", 500);
420
+ }
421
+ }
422
+ /**
423
+ * Refresh authentication tokens using AWS Cognito
424
+ */
425
+ async refreshTokens() {
426
+ const currentTokens = this.client.getAuthTokens();
427
+ if (!currentTokens) {
428
+ throw new LidiaError("No tokens available to refresh. Please login first.", "NO_TOKENS", 401);
429
+ }
430
+ try {
431
+ const response = await fetch(this.getCognitoEndpoint(), {
432
+ method: "POST",
433
+ headers: {
434
+ "Content-Type": "application/x-amz-json-1.1",
435
+ "X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth"
436
+ },
437
+ body: JSON.stringify({
438
+ AuthParameters: {
439
+ REFRESH_TOKEN: currentTokens.refreshToken
440
+ },
441
+ AuthFlow: "REFRESH_TOKEN_AUTH",
442
+ ClientId: this.getClientId()
443
+ })
444
+ });
445
+ if (!response.ok) {
446
+ const errorData = await response.json();
447
+ throw new LidiaError(
448
+ errorData.message || `Token refresh failed with status ${response.status}`,
449
+ "REFRESH_FAILED",
450
+ response.status
451
+ );
452
+ }
453
+ const cognitoResponse = await response.json();
454
+ const authResult = cognitoResponse.AuthenticationResult;
455
+ const expiresAt = new Date(Date.now() + authResult.ExpiresIn * 1e3);
456
+ const tokens = {
457
+ accessToken: authResult.AccessToken,
458
+ refreshToken: currentTokens.refreshToken,
459
+ // Keep the original refresh token
460
+ tokenType: authResult.TokenType,
461
+ expiresIn: authResult.ExpiresIn,
462
+ expiresAt
463
+ };
464
+ this.client.setAuthTokens(tokens);
465
+ this.startAutoRefresh();
466
+ return tokens;
467
+ } catch (error) {
468
+ if (error instanceof LidiaError) {
469
+ throw error;
470
+ }
471
+ throw new LidiaError(`Token refresh failed: ${error.message}`, "REFRESH_ERROR", 500);
472
+ }
473
+ }
474
+ /**
475
+ * Check if the current access token is expired or will expire soon
476
+ */
477
+ isTokenExpired(bufferMinutes = 5) {
478
+ const tokens = this.client.getAuthTokens();
479
+ if (!tokens) {
480
+ return true;
481
+ }
482
+ const now = /* @__PURE__ */ new Date();
483
+ const bufferTime = bufferMinutes * 60 * 1e3;
484
+ const expirationTime = new Date(tokens.expiresAt.getTime() - bufferTime);
485
+ return now >= expirationTime;
486
+ }
487
+ /**
488
+ * Automatically refresh tokens if they are expired or about to expire
489
+ */
490
+ async ensureValidTokens(bufferMinutes = 5) {
491
+ if (!this.isTokenExpired(bufferMinutes)) {
492
+ const tokens = this.client.getAuthTokens();
493
+ if (tokens) {
494
+ return tokens;
495
+ }
496
+ }
497
+ return await this.refreshTokens();
498
+ }
499
+ /**
500
+ * Logout and clear tokens
501
+ */
502
+ logout() {
503
+ this.stopAutoRefresh();
504
+ this.client.clearAuthTokens();
505
+ }
506
+ /**
507
+ * Check if user is authenticated
508
+ */
509
+ isAuthenticated() {
510
+ return this.client.isAuthenticated();
511
+ }
512
+ /**
513
+ * Get current authentication tokens
514
+ */
515
+ getAuthTokens() {
516
+ return this.client.getAuthTokens();
517
+ }
518
+ /**
519
+ * Set authentication tokens manually
520
+ */
521
+ setAuthTokens(tokens) {
522
+ this.client.setAuthTokens(tokens);
523
+ }
524
+ /**
525
+ * Get the current access token
526
+ */
527
+ getAccessToken() {
528
+ const tokens = this.client.getAuthTokens();
529
+ return tokens == null ? void 0 : tokens.accessToken;
530
+ }
531
+ /**
532
+ * Get the current refresh token
533
+ */
534
+ getRefreshToken() {
535
+ const tokens = this.client.getAuthTokens();
536
+ return tokens == null ? void 0 : tokens.refreshToken;
537
+ }
538
+ /**
539
+ * Check if tokens will expire within the specified time
540
+ */
541
+ willExpireWithin(minutes) {
542
+ const tokens = this.client.getAuthTokens();
543
+ if (!tokens) {
544
+ return true;
545
+ }
546
+ const now = /* @__PURE__ */ new Date();
547
+ const expirationTime = new Date(tokens.expiresAt.getTime() - minutes * 60 * 1e3);
548
+ return now >= expirationTime;
549
+ }
550
+ /**
551
+ * Initialize with username and password, automatically logging in
552
+ */
553
+ async initializeWithCredentials(username, password) {
554
+ return this.login({ email: username, password });
555
+ }
556
+ /**
557
+ * Initialize with existing Bearer token
558
+ */
559
+ initializeWithToken(accessToken, expiresIn) {
560
+ const tokens = {
561
+ accessToken,
562
+ refreshToken: "",
563
+ // No refresh token available
564
+ tokenType: "Bearer",
565
+ expiresIn: expiresIn || 3600,
566
+ expiresAt: new Date(Date.now() + (expiresIn || 3600) * 1e3)
567
+ };
568
+ this.client.setAuthTokens(tokens);
569
+ this.startAutoRefresh();
570
+ }
571
+ /**
572
+ * Start automatic token refresh based on expiration time
573
+ */
574
+ startAutoRefresh() {
575
+ if (this.autoRefreshInterval) {
576
+ clearTimeout(this.autoRefreshInterval);
577
+ }
578
+ const tokens = this.client.getAuthTokens();
579
+ if (!tokens || !tokens.refreshToken) {
580
+ return;
581
+ }
582
+ const now = /* @__PURE__ */ new Date();
583
+ const refreshTime = new Date(
584
+ tokens.expiresAt.getTime() - this.refreshBufferMinutes * 60 * 1e3
585
+ );
586
+ const timeUntilRefresh = refreshTime.getTime() - now.getTime();
587
+ if (timeUntilRefresh <= 0) {
588
+ this.performAutoRefresh();
589
+ return;
590
+ }
591
+ this.autoRefreshInterval = setTimeout(() => {
592
+ this.performAutoRefresh();
593
+ }, timeUntilRefresh);
594
+ }
595
+ /**
596
+ * Perform automatic token refresh
597
+ */
598
+ async performAutoRefresh() {
599
+ try {
600
+ await this.refreshTokens();
601
+ } catch (error) {
602
+ console.warn("[LidiaSDK] Automatic token refresh failed:", error);
603
+ this.stopAutoRefresh();
604
+ }
605
+ }
606
+ /**
607
+ * Stop automatic token refresh
608
+ */
609
+ stopAutoRefresh() {
610
+ if (this.autoRefreshInterval) {
611
+ clearTimeout(this.autoRefreshInterval);
612
+ this.autoRefreshInterval = null;
613
+ }
614
+ }
615
+ /**
616
+ * Cleanup resources
617
+ */
618
+ destroy() {
619
+ this.stopAutoRefresh();
620
+ }
621
+ };
622
+
623
+ // src/utils/query.ts
624
+ function buildQueryString(params) {
625
+ const searchParams = new URLSearchParams();
626
+ for (const [key, value] of Object.entries(params)) {
627
+ if (value === void 0 || value === null) continue;
628
+ if (Array.isArray(value)) {
629
+ for (const item of value) {
630
+ if (item !== void 0 && item !== null) {
631
+ searchParams.append(key, String(item));
632
+ }
633
+ }
634
+ } else {
635
+ searchParams.append(key, String(value));
636
+ }
637
+ }
638
+ const qs = searchParams.toString();
639
+ return qs ? `?${qs}` : "";
640
+ }
641
+
642
+ // src/services/CaseService.ts
643
+ var CaseService = class {
644
+ constructor(client) {
645
+ this.client = client;
646
+ }
647
+ /** Get paginated cases */
648
+ async find(params) {
649
+ const qs = buildQueryString(params ?? {});
650
+ return this.client.get(`/cases${qs}`);
651
+ }
652
+ /** Create a new case */
653
+ async create(data) {
654
+ return this.client.post("/cases", data);
655
+ }
656
+ /** Get a case by ID */
657
+ async findOne(id) {
658
+ return this.client.get(`/cases/${id}`);
659
+ }
660
+ /** Update a case (partial) */
661
+ async update(id, data) {
662
+ return this.client.patch(`/cases/${id}`, data);
663
+ }
664
+ /** Delete a case */
665
+ async delete(id) {
666
+ return this.client.delete(`/cases/${id}`);
667
+ }
668
+ /** Get case participations */
669
+ async getParticipations(id) {
670
+ return this.client.get(`/cases/${id}/participations`);
671
+ }
672
+ /** Replace all case participations */
673
+ async replaceParticipations(id, participations) {
674
+ return this.client.put(`/cases/${id}/participations`, participations);
675
+ }
676
+ /** Delete a single case participation */
677
+ async deleteParticipation(id, participationType, participantId) {
678
+ return this.client.delete(
679
+ `/cases/${id}/participations/${participationType}/${participantId}`
680
+ );
681
+ }
682
+ };
683
+
684
+ // src/services/ConversationService.ts
685
+ var ConversationService = class {
686
+ constructor(client) {
687
+ this.client = client;
688
+ }
689
+ /** List conversations with filtering and pagination */
690
+ async find(params) {
691
+ const qs = buildQueryString(params ?? {});
692
+ return this.client.get(`/conversations${qs}`);
693
+ }
694
+ /** Get conversation by ID */
695
+ async findOne(id) {
696
+ return this.client.get(`/conversations/${id}`);
697
+ }
698
+ /** Create a new conversation */
699
+ async create(data) {
700
+ return this.client.post("/conversations", data);
701
+ }
702
+ /** Update a conversation */
703
+ async update(id, data) {
704
+ return this.client.patch(`/conversations/${id}`, data);
705
+ }
706
+ /** Delete a single conversation */
707
+ async delete(id) {
708
+ return this.client.delete(`/conversations/${id}`);
709
+ }
710
+ /** Bulk delete conversations */
711
+ async bulkDelete(conversationIds) {
712
+ return this.client.delete("/conversations", { ids: conversationIds });
713
+ }
714
+ /** Delete all messages from a conversation */
715
+ async clearHistory(id) {
716
+ return this.client.delete(`/conversations/${id}/messages`);
717
+ }
718
+ /** Export a conversation (or multiple messages) */
719
+ async export(data) {
720
+ return this.client.post("/conversations/export", data);
721
+ }
722
+ /** Download conversation in the selected format */
723
+ async download(id, exportType) {
724
+ return this.client.post(`/conversations/${id}/download/${exportType}`);
725
+ }
726
+ /** Save conversation as a document in the archive */
727
+ async saveToArchive(id, data) {
728
+ return this.client.post(`/conversations/${id}/save`, data);
729
+ }
730
+ /** Add conversation to a case */
731
+ async addToCase(conversationId, caseId) {
732
+ return this.client.put(`/conversations/${conversationId}/case/${caseId}`);
733
+ }
734
+ /** Remove conversation from case */
735
+ async removeFromCase(conversationId) {
736
+ return this.client.delete(`/conversations/${conversationId}/case`);
737
+ }
738
+ /** Change conversation's workflow */
739
+ async setWorkflow(conversationId, workflowId) {
740
+ return this.client.put(`/conversations/${conversationId}/workflow/${workflowId}`);
741
+ }
742
+ /** Remove conversation's workflow */
743
+ async removeWorkflow(conversationId) {
744
+ return this.client.delete(`/conversations/${conversationId}/workflow`);
745
+ }
746
+ /** Report a conversation to admins */
747
+ async report(id, data) {
748
+ return this.client.post(`/conversations/${id}/report`, data);
749
+ }
750
+ /** Get AgentCore WebSocket URL for word conversation */
751
+ async getAgentCoreWsUrl(id) {
752
+ return this.client.get(`/conversations/${id}/agentcore-ws`);
753
+ }
754
+ /** Persist word conversation result from AgentCore */
755
+ async saveWordResult(id, data) {
756
+ return this.client.post(`/conversations/${id}/word-result`, data);
757
+ }
758
+ };
759
+
760
+ // src/services/ConversationTemplateService.ts
761
+ var ConversationTemplateService = class {
762
+ constructor(client) {
763
+ this.client = client;
764
+ }
765
+ /** List all conversation templates */
766
+ async find(params) {
767
+ const qs = buildQueryString(params ?? {});
768
+ return this.client.get(`/conversation-templates${qs}`);
769
+ }
770
+ /** Get template by ID */
771
+ async findOne(id) {
772
+ return this.client.get(`/conversation-templates/${id}`);
773
+ }
774
+ /** Create a new template */
775
+ async create(data) {
776
+ return this.client.post("/conversation-templates", data);
777
+ }
778
+ /** Update a template */
779
+ async update(id, data) {
780
+ return this.client.patch(`/conversation-templates/${id}`, data);
781
+ }
782
+ /** Delete a template */
783
+ async delete(id) {
784
+ return this.client.delete(`/conversation-templates/${id}`);
785
+ }
786
+ };
787
+
788
+ // src/services/DocumentService.ts
789
+ var DocumentService = class {
790
+ constructor(client) {
791
+ this.client = client;
792
+ }
793
+ /** Search documents and folders with pagination */
794
+ async find(params) {
795
+ const qs = buildQueryString(params ?? {});
796
+ return this.client.get(`/documents${qs}`);
797
+ }
798
+ /** Get document details by ID */
799
+ async findOne(id) {
800
+ return this.client.get(`/documents/${id}`);
801
+ }
802
+ /** Create a document (returns upload URL) */
803
+ async create(data) {
804
+ return this.client.post("/documents", data);
805
+ }
806
+ /** Update a document */
807
+ async update(id, data) {
808
+ return this.client.patch(`/documents/${id}`, data);
809
+ }
810
+ /** Bulk delete documents and/or folders */
811
+ async bulkDelete(ids) {
812
+ return this.client.delete("/documents", { ids });
813
+ }
814
+ /** Download a document (returns download URL) */
815
+ async download(id) {
816
+ return this.client.get(`/documents/${id}/download`);
817
+ }
818
+ /** Get document preview URL */
819
+ async preview(id) {
820
+ return this.client.get(`/documents/${id}/preview`);
821
+ }
822
+ /** Bulk export documents as zip */
823
+ async bulkExport(data) {
824
+ return this.client.post("/documents/export", data);
825
+ }
826
+ /** Move documents and/or folders */
827
+ async move(data) {
828
+ return this.client.patch("/documents/move", data);
829
+ }
830
+ /** Attach multiple documents to multiple cases */
831
+ async bulkAttachToCases(data) {
832
+ return this.client.put("/documents/bulk/attachToCases", data);
833
+ }
834
+ /** Attach document to a single case */
835
+ async attachToCase(documentId, caseId) {
836
+ return this.client.put(`/documents/${documentId}/cases/${caseId}`);
837
+ }
838
+ /** Attach document to conversation */
839
+ async attachToConversation(documentId, conversationId) {
840
+ return this.client.put(`/documents/${documentId}/conversations/${conversationId}`);
841
+ }
842
+ /** Detach document from conversation */
843
+ async detachFromConversation(documentId, conversationId) {
844
+ return this.client.delete(`/documents/${documentId}/conversations/${conversationId}`);
845
+ }
846
+ /** Copy document reference into a common folder */
847
+ async copyToCommonFolder(documentId, commonFolderId) {
848
+ return this.client.post(
849
+ `/documents/${documentId}/common/${commonFolderId}`
850
+ );
851
+ }
852
+ /** Sync tags to documents */
853
+ async syncTags(data) {
854
+ return this.client.put("/documents/tags", data);
855
+ }
856
+ };
857
+
858
+ // src/services/FavoritesService.ts
859
+ var FavoritesService = class {
860
+ constructor(client) {
861
+ this.client = client;
862
+ }
863
+ /** List all favorites for the authorized user */
864
+ async find() {
865
+ return this.client.get("/favorites");
866
+ }
867
+ /** Create a single favorite */
868
+ async create(data) {
869
+ return this.client.put("/favorites", data);
870
+ }
871
+ /** Create multiple favorites */
872
+ async createBulk(data) {
873
+ return this.client.put("/favorites/bulk", data);
874
+ }
875
+ /** Delete a single favorite by type and ID */
876
+ async delete(type, id) {
877
+ return this.client.delete(`/favorites/${type}/${id}`);
878
+ }
879
+ };
880
+
881
+ // src/services/FolderService.ts
882
+ var FolderService = class {
883
+ constructor(client) {
884
+ this.client = client;
885
+ }
886
+ /** Search folders */
887
+ async find(params) {
888
+ const qs = buildQueryString(params);
889
+ return this.client.get(`/folders${qs}`);
890
+ }
891
+ /** Get folder with paginated content */
892
+ async getContent(id, params) {
893
+ const qs = buildQueryString(params ?? {});
894
+ return this.client.get(`/folders/${id}${qs}`);
895
+ }
896
+ /** Create a new folder */
897
+ async create(data) {
898
+ return this.client.post("/folders", data);
899
+ }
900
+ /** Update a folder (rename) */
901
+ async update(id, data) {
902
+ return this.client.patch(`/folders/${id}`, data);
903
+ }
904
+ };
905
+
906
+ // src/services/HealthService.ts
907
+ var HealthService = class {
908
+ constructor(client) {
909
+ this.client = client;
910
+ }
911
+ /** Check API health */
912
+ async check() {
913
+ return this.client.get("/health");
914
+ }
915
+ };
916
+
917
+ // src/services/LegisratioService.ts
918
+ var LegisratioService = class {
919
+ constructor(client) {
920
+ this.client = client;
921
+ }
922
+ /** Get a judgement text from LegisRatio */
923
+ async getJudgementText(id) {
924
+ return this.client.get(`/legisratio/judgement-text/${id}`);
925
+ }
926
+ /** Get an article text from LegisRatio */
927
+ async getLawArticleText(lawId, articleId) {
928
+ return this.client.get(
929
+ `/legisratio/law/${lawId}/article-text/${articleId}`
930
+ );
931
+ }
932
+ };
933
+
934
+ // src/services/MessageService.ts
935
+ var MessageService = class {
936
+ constructor(client) {
937
+ this.client = client;
938
+ }
939
+ /** List messages with pagination */
940
+ async find(params) {
941
+ const qs = buildQueryString(params);
942
+ return this.client.get(`/messages${qs}`);
943
+ }
944
+ /** Get message by ID */
945
+ async findOne(id) {
946
+ return this.client.get(`/messages/${id}`);
947
+ }
948
+ /** Create a new message */
949
+ async create(data) {
950
+ return this.client.post("/messages", data);
951
+ }
952
+ /** Create a "continue" message */
953
+ async continueMessage(data) {
954
+ return this.client.post("/messages/continue", data);
955
+ }
956
+ /** Bookmark or mark a message as relevant */
957
+ async update(id, data) {
958
+ return this.client.patch(`/messages/${id}`, data);
959
+ }
960
+ /** Cancel the processing of a message */
961
+ async cancel(id) {
962
+ return this.client.put(`/messages/${id}/cancel`);
963
+ }
964
+ /** Get a citation URL for a message */
965
+ async getCitation(id, citationKey) {
966
+ return this.client.get(`/messages/${id}/citations/${citationKey}`);
967
+ }
968
+ /** Get a URL registry entry for a message */
969
+ async getUrlRegistry(id, urlRegistryKey) {
970
+ return this.client.get(`/messages/${id}/url-registry/${urlRegistryKey}`);
971
+ }
972
+ /** Export a specific message */
973
+ async export(id, exportType, exportMedium) {
974
+ return this.client.post(`/messages/${id}/export/${exportType}/${exportMedium}`);
975
+ }
976
+ };
977
+
978
+ // src/services/NotificationService.ts
979
+ var NotificationService = class {
980
+ constructor(client) {
981
+ this.client = client;
982
+ }
983
+ /** Get the list of own notifications */
984
+ async find(params) {
985
+ const qs = buildQueryString(params ?? {});
986
+ return this.client.get(`/notifications${qs}`);
987
+ }
988
+ /** Acknowledge all notifications */
989
+ async acknowledgeAll() {
990
+ return this.client.put("/notifications/acknowledge/all");
991
+ }
992
+ /** Acknowledge a specific notification */
993
+ async acknowledge(id) {
994
+ return this.client.put(`/notifications/acknowledge/${id}`);
995
+ }
996
+ /** Create a notification */
997
+ async create(notificationType, data) {
998
+ return this.client.post(`/notifications/${notificationType}`, data);
999
+ }
1000
+ };
1001
+
1002
+ // src/services/OrganizationService.ts
1003
+ var OrganizationService = class {
1004
+ constructor(client) {
1005
+ this.client = client;
1006
+ }
1007
+ /** Get paginated organizations */
1008
+ async find(params) {
1009
+ const qs = buildQueryString(params ?? {});
1010
+ return this.client.get(`/organizations${qs}`);
1011
+ }
1012
+ /** Create a new organization */
1013
+ async create(data) {
1014
+ return this.client.post("/organizations", data);
1015
+ }
1016
+ /** Get an organization by ID */
1017
+ async findOne(id) {
1018
+ return this.client.get(`/organizations/${id}`);
1019
+ }
1020
+ /** Update an organization */
1021
+ async update(id, data) {
1022
+ return this.client.put(`/organizations/${id}`, data);
1023
+ }
1024
+ /** Delete (disable) an organization */
1025
+ async delete(id) {
1026
+ return this.client.delete(`/organizations/${id}`);
1027
+ }
1028
+ /** Assign quotas to an organization */
1029
+ async assignQuotas(id, data) {
1030
+ return this.client.put(`/organizations/${id}/quotas`, data);
1031
+ }
1032
+ /** Unassign quotas from an organization */
1033
+ async unassignQuotas(id) {
1034
+ return this.client.delete(`/organizations/${id}/quotas`);
1035
+ }
1036
+ /** Assign workflows to an organization */
1037
+ async assignWorkflows(id, data) {
1038
+ return this.client.put(`/organizations/${id}/workflows`, data);
1039
+ }
1040
+ };
1041
+
1042
+ // src/services/SmartAnswerService.ts
1043
+ var SmartAnswerService = class {
1044
+ constructor(client) {
1045
+ this.client = client;
1046
+ }
1047
+ /** Create a new smart answer session */
1048
+ async create(data) {
1049
+ return this.client.post("/smart-answers", data);
1050
+ }
1051
+ /** Get smart answer by ID (with full details) */
1052
+ async findOne(id) {
1053
+ return this.client.get(`/smart-answers/${id}`);
1054
+ }
1055
+ /** Update (rename) a smart answer */
1056
+ async update(id, data) {
1057
+ return this.client.patch(`/smart-answers/${id}`, data);
1058
+ }
1059
+ };
1060
+
1061
+ // src/services/TagService.ts
1062
+ var TagService = class {
1063
+ constructor(client) {
1064
+ this.client = client;
1065
+ }
1066
+ /** List all tags */
1067
+ async find() {
1068
+ return this.client.get("/tags");
1069
+ }
1070
+ /** Create a new tag */
1071
+ async create(name) {
1072
+ return this.client.post("/tags", { name });
1073
+ }
1074
+ /** Delete a tag */
1075
+ async delete(id) {
1076
+ return this.client.delete(`/tags/${id}`);
1077
+ }
1078
+ };
1079
+
1080
+ // src/services/UserService.ts
1081
+ var UserService = class {
1082
+ constructor(client) {
1083
+ this.client = client;
1084
+ }
1085
+ /** Get paginated users */
1086
+ async find(params) {
1087
+ const qs = buildQueryString(params ?? {});
1088
+ return this.client.get(`/users${qs}`);
1089
+ }
1090
+ /** Create a new user */
1091
+ async create(data) {
1092
+ return this.client.post("/users", data);
1093
+ }
1094
+ /** Get a user by ID */
1095
+ async findOne(id) {
1096
+ return this.client.get(`/users/${id}`);
1097
+ }
1098
+ /** Update a user */
1099
+ async update(id, data) {
1100
+ return this.client.put(`/users/${id}`, data);
1101
+ }
1102
+ /** Delete (disable) a user */
1103
+ async delete(id) {
1104
+ return this.client.delete(`/users/${id}`);
1105
+ }
1106
+ /** Get current authenticated user profile */
1107
+ async me() {
1108
+ return this.client.get("/users/me");
1109
+ }
1110
+ /** Resend invitation email to a user */
1111
+ async resendInvitation(id) {
1112
+ return this.client.post(`/users/${id}/resend-invitation`);
1113
+ }
1114
+ };
1115
+
1116
+ // src/services/WebSearchService.ts
1117
+ var WebSearchService = class {
1118
+ constructor(client) {
1119
+ this.client = client;
1120
+ }
1121
+ /** Create a new web search */
1122
+ async create(data) {
1123
+ return this.client.post("/web-searches", data);
1124
+ }
1125
+ /** Retrieve a specific web search */
1126
+ async findOne(id) {
1127
+ return this.client.get(`/web-searches/${id}`);
1128
+ }
1129
+ /** Update an existing web search */
1130
+ async update(id, data) {
1131
+ return this.client.patch(`/web-searches/${id}`, data);
1132
+ }
1133
+ };
1134
+
1135
+ // src/services/WorkflowService.ts
1136
+ var WorkflowService = class {
1137
+ constructor(client) {
1138
+ this.client = client;
1139
+ }
1140
+ /** Get paginated workflows */
1141
+ async find(params) {
1142
+ const qs = buildQueryString(params ?? {});
1143
+ return this.client.get(`/workflows${qs}`);
1144
+ }
1145
+ /** Create a new workflow */
1146
+ async create(data) {
1147
+ return this.client.post("/workflows", data);
1148
+ }
1149
+ /** Get a workflow by ID (editing view) */
1150
+ async findOne(id) {
1151
+ return this.client.get(`/workflows/${id}`);
1152
+ }
1153
+ /** Update a workflow */
1154
+ async update(id, data) {
1155
+ return this.client.put(`/workflows/${id}`, data);
1156
+ }
1157
+ /** Delete a workflow */
1158
+ async delete(id) {
1159
+ return this.client.delete(`/workflows/${id}`);
1160
+ }
1161
+ /** Get workflow description (for conversation sidebar) */
1162
+ async getDescription(id) {
1163
+ return this.client.get(`/workflows/${id}/description`);
1164
+ }
1165
+ /** List workflow categories */
1166
+ async getCategories() {
1167
+ return this.client.get("/workflows/categories");
1168
+ }
1169
+ };
1170
+
1171
+ // src/utils/env.ts
1172
+ var ENVIRONMENT_PRESETS = {
1173
+ ["Production" /* PRODUCTION */]: {
1174
+ baseUrl: "https://api.lidiatech.ai",
1175
+ region: "eu-central-1",
1176
+ clientId: "10lnfbvtu9lrg1ujeemf2uk0sa"
1177
+ },
1178
+ ["Development" /* DEVELOPMENT */]: {
1179
+ baseUrl: "https://api.dev.lidiatech.ai",
1180
+ region: "eu-west-1",
1181
+ clientId: "4uep6n7bmk8o1b7hs7e5ts7u9"
1182
+ },
1183
+ ["Staging" /* STAGING */]: {
1184
+ baseUrl: "https://api.staging.lidiatech.ai",
1185
+ region: "eu-west-1",
1186
+ clientId: "5og664h80v1tv1md0fsgtmln2u"
1187
+ }
1188
+ };
1189
+ function getEnvironmentPreset(env) {
1190
+ return ENVIRONMENT_PRESETS[env];
1191
+ }
1192
+ function parseLidiaEnv(value) {
1193
+ if (!value) return "Production" /* PRODUCTION */;
1194
+ const normalized = value.trim().toLowerCase();
1195
+ switch (normalized) {
1196
+ case "development":
1197
+ case "dev":
1198
+ return "Development" /* DEVELOPMENT */;
1199
+ case "staging":
1200
+ case "stg":
1201
+ return "Staging" /* STAGING */;
1202
+ case "production":
1203
+ case "prod":
1204
+ default:
1205
+ return "Production" /* PRODUCTION */;
1206
+ }
1207
+ }
1208
+ function getBaseUrlFromEnv() {
1209
+ return process.env["LIDIA_BASE_URL"];
1210
+ }
1211
+ function isNodeEnvironment() {
1212
+ return typeof process !== "undefined" && process.env !== void 0;
1213
+ }
1214
+
1215
+ // src/LidiaSDK.ts
1216
+ var LidiaSDK = class {
1217
+ constructor(config) {
1218
+ const mergedConfig = this.mergeConfigWithEnv(config);
1219
+ this.client = new LidiaClient(mergedConfig);
1220
+ this.cases = new CaseService(this.client);
1221
+ this.conversations = new ConversationService(this.client);
1222
+ this.conversationTemplates = new ConversationTemplateService(this.client);
1223
+ this.documents = new DocumentService(this.client);
1224
+ this.favorites = new FavoritesService(this.client);
1225
+ this.folders = new FolderService(this.client);
1226
+ this.health = new HealthService(this.client);
1227
+ this.legisratio = new LegisratioService(this.client);
1228
+ this.messages = new MessageService(this.client);
1229
+ this.notifications = new NotificationService(this.client);
1230
+ this.organizations = new OrganizationService(this.client);
1231
+ this.smartAnswers = new SmartAnswerService(this.client);
1232
+ this.tags = new TagService(this.client);
1233
+ this.users = new UserService(this.client);
1234
+ this.webSearches = new WebSearchService(this.client);
1235
+ this.workflows = new WorkflowService(this.client);
1236
+ if (this.shouldInitializeAuth(mergedConfig)) {
1237
+ this.auth = new AuthorizationService(this.client, mergedConfig);
1238
+ this.authInitPromise = this.initializeAuthentication(mergedConfig).catch((error) => {
1239
+ console.warn("[LidiaSDK] Authentication initialization failed:", error);
1240
+ });
1241
+ }
1242
+ }
1243
+ shouldInitializeAuth(config) {
1244
+ var _a, _b;
1245
+ return !!(((_a = config.cognito) == null ? void 0 : _a.region) && ((_b = config.cognito) == null ? void 0 : _b.clientId));
1246
+ }
1247
+ mergeConfigWithEnv(config) {
1248
+ var _a, _b, _c, _d;
1249
+ const mergedConfig = { ...config };
1250
+ if (!mergedConfig.environment && isNodeEnvironment()) {
1251
+ mergedConfig.environment = parseLidiaEnv(process.env["LIDIA_ENV"]);
1252
+ }
1253
+ const environment = mergedConfig.environment ?? "Production" /* PRODUCTION */;
1254
+ const preset = getEnvironmentPreset(environment);
1255
+ if (isNodeEnvironment()) {
1256
+ if (!mergedConfig.baseUrl) {
1257
+ const envBaseUrl = getBaseUrlFromEnv();
1258
+ mergedConfig.baseUrl = envBaseUrl ?? preset.baseUrl;
1259
+ }
1260
+ if (!((_a = mergedConfig.cognito) == null ? void 0 : _a.region) || !((_b = mergedConfig.cognito) == null ? void 0 : _b.clientId)) {
1261
+ const envRegion = process.env["AWS_REGION"];
1262
+ const envClientId = process.env["COGNITO_CLIENT_ID"];
1263
+ mergedConfig.cognito = {
1264
+ region: ((_c = mergedConfig.cognito) == null ? void 0 : _c.region) ?? envRegion ?? preset.region,
1265
+ clientId: ((_d = mergedConfig.cognito) == null ? void 0 : _d.clientId) ?? envClientId ?? preset.clientId
1266
+ };
1267
+ }
1268
+ if (!mergedConfig.username) {
1269
+ const envUsername = process.env["LIDIA_USERNAME"];
1270
+ if (envUsername) {
1271
+ mergedConfig.username = envUsername;
1272
+ }
1273
+ }
1274
+ if (!mergedConfig.password) {
1275
+ const envPassword = process.env["LIDIA_PASSWORD"];
1276
+ if (envPassword) {
1277
+ mergedConfig.password = envPassword;
1278
+ }
1279
+ }
1280
+ }
1281
+ if (!mergedConfig.baseUrl) {
1282
+ mergedConfig.baseUrl = preset.baseUrl;
1283
+ }
1284
+ if (!mergedConfig.cognito) {
1285
+ mergedConfig.cognito = { region: preset.region, clientId: preset.clientId };
1286
+ }
1287
+ return mergedConfig;
1288
+ }
1289
+ async initializeAuthentication(config) {
1290
+ if (!this.auth) return;
1291
+ if (config.username && config.password) {
1292
+ try {
1293
+ await this.auth.initializeWithCredentials(config.username, config.password);
1294
+ } catch (error) {
1295
+ console.warn("[LidiaSDK] Automatic login failed:", error);
1296
+ }
1297
+ } else if (config.accessToken) {
1298
+ this.auth.initializeWithToken(config.accessToken);
1299
+ }
1300
+ }
1301
+ /** Login with email and password using AWS Cognito */
1302
+ async login(credentials) {
1303
+ if (!this.auth) {
1304
+ throw new Error("Authentication service not initialized");
1305
+ }
1306
+ return this.auth.login(credentials);
1307
+ }
1308
+ /** Refresh authentication tokens */
1309
+ async refreshTokens() {
1310
+ if (!this.auth) {
1311
+ throw new Error("Authentication service not initialized");
1312
+ }
1313
+ return this.auth.refreshTokens();
1314
+ }
1315
+ /** Logout and clear tokens */
1316
+ logout() {
1317
+ if (this.auth) {
1318
+ this.auth.logout();
1319
+ }
1320
+ }
1321
+ /** Wait for authentication initialization to complete */
1322
+ async waitForAuthentication() {
1323
+ if (!this.auth) {
1324
+ throw new Error("Authentication service not initialized");
1325
+ }
1326
+ if (this.auth.isAuthenticated()) {
1327
+ return;
1328
+ }
1329
+ if (this.authInitPromise) {
1330
+ await this.authInitPromise;
1331
+ }
1332
+ if (!this.auth.isAuthenticated()) {
1333
+ throw new Error(
1334
+ "Authentication not initialized. Please login manually or check your credentials."
1335
+ );
1336
+ }
1337
+ }
1338
+ /** Check if user is authenticated */
1339
+ isAuthenticated() {
1340
+ var _a;
1341
+ return ((_a = this.auth) == null ? void 0 : _a.isAuthenticated()) ?? false;
1342
+ }
1343
+ /** Get current authentication tokens */
1344
+ getAuthTokens() {
1345
+ var _a;
1346
+ return (_a = this.auth) == null ? void 0 : _a.getAuthTokens();
1347
+ }
1348
+ /** Update SDK configuration */
1349
+ updateConfig(config) {
1350
+ this.client.updateConfig(config);
1351
+ }
1352
+ /** Get the underlying HTTP client for advanced usage */
1353
+ getClient() {
1354
+ return this.client;
1355
+ }
1356
+ };
1357
+
1358
+ // src/types/case.ts
1359
+ var CaseRole = /* @__PURE__ */ ((CaseRole2) => {
1360
+ CaseRole2["ADMIN"] = "ADMIN";
1361
+ CaseRole2["EDITOR"] = "EDITOR";
1362
+ CaseRole2["VIEWER"] = "VIEWER";
1363
+ return CaseRole2;
1364
+ })(CaseRole || {});
1365
+ var CaseParticipationType = /* @__PURE__ */ ((CaseParticipationType2) => {
1366
+ CaseParticipationType2["USER"] = "USER";
1367
+ CaseParticipationType2["ORGANIZATION"] = "ORGANIZATION";
1368
+ return CaseParticipationType2;
1369
+ })(CaseParticipationType || {});
1370
+
1371
+ // src/types/conversation.ts
1372
+ var ConversationType = /* @__PURE__ */ ((ConversationType2) => {
1373
+ ConversationType2["CONVERSATION"] = "conversation";
1374
+ ConversationType2["WORD"] = "word";
1375
+ ConversationType2["SMART_ANSWER"] = "smartAnswer";
1376
+ ConversationType2["WEB_SEARCH"] = "webSearch";
1377
+ ConversationType2["LEGAL_SEARCH"] = "legalSearch";
1378
+ return ConversationType2;
1379
+ })(ConversationType || {});
1380
+
1381
+ // src/types/document.ts
1382
+ var DocumentType = /* @__PURE__ */ ((DocumentType2) => {
1383
+ DocumentType2["DOCUMENT"] = "DOCUMENT";
1384
+ DocumentType2["REGULATION"] = "REGULATION";
1385
+ DocumentType2["RESEARCH"] = "RESEARCH";
1386
+ DocumentType2["MODEL"] = "MODEL";
1387
+ DocumentType2["FOLDER"] = "FOLDER";
1388
+ return DocumentType2;
1389
+ })(DocumentType || {});
1390
+ var DocumentVisibility = /* @__PURE__ */ ((DocumentVisibility2) => {
1391
+ DocumentVisibility2["COMMON"] = "COMMON";
1392
+ DocumentVisibility2["PRIVATE"] = "PRIVATE";
1393
+ DocumentVisibility2["CASE"] = "CASE";
1394
+ return DocumentVisibility2;
1395
+ })(DocumentVisibility || {});
1396
+ var DocumentStatus = /* @__PURE__ */ ((DocumentStatus2) => {
1397
+ DocumentStatus2["UPLOADING"] = "UPLOADING";
1398
+ DocumentStatus2["PROCESSING"] = "PROCESSING";
1399
+ DocumentStatus2["ERROR"] = "ERROR";
1400
+ DocumentStatus2["COMPLETE"] = "COMPLETE";
1401
+ return DocumentStatus2;
1402
+ })(DocumentStatus || {});
1403
+ var DocumentSmartAnswerStatus = /* @__PURE__ */ ((DocumentSmartAnswerStatus2) => {
1404
+ DocumentSmartAnswerStatus2["NOT_PRESENT"] = "NOT_PRESENT";
1405
+ DocumentSmartAnswerStatus2["PENDING"] = "PENDING";
1406
+ DocumentSmartAnswerStatus2["INDEXED"] = "INDEXED";
1407
+ DocumentSmartAnswerStatus2["FAILED"] = "FAILED";
1408
+ return DocumentSmartAnswerStatus2;
1409
+ })(DocumentSmartAnswerStatus || {});
1410
+
1411
+ // src/types/favorites.ts
1412
+ var FavoriteType = /* @__PURE__ */ ((FavoriteType2) => {
1413
+ FavoriteType2["CONVERSATION"] = "CONVERSATION";
1414
+ FavoriteType2["DOCUMENT"] = "DOCUMENT";
1415
+ FavoriteType2["CASE"] = "CASE";
1416
+ FavoriteType2["WORKFLOW"] = "WORKFLOW";
1417
+ return FavoriteType2;
1418
+ })(FavoriteType || {});
1419
+
1420
+ // src/types/message.ts
1421
+ var MessageSenderType = /* @__PURE__ */ ((MessageSenderType2) => {
1422
+ MessageSenderType2["USER"] = "user";
1423
+ MessageSenderType2["ASSISTANT"] = "assistant";
1424
+ MessageSenderType2["INFO"] = "info";
1425
+ return MessageSenderType2;
1426
+ })(MessageSenderType || {});
1427
+ var MessageStatus = /* @__PURE__ */ ((MessageStatus2) => {
1428
+ MessageStatus2["PROCESSING"] = "PROCESSING";
1429
+ MessageStatus2["DONE"] = "DONE";
1430
+ MessageStatus2["FAILED"] = "FAILED";
1431
+ MessageStatus2["CANCELED"] = "CANCELED";
1432
+ return MessageStatus2;
1433
+ })(MessageStatus || {});
1434
+
1435
+ // src/types/user.ts
1436
+ var UserRole = /* @__PURE__ */ ((UserRole2) => {
1437
+ UserRole2["ADMIN"] = "ADMIN";
1438
+ UserRole2["ORG_ADMIN"] = "ORG_ADMIN";
1439
+ UserRole2["USER"] = "USER";
1440
+ return UserRole2;
1441
+ })(UserRole || {});
1442
+ var Language = /* @__PURE__ */ ((Language2) => {
1443
+ Language2["IT"] = "it";
1444
+ Language2["EN"] = "en";
1445
+ return Language2;
1446
+ })(Language || {});
1447
+
1448
+ // src/errors/ValidationError.ts
1449
+ var ValidationError = class _ValidationError extends Error {
1450
+ constructor(message, details = []) {
1451
+ super(message);
1452
+ this.name = "ValidationError";
1453
+ this.details = details;
1454
+ if (Error.captureStackTrace) {
1455
+ Error.captureStackTrace(this, _ValidationError);
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Get errors for a specific field
1460
+ */
1461
+ getFieldErrors(field) {
1462
+ return this.details.filter((detail) => detail.field === field);
1463
+ }
1464
+ /**
1465
+ * Check if a specific field has errors
1466
+ */
1467
+ hasFieldError(field) {
1468
+ return this.details.some((detail) => detail.field === field);
1469
+ }
1470
+ /**
1471
+ * Get all field names that have errors
1472
+ */
1473
+ getErrorFields() {
1474
+ return [...new Set(this.details.map((detail) => detail.field))];
1475
+ }
1476
+ /**
1477
+ * Get a user-friendly error message
1478
+ */
1479
+ getUserMessage() {
1480
+ if (this.details.length === 0) {
1481
+ return this.message;
1482
+ }
1483
+ const fieldErrors = this.details.map((detail) => `${detail.field}: ${detail.message}`).join(", ");
1484
+ return `${this.message} (${fieldErrors})`;
1485
+ }
1486
+ };
1487
+ // Annotate the CommonJS export names for ESM import in node:
1488
+ 0 && (module.exports = {
1489
+ AuthorizationService,
1490
+ CaseParticipationType,
1491
+ CaseRole,
1492
+ CaseService,
1493
+ ConversationService,
1494
+ ConversationTemplateService,
1495
+ ConversationType,
1496
+ DocumentService,
1497
+ DocumentSmartAnswerStatus,
1498
+ DocumentStatus,
1499
+ DocumentType,
1500
+ DocumentVisibility,
1501
+ FavoriteType,
1502
+ FavoritesService,
1503
+ FolderService,
1504
+ HealthService,
1505
+ Language,
1506
+ LegisratioService,
1507
+ LidiaClient,
1508
+ LidiaError,
1509
+ LidiaSDK,
1510
+ MessageSenderType,
1511
+ MessageService,
1512
+ MessageStatus,
1513
+ NetworkError,
1514
+ NotificationService,
1515
+ OrganizationService,
1516
+ SmartAnswerService,
1517
+ TagService,
1518
+ UserRole,
1519
+ UserService,
1520
+ ValidationError,
1521
+ WebSearchService,
1522
+ WorkflowService,
1523
+ buildQueryString
1524
+ });