@uipath/uipath-typescript 1.3.11 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/agent-memory/index.cjs +1765 -0
  2. package/dist/agent-memory/index.d.ts +588 -0
  3. package/dist/agent-memory/index.mjs +1763 -0
  4. package/dist/agents/index.cjs +1726 -0
  5. package/dist/agents/index.d.ts +502 -0
  6. package/dist/agents/index.mjs +1724 -0
  7. package/dist/assets/index.cjs +155 -30
  8. package/dist/assets/index.d.ts +84 -5
  9. package/dist/assets/index.mjs +155 -30
  10. package/dist/attachments/index.cjs +37 -6
  11. package/dist/attachments/index.d.ts +1 -0
  12. package/dist/attachments/index.mjs +37 -6
  13. package/dist/buckets/index.cjs +37 -6
  14. package/dist/buckets/index.d.ts +1 -0
  15. package/dist/buckets/index.mjs +37 -6
  16. package/dist/cases/index.cjs +141 -10
  17. package/dist/cases/index.d.ts +118 -7
  18. package/dist/cases/index.mjs +141 -11
  19. package/dist/conversational-agent/index.cjs +124 -57
  20. package/dist/conversational-agent/index.d.ts +190 -122
  21. package/dist/conversational-agent/index.mjs +124 -57
  22. package/dist/core/index.cjs +413 -105
  23. package/dist/core/index.d.ts +15 -0
  24. package/dist/core/index.mjs +413 -105
  25. package/dist/entities/index.cjs +122 -43
  26. package/dist/entities/index.d.ts +140 -35
  27. package/dist/entities/index.mjs +122 -43
  28. package/dist/feedback/index.cjs +37 -6
  29. package/dist/feedback/index.d.ts +1 -0
  30. package/dist/feedback/index.mjs +37 -6
  31. package/dist/governance/index.cjs +1782 -0
  32. package/dist/governance/index.d.ts +598 -0
  33. package/dist/governance/index.mjs +1780 -0
  34. package/dist/index.cjs +956 -283
  35. package/dist/index.d.ts +1138 -121
  36. package/dist/index.mjs +956 -284
  37. package/dist/index.umd.js +3113 -2423
  38. package/dist/jobs/index.cjs +37 -6
  39. package/dist/jobs/index.d.ts +1 -0
  40. package/dist/jobs/index.mjs +37 -6
  41. package/dist/maestro-processes/index.cjs +173 -18
  42. package/dist/maestro-processes/index.d.ts +131 -9
  43. package/dist/maestro-processes/index.mjs +173 -18
  44. package/dist/processes/index.cjs +37 -6
  45. package/dist/processes/index.d.ts +1 -0
  46. package/dist/processes/index.mjs +37 -6
  47. package/dist/queues/index.cjs +37 -6
  48. package/dist/queues/index.d.ts +1 -0
  49. package/dist/queues/index.mjs +37 -6
  50. package/dist/tasks/index.cjs +37 -6
  51. package/dist/tasks/index.d.ts +1 -0
  52. package/dist/tasks/index.mjs +37 -6
  53. package/dist/traces/index.cjs +37 -6
  54. package/dist/traces/index.d.ts +1 -0
  55. package/dist/traces/index.mjs +37 -6
  56. package/package.json +32 -2
@@ -0,0 +1,1782 @@
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
+ * Governance pagination constants for page-number-based pagination
924
+ */
925
+ const GOVERNANCE_PAGINATION = {
926
+ /** Field name for items in governance response */
927
+ ITEMS_FIELD: 'items'
928
+ };
929
+ /**
930
+ * Governance OFFSET pagination parameter names (page-number style, 0-based, no skip conversion)
931
+ */
932
+ const GOVERNANCE_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
+ * OData OFFSET pagination parameter names (ODATA-style)
942
+ */
943
+ const ODATA_OFFSET_PARAMS = {
944
+ /** OData page size parameter name */
945
+ PAGE_SIZE_PARAM: '$top',
946
+ /** OData offset parameter name */
947
+ OFFSET_PARAM: '$skip',
948
+ /** OData count parameter name */
949
+ COUNT_PARAM: '$count'
950
+ };
951
+ /**
952
+ * Bucket TOKEN pagination parameter names
953
+ */
954
+ const BUCKET_TOKEN_PARAMS = {
955
+ /** Bucket page size parameter name */
956
+ PAGE_SIZE_PARAM: 'takeHint',
957
+ /** Bucket token parameter name */
958
+ TOKEN_PARAM: 'continuationToken'
959
+ };
960
+
961
+ /**
962
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
963
+ * Returns the original value if parsing fails.
964
+ */
965
+ /**
966
+ * Adds a prefix to specified keys in an object, returning a new object.
967
+ * Only the provided keys are prefixed; all others are left unchanged.
968
+ *
969
+ * @param obj The source object
970
+ * @param prefix The prefix to add (e.g., '$')
971
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
972
+ * @returns A new object with specified keys prefixed
973
+ *
974
+ * @example
975
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
976
+ */
977
+ function addPrefixToKeys(obj, prefix, keys) {
978
+ const result = {};
979
+ for (const [key, value] of Object.entries(obj)) {
980
+ if (keys.includes(key)) {
981
+ result[`${prefix}${key}`] = value;
982
+ }
983
+ else {
984
+ result[key] = value;
985
+ }
986
+ }
987
+ return result;
988
+ }
989
+
990
+ /**
991
+ * Constants used throughout the pagination system
992
+ */
993
+ /** Maximum number of items that can be requested in a single page */
994
+ const MAX_PAGE_SIZE = 1000;
995
+ /** Default page size when jumpToPage is used without specifying pageSize */
996
+ const DEFAULT_PAGE_SIZE = 50;
997
+ /** Default field name for items in a paginated response */
998
+ const DEFAULT_ITEMS_FIELD = 'value';
999
+ /** Default field name for total count in a paginated response */
1000
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1001
+ /**
1002
+ * Limits the page size to the maximum allowed value
1003
+ * @param pageSize - Requested page size
1004
+ * @returns Limited page size value
1005
+ */
1006
+ function getLimitedPageSize(pageSize) {
1007
+ if (pageSize === undefined || pageSize === null) {
1008
+ return DEFAULT_PAGE_SIZE;
1009
+ }
1010
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1011
+ }
1012
+
1013
+ /**
1014
+ * Helper functions for pagination that can be used across services
1015
+ */
1016
+ class PaginationHelpers {
1017
+ /**
1018
+ * Checks if any pagination parameters are provided
1019
+ *
1020
+ * @param options - The options object to check
1021
+ * @returns True if any pagination parameter is defined, false otherwise
1022
+ */
1023
+ static hasPaginationParameters(options = {}) {
1024
+ const { cursor, pageSize, jumpToPage } = options;
1025
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1026
+ }
1027
+ /**
1028
+ * Parse a pagination cursor string into cursor data
1029
+ */
1030
+ static parseCursor(cursorString) {
1031
+ try {
1032
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1033
+ return cursorData;
1034
+ }
1035
+ catch {
1036
+ throw new Error('Invalid pagination cursor');
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Validates cursor format and structure
1041
+ *
1042
+ * @param paginationOptions - The pagination options containing the cursor
1043
+ * @param paginationType - Optional pagination type to validate against
1044
+ */
1045
+ static validateCursor(paginationOptions, paginationType) {
1046
+ if (paginationOptions.cursor !== undefined) {
1047
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1048
+ throw new Error('cursor must contain a valid cursor string');
1049
+ }
1050
+ try {
1051
+ // Try to parse the cursor to validate it
1052
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1053
+ // If type is provided, validate cursor contains expected type information
1054
+ if (paginationType) {
1055
+ if (!cursorData.type) {
1056
+ throw new Error('Invalid cursor: missing pagination type');
1057
+ }
1058
+ // Check pagination type compatibility
1059
+ if (cursorData.type !== paginationType) {
1060
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1061
+ }
1062
+ }
1063
+ }
1064
+ catch (error) {
1065
+ if (error instanceof Error) {
1066
+ // If it's already our error with specific message, pass it through
1067
+ if (error.message.startsWith('Invalid cursor') ||
1068
+ error.message.startsWith('Pagination type mismatch')) {
1069
+ throw error;
1070
+ }
1071
+ }
1072
+ throw new Error('Invalid pagination cursor format');
1073
+ }
1074
+ }
1075
+ }
1076
+ /**
1077
+ * Comprehensive validation for pagination options
1078
+ *
1079
+ * @param options - The pagination options to validate
1080
+ * @param paginationType - The pagination type these options will be used with
1081
+ * @returns Processed pagination parameters ready for use
1082
+ */
1083
+ static validatePaginationOptions(options, paginationType) {
1084
+ // Validate pageSize
1085
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1086
+ throw new Error('pageSize must be a positive number');
1087
+ }
1088
+ // Validate jumpToPage
1089
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1090
+ throw new Error('jumpToPage must be a positive number');
1091
+ }
1092
+ // Validate cursor
1093
+ PaginationHelpers.validateCursor(options, paginationType);
1094
+ // Validate service compatibility
1095
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1096
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1097
+ }
1098
+ // Get processed parameters
1099
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1100
+ }
1101
+ /**
1102
+ * Convert a unified pagination options to service-specific parameters
1103
+ */
1104
+ static getRequestParameters(options, paginationType) {
1105
+ // Handle jumpToPage
1106
+ if (options.jumpToPage !== undefined) {
1107
+ const jumpToPageOptions = {
1108
+ pageSize: options.pageSize,
1109
+ pageNumber: options.jumpToPage
1110
+ };
1111
+ return filterUndefined(jumpToPageOptions);
1112
+ }
1113
+ // If no cursor is provided, it's a first page request
1114
+ if (!options.cursor) {
1115
+ const firstPageOptions = {
1116
+ pageSize: options.pageSize,
1117
+ // Only set pageNumber for OFFSET pagination
1118
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1119
+ };
1120
+ return filterUndefined(firstPageOptions);
1121
+ }
1122
+ // Parse the cursor
1123
+ try {
1124
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1125
+ const cursorBasedOptions = {
1126
+ pageSize: cursorData.pageSize || options.pageSize,
1127
+ pageNumber: cursorData.pageNumber,
1128
+ continuationToken: cursorData.continuationToken,
1129
+ type: cursorData.type,
1130
+ };
1131
+ return filterUndefined(cursorBasedOptions);
1132
+ }
1133
+ catch {
1134
+ throw new Error('Invalid pagination cursor');
1135
+ }
1136
+ }
1137
+ /**
1138
+ * Helper method for paginated resource retrieval
1139
+ *
1140
+ * @param params - Parameters for pagination
1141
+ * @returns Promise resolving to a paginated result
1142
+ */
1143
+ static async getAllPaginated(params) {
1144
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1145
+ const endpoint = getEndpoint(folderId);
1146
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1147
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1148
+ headers,
1149
+ params: additionalParams,
1150
+ pagination: {
1151
+ paginationType: options.paginationType || PaginationType.OFFSET,
1152
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1153
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1154
+ continuationTokenField: options.continuationTokenField,
1155
+ paginationParams: options.paginationParams
1156
+ }
1157
+ });
1158
+ // Parse items - automatically handle JSON string responses
1159
+ const rawItems = paginatedResponse.items;
1160
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1161
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1162
+ return {
1163
+ ...paginatedResponse,
1164
+ items: transformedItems
1165
+ };
1166
+ }
1167
+ /**
1168
+ * Helper method for non-paginated resource retrieval
1169
+ *
1170
+ * @param params - Parameters for non-paginated resource retrieval
1171
+ * @returns Promise resolving to an object with data and totalCount
1172
+ */
1173
+ static async getAllNonPaginated(params) {
1174
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1175
+ // Set default field names
1176
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1177
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1178
+ // Determine endpoint and headers based on folderId
1179
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1180
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1181
+ // Make the API call based on method
1182
+ let response;
1183
+ if (method === HTTP_METHODS.POST) {
1184
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1185
+ }
1186
+ else {
1187
+ response = await serviceAccess.get(endpoint, {
1188
+ params: additionalParams,
1189
+ headers
1190
+ });
1191
+ }
1192
+ // Extract and transform items from response
1193
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1194
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1195
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
1196
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1197
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1198
+ // Parse items - automatically handle JSON string responses
1199
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1200
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1201
+ return {
1202
+ items,
1203
+ totalCount
1204
+ };
1205
+ }
1206
+ /**
1207
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1208
+ *
1209
+ * @param config - Configuration for the getAll operation
1210
+ * @param options - Request options including pagination parameters
1211
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1212
+ */
1213
+ static async getAll(config, options) {
1214
+ const optionsWithDefaults = options || {};
1215
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1216
+ // Determine if pagination is requested
1217
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1218
+ // Process parameters (custom processing if provided, otherwise default)
1219
+ let processedOptions = restOptions;
1220
+ if (config.processParametersFn) {
1221
+ processedOptions = config.processParametersFn(restOptions, folderId);
1222
+ }
1223
+ // Apply ODATA prefix to keys (excluding specified keys)
1224
+ const excludeKeys = config.excludeFromPrefix || [];
1225
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1226
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1227
+ // Default pagination options
1228
+ const paginationOptions = {
1229
+ paginationType: PaginationType.OFFSET,
1230
+ itemsField: DEFAULT_ITEMS_FIELD,
1231
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1232
+ ...config.pagination
1233
+ };
1234
+ // Paginated flow
1235
+ if (isPaginationRequested) {
1236
+ return PaginationHelpers.getAllPaginated({
1237
+ serviceAccess: config.serviceAccess,
1238
+ getEndpoint: config.getEndpoint,
1239
+ folderId,
1240
+ headers: config.headers,
1241
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
1242
+ additionalParams: prefixedOptions,
1243
+ transformFn: config.transformFn,
1244
+ method: config.method,
1245
+ options: {
1246
+ ...paginationOptions,
1247
+ paginationParams: config.pagination?.paginationParams
1248
+ }
1249
+ }); // Type assertion needed due to conditional return
1250
+ }
1251
+ // Non-paginated flow
1252
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1253
+ return PaginationHelpers.getAllNonPaginated({
1254
+ serviceAccess: config.serviceAccess,
1255
+ getAllEndpoint: config.getEndpoint(),
1256
+ getByFolderEndpoint: byFolderEndpoint,
1257
+ folderId,
1258
+ headers: config.headers,
1259
+ additionalParams: prefixedOptions,
1260
+ transformFn: config.transformFn,
1261
+ method: config.method,
1262
+ options: {
1263
+ itemsField: paginationOptions.itemsField,
1264
+ totalCountField: paginationOptions.totalCountField
1265
+ }
1266
+ });
1267
+ }
1268
+ }
1269
+
1270
+ /**
1271
+ * SDK Internals Registry - Internal registry for SDK instances
1272
+ *
1273
+ * This class is NOT exported in the public API.
1274
+ * It provides a secure way to share SDK internals between
1275
+ * the UiPath class and service classes without exposing them publicly.
1276
+ *
1277
+ * @internal
1278
+ */
1279
+ // Global symbol key to ensure WeakMap is shared across module instances
1280
+ // This prevents issues when core and service modules are bundled separately
1281
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1282
+ // Get or create the global WeakMap store
1283
+ const getGlobalStore = () => {
1284
+ const globalObj = globalThis;
1285
+ if (!globalObj[REGISTRY_KEY]) {
1286
+ globalObj[REGISTRY_KEY] = new WeakMap();
1287
+ }
1288
+ return globalObj[REGISTRY_KEY];
1289
+ };
1290
+ /**
1291
+ * Internal registry for SDK private components.
1292
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1293
+ * garbage collected when the SDK instance is no longer referenced.
1294
+ *
1295
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1296
+ * across separately bundled modules (core, entities, tasks, etc.).
1297
+ *
1298
+ * @internal - Not exported in public API
1299
+ */
1300
+ class SDKInternalsRegistry {
1301
+ // Use global store to ensure sharing across module bundles
1302
+ static get store() {
1303
+ return getGlobalStore();
1304
+ }
1305
+ /**
1306
+ * Register SDK instance internals
1307
+ * Called by UiPath constructor
1308
+ */
1309
+ static set(instance, internals) {
1310
+ this.store.set(instance, internals);
1311
+ }
1312
+ /**
1313
+ * Retrieve SDK instance internals
1314
+ * Called by BaseService constructor
1315
+ */
1316
+ static get(instance) {
1317
+ const internals = this.store.get(instance);
1318
+ if (!internals) {
1319
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1320
+ }
1321
+ return internals;
1322
+ }
1323
+ }
1324
+
1325
+ var _BaseService_apiClient;
1326
+ /**
1327
+ * Base class for all UiPath SDK services.
1328
+ *
1329
+ * Provides common functionality for authentication, configuration, and API communication.
1330
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1331
+ *
1332
+ * This class implements the dependency injection pattern where services receive a configured
1333
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1334
+ * including authentication token management.
1335
+ *
1336
+ * @remarks
1337
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1338
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1339
+ *
1340
+ */
1341
+ class BaseService {
1342
+ /**
1343
+ * Creates a base service instance with dependency injection.
1344
+ *
1345
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1346
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1347
+ * and token management internally.
1348
+ *
1349
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1350
+ * Services receive this via dependency injection in the modular pattern.
1351
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1352
+ * CAS external-app auth)
1353
+ *
1354
+ * @example
1355
+ * ```typescript
1356
+ * // Services automatically call this via super()
1357
+ * export class EntityService extends BaseService {
1358
+ * constructor(instance: IUiPath) {
1359
+ * super(instance); // Initializes the internal ApiClient
1360
+ * }
1361
+ * }
1362
+ *
1363
+ * // Usage in modular pattern
1364
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1365
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1366
+ *
1367
+ * const sdk = new UiPath(config);
1368
+ * await sdk.initialize();
1369
+ * const entities = new Entities(sdk);
1370
+ * ```
1371
+ */
1372
+ constructor(instance, headers) {
1373
+ // Private field - not visible via Object.keys() or any reflection
1374
+ _BaseService_apiClient.set(this, void 0);
1375
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1376
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1377
+ this.config = { folderKey };
1378
+ }
1379
+ /**
1380
+ * Gets a valid authentication token, refreshing if necessary.
1381
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1382
+ *
1383
+ * @returns Promise resolving to a valid access token string
1384
+ * @throws AuthenticationError if no token is available or refresh fails
1385
+ */
1386
+ async getValidAuthToken() {
1387
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1388
+ }
1389
+ /**
1390
+ * Creates a service accessor for pagination helpers
1391
+ * This allows pagination helpers to access protected methods without making them public
1392
+ */
1393
+ createPaginationServiceAccess() {
1394
+ return {
1395
+ get: (path, options) => this.get(path, options || {}),
1396
+ post: (path, body, options) => this.post(path, body, options || {}),
1397
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1398
+ };
1399
+ }
1400
+ async request(method, path, options = {}) {
1401
+ switch (method.toUpperCase()) {
1402
+ case 'GET':
1403
+ return this.get(path, options);
1404
+ case 'POST':
1405
+ return this.post(path, options.body, options);
1406
+ case 'PUT':
1407
+ return this.put(path, options.body, options);
1408
+ case 'PATCH':
1409
+ return this.patch(path, options.body, options);
1410
+ case 'DELETE':
1411
+ return this.delete(path, options);
1412
+ default:
1413
+ throw new Error(`Unsupported HTTP method: ${method}`);
1414
+ }
1415
+ }
1416
+ async requestWithSpec(spec) {
1417
+ if (!spec.method || !spec.url) {
1418
+ throw new Error('Request spec must include method and url');
1419
+ }
1420
+ return this.request(spec.method, spec.url, spec);
1421
+ }
1422
+ async get(path, options = {}) {
1423
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1424
+ return { data: response };
1425
+ }
1426
+ async post(path, data, options = {}) {
1427
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1428
+ return { data: response };
1429
+ }
1430
+ async put(path, data, options = {}) {
1431
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1432
+ return { data: response };
1433
+ }
1434
+ async patch(path, data, options = {}) {
1435
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1436
+ return { data: response };
1437
+ }
1438
+ async delete(path, options = {}) {
1439
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1440
+ return { data: response };
1441
+ }
1442
+ /**
1443
+ * Execute a request with cursor-based pagination
1444
+ */
1445
+ async requestWithPagination(method, path, paginationOptions, options) {
1446
+ const paginationType = options.pagination.paginationType;
1447
+ // Validate and prepare pagination parameters
1448
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1449
+ // Prepare request parameters based on pagination type
1450
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1451
+ // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1452
+ if (method.toUpperCase() === 'POST') {
1453
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1454
+ options.body = {
1455
+ ...existingBody,
1456
+ ...options.params,
1457
+ ...requestParams
1458
+ };
1459
+ options.params = undefined;
1460
+ }
1461
+ else {
1462
+ // Merge pagination parameters with existing parameters
1463
+ options.params = {
1464
+ ...options.params,
1465
+ ...requestParams
1466
+ };
1467
+ }
1468
+ // Make the request
1469
+ const response = await this.request(method, path, options);
1470
+ // Extract data from the response and create page result
1471
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1472
+ itemsField: options.pagination.itemsField,
1473
+ totalCountField: options.pagination.totalCountField,
1474
+ continuationTokenField: options.pagination.continuationTokenField
1475
+ });
1476
+ }
1477
+ /**
1478
+ * Validates and prepares pagination parameters from options
1479
+ */
1480
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1481
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1482
+ }
1483
+ /**
1484
+ * Prepares request parameters for pagination based on pagination type
1485
+ */
1486
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1487
+ const requestParams = {};
1488
+ let limitedPageSize;
1489
+ const paginationParams = paginationConfig?.paginationParams;
1490
+ switch (paginationType) {
1491
+ case PaginationType.OFFSET:
1492
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1493
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1494
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1495
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1496
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1497
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1498
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1499
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
1500
+ const zeroBased = paginationParams?.zeroBased ?? false;
1501
+ requestParams[pageSizeParam] = limitedPageSize;
1502
+ if (convertToSkip) {
1503
+ if (params.pageNumber && params.pageNumber > 1) {
1504
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1505
+ }
1506
+ }
1507
+ else {
1508
+ const sdkPageNumber = params.pageNumber || 1;
1509
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
1510
+ }
1511
+ {
1512
+ requestParams[countParam] = true;
1513
+ }
1514
+ break;
1515
+ case PaginationType.TOKEN:
1516
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1517
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1518
+ if (params.pageSize) {
1519
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1520
+ }
1521
+ if (params.continuationToken) {
1522
+ requestParams[tokenParam] = params.continuationToken;
1523
+ }
1524
+ break;
1525
+ }
1526
+ return requestParams;
1527
+ }
1528
+ /**
1529
+ * Creates a paginated response from API response
1530
+ */
1531
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1532
+ // Extract fields from response
1533
+ const itemsField = fields.itemsField ||
1534
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1535
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1536
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1537
+ // Extract items and metadata
1538
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1539
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1540
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
1541
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1542
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1543
+ const continuationToken = response.data[continuationTokenField];
1544
+ // Determine if there are more pages
1545
+ const hasMore = this.determineHasMorePages(paginationType, {
1546
+ totalCount,
1547
+ pageSize: params.pageSize,
1548
+ currentPage: params.pageNumber || 1,
1549
+ itemsCount: items.length,
1550
+ continuationToken
1551
+ });
1552
+ // Create and return the page result
1553
+ return PaginationManager.createPaginatedResponse({
1554
+ pageInfo: {
1555
+ hasMore,
1556
+ totalCount,
1557
+ currentPage: params.pageNumber,
1558
+ pageSize: params.pageSize,
1559
+ continuationToken
1560
+ },
1561
+ type: paginationType,
1562
+ }, items);
1563
+ }
1564
+ /**
1565
+ * Determines if there are more pages based on pagination type and metadata
1566
+ */
1567
+ determineHasMorePages(paginationType, info) {
1568
+ switch (paginationType) {
1569
+ case PaginationType.OFFSET:
1570
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1571
+ // If totalCount is available, use it for precise calculation
1572
+ if (info.totalCount !== undefined) {
1573
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1574
+ }
1575
+ // Fallback when totalCount is not available
1576
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1577
+ return info.itemsCount === effectivePageSize;
1578
+ case PaginationType.TOKEN:
1579
+ return !!info.continuationToken;
1580
+ default:
1581
+ return false;
1582
+ }
1583
+ }
1584
+ }
1585
+ _BaseService_apiClient = new WeakMap();
1586
+
1587
+ /**
1588
+ * Base path constants for different services
1589
+ */
1590
+ const INSIGHTS_RTM_BASE = 'insightsrtm_';
1591
+
1592
+ /**
1593
+ * Governance Service Endpoints
1594
+ */
1595
+ /**
1596
+ * Governance Service Endpoints
1597
+ * Endpoints require an organization-admin caller
1598
+ */
1599
+ const GOVERNANCE_ENDPOINTS = {
1600
+ POLICY: {
1601
+ /** Policy evaluation traces (paginated). */
1602
+ TRACES: `${INSIGHTS_RTM_BASE}/Governance/policy/traces`,
1603
+ },
1604
+ OPERATION: {
1605
+ /** Aggregate governed-operation enforcement counts. */
1606
+ SUMMARY: `${INSIGHTS_RTM_BASE}/Governance/operation/summary`,
1607
+ },
1608
+ };
1609
+
1610
+ /**
1611
+ * SDK Telemetry constants.
1612
+ *
1613
+ * Only the SDK's identity (version, service name, role name, …) lives
1614
+ * here. The Application Insights connection string is injected into
1615
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
1616
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
1617
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
1618
+ * SDK's public API.
1619
+ */
1620
+ /** SDK version placeholder — patched by the SDK publish workflow. */
1621
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
1622
+
1623
+ /**
1624
+ * UiPath TypeScript SDK Telemetry
1625
+ *
1626
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
1627
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
1628
+ * does this independently, so events carry their own consumer's identity
1629
+ * and tenant context.
1630
+ */
1631
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
1632
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
1633
+ // from the `UiPath` constructor therefore wires up `@track` decorators
1634
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
1635
+ const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
1636
+ const track = coreTelemetry.createTrack(sdkClient);
1637
+ coreTelemetry.createTrackEvent(sdkClient);
1638
+
1639
+ /**
1640
+ * Service for inspecting governance policy enforcement on the UiPath platform.
1641
+ */
1642
+ class GovernanceService extends BaseService {
1643
+ /**
1644
+ * Gets per-policy enforcement decisions across the requested time range.
1645
+ *
1646
+ * Each result row represents one policy's verdict within a single governance enforcement event.
1647
+ * A single user action can produce multiple rows when multiple policies were consulted.
1648
+ * Results are ordered by event start time, descending.
1649
+ *
1650
+ * @param startTime - Inclusive lower bound on the trace start time.
1651
+ * @param options - Optional filters and pagination options
1652
+ * @returns Promise resolving to {@link NonPaginatedResponse} of {@link GovernancePolicyTrace}
1653
+ * without pagination options, or {@link PaginatedResponse} of
1654
+ * {@link GovernancePolicyTrace} when pagination options are used.
1655
+ *
1656
+ * @example
1657
+ * ```typescript
1658
+ * import { Governance, PolicyEvaluationResult } from '@uipath/uipath-typescript/governance';
1659
+ *
1660
+ * const governance = new Governance(sdk);
1661
+ *
1662
+ * // Get all policy traces from the specified start time
1663
+ * const recent = await governance.getPolicyTraces(new Date('2024-01-01'));
1664
+ * console.log(recent.items.length);
1665
+ *
1666
+ * // Get all denied decisions across the whole organization
1667
+ * const page1 = await governance.getPolicyTraces(
1668
+ * new Date('2024-01-01'),
1669
+ * {
1670
+ * endTime: new Date(),
1671
+ * evaluationResult: [PolicyEvaluationResult.Deny, PolicyEvaluationResult.SimulatedDeny],
1672
+ * fullOrganization: true,
1673
+ * pageSize: 25,
1674
+ * },
1675
+ * );
1676
+ *
1677
+ * if (page1.hasNextPage) {
1678
+ * const page2 = await governance.getPolicyTraces(
1679
+ * new Date('2024-01-01'),
1680
+ * { cursor: page1.nextCursor },
1681
+ * );
1682
+ * }
1683
+ * ```
1684
+ */
1685
+ async getPolicyTraces(startTime, options) {
1686
+ if (!startTime) {
1687
+ throw new ValidationError({ message: 'startTime is required for getPolicyTraces' });
1688
+ }
1689
+ const apiOptions = {
1690
+ ...options,
1691
+ startTime: startTime.toISOString(),
1692
+ endTime: options?.endTime?.toISOString(),
1693
+ };
1694
+ return PaginationHelpers.getAll({
1695
+ serviceAccess: this.createPaginationServiceAccess(),
1696
+ getEndpoint: () => GOVERNANCE_ENDPOINTS.POLICY.TRACES,
1697
+ method: HTTP_METHODS.POST,
1698
+ excludeFromPrefix: Object.keys(apiOptions),
1699
+ pagination: {
1700
+ paginationType: PaginationType.OFFSET,
1701
+ itemsField: GOVERNANCE_PAGINATION.ITEMS_FIELD,
1702
+ paginationParams: {
1703
+ pageSizeParam: GOVERNANCE_OFFSET_PARAMS.PAGE_SIZE_PARAM,
1704
+ offsetParam: GOVERNANCE_OFFSET_PARAMS.OFFSET_PARAM,
1705
+ countParam: GOVERNANCE_OFFSET_PARAMS.COUNT_PARAM,
1706
+ convertToSkip: false,
1707
+ zeroBased: true,
1708
+ },
1709
+ },
1710
+ }, apiOptions);
1711
+ }
1712
+ /**
1713
+ * Gets aggregate governance enforcement counts across the requested time range.
1714
+ *
1715
+ * Returns the total number of evaluations along with how many resolved to
1716
+ * `Allow`, `Deny`, or `NoOp`.
1717
+ *
1718
+ * @param startTime - Inclusive lower bound on the evaluation time.
1719
+ * @param options - Optional `endTime` upper bound and `fullOrganization` flag
1720
+ * @returns Promise resolving to {@link GovernanceOperationSummary}
1721
+ *
1722
+ * @example
1723
+ * ```typescript
1724
+ * import { Governance } from '@uipath/uipath-typescript/governance';
1725
+ *
1726
+ * const governance = new Governance(sdk);
1727
+ *
1728
+ * // Get operation summary from the specified start time to right now
1729
+ * const summary = await governance.getOperationSummary(new Date('2024-01-01'));
1730
+ * console.log(summary.totalEvaluations, summary.allowedCount, summary.deniedCount, summary.noOpCount);
1731
+ *
1732
+ * // Bounded range across the whole organization
1733
+ * const ranged = await governance.getOperationSummary(
1734
+ * new Date('2024-01-01'),
1735
+ * { endTime: new Date(), fullOrganization: true },
1736
+ * );
1737
+ * ```
1738
+ */
1739
+ async getOperationSummary(startTime, options) {
1740
+ if (!startTime) {
1741
+ throw new ValidationError({ message: 'startTime is required for getOperationSummary' });
1742
+ }
1743
+ const body = filterUndefined({
1744
+ startTime: startTime.toISOString(),
1745
+ endTime: options?.endTime?.toISOString(),
1746
+ fullOrganization: options?.fullOrganization,
1747
+ });
1748
+ const response = await this.post(GOVERNANCE_ENDPOINTS.OPERATION.SUMMARY, body);
1749
+ const data = response.data;
1750
+ return {
1751
+ totalEvaluations: data.totalEvaluations ?? 0,
1752
+ allowedCount: data.allow ?? 0,
1753
+ deniedCount: data.deny ?? 0,
1754
+ noOpCount: data.noOp ?? 0,
1755
+ };
1756
+ }
1757
+ }
1758
+ __decorate([
1759
+ track('Governance.GetPolicyTraces')
1760
+ ], GovernanceService.prototype, "getPolicyTraces", null);
1761
+ __decorate([
1762
+ track('Governance.GetOperationSummary')
1763
+ ], GovernanceService.prototype, "getOperationSummary", null);
1764
+
1765
+ /**
1766
+ * Governance Service Types
1767
+ *
1768
+ * Public types exposed via `@uipath/uipath-typescript/governance`.
1769
+ */
1770
+ exports.PolicyEvaluationResult = void 0;
1771
+ (function (PolicyEvaluationResult) {
1772
+ /** Active policy permitted the action. */
1773
+ PolicyEvaluationResult["Allow"] = "Allow";
1774
+ /** Active policy blocked the action. */
1775
+ PolicyEvaluationResult["Deny"] = "Deny";
1776
+ /** Simulated (NoOp) policy would have permitted the action. */
1777
+ PolicyEvaluationResult["SimulatedAllow"] = "SimulatedAllow";
1778
+ /** Simulated (NoOp) policy would have blocked the action. */
1779
+ PolicyEvaluationResult["SimulatedDeny"] = "SimulatedDeny";
1780
+ })(exports.PolicyEvaluationResult || (exports.PolicyEvaluationResult = {}));
1781
+
1782
+ exports.Governance = GovernanceService;