@uipath/uipath-typescript 1.3.11 → 1.4.1

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 (59) hide show
  1. package/dist/agent-memory/index.cjs +1772 -0
  2. package/dist/agent-memory/index.d.ts +588 -0
  3. package/dist/agent-memory/index.mjs +1770 -0
  4. package/dist/agents/index.cjs +1995 -0
  5. package/dist/agents/index.d.ts +961 -0
  6. package/dist/agents/index.mjs +1993 -0
  7. package/dist/assets/index.cjs +171 -39
  8. package/dist/assets/index.d.ts +84 -5
  9. package/dist/assets/index.mjs +171 -39
  10. package/dist/attachments/index.cjs +53 -15
  11. package/dist/attachments/index.d.ts +1 -0
  12. package/dist/attachments/index.mjs +53 -15
  13. package/dist/buckets/index.cjs +151 -130
  14. package/dist/buckets/index.d.ts +198 -84
  15. package/dist/buckets/index.mjs +151 -130
  16. package/dist/cases/index.cjs +220 -23
  17. package/dist/cases/index.d.ts +148 -10
  18. package/dist/cases/index.mjs +220 -24
  19. package/dist/conversational-agent/index.cjs +140 -66
  20. package/dist/conversational-agent/index.d.ts +190 -122
  21. package/dist/conversational-agent/index.mjs +140 -66
  22. package/dist/core/index.cjs +445 -108
  23. package/dist/core/index.d.ts +15 -0
  24. package/dist/core/index.mjs +445 -108
  25. package/dist/entities/index.cjs +365 -102
  26. package/dist/entities/index.d.ts +446 -114
  27. package/dist/entities/index.mjs +365 -102
  28. package/dist/feedback/index.cjs +53 -15
  29. package/dist/feedback/index.d.ts +1 -0
  30. package/dist/feedback/index.mjs +53 -15
  31. package/dist/governance/index.cjs +1789 -0
  32. package/dist/governance/index.d.ts +598 -0
  33. package/dist/governance/index.mjs +1787 -0
  34. package/dist/index.cjs +1453 -444
  35. package/dist/index.d.ts +4150 -1742
  36. package/dist/index.mjs +1452 -445
  37. package/dist/index.umd.js +5035 -4009
  38. package/dist/jobs/index.cjs +53 -15
  39. package/dist/jobs/index.d.ts +1 -0
  40. package/dist/jobs/index.mjs +53 -15
  41. package/dist/maestro-processes/index.cjs +189 -27
  42. package/dist/maestro-processes/index.d.ts +131 -9
  43. package/dist/maestro-processes/index.mjs +189 -27
  44. package/dist/orchestrator-du-module/index.cjs +1788 -0
  45. package/dist/orchestrator-du-module/index.d.ts +757 -0
  46. package/dist/orchestrator-du-module/index.mjs +1785 -0
  47. package/dist/processes/index.cjs +53 -15
  48. package/dist/processes/index.d.ts +1 -0
  49. package/dist/processes/index.mjs +53 -15
  50. package/dist/queues/index.cjs +53 -15
  51. package/dist/queues/index.d.ts +1 -0
  52. package/dist/queues/index.mjs +53 -15
  53. package/dist/tasks/index.cjs +116 -19
  54. package/dist/tasks/index.d.ts +110 -4
  55. package/dist/tasks/index.mjs +117 -20
  56. package/dist/traces/index.cjs +340 -15
  57. package/dist/traces/index.d.ts +483 -2
  58. package/dist/traces/index.mjs +339 -16
  59. package/package.json +42 -2
@@ -0,0 +1,1772 @@
1
+ 'use strict';
2
+
3
+ var coreTelemetry = require('@uipath/core-telemetry');
4
+
5
+ /******************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
20
+
21
+
22
+ function __decorate(decorators, target, key, desc) {
23
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
25
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
26
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
27
+ }
28
+
29
+ function __classPrivateFieldGet(receiver, state, kind, f) {
30
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
31
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
32
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
33
+ }
34
+
35
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
36
+ if (kind === "m") throw new TypeError("Private method is not writable");
37
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
38
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
39
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
40
+ }
41
+
42
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
43
+ var e = new Error(message);
44
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
45
+ };
46
+
47
+ /**
48
+ * Type guards for error response types
49
+ */
50
+ function isOrchestratorError(error) {
51
+ return typeof error === 'object' &&
52
+ error !== null &&
53
+ 'message' in error &&
54
+ 'errorCode' in error &&
55
+ typeof error.message === 'string' &&
56
+ typeof error.errorCode === 'number';
57
+ }
58
+ function isEntityError(error) {
59
+ return typeof error === 'object' &&
60
+ error !== null &&
61
+ 'error' in error &&
62
+ typeof error.error === 'string';
63
+ }
64
+ function isPimsError(error) {
65
+ return typeof error === 'object' &&
66
+ error !== null &&
67
+ 'type' in error &&
68
+ 'title' in error &&
69
+ 'status' in error &&
70
+ typeof error.type === 'string' &&
71
+ typeof error.title === 'string' &&
72
+ typeof error.status === 'number';
73
+ }
74
+
75
+ /**
76
+ * HTTP status code constants for error handling
77
+ */
78
+ const HttpStatus = {
79
+ // Client errors (4xx)
80
+ BAD_REQUEST: 400,
81
+ UNAUTHORIZED: 401,
82
+ FORBIDDEN: 403,
83
+ NOT_FOUND: 404,
84
+ TOO_MANY_REQUESTS: 429,
85
+ // Server errors (5xx)
86
+ INTERNAL_SERVER_ERROR: 500,
87
+ BAD_GATEWAY: 502,
88
+ SERVICE_UNAVAILABLE: 503,
89
+ GATEWAY_TIMEOUT: 504
90
+ };
91
+ /**
92
+ * Error type constants for consistent error identification
93
+ */
94
+ const ErrorType = {
95
+ AUTHENTICATION: 'AuthenticationError',
96
+ AUTHORIZATION: 'AuthorizationError',
97
+ VALIDATION: 'ValidationError',
98
+ NOT_FOUND: 'NotFoundError',
99
+ RATE_LIMIT: 'RateLimitError',
100
+ SERVER: 'ServerError',
101
+ NETWORK: 'NetworkError'
102
+ };
103
+ /**
104
+ * HTTP header constants for error handling
105
+ */
106
+ const HttpHeaders = {
107
+ X_REQUEST_ID: 'x-request-id'
108
+ };
109
+ /**
110
+ * Standard error message constants
111
+ */
112
+ const ErrorMessages = {
113
+ // Authentication errors
114
+ AUTHENTICATION_FAILED: 'Authentication failed',
115
+ // Authorization errors
116
+ ACCESS_DENIED: 'Access denied',
117
+ // Validation errors
118
+ VALIDATION_FAILED: 'Validation failed',
119
+ // Not found errors
120
+ RESOURCE_NOT_FOUND: 'Resource not found',
121
+ // Rate limit errors
122
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
123
+ // Server errors
124
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
125
+ // Network errors
126
+ NETWORK_ERROR: 'Network error occurred',
127
+ REQUEST_TIMEOUT: 'Request timed out',
128
+ REQUEST_ABORTED: 'Request was aborted',
129
+ };
130
+ /**
131
+ * Error name constants for network error identification
132
+ */
133
+ const ErrorNames = {
134
+ ABORT_ERROR: 'AbortError'};
135
+
136
+ /**
137
+ * Parser for Orchestrator/Task error format
138
+ */
139
+ class OrchestratorErrorParser {
140
+ canParse(errorBody) {
141
+ return isOrchestratorError(errorBody);
142
+ }
143
+ parse(errorBody, response) {
144
+ const error = errorBody;
145
+ return {
146
+ message: error.message,
147
+ code: response?.status?.toString(),
148
+ details: {
149
+ errorCode: error.errorCode,
150
+ traceId: error.traceId,
151
+ originalResponse: error
152
+ },
153
+ requestId: error.traceId
154
+ };
155
+ }
156
+ }
157
+ /**
158
+ * Parser for Entity (Data Fabric) error format
159
+ */
160
+ class EntityErrorParser {
161
+ canParse(errorBody) {
162
+ return isEntityError(errorBody);
163
+ }
164
+ parse(errorBody, response) {
165
+ const error = errorBody;
166
+ return {
167
+ message: error.error,
168
+ code: response?.status?.toString(),
169
+ details: {
170
+ error: error.error,
171
+ traceId: error.traceId,
172
+ originalResponse: error
173
+ },
174
+ requestId: error.traceId
175
+ };
176
+ }
177
+ }
178
+ /**
179
+ * Parser for PIMS error format
180
+ */
181
+ class PimsErrorParser {
182
+ canParse(errorBody) {
183
+ return isPimsError(errorBody);
184
+ }
185
+ parse(errorBody, response) {
186
+ const error = errorBody;
187
+ let message = error.title;
188
+ // If there are validation errors, append them to the message for better visibility
189
+ if (error.errors && Object.keys(error.errors).length > 0) {
190
+ const errorMessages = Object.entries(error.errors)
191
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
192
+ .join('; ');
193
+ message += `. Validation errors: ${errorMessages}`;
194
+ }
195
+ return {
196
+ message,
197
+ code: response?.status?.toString(),
198
+ details: {
199
+ type: error.type,
200
+ title: error.title,
201
+ status: error.status,
202
+ errors: error.errors,
203
+ traceId: error.traceId,
204
+ originalResponse: error
205
+ },
206
+ requestId: error.traceId
207
+ };
208
+ }
209
+ }
210
+ /**
211
+ * Fallback parser for unrecognized formats
212
+ */
213
+ class GenericErrorParser {
214
+ canParse(_errorBody) {
215
+ return true; // Always can parse as last resort
216
+ }
217
+ parse(errorBody, response) {
218
+ // For unknown error formats, just pass through the raw error with fallback message
219
+ const message = response?.statusText || 'An error occurred';
220
+ return {
221
+ message,
222
+ code: response?.status?.toString(),
223
+ details: {
224
+ originalResponse: errorBody
225
+ },
226
+ };
227
+ }
228
+ }
229
+ /**
230
+ * Main error response parser using Chain of Responsibility pattern
231
+ *
232
+ * This parser standardizes error responses from different UiPath services into a
233
+ * consistent format, regardless of the original error structure.
234
+ *
235
+ * Supported formats:
236
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
237
+ * 2. Entity (Data Fabric): { error, traceId }
238
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
239
+ * 4. Generic: Fallback for any other format
240
+ *
241
+ * @example
242
+ * const parser = new ErrorResponseParser();
243
+ * const errorInfo = await parser.parse(response);
244
+ * // errorInfo will have consistent structure regardless of service
245
+ */
246
+ class ErrorResponseParser {
247
+ constructor() {
248
+ this.strategies = [
249
+ new OrchestratorErrorParser(),
250
+ new EntityErrorParser(),
251
+ new PimsErrorParser(),
252
+ new GenericErrorParser() // Must be last
253
+ ];
254
+ }
255
+ /**
256
+ * Parses error response body into standardized format
257
+ * @param response - The HTTP response object
258
+ * @returns Standardized error information
259
+ */
260
+ async parse(response) {
261
+ try {
262
+ const errorBody = await response.json();
263
+ // Find the first strategy that can parse this error format
264
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
265
+ // GenericErrorParser always returns true, so this will never be null
266
+ return strategy.parse(errorBody, response);
267
+ }
268
+ catch {
269
+ // Handle non-JSON responses
270
+ const responseText = await response.text().catch(() => '');
271
+ return {
272
+ message: response.statusText,
273
+ code: response.status.toString(),
274
+ details: {
275
+ parseError: 'Failed to parse error response as JSON',
276
+ responseText
277
+ },
278
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
279
+ };
280
+ }
281
+ }
282
+ }
283
+ // Export singleton instance
284
+ const errorResponseParser = new ErrorResponseParser();
285
+
286
+ /**
287
+ * Base error class for all UiPath SDK errors
288
+ * Extends Error for standard error handling compatibility
289
+ */
290
+ class UiPathError extends Error {
291
+ constructor(type, params) {
292
+ super(params.message);
293
+ this.name = type;
294
+ this.type = type;
295
+ this.statusCode = params.statusCode;
296
+ this.requestId = params.requestId;
297
+ this.timestamp = new Date();
298
+ // Maintains proper stack trace for where our error was thrown
299
+ if (Error.captureStackTrace) {
300
+ Error.captureStackTrace(this, this.constructor);
301
+ }
302
+ }
303
+ /**
304
+ * Returns a clean JSON representation of the error
305
+ */
306
+ toJSON() {
307
+ return {
308
+ type: this.type,
309
+ message: this.message,
310
+ statusCode: this.statusCode,
311
+ requestId: this.requestId,
312
+ timestamp: this.timestamp
313
+ };
314
+ }
315
+ /**
316
+ * Returns detailed debug information including stack trace
317
+ */
318
+ getDebugInfo() {
319
+ return {
320
+ ...this.toJSON(),
321
+ stack: this.stack
322
+ };
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Error thrown when authentication fails (401 errors)
328
+ * Common scenarios:
329
+ * - Invalid credentials
330
+ * - Expired token
331
+ * - Missing authentication
332
+ */
333
+ class AuthenticationError extends UiPathError {
334
+ constructor(params = {}) {
335
+ super(ErrorType.AUTHENTICATION, {
336
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
337
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
338
+ requestId: params.requestId
339
+ });
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Error thrown when authorization fails (403 errors)
345
+ * Common scenarios:
346
+ * - Insufficient permissions
347
+ * - Access denied to resource
348
+ * - Invalid scope
349
+ */
350
+ class AuthorizationError extends UiPathError {
351
+ constructor(params = {}) {
352
+ super(ErrorType.AUTHORIZATION, {
353
+ message: params.message || ErrorMessages.ACCESS_DENIED,
354
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
355
+ requestId: params.requestId
356
+ });
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Error thrown when validation fails (400 errors or client-side validation)
362
+ * Common scenarios:
363
+ * - Invalid input parameters
364
+ * - Missing required fields
365
+ * - Invalid data format
366
+ */
367
+ class ValidationError extends UiPathError {
368
+ constructor(params = {}) {
369
+ super(ErrorType.VALIDATION, {
370
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
371
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
372
+ requestId: params.requestId
373
+ });
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Error thrown when a resource is not found (404 errors)
379
+ * Common scenarios:
380
+ * - Resource doesn't exist
381
+ * - Invalid ID provided
382
+ * - Resource deleted
383
+ */
384
+ class NotFoundError extends UiPathError {
385
+ constructor(params = {}) {
386
+ super(ErrorType.NOT_FOUND, {
387
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
388
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
389
+ requestId: params.requestId
390
+ });
391
+ }
392
+ }
393
+
394
+ /**
395
+ * Error thrown when rate limit is exceeded (429 errors)
396
+ * Common scenarios:
397
+ * - Too many requests in a time window
398
+ * - API throttling
399
+ */
400
+ class RateLimitError extends UiPathError {
401
+ constructor(params = {}) {
402
+ super(ErrorType.RATE_LIMIT, {
403
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
404
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
405
+ requestId: params.requestId
406
+ });
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Error thrown when server encounters an error (5xx errors)
412
+ * Common scenarios:
413
+ * - Internal server error
414
+ * - Service unavailable
415
+ * - Gateway timeout
416
+ */
417
+ class ServerError extends UiPathError {
418
+ constructor(params = {}) {
419
+ super(ErrorType.SERVER, {
420
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
421
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
422
+ requestId: params.requestId
423
+ });
424
+ }
425
+ /**
426
+ * Checks if this is a temporary error that might succeed on retry
427
+ */
428
+ get isRetryable() {
429
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
430
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
431
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Error thrown when network/connection issues occur
437
+ * Common scenarios:
438
+ * - Connection timeout
439
+ * - DNS resolution failure
440
+ * - Network unreachable
441
+ * - Request aborted
442
+ */
443
+ class NetworkError extends UiPathError {
444
+ constructor(params = {}) {
445
+ super(ErrorType.NETWORK, {
446
+ message: params.message || ErrorMessages.NETWORK_ERROR,
447
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
448
+ requestId: params.requestId
449
+ });
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Factory for creating typed errors based on HTTP status codes
455
+ * Follows the Factory pattern for clean error instantiation
456
+ */
457
+ class ErrorFactory {
458
+ /**
459
+ * Creates appropriate error instance based on HTTP status code
460
+ */
461
+ static createFromHttpStatus(statusCode, errorInfo) {
462
+ const { message, requestId } = errorInfo;
463
+ // Map status codes to error types
464
+ switch (statusCode) {
465
+ case HttpStatus.BAD_REQUEST:
466
+ return new ValidationError({ message, statusCode, requestId });
467
+ case HttpStatus.UNAUTHORIZED:
468
+ return new AuthenticationError({ message, statusCode, requestId });
469
+ case HttpStatus.FORBIDDEN:
470
+ return new AuthorizationError({ message, statusCode, requestId });
471
+ case HttpStatus.NOT_FOUND:
472
+ return new NotFoundError({ message, statusCode, requestId });
473
+ case HttpStatus.TOO_MANY_REQUESTS:
474
+ return new RateLimitError({ message, statusCode, requestId });
475
+ default:
476
+ // For 5xx errors or any other status code
477
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
478
+ return new ServerError({ message, statusCode, requestId });
479
+ }
480
+ // For unknown client errors, treat as validation error
481
+ return new ValidationError({
482
+ message: `${message} (HTTP ${statusCode})`,
483
+ statusCode,
484
+ requestId
485
+ });
486
+ }
487
+ }
488
+ /**
489
+ * Creates a NetworkError from a fetch/network error
490
+ */
491
+ static createNetworkError(error) {
492
+ let message = ErrorMessages.NETWORK_ERROR;
493
+ if (error instanceof Error) {
494
+ if (error.name === ErrorNames.ABORT_ERROR) {
495
+ message = ErrorMessages.REQUEST_ABORTED;
496
+ }
497
+ else if (error.message.includes('timeout')) {
498
+ message = ErrorMessages.REQUEST_TIMEOUT;
499
+ }
500
+ else {
501
+ message = error.message;
502
+ }
503
+ }
504
+ return new NetworkError({ message });
505
+ }
506
+ }
507
+
508
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
509
+ const TRACEPARENT = 'traceparent';
510
+ const UIPATH_TRACEPARENT_ID = 'x-uipath-traceparent-id';
511
+ /**
512
+ * Content type constants for HTTP requests/responses
513
+ */
514
+ const CONTENT_TYPES = {
515
+ JSON: 'application/json',
516
+ XML: 'application/xml',
517
+ OCTET_STREAM: 'application/octet-stream'
518
+ };
519
+ /**
520
+ * Response type constants for HTTP requests
521
+ */
522
+ const RESPONSE_TYPES = {
523
+ JSON: 'json',
524
+ TEXT: 'text',
525
+ BLOB: 'blob',
526
+ ARRAYBUFFER: 'arraybuffer'
527
+ };
528
+
529
+ class ApiClient {
530
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
531
+ this.config = config;
532
+ this.executionContext = executionContext;
533
+ this.clientConfig = clientConfig;
534
+ this.tokenManager = tokenManager;
535
+ }
536
+ /**
537
+ * Gets a valid authentication token, refreshing if necessary.
538
+ * Used internally for API requests and exposed for services that need manual auth headers.
539
+ *
540
+ * @returns The valid token
541
+ * @throws AuthenticationError if no token available or refresh fails
542
+ */
543
+ async getValidToken() {
544
+ return this.tokenManager.getValidToken();
545
+ }
546
+ async getDefaultHeaders() {
547
+ const token = await this.getValidToken();
548
+ return {
549
+ 'Authorization': `Bearer ${token}`,
550
+ 'Content-Type': CONTENT_TYPES.JSON,
551
+ ...this.clientConfig.headers
552
+ };
553
+ }
554
+ async request(method, path, options = {}) {
555
+ // Ensure path starts with a forward slash
556
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
557
+ // Construct URL with org and tenant names
558
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
559
+ const isFormData = options.body instanceof FormData;
560
+ const defaultHeaders = await this.getDefaultHeaders();
561
+ if (isFormData) {
562
+ delete defaultHeaders['Content-Type'];
563
+ }
564
+ const traceId = crypto.randomUUID().replace(/-/g, '');
565
+ const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
566
+ const traceparentValue = `00-${traceId}-${spanId}-01`;
567
+ const headers = {
568
+ ...defaultHeaders,
569
+ [TRACEPARENT]: traceparentValue,
570
+ [UIPATH_TRACEPARENT_ID]: traceparentValue,
571
+ ...options.headers
572
+ };
573
+ // Convert params to URLSearchParams
574
+ const searchParams = new URLSearchParams();
575
+ if (options.params) {
576
+ Object.entries(options.params).forEach(([key, value]) => {
577
+ searchParams.append(key, value.toString());
578
+ });
579
+ }
580
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
581
+ let body = undefined;
582
+ if (options.body) {
583
+ body = isFormData ? options.body : JSON.stringify(options.body);
584
+ }
585
+ try {
586
+ const response = await fetch(fullUrl, {
587
+ method,
588
+ headers,
589
+ body,
590
+ signal: options.signal
591
+ });
592
+ if (!response.ok) {
593
+ const errorInfo = await errorResponseParser.parse(response);
594
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
595
+ }
596
+ if (response.status === 204) {
597
+ return undefined;
598
+ }
599
+ // Handle blob response type for binary data (e.g., file downloads)
600
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
601
+ const blob = await response.blob();
602
+ return blob;
603
+ }
604
+ // Check if we're expecting XML
605
+ const acceptHeader = headers['Accept'] || headers['accept'];
606
+ if (acceptHeader === CONTENT_TYPES.XML) {
607
+ const text = await response.text();
608
+ return text;
609
+ }
610
+ const text = await response.text();
611
+ if (!text) {
612
+ return undefined;
613
+ }
614
+ try {
615
+ return JSON.parse(text);
616
+ }
617
+ catch (error) {
618
+ if (error instanceof SyntaxError) {
619
+ throw new ServerError({
620
+ message: `Server returned non-JSON response (${response.status} ${response.url}): ${error.message}`,
621
+ statusCode: response.status,
622
+ });
623
+ }
624
+ throw error;
625
+ }
626
+ }
627
+ catch (error) {
628
+ // If it's already one of our errors, re-throw it
629
+ if (error.type && error.type.includes('Error')) {
630
+ throw error;
631
+ }
632
+ // Otherwise, it's a genuine network/fetch failure
633
+ throw ErrorFactory.createNetworkError(error);
634
+ }
635
+ }
636
+ async get(path, options = {}) {
637
+ return this.request('GET', path, options);
638
+ }
639
+ async post(path, data, options = {}) {
640
+ return this.request('POST', path, { ...options, body: data });
641
+ }
642
+ async put(path, data, options = {}) {
643
+ return this.request('PUT', path, { ...options, body: data });
644
+ }
645
+ async patch(path, data, options = {}) {
646
+ return this.request('PATCH', path, { ...options, body: data });
647
+ }
648
+ async delete(path, options = {}) {
649
+ return this.request('DELETE', path, options);
650
+ }
651
+ }
652
+
653
+ /**
654
+ * Pagination types supported by the SDK
655
+ */
656
+ var PaginationType;
657
+ (function (PaginationType) {
658
+ PaginationType["OFFSET"] = "offset";
659
+ PaginationType["TOKEN"] = "token";
660
+ })(PaginationType || (PaginationType = {}));
661
+
662
+ /**
663
+ * Collection of utility functions for working with objects
664
+ */
665
+ /**
666
+ * Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
667
+ * and dot-separated nested paths (e.g., 'pagination.totalCount').
668
+ * Direct key match takes priority over nested traversal.
669
+ */
670
+ function resolveNestedField(data, fieldPath) {
671
+ if (!data) {
672
+ return undefined;
673
+ }
674
+ if (fieldPath in data) {
675
+ return data[fieldPath];
676
+ }
677
+ if (!fieldPath.includes('.')) {
678
+ return undefined;
679
+ }
680
+ let value = data;
681
+ for (const part of fieldPath.split('.')) {
682
+ value = value?.[part];
683
+ }
684
+ return value;
685
+ }
686
+ /**
687
+ * Filters out undefined values from an object
688
+ * @param obj The source object
689
+ * @returns A new object without undefined values
690
+ *
691
+ * @example
692
+ * ```typescript
693
+ * // Object with undefined values
694
+ * const options = {
695
+ * name: 'test',
696
+ * count: 5,
697
+ * prefix: undefined,
698
+ * suffix: null
699
+ * };
700
+ * const result = filterUndefined(options);
701
+ * // result = { name: 'test', count: 5, suffix: null }
702
+ * ```
703
+ */
704
+ function filterUndefined(obj) {
705
+ const result = {};
706
+ for (const [key, value] of Object.entries(obj)) {
707
+ if (value !== undefined) {
708
+ result[key] = value;
709
+ }
710
+ }
711
+ return result;
712
+ }
713
+
714
+ /**
715
+ * Utility functions for platform detection
716
+ */
717
+ /**
718
+ * Checks if code is running in a browser environment
719
+ */
720
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
721
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
722
+ const _params = isBrowser ? new URLSearchParams(window.location.search) : null;
723
+ /**
724
+ * True when the coded app has been loaded inside a host frame that explicitly
725
+ * opted into token delegation by adding `?host=embed` to the iframe src URL.
726
+ */
727
+ const isHostEmbedded = isBrowser && window.self !== window.top && _params?.get('host') === 'embed';
728
+ /**
729
+ * The validated parent origin, read from the `?basedomain=` query param set
730
+ * by the embedding host in the iframe src URL.
731
+ * Mirrors the same mechanism used by ActionCenterTokenManager.
732
+ * Non-null only when `?host=embed` is present and `?basedomain=` is a valid URL.
733
+ */
734
+ (() => {
735
+ if (!isHostEmbedded)
736
+ return null;
737
+ const basedomain = _params?.get('basedomain');
738
+ if (!basedomain)
739
+ return null;
740
+ try {
741
+ return new URL(basedomain).origin;
742
+ }
743
+ catch {
744
+ console.warn('embeddingOrigin: basedomain query param is not a valid URL', basedomain);
745
+ return null;
746
+ }
747
+ })();
748
+
749
+ /**
750
+ * Base64 encoding/decoding
751
+ */
752
+ /**
753
+ * Encodes a string to base64
754
+ * @param str - The string to encode
755
+ * @returns Base64 encoded string
756
+ */
757
+ function encodeBase64(str) {
758
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
759
+ const encoder = new TextEncoder();
760
+ const data = encoder.encode(str);
761
+ // Convert Uint8Array to base64
762
+ if (isBrowser) {
763
+ // Browser environment
764
+ // Convert Uint8Array to binary string then to base64
765
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
766
+ return btoa(binaryString);
767
+ }
768
+ else {
769
+ // Node.js environment
770
+ return Buffer.from(data).toString('base64');
771
+ }
772
+ }
773
+ /**
774
+ * Decodes a base64 string
775
+ * @param base64 - The base64 string to decode
776
+ * @returns Decoded string
777
+ */
778
+ function decodeBase64(base64) {
779
+ let bytes;
780
+ if (isBrowser) {
781
+ // Browser environment
782
+ const binaryString = atob(base64);
783
+ bytes = new Uint8Array(binaryString.length);
784
+ for (let i = 0; i < binaryString.length; i++) {
785
+ bytes[i] = binaryString.charCodeAt(i);
786
+ }
787
+ }
788
+ else {
789
+ // Node.js environment
790
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
791
+ }
792
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
793
+ const decoder = new TextDecoder();
794
+ return decoder.decode(bytes);
795
+ }
796
+
797
+ /**
798
+ * PaginationManager handles the conversion between uniform cursor-based pagination
799
+ * and the specific pagination type for each service
800
+ */
801
+ class PaginationManager {
802
+ /**
803
+ * Create a pagination cursor for subsequent page requests
804
+ */
805
+ static createCursor({ pageInfo, type }) {
806
+ if (!pageInfo.hasMore) {
807
+ return undefined;
808
+ }
809
+ const cursorData = {
810
+ type,
811
+ pageSize: pageInfo.pageSize,
812
+ };
813
+ switch (type) {
814
+ case PaginationType.OFFSET:
815
+ if (pageInfo.currentPage) {
816
+ cursorData.pageNumber = pageInfo.currentPage + 1;
817
+ }
818
+ break;
819
+ case PaginationType.TOKEN:
820
+ if (pageInfo.continuationToken) {
821
+ cursorData.continuationToken = pageInfo.continuationToken;
822
+ }
823
+ else {
824
+ return undefined; // No continuation token, can't continue
825
+ }
826
+ break;
827
+ }
828
+ return {
829
+ value: encodeBase64(JSON.stringify(cursorData))
830
+ };
831
+ }
832
+ /**
833
+ * Create a paginated response with navigation cursors
834
+ */
835
+ static createPaginatedResponse({ pageInfo, type }, items) {
836
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
837
+ // Create previous page cursor if applicable
838
+ let previousCursor = undefined;
839
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
840
+ const prevCursorData = {
841
+ type,
842
+ pageNumber: pageInfo.currentPage - 1,
843
+ pageSize: pageInfo.pageSize,
844
+ };
845
+ previousCursor = {
846
+ value: encodeBase64(JSON.stringify(prevCursorData))
847
+ };
848
+ }
849
+ // Calculate total pages if we have totalCount and pageSize
850
+ let totalPages = undefined;
851
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
852
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
853
+ }
854
+ // Determine if this pagination type supports page jumping
855
+ const supportsPageJump = type === PaginationType.OFFSET;
856
+ // Create the result object with all fields, then filter out undefined values
857
+ const result = filterUndefined({
858
+ items,
859
+ totalCount: pageInfo.totalCount,
860
+ hasNextPage: pageInfo.hasMore,
861
+ nextCursor: nextCursor,
862
+ previousCursor: previousCursor,
863
+ currentPage: pageInfo.currentPage,
864
+ totalPages,
865
+ supportsPageJump
866
+ });
867
+ return result;
868
+ }
869
+ }
870
+
871
+ /**
872
+ * Creates headers object from key-value pairs
873
+ * @param headersObj - Object containing header key-value pairs
874
+ * @returns Headers object with all values converted to strings
875
+ *
876
+ * @example
877
+ * ```typescript
878
+ * // Single header
879
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
880
+ *
881
+ * // Multiple headers
882
+ * const headers = createHeaders({
883
+ * 'X-UIPATH-FolderKey': '1234567890',
884
+ * 'X-UIPATH-OrganizationUnitId': 123,
885
+ * 'Accept': 'application/json'
886
+ * });
887
+ *
888
+ * // Using constants
889
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
890
+ * const headers = createHeaders({
891
+ * [FOLDER_KEY]: 'abc-123',
892
+ * [FOLDER_ID]: 456
893
+ * });
894
+ *
895
+ * // Empty headers
896
+ * const headers = createHeaders();
897
+ * ```
898
+ */
899
+ function createHeaders(headersObj) {
900
+ const headers = {};
901
+ for (const [key, value] of Object.entries(headersObj)) {
902
+ if (value !== undefined && value !== null) {
903
+ headers[key] = value.toString();
904
+ }
905
+ }
906
+ return headers;
907
+ }
908
+
909
+ /**
910
+ * Common constants used across the SDK
911
+ */
912
+ /**
913
+ * Prefix used for OData query parameters
914
+ */
915
+ const ODATA_PREFIX = '$';
916
+ /**
917
+ * HTTP methods
918
+ */
919
+ const HTTP_METHODS = {
920
+ GET: 'GET',
921
+ POST: 'POST'};
922
+ /**
923
+ * OData OFFSET pagination parameter names (ODATA-style)
924
+ */
925
+ const ODATA_OFFSET_PARAMS = {
926
+ /** OData page size parameter name */
927
+ PAGE_SIZE_PARAM: '$top',
928
+ /** OData offset parameter name */
929
+ OFFSET_PARAM: '$skip',
930
+ /** OData count parameter name */
931
+ COUNT_PARAM: '$count'
932
+ };
933
+ /**
934
+ * Bucket TOKEN pagination parameter names
935
+ */
936
+ const BUCKET_TOKEN_PARAMS = {
937
+ /** Bucket page size parameter name */
938
+ PAGE_SIZE_PARAM: 'takeHint',
939
+ /** Bucket token parameter name */
940
+ TOKEN_PARAM: 'continuationToken'
941
+ };
942
+
943
+ /**
944
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
945
+ * Returns the original value if parsing fails.
946
+ */
947
+ /**
948
+ * Adds a prefix to specified keys in an object, returning a new object.
949
+ * Only the provided keys are prefixed; all others are left unchanged.
950
+ *
951
+ * @param obj The source object
952
+ * @param prefix The prefix to add (e.g., '$')
953
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
954
+ * @returns A new object with specified keys prefixed
955
+ *
956
+ * @example
957
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
958
+ */
959
+ function addPrefixToKeys(obj, prefix, keys) {
960
+ const result = {};
961
+ for (const [key, value] of Object.entries(obj)) {
962
+ if (keys.includes(key)) {
963
+ result[`${prefix}${key}`] = value;
964
+ }
965
+ else {
966
+ result[key] = value;
967
+ }
968
+ }
969
+ return result;
970
+ }
971
+
972
+ /**
973
+ * Constants used throughout the pagination system
974
+ */
975
+ /** Maximum number of items that can be requested in a single page */
976
+ const MAX_PAGE_SIZE = 1000;
977
+ /** Default page size when jumpToPage is used without specifying pageSize */
978
+ const DEFAULT_PAGE_SIZE = 50;
979
+ /** Default field name for items in a paginated response */
980
+ const DEFAULT_ITEMS_FIELD = 'value';
981
+ /** Default field name for total count in a paginated response */
982
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
983
+ /**
984
+ * Limits the page size to the maximum allowed value
985
+ * @param pageSize - Requested page size
986
+ * @returns Limited page size value
987
+ */
988
+ function getLimitedPageSize(pageSize) {
989
+ if (pageSize === undefined || pageSize === null) {
990
+ return DEFAULT_PAGE_SIZE;
991
+ }
992
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
993
+ }
994
+
995
+ /**
996
+ * Helper functions for pagination that can be used across services
997
+ */
998
+ class PaginationHelpers {
999
+ /**
1000
+ * Checks if any pagination parameters are provided
1001
+ *
1002
+ * @param options - The options object to check
1003
+ * @returns True if any pagination parameter is defined, false otherwise
1004
+ */
1005
+ static hasPaginationParameters(options = {}) {
1006
+ const { cursor, pageSize, jumpToPage } = options;
1007
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1008
+ }
1009
+ /**
1010
+ * Parse a pagination cursor string into cursor data
1011
+ */
1012
+ static parseCursor(cursorString) {
1013
+ try {
1014
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1015
+ return cursorData;
1016
+ }
1017
+ catch {
1018
+ throw new Error('Invalid pagination cursor');
1019
+ }
1020
+ }
1021
+ /**
1022
+ * Validates cursor format and structure
1023
+ *
1024
+ * @param paginationOptions - The pagination options containing the cursor
1025
+ * @param paginationType - Optional pagination type to validate against
1026
+ */
1027
+ static validateCursor(paginationOptions, paginationType) {
1028
+ if (paginationOptions.cursor !== undefined) {
1029
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1030
+ throw new Error('cursor must contain a valid cursor string');
1031
+ }
1032
+ try {
1033
+ // Try to parse the cursor to validate it
1034
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1035
+ // If type is provided, validate cursor contains expected type information
1036
+ if (paginationType) {
1037
+ if (!cursorData.type) {
1038
+ throw new Error('Invalid cursor: missing pagination type');
1039
+ }
1040
+ // Check pagination type compatibility
1041
+ if (cursorData.type !== paginationType) {
1042
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1043
+ }
1044
+ }
1045
+ }
1046
+ catch (error) {
1047
+ if (error instanceof Error) {
1048
+ // If it's already our error with specific message, pass it through
1049
+ if (error.message.startsWith('Invalid cursor') ||
1050
+ error.message.startsWith('Pagination type mismatch')) {
1051
+ throw error;
1052
+ }
1053
+ }
1054
+ throw new Error('Invalid pagination cursor format');
1055
+ }
1056
+ }
1057
+ }
1058
+ /**
1059
+ * Comprehensive validation for pagination options
1060
+ *
1061
+ * @param options - The pagination options to validate
1062
+ * @param paginationType - The pagination type these options will be used with
1063
+ * @returns Processed pagination parameters ready for use
1064
+ */
1065
+ static validatePaginationOptions(options, paginationType) {
1066
+ // Validate pageSize
1067
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1068
+ throw new Error('pageSize must be a positive number');
1069
+ }
1070
+ // Validate jumpToPage
1071
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1072
+ throw new Error('jumpToPage must be a positive number');
1073
+ }
1074
+ // Validate cursor
1075
+ PaginationHelpers.validateCursor(options, paginationType);
1076
+ // Validate service compatibility
1077
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1078
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1079
+ }
1080
+ // Get processed parameters
1081
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1082
+ }
1083
+ /**
1084
+ * Convert a unified pagination options to service-specific parameters
1085
+ */
1086
+ static getRequestParameters(options, paginationType) {
1087
+ // Handle jumpToPage
1088
+ if (options.jumpToPage !== undefined) {
1089
+ const jumpToPageOptions = {
1090
+ pageSize: options.pageSize,
1091
+ pageNumber: options.jumpToPage
1092
+ };
1093
+ return filterUndefined(jumpToPageOptions);
1094
+ }
1095
+ // If no cursor is provided, it's a first page request
1096
+ if (!options.cursor) {
1097
+ const firstPageOptions = {
1098
+ pageSize: options.pageSize,
1099
+ // Only set pageNumber for OFFSET pagination
1100
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1101
+ };
1102
+ return filterUndefined(firstPageOptions);
1103
+ }
1104
+ // Parse the cursor
1105
+ try {
1106
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1107
+ const cursorBasedOptions = {
1108
+ pageSize: cursorData.pageSize || options.pageSize,
1109
+ pageNumber: cursorData.pageNumber,
1110
+ continuationToken: cursorData.continuationToken,
1111
+ type: cursorData.type,
1112
+ };
1113
+ return filterUndefined(cursorBasedOptions);
1114
+ }
1115
+ catch {
1116
+ throw new Error('Invalid pagination cursor');
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Helper method for paginated resource retrieval
1121
+ *
1122
+ * @param params - Parameters for pagination
1123
+ * @returns Promise resolving to a paginated result
1124
+ */
1125
+ static async getAllPaginated(params) {
1126
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1127
+ const endpoint = getEndpoint(folderId);
1128
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1129
+ // On POST, the caller's options go in the body; queryParams stays in the URL.
1130
+ // On GET, everything is URL — queryParams merges with additionalParams.
1131
+ const isPost = method === HTTP_METHODS.POST;
1132
+ const requestSpec = isPost
1133
+ ? { body: additionalParams, params: queryParams }
1134
+ : { params: { ...additionalParams, ...queryParams } };
1135
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1136
+ headers,
1137
+ ...requestSpec,
1138
+ pagination: {
1139
+ paginationType: options.paginationType || PaginationType.OFFSET,
1140
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1141
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1142
+ continuationTokenField: options.continuationTokenField,
1143
+ paginationParams: options.paginationParams
1144
+ }
1145
+ });
1146
+ // Parse items - automatically handle JSON string responses
1147
+ const rawItems = paginatedResponse.items;
1148
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1149
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1150
+ return {
1151
+ ...paginatedResponse,
1152
+ items: transformedItems
1153
+ };
1154
+ }
1155
+ /**
1156
+ * Helper method for non-paginated resource retrieval
1157
+ *
1158
+ * @param params - Parameters for non-paginated resource retrieval
1159
+ * @returns Promise resolving to an object with data and totalCount
1160
+ */
1161
+ static async getAllNonPaginated(params) {
1162
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1163
+ // Set default field names
1164
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1165
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1166
+ // Determine endpoint and headers based on folderId
1167
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1168
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1169
+ // Make the API call based on method
1170
+ let response;
1171
+ if (method === HTTP_METHODS.POST) {
1172
+ response = await serviceAccess.post(endpoint, additionalParams, { headers, params: queryParams });
1173
+ }
1174
+ else {
1175
+ response = await serviceAccess.get(endpoint, {
1176
+ params: { ...additionalParams, ...queryParams },
1177
+ headers
1178
+ });
1179
+ }
1180
+ // Extract and transform items from response
1181
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1182
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1183
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
1184
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1185
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1186
+ // Parse items - automatically handle JSON string responses
1187
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1188
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1189
+ return {
1190
+ items,
1191
+ totalCount
1192
+ };
1193
+ }
1194
+ /**
1195
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1196
+ *
1197
+ * @param config - Configuration for the getAll operation
1198
+ * @param options - Request options including pagination parameters
1199
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1200
+ */
1201
+ static async getAll(config, options) {
1202
+ const optionsWithDefaults = options || {};
1203
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1204
+ // Determine if pagination is requested
1205
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1206
+ // Process parameters (custom processing if provided, otherwise default)
1207
+ let processedOptions = restOptions;
1208
+ if (config.processParametersFn) {
1209
+ processedOptions = config.processParametersFn(restOptions, folderId);
1210
+ }
1211
+ // Apply ODATA prefix to keys (excluding specified keys)
1212
+ const excludeKeys = config.excludeFromPrefix || [];
1213
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1214
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1215
+ // Default pagination options
1216
+ const paginationOptions = {
1217
+ paginationType: PaginationType.OFFSET,
1218
+ itemsField: DEFAULT_ITEMS_FIELD,
1219
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1220
+ ...config.pagination
1221
+ };
1222
+ // Paginated flow
1223
+ if (isPaginationRequested) {
1224
+ return PaginationHelpers.getAllPaginated({
1225
+ serviceAccess: config.serviceAccess,
1226
+ getEndpoint: config.getEndpoint,
1227
+ folderId,
1228
+ headers: config.headers,
1229
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
1230
+ additionalParams: prefixedOptions,
1231
+ queryParams: config.queryParams,
1232
+ transformFn: config.transformFn,
1233
+ method: config.method,
1234
+ options: {
1235
+ ...paginationOptions,
1236
+ paginationParams: config.pagination?.paginationParams
1237
+ }
1238
+ }); // Type assertion needed due to conditional return
1239
+ }
1240
+ // Non-paginated flow
1241
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1242
+ return PaginationHelpers.getAllNonPaginated({
1243
+ serviceAccess: config.serviceAccess,
1244
+ getAllEndpoint: config.getEndpoint(),
1245
+ getByFolderEndpoint: byFolderEndpoint,
1246
+ folderId,
1247
+ headers: config.headers,
1248
+ additionalParams: prefixedOptions,
1249
+ queryParams: config.queryParams,
1250
+ transformFn: config.transformFn,
1251
+ method: config.method,
1252
+ options: {
1253
+ itemsField: paginationOptions.itemsField,
1254
+ totalCountField: paginationOptions.totalCountField
1255
+ }
1256
+ });
1257
+ }
1258
+ }
1259
+
1260
+ /**
1261
+ * SDK Internals Registry - Internal registry for SDK instances
1262
+ *
1263
+ * This class is NOT exported in the public API.
1264
+ * It provides a secure way to share SDK internals between
1265
+ * the UiPath class and service classes without exposing them publicly.
1266
+ *
1267
+ * @internal
1268
+ */
1269
+ // Global symbol key to ensure WeakMap is shared across module instances
1270
+ // This prevents issues when core and service modules are bundled separately
1271
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1272
+ // Get or create the global WeakMap store
1273
+ const getGlobalStore = () => {
1274
+ const globalObj = globalThis;
1275
+ if (!globalObj[REGISTRY_KEY]) {
1276
+ globalObj[REGISTRY_KEY] = new WeakMap();
1277
+ }
1278
+ return globalObj[REGISTRY_KEY];
1279
+ };
1280
+ /**
1281
+ * Internal registry for SDK private components.
1282
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1283
+ * garbage collected when the SDK instance is no longer referenced.
1284
+ *
1285
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1286
+ * across separately bundled modules (core, entities, tasks, etc.).
1287
+ *
1288
+ * @internal - Not exported in public API
1289
+ */
1290
+ class SDKInternalsRegistry {
1291
+ // Use global store to ensure sharing across module bundles
1292
+ static get store() {
1293
+ return getGlobalStore();
1294
+ }
1295
+ /**
1296
+ * Register SDK instance internals
1297
+ * Called by UiPath constructor
1298
+ */
1299
+ static set(instance, internals) {
1300
+ this.store.set(instance, internals);
1301
+ }
1302
+ /**
1303
+ * Retrieve SDK instance internals
1304
+ * Called by BaseService constructor
1305
+ */
1306
+ static get(instance) {
1307
+ const internals = this.store.get(instance);
1308
+ if (!internals) {
1309
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1310
+ }
1311
+ return internals;
1312
+ }
1313
+ }
1314
+
1315
+ var _BaseService_apiClient;
1316
+ /**
1317
+ * Base class for all UiPath SDK services.
1318
+ *
1319
+ * Provides common functionality for authentication, configuration, and API communication.
1320
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1321
+ *
1322
+ * This class implements the dependency injection pattern where services receive a configured
1323
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1324
+ * including authentication token management.
1325
+ *
1326
+ * @remarks
1327
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1328
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1329
+ *
1330
+ */
1331
+ class BaseService {
1332
+ /**
1333
+ * Creates a base service instance with dependency injection.
1334
+ *
1335
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1336
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1337
+ * and token management internally.
1338
+ *
1339
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1340
+ * Services receive this via dependency injection in the modular pattern.
1341
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1342
+ * CAS external-app auth)
1343
+ *
1344
+ * @example
1345
+ * ```typescript
1346
+ * // Services automatically call this via super()
1347
+ * export class EntityService extends BaseService {
1348
+ * constructor(instance: IUiPath) {
1349
+ * super(instance); // Initializes the internal ApiClient
1350
+ * }
1351
+ * }
1352
+ *
1353
+ * // Usage in modular pattern
1354
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1355
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1356
+ *
1357
+ * const sdk = new UiPath(config);
1358
+ * await sdk.initialize();
1359
+ * const entities = new Entities(sdk);
1360
+ * ```
1361
+ */
1362
+ constructor(instance, headers) {
1363
+ // Private field - not visible via Object.keys() or any reflection
1364
+ _BaseService_apiClient.set(this, void 0);
1365
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1366
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1367
+ this.config = { folderKey };
1368
+ }
1369
+ /**
1370
+ * Gets a valid authentication token, refreshing if necessary.
1371
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1372
+ *
1373
+ * @returns Promise resolving to a valid access token string
1374
+ * @throws AuthenticationError if no token is available or refresh fails
1375
+ */
1376
+ async getValidAuthToken() {
1377
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1378
+ }
1379
+ /**
1380
+ * Creates a service accessor for pagination helpers
1381
+ * This allows pagination helpers to access protected methods without making them public
1382
+ */
1383
+ createPaginationServiceAccess() {
1384
+ return {
1385
+ get: (path, options) => this.get(path, options || {}),
1386
+ post: (path, body, options) => this.post(path, body, options || {}),
1387
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1388
+ };
1389
+ }
1390
+ async request(method, path, options = {}) {
1391
+ switch (method.toUpperCase()) {
1392
+ case 'GET':
1393
+ return this.get(path, options);
1394
+ case 'POST':
1395
+ return this.post(path, options.body, options);
1396
+ case 'PUT':
1397
+ return this.put(path, options.body, options);
1398
+ case 'PATCH':
1399
+ return this.patch(path, options.body, options);
1400
+ case 'DELETE':
1401
+ return this.delete(path, options);
1402
+ default:
1403
+ throw new Error(`Unsupported HTTP method: ${method}`);
1404
+ }
1405
+ }
1406
+ async requestWithSpec(spec) {
1407
+ if (!spec.method || !spec.url) {
1408
+ throw new Error('Request spec must include method and url');
1409
+ }
1410
+ return this.request(spec.method, spec.url, spec);
1411
+ }
1412
+ async get(path, options = {}) {
1413
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1414
+ return { data: response };
1415
+ }
1416
+ async post(path, data, options = {}) {
1417
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1418
+ return { data: response };
1419
+ }
1420
+ async put(path, data, options = {}) {
1421
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1422
+ return { data: response };
1423
+ }
1424
+ async patch(path, data, options = {}) {
1425
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1426
+ return { data: response };
1427
+ }
1428
+ async delete(path, options = {}) {
1429
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1430
+ return { data: response };
1431
+ }
1432
+ /**
1433
+ * Execute a request with cursor-based pagination
1434
+ */
1435
+ async requestWithPagination(method, path, paginationOptions, options) {
1436
+ const paginationType = options.pagination.paginationType;
1437
+ // Validate and prepare pagination parameters
1438
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1439
+ // Prepare request parameters based on pagination type
1440
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1441
+ // Route pagination state to wherever the API expects it (body for POST, URL for GET).
1442
+ // Caller-supplied options.body / options.params are respected as-is — the api-client
1443
+ // already handles params (URL) and body (request body) independently for every method.
1444
+ if (method.toUpperCase() === 'POST') {
1445
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1446
+ options.body = {
1447
+ ...existingBody,
1448
+ ...requestParams
1449
+ };
1450
+ }
1451
+ else {
1452
+ options.params = {
1453
+ ...options.params,
1454
+ ...requestParams
1455
+ };
1456
+ }
1457
+ // Make the request
1458
+ const response = await this.request(method, path, options);
1459
+ // Extract data from the response and create page result
1460
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1461
+ itemsField: options.pagination.itemsField,
1462
+ totalCountField: options.pagination.totalCountField,
1463
+ continuationTokenField: options.pagination.continuationTokenField
1464
+ });
1465
+ }
1466
+ /**
1467
+ * Validates and prepares pagination parameters from options
1468
+ */
1469
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1470
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1471
+ }
1472
+ /**
1473
+ * Prepares request parameters for pagination based on pagination type
1474
+ */
1475
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1476
+ const requestParams = {};
1477
+ let limitedPageSize;
1478
+ const paginationParams = paginationConfig?.paginationParams;
1479
+ switch (paginationType) {
1480
+ case PaginationType.OFFSET:
1481
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1482
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1483
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1484
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1485
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1486
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1487
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1488
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
1489
+ const zeroBased = paginationParams?.zeroBased ?? false;
1490
+ requestParams[pageSizeParam] = limitedPageSize;
1491
+ if (convertToSkip) {
1492
+ if (params.pageNumber && params.pageNumber > 1) {
1493
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1494
+ }
1495
+ }
1496
+ else {
1497
+ const sdkPageNumber = params.pageNumber || 1;
1498
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
1499
+ }
1500
+ {
1501
+ requestParams[countParam] = true;
1502
+ }
1503
+ break;
1504
+ case PaginationType.TOKEN:
1505
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1506
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1507
+ if (params.pageSize) {
1508
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1509
+ }
1510
+ if (params.continuationToken) {
1511
+ requestParams[tokenParam] = params.continuationToken;
1512
+ }
1513
+ break;
1514
+ }
1515
+ return requestParams;
1516
+ }
1517
+ /**
1518
+ * Creates a paginated response from API response
1519
+ */
1520
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1521
+ // Extract fields from response
1522
+ const itemsField = fields.itemsField ||
1523
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1524
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1525
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1526
+ // Extract items and metadata
1527
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1528
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1529
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
1530
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1531
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1532
+ const continuationToken = response.data[continuationTokenField];
1533
+ // Determine if there are more pages
1534
+ const hasMore = this.determineHasMorePages(paginationType, {
1535
+ totalCount,
1536
+ pageSize: params.pageSize,
1537
+ currentPage: params.pageNumber || 1,
1538
+ itemsCount: items.length,
1539
+ continuationToken
1540
+ });
1541
+ // Create and return the page result
1542
+ return PaginationManager.createPaginatedResponse({
1543
+ pageInfo: {
1544
+ hasMore,
1545
+ totalCount,
1546
+ currentPage: params.pageNumber,
1547
+ pageSize: params.pageSize,
1548
+ continuationToken
1549
+ },
1550
+ type: paginationType,
1551
+ }, items);
1552
+ }
1553
+ /**
1554
+ * Determines if there are more pages based on pagination type and metadata
1555
+ */
1556
+ determineHasMorePages(paginationType, info) {
1557
+ switch (paginationType) {
1558
+ case PaginationType.OFFSET:
1559
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1560
+ // If totalCount is available, use it for precise calculation
1561
+ if (info.totalCount !== undefined) {
1562
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1563
+ }
1564
+ // Fallback when totalCount is not available
1565
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1566
+ return info.itemsCount === effectivePageSize;
1567
+ case PaginationType.TOKEN:
1568
+ return !!info.continuationToken;
1569
+ default:
1570
+ return false;
1571
+ }
1572
+ }
1573
+ }
1574
+ _BaseService_apiClient = new WeakMap();
1575
+
1576
+ /**
1577
+ * Base path constants for different services
1578
+ */
1579
+ const INSIGHTS_RTM_BASE = 'insightsrtm_';
1580
+
1581
+ /**
1582
+ * Agent Memory Service Endpoints
1583
+ */
1584
+ const MEMORY_ENDPOINTS = {
1585
+ /** Time-series of agent-memory state counts bucketed across the requested window. */
1586
+ GET_TIMELINE: `${INSIGHTS_RTM_BASE}/Traceview/memoryTimeline`,
1587
+ /** Time-series of memory-call counts bucketed across the requested window. */
1588
+ GET_CALLS_TIMELINE: `${INSIGHTS_RTM_BASE}/Traceview/memoryCallsTimeline`,
1589
+ /** Top-N memory spaces ranked by memory count over the requested window. */
1590
+ GET_TOP_SPACES: `${INSIGHTS_RTM_BASE}/Traceview/topMemorySpaces`,
1591
+ };
1592
+
1593
+ /**
1594
+ * SDK Telemetry constants.
1595
+ *
1596
+ * Only the SDK's identity (version, service name, role name, …) lives
1597
+ * here. The Application Insights connection string is injected into
1598
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
1599
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
1600
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
1601
+ * SDK's public API.
1602
+ */
1603
+ /** SDK version placeholder — patched by the SDK publish workflow. */
1604
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
1605
+
1606
+ /**
1607
+ * UiPath TypeScript SDK Telemetry
1608
+ *
1609
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
1610
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
1611
+ * does this independently, so events carry their own consumer's identity
1612
+ * and tenant context.
1613
+ */
1614
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
1615
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
1616
+ // from the `UiPath` constructor therefore wires up `@track` decorators
1617
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
1618
+ const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
1619
+ const track = coreTelemetry.createTrack(sdkClient);
1620
+ coreTelemetry.createTrackEvent(sdkClient);
1621
+
1622
+ /**
1623
+ * Service for managing UiPath Agent Memory.
1624
+ */
1625
+ class MemoryService extends BaseService {
1626
+ /**
1627
+ * Gets agent memory state over time, with optional filters.
1628
+ *
1629
+ * @param options - Optional time window and scope filters
1630
+ * @returns Promise resolving to an array of {@link AgentMemoryGetTimelineResponse}, one per time bucket.
1631
+ * @example
1632
+ * ```typescript
1633
+ * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory';
1634
+ *
1635
+ * const memory = new AgentMemory(sdk);
1636
+ *
1637
+ * // Last 24 hours (default window)
1638
+ * const timeline = await memory.getTimeline();
1639
+ * console.log(timeline[0]?.inMemoryCount);
1640
+ * ```
1641
+ * @example
1642
+ * ```typescript
1643
+ * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory';
1644
+ *
1645
+ * // Scoped to one agent in one folder, runtime executions only
1646
+ * const scoped = await memory.getTimeline({
1647
+ * startTime: new Date('2026-05-01T00:00:00Z'),
1648
+ * endTime: new Date('2026-06-01T00:00:00Z'),
1649
+ * agentId: '<agentId>',
1650
+ * folderKeys: ['<folderKey>'],
1651
+ * executionType: AgentMemoryExecutionType.Runtime,
1652
+ * });
1653
+ * ```
1654
+ */
1655
+ async getTimeline(options) {
1656
+ const body = this.buildMemoryFilterBody(options);
1657
+ const response = await this.post(MEMORY_ENDPOINTS.GET_TIMELINE, body);
1658
+ return response.data.data;
1659
+ }
1660
+ /**
1661
+ * Gets agent memory-access counts over time, with optional filters.
1662
+ *
1663
+ * @param options - Optional time window and scope filters
1664
+ * @returns Promise resolving to an array of {@link AgentMemoryGetCallsTimelineResponse}, one per time bucket.
1665
+ * @example
1666
+ * ```typescript
1667
+ * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory';
1668
+ *
1669
+ * const memory = new AgentMemory(sdk);
1670
+ *
1671
+ * // Last 24 hours (default window)
1672
+ * const timeline = await memory.getCallsTimeline();
1673
+ * console.log(timeline[0]?.memoryCallsCount);
1674
+ * ```
1675
+ * @example
1676
+ * ```typescript
1677
+ * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory';
1678
+ *
1679
+ * // Scoped to one agent in one folder, runtime executions only
1680
+ * const scoped = await memory.getCallsTimeline({
1681
+ * startTime: new Date('2026-05-01T00:00:00Z'),
1682
+ * endTime: new Date('2026-06-01T00:00:00Z'),
1683
+ * agentId: '<agentId>',
1684
+ * folderKeys: ['<folderKey>'],
1685
+ * executionType: AgentMemoryExecutionType.Runtime,
1686
+ * });
1687
+ * ```
1688
+ */
1689
+ async getCallsTimeline(options) {
1690
+ const body = this.buildMemoryFilterBody(options);
1691
+ const response = await this.post(MEMORY_ENDPOINTS.GET_CALLS_TIMELINE, body);
1692
+ return response.data.data;
1693
+ }
1694
+ /**
1695
+ * Gets the top memory spaces by memory count, with optional filters
1696
+ *
1697
+ * @param options - Optional limit, time window, and scope filters
1698
+ * @returns Promise resolving to an array of {@link AgentMemoryGetTopSpacesResponse}, ranked by memory count.
1699
+ * @example
1700
+ * ```typescript
1701
+ * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory';
1702
+ *
1703
+ * const memory = new AgentMemory(sdk);
1704
+ *
1705
+ * // Top 5 memory spaces (default limit and window)
1706
+ * const top = await memory.getTopSpaces();
1707
+ * console.log(top[0]?.memorySpaceName, top[0]?.memoryCount);
1708
+ * ```
1709
+ * @example
1710
+ * ```typescript
1711
+ * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory';
1712
+ *
1713
+ * // Top 10 spaces for one folder over an explicit window, runtime executions only
1714
+ * const topScoped = await memory.getTopSpaces({
1715
+ * startTime: new Date('2026-05-01T00:00:00Z'),
1716
+ * endTime: new Date('2026-06-01T00:00:00Z'),
1717
+ * folderKeys: ['<folderKey>'],
1718
+ * executionType: AgentMemoryExecutionType.Runtime,
1719
+ * limit: 10,
1720
+ * });
1721
+ * ```
1722
+ */
1723
+ async getTopSpaces(options) {
1724
+ const body = this.buildMemoryFilterBody(options);
1725
+ if (options?.limit !== undefined)
1726
+ body.limit = options.limit;
1727
+ const response = await this.post(MEMORY_ENDPOINTS.GET_TOP_SPACES, body);
1728
+ return response.data.data;
1729
+ }
1730
+ buildMemoryFilterBody(options) {
1731
+ const body = {};
1732
+ if (options?.startTime !== undefined)
1733
+ body.startTime = options.startTime.toISOString();
1734
+ if (options?.endTime !== undefined)
1735
+ body.endTime = options.endTime.toISOString();
1736
+ if (options?.agentId !== undefined)
1737
+ body.agentId = options.agentId;
1738
+ if (options?.agentVersion !== undefined)
1739
+ body.agentVersion = options.agentVersion;
1740
+ if (options?.folderKeys !== undefined)
1741
+ body.folderKeys = options.folderKeys;
1742
+ if (options?.executionType !== undefined)
1743
+ body.executionType = options.executionType;
1744
+ return body;
1745
+ }
1746
+ }
1747
+ __decorate([
1748
+ track('AgentMemory.GetTimeline')
1749
+ ], MemoryService.prototype, "getTimeline", null);
1750
+ __decorate([
1751
+ track('AgentMemory.GetCallsTimeline')
1752
+ ], MemoryService.prototype, "getCallsTimeline", null);
1753
+ __decorate([
1754
+ track('AgentMemory.GetTopSpaces')
1755
+ ], MemoryService.prototype, "getTopSpaces", null);
1756
+
1757
+ /**
1758
+ * Types for the Agent Memory metrics service.
1759
+ */
1760
+ /**
1761
+ * Execution kind to filter Agent Memory queries by. Omit to include both
1762
+ * Debug and Runtime executions.
1763
+ */
1764
+ exports.AgentMemoryExecutionType = void 0;
1765
+ (function (AgentMemoryExecutionType) {
1766
+ /** Executions produced during agent debugging sessions. */
1767
+ AgentMemoryExecutionType["Debug"] = "Debug";
1768
+ /** Executions produced during production runtime. */
1769
+ AgentMemoryExecutionType["Runtime"] = "Runtime";
1770
+ })(exports.AgentMemoryExecutionType || (exports.AgentMemoryExecutionType = {}));
1771
+
1772
+ exports.AgentMemory = MemoryService;