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