@uipath/uipath-typescript 1.3.1 → 1.3.3

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