@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,1995 @@
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
+ * Agents pagination constants — items and total count are nested under the response envelope
924
+ */
925
+ const AGENTS_PAGINATION = {
926
+ /** Dotted path to the items array in the agents response envelope */
927
+ ITEMS_FIELD: 'data.agents',
928
+ /** Dotted path to the total count in the agents response envelope */
929
+ TOTAL_COUNT_FIELD: 'pagination.totalCount'
930
+ };
931
+ /**
932
+ * Agents OFFSET pagination parameter names (page-number style, 0-based, no skip conversion)
933
+ */
934
+ const AGENTS_OFFSET_PARAMS = {
935
+ /** Page size parameter name */
936
+ PAGE_SIZE_PARAM: 'pageSize',
937
+ /** Page number parameter name (sent directly, 0-based) */
938
+ OFFSET_PARAM: 'pageNumber',
939
+ /** No count param needed */
940
+ COUNT_PARAM: undefined
941
+ };
942
+ /**
943
+ * Agents incidents pagination constants — the items array is the `data` field
944
+ * itself, total count is nested under the response envelope. Reuses
945
+ * AGENTS_OFFSET_PARAMS for request params (same 0-based page-number style).
946
+ */
947
+ const AGENTS_INCIDENTS_PAGINATION = {
948
+ /** Dotted path to the items array in the incidents response envelope */
949
+ ITEMS_FIELD: 'data',
950
+ /** Total count path — same envelope location as the agents list. */
951
+ TOTAL_COUNT_FIELD: AGENTS_PAGINATION.TOTAL_COUNT_FIELD
952
+ };
953
+ /**
954
+ * OData OFFSET pagination parameter names (ODATA-style)
955
+ */
956
+ const ODATA_OFFSET_PARAMS = {
957
+ /** OData page size parameter name */
958
+ PAGE_SIZE_PARAM: '$top',
959
+ /** OData offset parameter name */
960
+ OFFSET_PARAM: '$skip',
961
+ /** OData count parameter name */
962
+ COUNT_PARAM: '$count'
963
+ };
964
+ /**
965
+ * Bucket TOKEN pagination parameter names
966
+ */
967
+ const BUCKET_TOKEN_PARAMS = {
968
+ /** Bucket page size parameter name */
969
+ PAGE_SIZE_PARAM: 'takeHint',
970
+ /** Bucket token parameter name */
971
+ TOKEN_PARAM: 'continuationToken'
972
+ };
973
+
974
+ /**
975
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
976
+ * Returns the original value if parsing fails.
977
+ */
978
+ /**
979
+ * Adds a prefix to specified keys in an object, returning a new object.
980
+ * Only the provided keys are prefixed; all others are left unchanged.
981
+ *
982
+ * @param obj The source object
983
+ * @param prefix The prefix to add (e.g., '$')
984
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
985
+ * @returns A new object with specified keys prefixed
986
+ *
987
+ * @example
988
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
989
+ */
990
+ function addPrefixToKeys(obj, prefix, keys) {
991
+ const result = {};
992
+ for (const [key, value] of Object.entries(obj)) {
993
+ if (keys.includes(key)) {
994
+ result[`${prefix}${key}`] = value;
995
+ }
996
+ else {
997
+ result[key] = value;
998
+ }
999
+ }
1000
+ return result;
1001
+ }
1002
+
1003
+ /**
1004
+ * Constants used throughout the pagination system
1005
+ */
1006
+ /** Maximum number of items that can be requested in a single page */
1007
+ const MAX_PAGE_SIZE = 1000;
1008
+ /** Default page size when jumpToPage is used without specifying pageSize */
1009
+ const DEFAULT_PAGE_SIZE = 50;
1010
+ /** Default field name for items in a paginated response */
1011
+ const DEFAULT_ITEMS_FIELD = 'value';
1012
+ /** Default field name for total count in a paginated response */
1013
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1014
+ /**
1015
+ * Limits the page size to the maximum allowed value
1016
+ * @param pageSize - Requested page size
1017
+ * @returns Limited page size value
1018
+ */
1019
+ function getLimitedPageSize(pageSize) {
1020
+ if (pageSize === undefined || pageSize === null) {
1021
+ return DEFAULT_PAGE_SIZE;
1022
+ }
1023
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1024
+ }
1025
+
1026
+ /**
1027
+ * Helper functions for pagination that can be used across services
1028
+ */
1029
+ class PaginationHelpers {
1030
+ /**
1031
+ * Checks if any pagination parameters are provided
1032
+ *
1033
+ * @param options - The options object to check
1034
+ * @returns True if any pagination parameter is defined, false otherwise
1035
+ */
1036
+ static hasPaginationParameters(options = {}) {
1037
+ const { cursor, pageSize, jumpToPage } = options;
1038
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1039
+ }
1040
+ /**
1041
+ * Parse a pagination cursor string into cursor data
1042
+ */
1043
+ static parseCursor(cursorString) {
1044
+ try {
1045
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1046
+ return cursorData;
1047
+ }
1048
+ catch {
1049
+ throw new Error('Invalid pagination cursor');
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Validates cursor format and structure
1054
+ *
1055
+ * @param paginationOptions - The pagination options containing the cursor
1056
+ * @param paginationType - Optional pagination type to validate against
1057
+ */
1058
+ static validateCursor(paginationOptions, paginationType) {
1059
+ if (paginationOptions.cursor !== undefined) {
1060
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1061
+ throw new Error('cursor must contain a valid cursor string');
1062
+ }
1063
+ try {
1064
+ // Try to parse the cursor to validate it
1065
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1066
+ // If type is provided, validate cursor contains expected type information
1067
+ if (paginationType) {
1068
+ if (!cursorData.type) {
1069
+ throw new Error('Invalid cursor: missing pagination type');
1070
+ }
1071
+ // Check pagination type compatibility
1072
+ if (cursorData.type !== paginationType) {
1073
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1074
+ }
1075
+ }
1076
+ }
1077
+ catch (error) {
1078
+ if (error instanceof Error) {
1079
+ // If it's already our error with specific message, pass it through
1080
+ if (error.message.startsWith('Invalid cursor') ||
1081
+ error.message.startsWith('Pagination type mismatch')) {
1082
+ throw error;
1083
+ }
1084
+ }
1085
+ throw new Error('Invalid pagination cursor format');
1086
+ }
1087
+ }
1088
+ }
1089
+ /**
1090
+ * Comprehensive validation for pagination options
1091
+ *
1092
+ * @param options - The pagination options to validate
1093
+ * @param paginationType - The pagination type these options will be used with
1094
+ * @returns Processed pagination parameters ready for use
1095
+ */
1096
+ static validatePaginationOptions(options, paginationType) {
1097
+ // Validate pageSize
1098
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1099
+ throw new Error('pageSize must be a positive number');
1100
+ }
1101
+ // Validate jumpToPage
1102
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1103
+ throw new Error('jumpToPage must be a positive number');
1104
+ }
1105
+ // Validate cursor
1106
+ PaginationHelpers.validateCursor(options, paginationType);
1107
+ // Validate service compatibility
1108
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1109
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1110
+ }
1111
+ // Get processed parameters
1112
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1113
+ }
1114
+ /**
1115
+ * Convert a unified pagination options to service-specific parameters
1116
+ */
1117
+ static getRequestParameters(options, paginationType) {
1118
+ // Handle jumpToPage
1119
+ if (options.jumpToPage !== undefined) {
1120
+ const jumpToPageOptions = {
1121
+ pageSize: options.pageSize,
1122
+ pageNumber: options.jumpToPage
1123
+ };
1124
+ return filterUndefined(jumpToPageOptions);
1125
+ }
1126
+ // If no cursor is provided, it's a first page request
1127
+ if (!options.cursor) {
1128
+ const firstPageOptions = {
1129
+ pageSize: options.pageSize,
1130
+ // Only set pageNumber for OFFSET pagination
1131
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1132
+ };
1133
+ return filterUndefined(firstPageOptions);
1134
+ }
1135
+ // Parse the cursor
1136
+ try {
1137
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1138
+ const cursorBasedOptions = {
1139
+ pageSize: cursorData.pageSize || options.pageSize,
1140
+ pageNumber: cursorData.pageNumber,
1141
+ continuationToken: cursorData.continuationToken,
1142
+ type: cursorData.type,
1143
+ };
1144
+ return filterUndefined(cursorBasedOptions);
1145
+ }
1146
+ catch {
1147
+ throw new Error('Invalid pagination cursor');
1148
+ }
1149
+ }
1150
+ /**
1151
+ * Helper method for paginated resource retrieval
1152
+ *
1153
+ * @param params - Parameters for pagination
1154
+ * @returns Promise resolving to a paginated result
1155
+ */
1156
+ static async getAllPaginated(params) {
1157
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1158
+ const endpoint = getEndpoint(folderId);
1159
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1160
+ // On POST, the caller's options go in the body; queryParams stays in the URL.
1161
+ // On GET, everything is URL — queryParams merges with additionalParams.
1162
+ const isPost = method === HTTP_METHODS.POST;
1163
+ const requestSpec = isPost
1164
+ ? { body: additionalParams, params: queryParams }
1165
+ : { params: { ...additionalParams, ...queryParams } };
1166
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1167
+ headers,
1168
+ ...requestSpec,
1169
+ pagination: {
1170
+ paginationType: options.paginationType || PaginationType.OFFSET,
1171
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1172
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1173
+ continuationTokenField: options.continuationTokenField,
1174
+ paginationParams: options.paginationParams
1175
+ }
1176
+ });
1177
+ // Parse items - automatically handle JSON string responses
1178
+ const rawItems = paginatedResponse.items;
1179
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1180
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1181
+ return {
1182
+ ...paginatedResponse,
1183
+ items: transformedItems
1184
+ };
1185
+ }
1186
+ /**
1187
+ * Helper method for non-paginated resource retrieval
1188
+ *
1189
+ * @param params - Parameters for non-paginated resource retrieval
1190
+ * @returns Promise resolving to an object with data and totalCount
1191
+ */
1192
+ static async getAllNonPaginated(params) {
1193
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1194
+ // Set default field names
1195
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1196
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1197
+ // Determine endpoint and headers based on folderId
1198
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1199
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1200
+ // Make the API call based on method
1201
+ let response;
1202
+ if (method === HTTP_METHODS.POST) {
1203
+ response = await serviceAccess.post(endpoint, additionalParams, { headers, params: queryParams });
1204
+ }
1205
+ else {
1206
+ response = await serviceAccess.get(endpoint, {
1207
+ params: { ...additionalParams, ...queryParams },
1208
+ headers
1209
+ });
1210
+ }
1211
+ // Extract and transform items from response
1212
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1213
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1214
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
1215
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1216
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1217
+ // Parse items - automatically handle JSON string responses
1218
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1219
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1220
+ return {
1221
+ items,
1222
+ totalCount
1223
+ };
1224
+ }
1225
+ /**
1226
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1227
+ *
1228
+ * @param config - Configuration for the getAll operation
1229
+ * @param options - Request options including pagination parameters
1230
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1231
+ */
1232
+ static async getAll(config, options) {
1233
+ const optionsWithDefaults = options || {};
1234
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1235
+ // Determine if pagination is requested
1236
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1237
+ // Process parameters (custom processing if provided, otherwise default)
1238
+ let processedOptions = restOptions;
1239
+ if (config.processParametersFn) {
1240
+ processedOptions = config.processParametersFn(restOptions, folderId);
1241
+ }
1242
+ // Apply ODATA prefix to keys (excluding specified keys)
1243
+ const excludeKeys = config.excludeFromPrefix || [];
1244
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1245
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1246
+ // Default pagination options
1247
+ const paginationOptions = {
1248
+ paginationType: PaginationType.OFFSET,
1249
+ itemsField: DEFAULT_ITEMS_FIELD,
1250
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1251
+ ...config.pagination
1252
+ };
1253
+ // Paginated flow
1254
+ if (isPaginationRequested) {
1255
+ return PaginationHelpers.getAllPaginated({
1256
+ serviceAccess: config.serviceAccess,
1257
+ getEndpoint: config.getEndpoint,
1258
+ folderId,
1259
+ headers: config.headers,
1260
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
1261
+ additionalParams: prefixedOptions,
1262
+ queryParams: config.queryParams,
1263
+ transformFn: config.transformFn,
1264
+ method: config.method,
1265
+ options: {
1266
+ ...paginationOptions,
1267
+ paginationParams: config.pagination?.paginationParams
1268
+ }
1269
+ }); // Type assertion needed due to conditional return
1270
+ }
1271
+ // Non-paginated flow
1272
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1273
+ return PaginationHelpers.getAllNonPaginated({
1274
+ serviceAccess: config.serviceAccess,
1275
+ getAllEndpoint: config.getEndpoint(),
1276
+ getByFolderEndpoint: byFolderEndpoint,
1277
+ folderId,
1278
+ headers: config.headers,
1279
+ additionalParams: prefixedOptions,
1280
+ queryParams: config.queryParams,
1281
+ transformFn: config.transformFn,
1282
+ method: config.method,
1283
+ options: {
1284
+ itemsField: paginationOptions.itemsField,
1285
+ totalCountField: paginationOptions.totalCountField
1286
+ }
1287
+ });
1288
+ }
1289
+ }
1290
+
1291
+ /**
1292
+ * SDK Internals Registry - Internal registry for SDK instances
1293
+ *
1294
+ * This class is NOT exported in the public API.
1295
+ * It provides a secure way to share SDK internals between
1296
+ * the UiPath class and service classes without exposing them publicly.
1297
+ *
1298
+ * @internal
1299
+ */
1300
+ // Global symbol key to ensure WeakMap is shared across module instances
1301
+ // This prevents issues when core and service modules are bundled separately
1302
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1303
+ // Get or create the global WeakMap store
1304
+ const getGlobalStore = () => {
1305
+ const globalObj = globalThis;
1306
+ if (!globalObj[REGISTRY_KEY]) {
1307
+ globalObj[REGISTRY_KEY] = new WeakMap();
1308
+ }
1309
+ return globalObj[REGISTRY_KEY];
1310
+ };
1311
+ /**
1312
+ * Internal registry for SDK private components.
1313
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1314
+ * garbage collected when the SDK instance is no longer referenced.
1315
+ *
1316
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1317
+ * across separately bundled modules (core, entities, tasks, etc.).
1318
+ *
1319
+ * @internal - Not exported in public API
1320
+ */
1321
+ class SDKInternalsRegistry {
1322
+ // Use global store to ensure sharing across module bundles
1323
+ static get store() {
1324
+ return getGlobalStore();
1325
+ }
1326
+ /**
1327
+ * Register SDK instance internals
1328
+ * Called by UiPath constructor
1329
+ */
1330
+ static set(instance, internals) {
1331
+ this.store.set(instance, internals);
1332
+ }
1333
+ /**
1334
+ * Retrieve SDK instance internals
1335
+ * Called by BaseService constructor
1336
+ */
1337
+ static get(instance) {
1338
+ const internals = this.store.get(instance);
1339
+ if (!internals) {
1340
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1341
+ }
1342
+ return internals;
1343
+ }
1344
+ }
1345
+
1346
+ var _BaseService_apiClient;
1347
+ /**
1348
+ * Base class for all UiPath SDK services.
1349
+ *
1350
+ * Provides common functionality for authentication, configuration, and API communication.
1351
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1352
+ *
1353
+ * This class implements the dependency injection pattern where services receive a configured
1354
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1355
+ * including authentication token management.
1356
+ *
1357
+ * @remarks
1358
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1359
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1360
+ *
1361
+ */
1362
+ class BaseService {
1363
+ /**
1364
+ * Creates a base service instance with dependency injection.
1365
+ *
1366
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1367
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1368
+ * and token management internally.
1369
+ *
1370
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1371
+ * Services receive this via dependency injection in the modular pattern.
1372
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1373
+ * CAS external-app auth)
1374
+ *
1375
+ * @example
1376
+ * ```typescript
1377
+ * // Services automatically call this via super()
1378
+ * export class EntityService extends BaseService {
1379
+ * constructor(instance: IUiPath) {
1380
+ * super(instance); // Initializes the internal ApiClient
1381
+ * }
1382
+ * }
1383
+ *
1384
+ * // Usage in modular pattern
1385
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1386
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1387
+ *
1388
+ * const sdk = new UiPath(config);
1389
+ * await sdk.initialize();
1390
+ * const entities = new Entities(sdk);
1391
+ * ```
1392
+ */
1393
+ constructor(instance, headers) {
1394
+ // Private field - not visible via Object.keys() or any reflection
1395
+ _BaseService_apiClient.set(this, void 0);
1396
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1397
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1398
+ this.config = { folderKey };
1399
+ }
1400
+ /**
1401
+ * Gets a valid authentication token, refreshing if necessary.
1402
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1403
+ *
1404
+ * @returns Promise resolving to a valid access token string
1405
+ * @throws AuthenticationError if no token is available or refresh fails
1406
+ */
1407
+ async getValidAuthToken() {
1408
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1409
+ }
1410
+ /**
1411
+ * Creates a service accessor for pagination helpers
1412
+ * This allows pagination helpers to access protected methods without making them public
1413
+ */
1414
+ createPaginationServiceAccess() {
1415
+ return {
1416
+ get: (path, options) => this.get(path, options || {}),
1417
+ post: (path, body, options) => this.post(path, body, options || {}),
1418
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1419
+ };
1420
+ }
1421
+ async request(method, path, options = {}) {
1422
+ switch (method.toUpperCase()) {
1423
+ case 'GET':
1424
+ return this.get(path, options);
1425
+ case 'POST':
1426
+ return this.post(path, options.body, options);
1427
+ case 'PUT':
1428
+ return this.put(path, options.body, options);
1429
+ case 'PATCH':
1430
+ return this.patch(path, options.body, options);
1431
+ case 'DELETE':
1432
+ return this.delete(path, options);
1433
+ default:
1434
+ throw new Error(`Unsupported HTTP method: ${method}`);
1435
+ }
1436
+ }
1437
+ async requestWithSpec(spec) {
1438
+ if (!spec.method || !spec.url) {
1439
+ throw new Error('Request spec must include method and url');
1440
+ }
1441
+ return this.request(spec.method, spec.url, spec);
1442
+ }
1443
+ async get(path, options = {}) {
1444
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1445
+ return { data: response };
1446
+ }
1447
+ async post(path, data, options = {}) {
1448
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1449
+ return { data: response };
1450
+ }
1451
+ async put(path, data, options = {}) {
1452
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1453
+ return { data: response };
1454
+ }
1455
+ async patch(path, data, options = {}) {
1456
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1457
+ return { data: response };
1458
+ }
1459
+ async delete(path, options = {}) {
1460
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1461
+ return { data: response };
1462
+ }
1463
+ /**
1464
+ * Execute a request with cursor-based pagination
1465
+ */
1466
+ async requestWithPagination(method, path, paginationOptions, options) {
1467
+ const paginationType = options.pagination.paginationType;
1468
+ // Validate and prepare pagination parameters
1469
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1470
+ // Prepare request parameters based on pagination type
1471
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1472
+ // Route pagination state to wherever the API expects it (body for POST, URL for GET).
1473
+ // Caller-supplied options.body / options.params are respected as-is — the api-client
1474
+ // already handles params (URL) and body (request body) independently for every method.
1475
+ if (method.toUpperCase() === 'POST') {
1476
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1477
+ options.body = {
1478
+ ...existingBody,
1479
+ ...requestParams
1480
+ };
1481
+ }
1482
+ else {
1483
+ options.params = {
1484
+ ...options.params,
1485
+ ...requestParams
1486
+ };
1487
+ }
1488
+ // Make the request
1489
+ const response = await this.request(method, path, options);
1490
+ // Extract data from the response and create page result
1491
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1492
+ itemsField: options.pagination.itemsField,
1493
+ totalCountField: options.pagination.totalCountField,
1494
+ continuationTokenField: options.pagination.continuationTokenField
1495
+ });
1496
+ }
1497
+ /**
1498
+ * Validates and prepares pagination parameters from options
1499
+ */
1500
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1501
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1502
+ }
1503
+ /**
1504
+ * Prepares request parameters for pagination based on pagination type
1505
+ */
1506
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1507
+ const requestParams = {};
1508
+ let limitedPageSize;
1509
+ const paginationParams = paginationConfig?.paginationParams;
1510
+ switch (paginationType) {
1511
+ case PaginationType.OFFSET:
1512
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1513
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1514
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1515
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1516
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1517
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1518
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1519
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
1520
+ const zeroBased = paginationParams?.zeroBased ?? false;
1521
+ requestParams[pageSizeParam] = limitedPageSize;
1522
+ if (convertToSkip) {
1523
+ if (params.pageNumber && params.pageNumber > 1) {
1524
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1525
+ }
1526
+ }
1527
+ else {
1528
+ const sdkPageNumber = params.pageNumber || 1;
1529
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
1530
+ }
1531
+ {
1532
+ requestParams[countParam] = true;
1533
+ }
1534
+ break;
1535
+ case PaginationType.TOKEN:
1536
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1537
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1538
+ if (params.pageSize) {
1539
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1540
+ }
1541
+ if (params.continuationToken) {
1542
+ requestParams[tokenParam] = params.continuationToken;
1543
+ }
1544
+ break;
1545
+ }
1546
+ return requestParams;
1547
+ }
1548
+ /**
1549
+ * Creates a paginated response from API response
1550
+ */
1551
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1552
+ // Extract fields from response
1553
+ const itemsField = fields.itemsField ||
1554
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1555
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1556
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1557
+ // Extract items and metadata
1558
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1559
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1560
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
1561
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1562
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1563
+ const continuationToken = response.data[continuationTokenField];
1564
+ // Determine if there are more pages
1565
+ const hasMore = this.determineHasMorePages(paginationType, {
1566
+ totalCount,
1567
+ pageSize: params.pageSize,
1568
+ currentPage: params.pageNumber || 1,
1569
+ itemsCount: items.length,
1570
+ continuationToken
1571
+ });
1572
+ // Create and return the page result
1573
+ return PaginationManager.createPaginatedResponse({
1574
+ pageInfo: {
1575
+ hasMore,
1576
+ totalCount,
1577
+ currentPage: params.pageNumber,
1578
+ pageSize: params.pageSize,
1579
+ continuationToken
1580
+ },
1581
+ type: paginationType,
1582
+ }, items);
1583
+ }
1584
+ /**
1585
+ * Determines if there are more pages based on pagination type and metadata
1586
+ */
1587
+ determineHasMorePages(paginationType, info) {
1588
+ switch (paginationType) {
1589
+ case PaginationType.OFFSET:
1590
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1591
+ // If totalCount is available, use it for precise calculation
1592
+ if (info.totalCount !== undefined) {
1593
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1594
+ }
1595
+ // Fallback when totalCount is not available
1596
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1597
+ return info.itemsCount === effectivePageSize;
1598
+ case PaginationType.TOKEN:
1599
+ return !!info.continuationToken;
1600
+ default:
1601
+ return false;
1602
+ }
1603
+ }
1604
+ }
1605
+ _BaseService_apiClient = new WeakMap();
1606
+
1607
+ /**
1608
+ * Base path constants for different services
1609
+ */
1610
+ const INSIGHTS_RTM_BASE = 'insightsrtm_';
1611
+
1612
+ /**
1613
+ * Agent Service Endpoints
1614
+ */
1615
+ const AGENTS_ENDPOINTS = {
1616
+ /** Paginated list of agents with consumption and health metadata. */
1617
+ GET_AGENTS: `${INSIGHTS_RTM_BASE}/Agents/agents`,
1618
+ /** Paginated list of agent incidents (errors) over the requested window. */
1619
+ GET_INCIDENTS: `${INSIGHTS_RTM_BASE}/Agents/incidents`,
1620
+ /** Time-series of error counts grouped by agent over the requested window. */
1621
+ GET_ERRORS_TIMELINE: `${INSIGHTS_RTM_BASE}/Agents/errors`,
1622
+ /** Time-series of AGU consumption over the requested window. */
1623
+ GET_CONSUMPTION_TIMELINE: `${INSIGHTS_RTM_BASE}/Agents/consumptionTimeline`,
1624
+ /** Time-series of agent latency (per-percentile) over the requested window. */
1625
+ GET_LATENCY_TIMELINE: `${INSIGHTS_RTM_BASE}/Agents/latencyTimeline`,
1626
+ };
1627
+
1628
+ /**
1629
+ * SDK Telemetry constants.
1630
+ *
1631
+ * Only the SDK's identity (version, service name, role name, …) lives
1632
+ * here. The Application Insights connection string is injected into
1633
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
1634
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
1635
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
1636
+ * SDK's public API.
1637
+ */
1638
+ /** SDK version placeholder — patched by the SDK publish workflow. */
1639
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
1640
+
1641
+ /**
1642
+ * UiPath TypeScript SDK Telemetry
1643
+ *
1644
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
1645
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
1646
+ * does this independently, so events carry their own consumer's identity
1647
+ * and tenant context.
1648
+ */
1649
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
1650
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
1651
+ // from the `UiPath` constructor therefore wires up `@track` decorators
1652
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
1653
+ const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
1654
+ const track = coreTelemetry.createTrack(sdkClient);
1655
+ coreTelemetry.createTrackEvent(sdkClient);
1656
+
1657
+ /**
1658
+ * Service for interacting with the UiPath Agents API.
1659
+ */
1660
+ class AgentService extends BaseService {
1661
+ /**
1662
+ * Retrieves the list of agents on the tenant with consumption and health
1663
+ * metadata over the requested window.
1664
+ *
1665
+ * Returns a {@link PaginatedResponse} when pagination options (`pageSize`,
1666
+ * `cursor`, or `jumpToPage`) are provided, otherwise a
1667
+ * {@link NonPaginatedResponse}.
1668
+ *
1669
+ * @param startTime - Inclusive lower bound for the query window
1670
+ * @param endTime - Exclusive upper bound for the query window
1671
+ * @param options - Optional pagination, sort, and filters
1672
+ * @returns Promise resolving to a paginated or non-paginated list of {@link AgentListItem}
1673
+ * @example
1674
+ * ```typescript
1675
+ * import { Agents, AgentListSortColumn } from '@uipath/uipath-typescript/agents';
1676
+ *
1677
+ * const agents = new Agents(sdk);
1678
+ *
1679
+ * // Non-paginated — returns the server default page
1680
+ * const result = await agents.getAll(
1681
+ * new Date('2025-05-01T00:00:00Z'),
1682
+ * new Date('2026-05-14T00:00:00Z'),
1683
+ * );
1684
+ * result.items.forEach((agent) => {
1685
+ * console.log(`${agent.agentName} — ${agent.unitsQuantity} units, health=${agent.healthScore}`);
1686
+ * });
1687
+ *
1688
+ * // Paginated — sorted by health score descending
1689
+ * const page = await agents.getAll(
1690
+ * new Date('2025-05-01T00:00:00Z'),
1691
+ * new Date('2026-05-14T00:00:00Z'),
1692
+ * {
1693
+ * pageSize: 25,
1694
+ * orderBy: { column: AgentListSortColumn.HealthScore, desc: true },
1695
+ * folderKeys: ['<folderKey1>'],
1696
+ * },
1697
+ * );
1698
+ *
1699
+ * if (page.hasNextPage && page.nextCursor) {
1700
+ * const next = await agents.getAll(
1701
+ * new Date('2025-05-01T00:00:00Z'),
1702
+ * new Date('2026-05-14T00:00:00Z'),
1703
+ * { cursor: page.nextCursor },
1704
+ * );
1705
+ * }
1706
+ * ```
1707
+ */
1708
+ async getAll(startTime, endTime, options) {
1709
+ const apiOptions = { ...options, startTime: startTime.toISOString(), endTime: endTime.toISOString() };
1710
+ return PaginationHelpers.getAll({
1711
+ serviceAccess: this.createPaginationServiceAccess(),
1712
+ getEndpoint: () => AGENTS_ENDPOINTS.GET_AGENTS,
1713
+ method: HTTP_METHODS.POST,
1714
+ excludeFromPrefix: Object.keys(apiOptions),
1715
+ pagination: {
1716
+ paginationType: PaginationType.OFFSET,
1717
+ itemsField: AGENTS_PAGINATION.ITEMS_FIELD,
1718
+ totalCountField: AGENTS_PAGINATION.TOTAL_COUNT_FIELD,
1719
+ paginationParams: {
1720
+ pageSizeParam: AGENTS_OFFSET_PARAMS.PAGE_SIZE_PARAM,
1721
+ offsetParam: AGENTS_OFFSET_PARAMS.OFFSET_PARAM,
1722
+ countParam: AGENTS_OFFSET_PARAMS.COUNT_PARAM,
1723
+ convertToSkip: false,
1724
+ zeroBased: true,
1725
+ },
1726
+ },
1727
+ }, apiOptions);
1728
+ }
1729
+ /**
1730
+ * Retrieves agent errors (error-classes observed for agents) over the
1731
+ * requested window.
1732
+ *
1733
+ * Returns a {@link PaginatedResponse} when pagination options (`pageSize`,
1734
+ * `cursor`, or `jumpToPage`) are provided, otherwise a
1735
+ * {@link NonPaginatedResponse}.
1736
+ *
1737
+ * @param startTime - Inclusive lower bound for the query window
1738
+ * @param endTime - Exclusive upper bound for the query window
1739
+ * @param options - Optional pagination, sort/group, and filters
1740
+ * @returns Promise resolving to a paginated or non-paginated list of {@link AgentError}
1741
+ * @example
1742
+ * ```typescript
1743
+ * import { Agents, AgentErrorSortColumn } from '@uipath/uipath-typescript/agents';
1744
+ *
1745
+ * const agents = new Agents(sdk);
1746
+ *
1747
+ * // Non-paginated — errors in the window
1748
+ * const result = await agents.getErrors(
1749
+ * new Date('2025-05-01T00:00:00Z'),
1750
+ * new Date('2026-05-14T00:00:00Z'),
1751
+ * );
1752
+ * result.items.forEach((error) => {
1753
+ * console.log(`${error.type}: ${error.description} (count=${error.count})`);
1754
+ * });
1755
+ *
1756
+ * // Paginated — sorted by execution count descending
1757
+ * const page = await agents.getErrors(
1758
+ * new Date('2025-05-01T00:00:00Z'),
1759
+ * new Date('2026-05-14T00:00:00Z'),
1760
+ * {
1761
+ * pageSize: 25,
1762
+ * orderBy: { column: AgentErrorSortColumn.ExecutionCount, desc: true },
1763
+ * },
1764
+ * );
1765
+ *
1766
+ * if (page.hasNextPage && page.nextCursor) {
1767
+ * const next = await agents.getErrors(
1768
+ * new Date('2025-05-01T00:00:00Z'),
1769
+ * new Date('2026-05-14T00:00:00Z'),
1770
+ * { cursor: page.nextCursor },
1771
+ * );
1772
+ * }
1773
+ * ```
1774
+ */
1775
+ async getErrors(startTime, endTime, options) {
1776
+ const apiOptions = { ...options, startTime: startTime.toISOString(), endTime: endTime.toISOString() };
1777
+ return PaginationHelpers.getAll({
1778
+ serviceAccess: this.createPaginationServiceAccess(),
1779
+ getEndpoint: () => AGENTS_ENDPOINTS.GET_INCIDENTS,
1780
+ method: HTTP_METHODS.POST,
1781
+ excludeFromPrefix: Object.keys(apiOptions),
1782
+ pagination: {
1783
+ paginationType: PaginationType.OFFSET,
1784
+ itemsField: AGENTS_INCIDENTS_PAGINATION.ITEMS_FIELD,
1785
+ totalCountField: AGENTS_INCIDENTS_PAGINATION.TOTAL_COUNT_FIELD,
1786
+ paginationParams: {
1787
+ pageSizeParam: AGENTS_OFFSET_PARAMS.PAGE_SIZE_PARAM,
1788
+ offsetParam: AGENTS_OFFSET_PARAMS.OFFSET_PARAM,
1789
+ countParam: AGENTS_OFFSET_PARAMS.COUNT_PARAM,
1790
+ convertToSkip: false,
1791
+ zeroBased: true,
1792
+ },
1793
+ },
1794
+ }, apiOptions);
1795
+ }
1796
+ /**
1797
+ * Retrieves a time-series of error counts grouped by agent over the requested window.
1798
+ *
1799
+ * @param startTime - Inclusive lower bound for the query window
1800
+ * @param endTime - Exclusive upper bound for the query window
1801
+ * @param options - Optional filters
1802
+ * @returns Promise resolving to an array of {@link AgentGetErrorsTimelineResponse}
1803
+ * @example
1804
+ * ```typescript
1805
+ * import { Agents } from '@uipath/uipath-typescript/agents';
1806
+ *
1807
+ * const agents = new Agents(sdk);
1808
+ *
1809
+ * // All errors in May 2025
1810
+ * const result = await agents.getErrorsTimeline(
1811
+ * new Date('2025-05-01T00:00:00Z'),
1812
+ * new Date('2025-06-01T00:00:00Z'),
1813
+ * );
1814
+ * result.forEach((point) => {
1815
+ * console.log(`${point.date} ${point.name}: ${point.value} errors`);
1816
+ * });
1817
+ * ```
1818
+ * @example
1819
+ * ```typescript
1820
+ * // Scope to specific folders and top 5 agents
1821
+ * const result = await agents.getErrorsTimeline(
1822
+ * new Date('2025-05-01T00:00:00Z'),
1823
+ * new Date('2025-06-01T00:00:00Z'),
1824
+ * {
1825
+ * folderKeys: ['<folderKey1>'],
1826
+ * agentNames: ['JokeAgent', 'StoryAgent'],
1827
+ * limit: 5,
1828
+ * },
1829
+ * );
1830
+ * ```
1831
+ */
1832
+ async getErrorsTimeline(startTime, endTime, options) {
1833
+ const body = this.buildAgentFilterBody(startTime, endTime, options);
1834
+ const response = await this.post(AGENTS_ENDPOINTS.GET_ERRORS_TIMELINE, body);
1835
+ return response.data.data;
1836
+ }
1837
+ /**
1838
+ * Retrieves a time-series of AGU (Agent Units) consumption over the requested window.
1839
+ *
1840
+ * @param startTime - Inclusive lower bound for the query window
1841
+ * @param endTime - Exclusive upper bound for the query window
1842
+ * @param options - Optional filters
1843
+ * @returns Promise resolving to an array of {@link AgentGetConsumptionTimelineResponse}
1844
+ * @example
1845
+ * ```typescript
1846
+ * import { Agents } from '@uipath/uipath-typescript/agents';
1847
+ *
1848
+ * const agents = new Agents(sdk);
1849
+ *
1850
+ * // AGU consumption timeline in May 2025
1851
+ * const result = await agents.getConsumptionTimeline(
1852
+ * new Date('2025-05-01T00:00:00Z'),
1853
+ * new Date('2025-06-01T00:00:00Z'),
1854
+ * );
1855
+ * result.forEach((point) => {
1856
+ * console.log(`${point.timeSlice}: ${point.aguConsumption} AGU`);
1857
+ * });
1858
+ * ```
1859
+ * @example
1860
+ * ```typescript
1861
+ * // Scope to specific folders and agents
1862
+ * const result = await agents.getConsumptionTimeline(
1863
+ * new Date('2025-05-01T00:00:00Z'),
1864
+ * new Date('2025-06-01T00:00:00Z'),
1865
+ * {
1866
+ * folderKeys: ['<folderKey1>'],
1867
+ * agentNames: ['JokeAgent'],
1868
+ * },
1869
+ * );
1870
+ * ```
1871
+ */
1872
+ async getConsumptionTimeline(startTime, endTime, options) {
1873
+ const body = this.buildAgentFilterBody(startTime, endTime, options);
1874
+ const response = await this.post(AGENTS_ENDPOINTS.GET_CONSUMPTION_TIMELINE, body);
1875
+ return response.data.data;
1876
+ }
1877
+ /**
1878
+ * Retrieves a time-series of agent latency (milliseconds) over the requested
1879
+ * window.
1880
+ *
1881
+ * @param startTime - Inclusive lower bound for the query window
1882
+ * @param endTime - Exclusive upper bound for the query window
1883
+ * @param options - Optional filters
1884
+ * @returns Promise resolving to an array of {@link AgentGetLatencyTimelineResponse}
1885
+ * @example
1886
+ * ```typescript
1887
+ * import { Agents } from '@uipath/uipath-typescript/agents';
1888
+ *
1889
+ * const agents = new Agents(sdk);
1890
+ *
1891
+ * // Latency timeline in May 2025
1892
+ * const result = await agents.getLatencyTimeline(
1893
+ * new Date('2025-05-01T00:00:00Z'),
1894
+ * new Date('2025-06-01T00:00:00Z'),
1895
+ * );
1896
+ * result.forEach((point) => {
1897
+ * console.log(`${point.date} ${point.name}: ${point.value} ms`);
1898
+ * });
1899
+ * ```
1900
+ * @example
1901
+ * ```typescript
1902
+ * // Scope to specific folders and a single agent
1903
+ * const result = await agents.getLatencyTimeline(
1904
+ * new Date('2025-05-01T00:00:00Z'),
1905
+ * new Date('2025-06-01T00:00:00Z'),
1906
+ * {
1907
+ * folderKeys: ['<folderKey1>'],
1908
+ * agentId: '<agentId>',
1909
+ * },
1910
+ * );
1911
+ * ```
1912
+ */
1913
+ async getLatencyTimeline(startTime, endTime, options) {
1914
+ const body = this.buildAgentFilterBody(startTime, endTime, options);
1915
+ const response = await this.post(AGENTS_ENDPOINTS.GET_LATENCY_TIMELINE, body);
1916
+ return response.data.data;
1917
+ }
1918
+ /**
1919
+ * Builds the common POST request body shared by the agent filter endpoints —
1920
+ * the required time window plus any optional folder/agent/project/process
1921
+ * filters. Undefined options are omitted so the server applies its defaults.
1922
+ */
1923
+ buildAgentFilterBody(startTime, endTime, options) {
1924
+ const body = {
1925
+ startTime: startTime.toISOString(),
1926
+ endTime: endTime.toISOString(),
1927
+ };
1928
+ if (options?.folderKeys !== undefined)
1929
+ body.folderKeys = options.folderKeys;
1930
+ if (options?.agentNames !== undefined)
1931
+ body.agentNames = options.agentNames;
1932
+ if (options?.projectKeys !== undefined)
1933
+ body.projectKeys = options.projectKeys;
1934
+ if (options?.agentId !== undefined)
1935
+ body.agentId = options.agentId;
1936
+ if (options?.processVersion !== undefined)
1937
+ body.processVersion = options.processVersion;
1938
+ if (options?.limit !== undefined)
1939
+ body.limit = options.limit;
1940
+ return body;
1941
+ }
1942
+ }
1943
+ __decorate([
1944
+ track('Agents.GetAll')
1945
+ ], AgentService.prototype, "getAll", null);
1946
+ __decorate([
1947
+ track('Agents.GetErrors')
1948
+ ], AgentService.prototype, "getErrors", null);
1949
+ __decorate([
1950
+ track('Agents.GetErrorsTimeline')
1951
+ ], AgentService.prototype, "getErrorsTimeline", null);
1952
+ __decorate([
1953
+ track('Agents.GetConsumptionTimeline')
1954
+ ], AgentService.prototype, "getConsumptionTimeline", null);
1955
+ __decorate([
1956
+ track('Agents.GetLatencyTimeline')
1957
+ ], AgentService.prototype, "getLatencyTimeline", null);
1958
+
1959
+ /**
1960
+ * Columns available for ordering results.
1961
+ */
1962
+ exports.AgentListSortColumn = void 0;
1963
+ (function (AgentListSortColumn) {
1964
+ AgentListSortColumn["AgentName"] = "AgentName";
1965
+ AgentListSortColumn["ParentProcess"] = "ParentProcess";
1966
+ AgentListSortColumn["LastRun"] = "LastRun";
1967
+ AgentListSortColumn["HealthScore"] = "HealthScore";
1968
+ AgentListSortColumn["LastIncident"] = "LastIncident";
1969
+ AgentListSortColumn["FolderName"] = "FolderName";
1970
+ /** Quantity of AGU (Agent Units) consumed */
1971
+ AgentListSortColumn["QuantityAGU"] = "QuantityAGU";
1972
+ /** Quantity of PLTU (Platform Units) consumed */
1973
+ AgentListSortColumn["QuantityPLTU"] = "QuantityPLTU";
1974
+ AgentListSortColumn["FolderPath"] = "FolderPath";
1975
+ })(exports.AgentListSortColumn || (exports.AgentListSortColumn = {}));
1976
+ /**
1977
+ * Columns available for ordering / grouping the agent errors list.
1978
+ */
1979
+ exports.AgentErrorSortColumn = void 0;
1980
+ (function (AgentErrorSortColumn) {
1981
+ AgentErrorSortColumn["AgentId"] = "AgentId";
1982
+ AgentErrorSortColumn["AgentName"] = "AgentName";
1983
+ AgentErrorSortColumn["ParentProcessName"] = "ParentProcessName";
1984
+ AgentErrorSortColumn["ErrorTitle"] = "ErrorTitle";
1985
+ AgentErrorSortColumn["FirstSeenStartTime"] = "FirstSeenStartTime";
1986
+ AgentErrorSortColumn["ExecutionCount"] = "ExecutionCount";
1987
+ AgentErrorSortColumn["Type"] = "Type";
1988
+ AgentErrorSortColumn["FirstSeenFolderName"] = "FirstSeenFolderName";
1989
+ AgentErrorSortColumn["FirstSeenFolderPath"] = "FirstSeenFolderPath";
1990
+ AgentErrorSortColumn["LastSeenStartTime"] = "LastSeenStartTime";
1991
+ AgentErrorSortColumn["LastSeenFolderName"] = "LastSeenFolderName";
1992
+ AgentErrorSortColumn["LastSeenFolderPath"] = "LastSeenFolderPath";
1993
+ })(exports.AgentErrorSortColumn || (exports.AgentErrorSortColumn = {}));
1994
+
1995
+ exports.Agents = AgentService;