@uipath/uipath-typescript 1.3.2 → 1.3.4

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 (38) hide show
  1. package/dist/assets/index.cjs +21 -8
  2. package/dist/assets/index.mjs +21 -8
  3. package/dist/attachments/index.cjs +21 -8
  4. package/dist/attachments/index.mjs +21 -8
  5. package/dist/buckets/index.cjs +21 -8
  6. package/dist/buckets/index.mjs +21 -8
  7. package/dist/cases/index.cjs +41 -13
  8. package/dist/cases/index.d.ts +15 -0
  9. package/dist/cases/index.mjs +41 -13
  10. package/dist/conversational-agent/index.cjs +39 -8
  11. package/dist/conversational-agent/index.d.ts +55 -2
  12. package/dist/conversational-agent/index.mjs +39 -8
  13. package/dist/core/index.cjs +16 -1
  14. package/dist/core/index.d.ts +1 -1
  15. package/dist/core/index.mjs +16 -1
  16. package/dist/entities/index.cjs +55 -8
  17. package/dist/entities/index.d.ts +54 -0
  18. package/dist/entities/index.mjs +55 -8
  19. package/dist/feedback/index.cjs +1911 -0
  20. package/dist/feedback/index.d.ts +475 -0
  21. package/dist/feedback/index.mjs +1909 -0
  22. package/dist/index.cjs +451 -189
  23. package/dist/index.d.ts +388 -13
  24. package/dist/index.mjs +452 -190
  25. package/dist/index.umd.js +451 -189
  26. package/dist/jobs/index.cjs +384 -8
  27. package/dist/jobs/index.d.ts +220 -2
  28. package/dist/jobs/index.mjs +385 -9
  29. package/dist/maestro-processes/index.cjs +21 -8
  30. package/dist/maestro-processes/index.mjs +21 -8
  31. package/dist/processes/index.cjs +21 -8
  32. package/dist/processes/index.mjs +21 -8
  33. package/dist/queues/index.cjs +21 -8
  34. package/dist/queues/index.mjs +21 -8
  35. package/dist/tasks/index.cjs +41 -13
  36. package/dist/tasks/index.d.ts +25 -10
  37. package/dist/tasks/index.mjs +42 -14
  38. package/package.json +13 -2
@@ -0,0 +1,1911 @@
1
+ 'use strict';
2
+
3
+ var sdkLogs = require('@opentelemetry/sdk-logs');
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
+ return JSON.parse(text);
615
+ }
616
+ catch (error) {
617
+ // If it's already one of our errors, re-throw it
618
+ if (error.type && error.type.includes('Error')) {
619
+ throw error;
620
+ }
621
+ // Otherwise, it's likely a network error
622
+ throw ErrorFactory.createNetworkError(error);
623
+ }
624
+ }
625
+ async get(path, options = {}) {
626
+ return this.request('GET', path, options);
627
+ }
628
+ async post(path, data, options = {}) {
629
+ return this.request('POST', path, { ...options, body: data });
630
+ }
631
+ async put(path, data, options = {}) {
632
+ return this.request('PUT', path, { ...options, body: data });
633
+ }
634
+ async patch(path, data, options = {}) {
635
+ return this.request('PATCH', path, { ...options, body: data });
636
+ }
637
+ async delete(path, options = {}) {
638
+ return this.request('DELETE', path, options);
639
+ }
640
+ }
641
+
642
+ /**
643
+ * Pagination types supported by the SDK
644
+ */
645
+ var PaginationType;
646
+ (function (PaginationType) {
647
+ PaginationType["OFFSET"] = "offset";
648
+ PaginationType["TOKEN"] = "token";
649
+ })(PaginationType || (PaginationType = {}));
650
+
651
+ /**
652
+ * Collection of utility functions for working with objects
653
+ */
654
+ /**
655
+ * Filters out undefined values from an object
656
+ * @param obj The source object
657
+ * @returns A new object without undefined values
658
+ *
659
+ * @example
660
+ * ```typescript
661
+ * // Object with undefined values
662
+ * const options = {
663
+ * name: 'test',
664
+ * count: 5,
665
+ * prefix: undefined,
666
+ * suffix: null
667
+ * };
668
+ * const result = filterUndefined(options);
669
+ * // result = { name: 'test', count: 5, suffix: null }
670
+ * ```
671
+ */
672
+ function filterUndefined(obj) {
673
+ const result = {};
674
+ for (const [key, value] of Object.entries(obj)) {
675
+ if (value !== undefined) {
676
+ result[key] = value;
677
+ }
678
+ }
679
+ return result;
680
+ }
681
+
682
+ /**
683
+ * Utility functions for platform detection
684
+ */
685
+ /**
686
+ * Checks if code is running in a browser environment
687
+ */
688
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
689
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
690
+
691
+ /**
692
+ * Base64 encoding/decoding
693
+ */
694
+ /**
695
+ * Encodes a string to base64
696
+ * @param str - The string to encode
697
+ * @returns Base64 encoded string
698
+ */
699
+ function encodeBase64(str) {
700
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
701
+ const encoder = new TextEncoder();
702
+ const data = encoder.encode(str);
703
+ // Convert Uint8Array to base64
704
+ if (isBrowser) {
705
+ // Browser environment
706
+ // Convert Uint8Array to binary string then to base64
707
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
708
+ return btoa(binaryString);
709
+ }
710
+ else {
711
+ // Node.js environment
712
+ return Buffer.from(data).toString('base64');
713
+ }
714
+ }
715
+ /**
716
+ * Decodes a base64 string
717
+ * @param base64 - The base64 string to decode
718
+ * @returns Decoded string
719
+ */
720
+ function decodeBase64(base64) {
721
+ let bytes;
722
+ if (isBrowser) {
723
+ // Browser environment
724
+ const binaryString = atob(base64);
725
+ bytes = new Uint8Array(binaryString.length);
726
+ for (let i = 0; i < binaryString.length; i++) {
727
+ bytes[i] = binaryString.charCodeAt(i);
728
+ }
729
+ }
730
+ else {
731
+ // Node.js environment
732
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
733
+ }
734
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
735
+ const decoder = new TextDecoder();
736
+ return decoder.decode(bytes);
737
+ }
738
+
739
+ /**
740
+ * PaginationManager handles the conversion between uniform cursor-based pagination
741
+ * and the specific pagination type for each service
742
+ */
743
+ class PaginationManager {
744
+ /**
745
+ * Create a pagination cursor for subsequent page requests
746
+ */
747
+ static createCursor({ pageInfo, type }) {
748
+ if (!pageInfo.hasMore) {
749
+ return undefined;
750
+ }
751
+ const cursorData = {
752
+ type,
753
+ pageSize: pageInfo.pageSize,
754
+ };
755
+ switch (type) {
756
+ case PaginationType.OFFSET:
757
+ if (pageInfo.currentPage) {
758
+ cursorData.pageNumber = pageInfo.currentPage + 1;
759
+ }
760
+ break;
761
+ case PaginationType.TOKEN:
762
+ if (pageInfo.continuationToken) {
763
+ cursorData.continuationToken = pageInfo.continuationToken;
764
+ }
765
+ else {
766
+ return undefined; // No continuation token, can't continue
767
+ }
768
+ break;
769
+ }
770
+ return {
771
+ value: encodeBase64(JSON.stringify(cursorData))
772
+ };
773
+ }
774
+ /**
775
+ * Create a paginated response with navigation cursors
776
+ */
777
+ static createPaginatedResponse({ pageInfo, type }, items) {
778
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
779
+ // Create previous page cursor if applicable
780
+ let previousCursor = undefined;
781
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
782
+ const prevCursorData = {
783
+ type,
784
+ pageNumber: pageInfo.currentPage - 1,
785
+ pageSize: pageInfo.pageSize,
786
+ };
787
+ previousCursor = {
788
+ value: encodeBase64(JSON.stringify(prevCursorData))
789
+ };
790
+ }
791
+ // Calculate total pages if we have totalCount and pageSize
792
+ let totalPages = undefined;
793
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
794
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
795
+ }
796
+ // Determine if this pagination type supports page jumping
797
+ const supportsPageJump = type === PaginationType.OFFSET;
798
+ // Create the result object with all fields, then filter out undefined values
799
+ const result = filterUndefined({
800
+ items,
801
+ totalCount: pageInfo.totalCount,
802
+ hasNextPage: pageInfo.hasMore,
803
+ nextCursor: nextCursor,
804
+ previousCursor: previousCursor,
805
+ currentPage: pageInfo.currentPage,
806
+ totalPages,
807
+ supportsPageJump
808
+ });
809
+ return result;
810
+ }
811
+ }
812
+
813
+ /**
814
+ * Creates headers object from key-value pairs
815
+ * @param headersObj - Object containing header key-value pairs
816
+ * @returns Headers object with all values converted to strings
817
+ *
818
+ * @example
819
+ * ```typescript
820
+ * // Single header
821
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
822
+ *
823
+ * // Multiple headers
824
+ * const headers = createHeaders({
825
+ * 'X-UIPATH-FolderKey': '1234567890',
826
+ * 'X-UIPATH-OrganizationUnitId': 123,
827
+ * 'Accept': 'application/json'
828
+ * });
829
+ *
830
+ * // Using constants
831
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
832
+ * const headers = createHeaders({
833
+ * [FOLDER_KEY]: 'abc-123',
834
+ * [FOLDER_ID]: 456
835
+ * });
836
+ *
837
+ * // Empty headers
838
+ * const headers = createHeaders();
839
+ * ```
840
+ */
841
+ function createHeaders(headersObj) {
842
+ const headers = {};
843
+ for (const [key, value] of Object.entries(headersObj)) {
844
+ if (value !== undefined && value !== null) {
845
+ headers[key] = value.toString();
846
+ }
847
+ }
848
+ return headers;
849
+ }
850
+
851
+ /**
852
+ * Common constants used across the SDK
853
+ */
854
+ /**
855
+ * Prefix used for OData query parameters
856
+ */
857
+ const ODATA_PREFIX = '$';
858
+ /**
859
+ * HTTP methods
860
+ */
861
+ const HTTP_METHODS = {
862
+ GET: 'GET',
863
+ POST: 'POST'};
864
+ /**
865
+ * OData OFFSET pagination parameter names (ODATA-style)
866
+ */
867
+ const ODATA_OFFSET_PARAMS = {
868
+ /** OData page size parameter name */
869
+ PAGE_SIZE_PARAM: '$top',
870
+ /** OData offset parameter name */
871
+ OFFSET_PARAM: '$skip',
872
+ /** OData count parameter name */
873
+ COUNT_PARAM: '$count'
874
+ };
875
+ /**
876
+ * Feedback OFFSET pagination parameter names (take/skip style)
877
+ */
878
+ const FEEDBACK_OFFSET_PARAMS = {
879
+ /** Feedback page size parameter name */
880
+ PAGE_SIZE_PARAM: 'take',
881
+ /** Feedback offset parameter name */
882
+ OFFSET_PARAM: 'skip',
883
+ /** Feedback count parameter (not used) */
884
+ COUNT_PARAM: undefined
885
+ };
886
+ /**
887
+ * Bucket TOKEN pagination parameter names
888
+ */
889
+ const BUCKET_TOKEN_PARAMS = {
890
+ /** Bucket page size parameter name */
891
+ PAGE_SIZE_PARAM: 'takeHint',
892
+ /** Bucket token parameter name */
893
+ TOKEN_PARAM: 'continuationToken'
894
+ };
895
+
896
+ /**
897
+ * Transforms data by mapping fields according to the provided field mapping
898
+ * @param data The source data to transform
899
+ * @param fieldMapping Object mapping source field names to target field names
900
+ * @returns Transformed data with mapped field names
901
+ *
902
+ * @example
903
+ * ```typescript
904
+ * // Single object transformation
905
+ * const data = { id: '123', userName: 'john' };
906
+ * const mapping = { id: 'userId', userName: 'name' };
907
+ * const result = transformData(data, mapping);
908
+ * // result = { userId: '123', name: 'john' }
909
+ *
910
+ * // Array transformation
911
+ * const dataArray = [
912
+ * { id: '123', userName: 'john' },
913
+ * { id: '456', userName: 'jane' }
914
+ * ];
915
+ * const result = transformData(dataArray, mapping);
916
+ * // result = [
917
+ * // { userId: '123', name: 'john' },
918
+ * // { userId: '456', name: 'jane' }
919
+ * // ]
920
+ * ```
921
+ */
922
+ function transformData(data, fieldMapping) {
923
+ // Handle array of objects
924
+ if (Array.isArray(data)) {
925
+ return data.map(item => transformData(item, fieldMapping));
926
+ }
927
+ // Handle single object
928
+ const result = { ...data };
929
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
930
+ if (sourceField in result) {
931
+ const value = result[sourceField];
932
+ delete result[sourceField];
933
+ result[targetField] = value;
934
+ }
935
+ }
936
+ return result;
937
+ }
938
+ /**
939
+ * Adds a prefix to specified keys in an object, returning a new object.
940
+ * Only the provided keys are prefixed; all others are left unchanged.
941
+ *
942
+ * @param obj The source object
943
+ * @param prefix The prefix to add (e.g., '$')
944
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
945
+ * @returns A new object with specified keys prefixed
946
+ *
947
+ * @example
948
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
949
+ */
950
+ function addPrefixToKeys(obj, prefix, keys) {
951
+ const result = {};
952
+ for (const [key, value] of Object.entries(obj)) {
953
+ if (keys.includes(key)) {
954
+ result[`${prefix}${key}`] = value;
955
+ }
956
+ else {
957
+ result[key] = value;
958
+ }
959
+ }
960
+ return result;
961
+ }
962
+
963
+ /**
964
+ * Constants used throughout the pagination system
965
+ */
966
+ /** Maximum number of items that can be requested in a single page */
967
+ const MAX_PAGE_SIZE = 1000;
968
+ /** Default page size when jumpToPage is used without specifying pageSize */
969
+ const DEFAULT_PAGE_SIZE = 50;
970
+ /** Default field name for items in a paginated response */
971
+ const DEFAULT_ITEMS_FIELD = 'value';
972
+ /** Default field name for total count in a paginated response */
973
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
974
+ /**
975
+ * Limits the page size to the maximum allowed value
976
+ * @param pageSize - Requested page size
977
+ * @returns Limited page size value
978
+ */
979
+ function getLimitedPageSize(pageSize) {
980
+ if (pageSize === undefined || pageSize === null) {
981
+ return DEFAULT_PAGE_SIZE;
982
+ }
983
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
984
+ }
985
+
986
+ /**
987
+ * Helper functions for pagination that can be used across services
988
+ */
989
+ class PaginationHelpers {
990
+ /**
991
+ * Checks if any pagination parameters are provided
992
+ *
993
+ * @param options - The options object to check
994
+ * @returns True if any pagination parameter is defined, false otherwise
995
+ */
996
+ static hasPaginationParameters(options = {}) {
997
+ const { cursor, pageSize, jumpToPage } = options;
998
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
999
+ }
1000
+ /**
1001
+ * Parse a pagination cursor string into cursor data
1002
+ */
1003
+ static parseCursor(cursorString) {
1004
+ try {
1005
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1006
+ return cursorData;
1007
+ }
1008
+ catch {
1009
+ throw new Error('Invalid pagination cursor');
1010
+ }
1011
+ }
1012
+ /**
1013
+ * Validates cursor format and structure
1014
+ *
1015
+ * @param paginationOptions - The pagination options containing the cursor
1016
+ * @param paginationType - Optional pagination type to validate against
1017
+ */
1018
+ static validateCursor(paginationOptions, paginationType) {
1019
+ if (paginationOptions.cursor !== undefined) {
1020
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1021
+ throw new Error('cursor must contain a valid cursor string');
1022
+ }
1023
+ try {
1024
+ // Try to parse the cursor to validate it
1025
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1026
+ // If type is provided, validate cursor contains expected type information
1027
+ if (paginationType) {
1028
+ if (!cursorData.type) {
1029
+ throw new Error('Invalid cursor: missing pagination type');
1030
+ }
1031
+ // Check pagination type compatibility
1032
+ if (cursorData.type !== paginationType) {
1033
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1034
+ }
1035
+ }
1036
+ }
1037
+ catch (error) {
1038
+ if (error instanceof Error) {
1039
+ // If it's already our error with specific message, pass it through
1040
+ if (error.message.startsWith('Invalid cursor') ||
1041
+ error.message.startsWith('Pagination type mismatch')) {
1042
+ throw error;
1043
+ }
1044
+ }
1045
+ throw new Error('Invalid pagination cursor format');
1046
+ }
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Comprehensive validation for pagination options
1051
+ *
1052
+ * @param options - The pagination options to validate
1053
+ * @param paginationType - The pagination type these options will be used with
1054
+ * @returns Processed pagination parameters ready for use
1055
+ */
1056
+ static validatePaginationOptions(options, paginationType) {
1057
+ // Validate pageSize
1058
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1059
+ throw new Error('pageSize must be a positive number');
1060
+ }
1061
+ // Validate jumpToPage
1062
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1063
+ throw new Error('jumpToPage must be a positive number');
1064
+ }
1065
+ // Validate cursor
1066
+ PaginationHelpers.validateCursor(options, paginationType);
1067
+ // Validate service compatibility
1068
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1069
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1070
+ }
1071
+ // Get processed parameters
1072
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1073
+ }
1074
+ /**
1075
+ * Convert a unified pagination options to service-specific parameters
1076
+ */
1077
+ static getRequestParameters(options, paginationType) {
1078
+ // Handle jumpToPage
1079
+ if (options.jumpToPage !== undefined) {
1080
+ const jumpToPageOptions = {
1081
+ pageSize: options.pageSize,
1082
+ pageNumber: options.jumpToPage
1083
+ };
1084
+ return filterUndefined(jumpToPageOptions);
1085
+ }
1086
+ // If no cursor is provided, it's a first page request
1087
+ if (!options.cursor) {
1088
+ const firstPageOptions = {
1089
+ pageSize: options.pageSize,
1090
+ // Only set pageNumber for OFFSET pagination
1091
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1092
+ };
1093
+ return filterUndefined(firstPageOptions);
1094
+ }
1095
+ // Parse the cursor
1096
+ try {
1097
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1098
+ const cursorBasedOptions = {
1099
+ pageSize: cursorData.pageSize || options.pageSize,
1100
+ pageNumber: cursorData.pageNumber,
1101
+ continuationToken: cursorData.continuationToken,
1102
+ type: cursorData.type,
1103
+ };
1104
+ return filterUndefined(cursorBasedOptions);
1105
+ }
1106
+ catch {
1107
+ throw new Error('Invalid pagination cursor');
1108
+ }
1109
+ }
1110
+ /**
1111
+ * Helper method for paginated resource retrieval
1112
+ *
1113
+ * @param params - Parameters for pagination
1114
+ * @returns Promise resolving to a paginated result
1115
+ */
1116
+ static async getAllPaginated(params) {
1117
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1118
+ const endpoint = getEndpoint(folderId);
1119
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1120
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1121
+ headers,
1122
+ params: additionalParams,
1123
+ pagination: {
1124
+ paginationType: options.paginationType || PaginationType.OFFSET,
1125
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1126
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1127
+ continuationTokenField: options.continuationTokenField,
1128
+ paginationParams: options.paginationParams
1129
+ }
1130
+ });
1131
+ // Parse items - automatically handle JSON string responses
1132
+ const rawItems = paginatedResponse.items;
1133
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1134
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1135
+ return {
1136
+ ...paginatedResponse,
1137
+ items: transformedItems
1138
+ };
1139
+ }
1140
+ /**
1141
+ * Helper method for non-paginated resource retrieval
1142
+ *
1143
+ * @param params - Parameters for non-paginated resource retrieval
1144
+ * @returns Promise resolving to an object with data and totalCount
1145
+ */
1146
+ static async getAllNonPaginated(params) {
1147
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1148
+ // Set default field names
1149
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1150
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1151
+ // Determine endpoint and headers based on folderId
1152
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1153
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1154
+ // Make the API call based on method
1155
+ let response;
1156
+ if (method === HTTP_METHODS.POST) {
1157
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1158
+ }
1159
+ else {
1160
+ response = await serviceAccess.get(endpoint, {
1161
+ params: additionalParams,
1162
+ headers
1163
+ });
1164
+ }
1165
+ // Extract and transform items from response
1166
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1167
+ const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
1168
+ const totalCount = Array.isArray(response.data) ? undefined : response.data?.[totalCountField];
1169
+ // Parse items - automatically handle JSON string responses
1170
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1171
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1172
+ return {
1173
+ items,
1174
+ totalCount
1175
+ };
1176
+ }
1177
+ /**
1178
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1179
+ *
1180
+ * @param config - Configuration for the getAll operation
1181
+ * @param options - Request options including pagination parameters
1182
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1183
+ */
1184
+ static async getAll(config, options) {
1185
+ const optionsWithDefaults = options || {};
1186
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1187
+ // Determine if pagination is requested
1188
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1189
+ // Process parameters (custom processing if provided, otherwise default)
1190
+ let processedOptions = restOptions;
1191
+ if (config.processParametersFn) {
1192
+ processedOptions = config.processParametersFn(restOptions, folderId);
1193
+ }
1194
+ // Apply ODATA prefix to keys (excluding specified keys)
1195
+ const excludeKeys = config.excludeFromPrefix || [];
1196
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1197
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1198
+ // Default pagination options
1199
+ const paginationOptions = {
1200
+ paginationType: PaginationType.OFFSET,
1201
+ itemsField: DEFAULT_ITEMS_FIELD,
1202
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1203
+ ...config.pagination
1204
+ };
1205
+ // Paginated flow
1206
+ if (isPaginationRequested) {
1207
+ return PaginationHelpers.getAllPaginated({
1208
+ serviceAccess: config.serviceAccess,
1209
+ getEndpoint: config.getEndpoint,
1210
+ folderId,
1211
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1212
+ additionalParams: prefixedOptions,
1213
+ transformFn: config.transformFn,
1214
+ method: config.method,
1215
+ options: {
1216
+ ...paginationOptions,
1217
+ paginationParams: config.pagination?.paginationParams
1218
+ }
1219
+ }); // Type assertion needed due to conditional return
1220
+ }
1221
+ // Non-paginated flow
1222
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1223
+ return PaginationHelpers.getAllNonPaginated({
1224
+ serviceAccess: config.serviceAccess,
1225
+ getAllEndpoint: config.getEndpoint(),
1226
+ getByFolderEndpoint: byFolderEndpoint,
1227
+ folderId,
1228
+ additionalParams: prefixedOptions,
1229
+ transformFn: config.transformFn,
1230
+ method: config.method,
1231
+ options: {
1232
+ itemsField: paginationOptions.itemsField,
1233
+ totalCountField: paginationOptions.totalCountField
1234
+ }
1235
+ });
1236
+ }
1237
+ }
1238
+
1239
+ /**
1240
+ * SDK Internals Registry - Internal registry for SDK instances
1241
+ *
1242
+ * This class is NOT exported in the public API.
1243
+ * It provides a secure way to share SDK internals between
1244
+ * the UiPath class and service classes without exposing them publicly.
1245
+ *
1246
+ * @internal
1247
+ */
1248
+ // Global symbol key to ensure WeakMap is shared across module instances
1249
+ // This prevents issues when core and service modules are bundled separately
1250
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1251
+ // Get or create the global WeakMap store
1252
+ const getGlobalStore = () => {
1253
+ const globalObj = globalThis;
1254
+ if (!globalObj[REGISTRY_KEY]) {
1255
+ globalObj[REGISTRY_KEY] = new WeakMap();
1256
+ }
1257
+ return globalObj[REGISTRY_KEY];
1258
+ };
1259
+ /**
1260
+ * Internal registry for SDK private components.
1261
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1262
+ * garbage collected when the SDK instance is no longer referenced.
1263
+ *
1264
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1265
+ * across separately bundled modules (core, entities, tasks, etc.).
1266
+ *
1267
+ * @internal - Not exported in public API
1268
+ */
1269
+ class SDKInternalsRegistry {
1270
+ // Use global store to ensure sharing across module bundles
1271
+ static get store() {
1272
+ return getGlobalStore();
1273
+ }
1274
+ /**
1275
+ * Register SDK instance internals
1276
+ * Called by UiPath constructor
1277
+ */
1278
+ static set(instance, internals) {
1279
+ this.store.set(instance, internals);
1280
+ }
1281
+ /**
1282
+ * Retrieve SDK instance internals
1283
+ * Called by BaseService constructor
1284
+ */
1285
+ static get(instance) {
1286
+ const internals = this.store.get(instance);
1287
+ if (!internals) {
1288
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1289
+ }
1290
+ return internals;
1291
+ }
1292
+ }
1293
+
1294
+ var _BaseService_apiClient;
1295
+ /**
1296
+ * Base class for all UiPath SDK services.
1297
+ *
1298
+ * Provides common functionality for authentication, configuration, and API communication.
1299
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1300
+ *
1301
+ * This class implements the dependency injection pattern where services receive a configured
1302
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1303
+ * including authentication token management.
1304
+ *
1305
+ * @remarks
1306
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1307
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1308
+ *
1309
+ */
1310
+ class BaseService {
1311
+ /**
1312
+ * Creates a base service instance with dependency injection.
1313
+ *
1314
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1315
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1316
+ * and token management internally.
1317
+ *
1318
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1319
+ * Services receive this via dependency injection in the modular pattern.
1320
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1321
+ * CAS external-app auth)
1322
+ *
1323
+ * @example
1324
+ * ```typescript
1325
+ * // Services automatically call this via super()
1326
+ * export class EntityService extends BaseService {
1327
+ * constructor(instance: IUiPath) {
1328
+ * super(instance); // Initializes the internal ApiClient
1329
+ * }
1330
+ * }
1331
+ *
1332
+ * // Usage in modular pattern
1333
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1334
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1335
+ *
1336
+ * const sdk = new UiPath(config);
1337
+ * await sdk.initialize();
1338
+ * const entities = new Entities(sdk);
1339
+ * ```
1340
+ */
1341
+ constructor(instance, headers) {
1342
+ // Private field - not visible via Object.keys() or any reflection
1343
+ _BaseService_apiClient.set(this, void 0);
1344
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1345
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1346
+ }
1347
+ /**
1348
+ * Gets a valid authentication token, refreshing if necessary.
1349
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1350
+ *
1351
+ * @returns Promise resolving to a valid access token string
1352
+ * @throws AuthenticationError if no token is available or refresh fails
1353
+ */
1354
+ async getValidAuthToken() {
1355
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1356
+ }
1357
+ /**
1358
+ * Creates a service accessor for pagination helpers
1359
+ * This allows pagination helpers to access protected methods without making them public
1360
+ */
1361
+ createPaginationServiceAccess() {
1362
+ return {
1363
+ get: (path, options) => this.get(path, options || {}),
1364
+ post: (path, body, options) => this.post(path, body, options || {}),
1365
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1366
+ };
1367
+ }
1368
+ async request(method, path, options = {}) {
1369
+ switch (method.toUpperCase()) {
1370
+ case 'GET':
1371
+ return this.get(path, options);
1372
+ case 'POST':
1373
+ return this.post(path, options.body, options);
1374
+ case 'PUT':
1375
+ return this.put(path, options.body, options);
1376
+ case 'PATCH':
1377
+ return this.patch(path, options.body, options);
1378
+ case 'DELETE':
1379
+ return this.delete(path, options);
1380
+ default:
1381
+ throw new Error(`Unsupported HTTP method: ${method}`);
1382
+ }
1383
+ }
1384
+ async requestWithSpec(spec) {
1385
+ if (!spec.method || !spec.url) {
1386
+ throw new Error('Request spec must include method and url');
1387
+ }
1388
+ return this.request(spec.method, spec.url, spec);
1389
+ }
1390
+ async get(path, options = {}) {
1391
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1392
+ return { data: response };
1393
+ }
1394
+ async post(path, data, options = {}) {
1395
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1396
+ return { data: response };
1397
+ }
1398
+ async put(path, data, options = {}) {
1399
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1400
+ return { data: response };
1401
+ }
1402
+ async patch(path, data, options = {}) {
1403
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1404
+ return { data: response };
1405
+ }
1406
+ async delete(path, options = {}) {
1407
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1408
+ return { data: response };
1409
+ }
1410
+ /**
1411
+ * Execute a request with cursor-based pagination
1412
+ */
1413
+ async requestWithPagination(method, path, paginationOptions, options) {
1414
+ const paginationType = options.pagination.paginationType;
1415
+ // Validate and prepare pagination parameters
1416
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1417
+ // Prepare request parameters based on pagination type
1418
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1419
+ // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1420
+ if (method.toUpperCase() === 'POST') {
1421
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1422
+ options.body = {
1423
+ ...existingBody,
1424
+ ...options.params,
1425
+ ...requestParams
1426
+ };
1427
+ options.params = undefined;
1428
+ }
1429
+ else {
1430
+ // Merge pagination parameters with existing parameters
1431
+ options.params = {
1432
+ ...options.params,
1433
+ ...requestParams
1434
+ };
1435
+ }
1436
+ // Make the request
1437
+ const response = await this.request(method, path, options);
1438
+ // Extract data from the response and create page result
1439
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1440
+ itemsField: options.pagination.itemsField,
1441
+ totalCountField: options.pagination.totalCountField,
1442
+ continuationTokenField: options.pagination.continuationTokenField
1443
+ });
1444
+ }
1445
+ /**
1446
+ * Validates and prepares pagination parameters from options
1447
+ */
1448
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1449
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1450
+ }
1451
+ /**
1452
+ * Prepares request parameters for pagination based on pagination type
1453
+ */
1454
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1455
+ const requestParams = {};
1456
+ let limitedPageSize;
1457
+ const paginationParams = paginationConfig?.paginationParams;
1458
+ switch (paginationType) {
1459
+ case PaginationType.OFFSET:
1460
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1461
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1462
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1463
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1464
+ requestParams[pageSizeParam] = limitedPageSize;
1465
+ if (params.pageNumber && params.pageNumber > 1) {
1466
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1467
+ }
1468
+ {
1469
+ requestParams[countParam] = true;
1470
+ }
1471
+ break;
1472
+ case PaginationType.TOKEN:
1473
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1474
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1475
+ if (params.pageSize) {
1476
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1477
+ }
1478
+ if (params.continuationToken) {
1479
+ requestParams[tokenParam] = params.continuationToken;
1480
+ }
1481
+ break;
1482
+ }
1483
+ return requestParams;
1484
+ }
1485
+ /**
1486
+ * Creates a paginated response from API response
1487
+ */
1488
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1489
+ // Extract fields from response
1490
+ const itemsField = fields.itemsField ||
1491
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1492
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1493
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1494
+ // Extract items and metadata
1495
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1496
+ const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
1497
+ const totalCount = Array.isArray(response.data) ? undefined : response.data[totalCountField];
1498
+ const continuationToken = response.data[continuationTokenField];
1499
+ // Determine if there are more pages
1500
+ const hasMore = this.determineHasMorePages(paginationType, {
1501
+ totalCount,
1502
+ pageSize: params.pageSize,
1503
+ currentPage: params.pageNumber || 1,
1504
+ itemsCount: items.length,
1505
+ continuationToken
1506
+ });
1507
+ // Create and return the page result
1508
+ return PaginationManager.createPaginatedResponse({
1509
+ pageInfo: {
1510
+ hasMore,
1511
+ totalCount,
1512
+ currentPage: params.pageNumber,
1513
+ pageSize: params.pageSize,
1514
+ continuationToken
1515
+ },
1516
+ type: paginationType,
1517
+ }, items);
1518
+ }
1519
+ /**
1520
+ * Determines if there are more pages based on pagination type and metadata
1521
+ */
1522
+ determineHasMorePages(paginationType, info) {
1523
+ switch (paginationType) {
1524
+ case PaginationType.OFFSET:
1525
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1526
+ // If totalCount is available, use it for precise calculation
1527
+ if (info.totalCount !== undefined) {
1528
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1529
+ }
1530
+ // Fallback when totalCount is not available
1531
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1532
+ return info.itemsCount === effectivePageSize;
1533
+ case PaginationType.TOKEN:
1534
+ return !!info.continuationToken;
1535
+ default:
1536
+ return false;
1537
+ }
1538
+ }
1539
+ }
1540
+ _BaseService_apiClient = new WeakMap();
1541
+
1542
+ /**
1543
+ * Maps fields for Feedback entities to ensure consistent naming.
1544
+ */
1545
+ const FeedbackMap = {
1546
+ createdAt: 'createdTime',
1547
+ updatedAt: 'updatedTime',
1548
+ };
1549
+
1550
+ /**
1551
+ * Base path constants for different services
1552
+ */
1553
+ const LLMOPS_BASE = 'llmopstenant_';
1554
+
1555
+ /**
1556
+ * Agent Feedback Service Endpoints
1557
+ */
1558
+ const FEEDBACK_ENDPOINTS = {
1559
+ GET_ALL: `${LLMOPS_BASE}/api/Feedback`,
1560
+ };
1561
+
1562
+ /**
1563
+ * SDK Telemetry constants
1564
+ */
1565
+ // Connection string placeholder that will be replaced during build
1566
+ 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";
1567
+ // SDK Version placeholder
1568
+ const SDK_VERSION = "1.3.4";
1569
+ const VERSION = "Version";
1570
+ const SERVICE = "Service";
1571
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1572
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1573
+ const CLOUD_URL = "CloudUrl";
1574
+ const CLOUD_CLIENT_ID = "CloudClientId";
1575
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1576
+ const APP_NAME = "ApplicationName";
1577
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1578
+ // Service and logger names
1579
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1580
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1581
+ // Event names
1582
+ const SDK_RUN_EVENT = "Sdk.Run";
1583
+ // Default value for unknown/empty attributes
1584
+ const UNKNOWN = "";
1585
+
1586
+ /**
1587
+ * Log exporter that sends ALL logs as Application Insights custom events
1588
+ */
1589
+ class ApplicationInsightsEventExporter {
1590
+ constructor(connectionString) {
1591
+ this.connectionString = connectionString;
1592
+ }
1593
+ export(logs, resultCallback) {
1594
+ try {
1595
+ logs.forEach(logRecord => {
1596
+ this.sendAsCustomEvent(logRecord);
1597
+ });
1598
+ resultCallback({ code: 0 });
1599
+ }
1600
+ catch (error) {
1601
+ console.debug('Failed to export logs to Application Insights:', error);
1602
+ resultCallback({ code: 2, error });
1603
+ }
1604
+ }
1605
+ shutdown() {
1606
+ return Promise.resolve();
1607
+ }
1608
+ sendAsCustomEvent(logRecord) {
1609
+ // Get event name from body or attributes
1610
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1611
+ const payload = {
1612
+ name: 'Microsoft.ApplicationInsights.Event',
1613
+ time: new Date().toISOString(),
1614
+ iKey: this.extractInstrumentationKey(),
1615
+ data: {
1616
+ baseType: 'EventData',
1617
+ baseData: {
1618
+ ver: 2,
1619
+ name: eventName,
1620
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1621
+ }
1622
+ },
1623
+ tags: {
1624
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1625
+ 'ai.cloud.roleInstance': SDK_VERSION
1626
+ }
1627
+ };
1628
+ this.sendToApplicationInsights(payload);
1629
+ }
1630
+ extractInstrumentationKey() {
1631
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1632
+ return match ? match[1] : '';
1633
+ }
1634
+ convertAttributesToProperties(attributes) {
1635
+ const properties = {};
1636
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1637
+ properties[key] = String(value);
1638
+ });
1639
+ return properties;
1640
+ }
1641
+ async sendToApplicationInsights(payload) {
1642
+ try {
1643
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1644
+ if (!ingestionEndpoint) {
1645
+ console.debug('No ingestion endpoint found in connection string');
1646
+ return;
1647
+ }
1648
+ const url = `${ingestionEndpoint}/v2/track`;
1649
+ const response = await fetch(url, {
1650
+ method: 'POST',
1651
+ headers: {
1652
+ 'Content-Type': 'application/json',
1653
+ },
1654
+ body: JSON.stringify(payload)
1655
+ });
1656
+ if (!response.ok) {
1657
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1658
+ }
1659
+ }
1660
+ catch (error) {
1661
+ console.debug('Error sending event telemetry to Application Insights:', error);
1662
+ }
1663
+ }
1664
+ extractIngestionEndpoint() {
1665
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1666
+ return match ? match[1] : '';
1667
+ }
1668
+ }
1669
+ /**
1670
+ * Singleton telemetry client
1671
+ */
1672
+ class TelemetryClient {
1673
+ constructor() {
1674
+ this.isInitialized = false;
1675
+ }
1676
+ static getInstance() {
1677
+ if (!TelemetryClient.instance) {
1678
+ TelemetryClient.instance = new TelemetryClient();
1679
+ }
1680
+ return TelemetryClient.instance;
1681
+ }
1682
+ /**
1683
+ * Initialize telemetry
1684
+ */
1685
+ initialize(config) {
1686
+ if (this.isInitialized) {
1687
+ return;
1688
+ }
1689
+ this.isInitialized = true;
1690
+ if (config) {
1691
+ this.telemetryContext = config;
1692
+ }
1693
+ try {
1694
+ const connectionString = this.getConnectionString();
1695
+ if (!connectionString) {
1696
+ return;
1697
+ }
1698
+ this.setupTelemetryProvider(connectionString);
1699
+ }
1700
+ catch (error) {
1701
+ // Silent failure - telemetry errors shouldn't break functionality
1702
+ console.debug('Failed to initialize OpenTelemetry:', error);
1703
+ }
1704
+ }
1705
+ getConnectionString() {
1706
+ const connectionString = CONNECTION_STRING;
1707
+ return connectionString;
1708
+ }
1709
+ setupTelemetryProvider(connectionString) {
1710
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
1711
+ const processor = new sdkLogs.BatchLogRecordProcessor(exporter);
1712
+ this.logProvider = new sdkLogs.LoggerProvider({
1713
+ processors: [processor]
1714
+ });
1715
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1716
+ }
1717
+ /**
1718
+ * Track a telemetry event
1719
+ */
1720
+ track(eventName, name, extraAttributes = {}) {
1721
+ try {
1722
+ // Skip if logger not initialized
1723
+ if (!this.logger) {
1724
+ return;
1725
+ }
1726
+ const finalDisplayName = name || eventName;
1727
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1728
+ // Emit as log
1729
+ this.logger.emit({
1730
+ body: finalDisplayName,
1731
+ attributes: attributes,
1732
+ timestamp: Date.now(),
1733
+ });
1734
+ }
1735
+ catch (error) {
1736
+ // Silent failure
1737
+ console.debug('Failed to track telemetry event:', error);
1738
+ }
1739
+ }
1740
+ /**
1741
+ * Get enriched attributes for telemetry events
1742
+ */
1743
+ getEnrichedAttributes(extraAttributes, eventName) {
1744
+ const attributes = {
1745
+ [APP_NAME]: SDK_SERVICE_NAME,
1746
+ [VERSION]: SDK_VERSION,
1747
+ [SERVICE]: eventName,
1748
+ [CLOUD_URL]: this.createCloudUrl(),
1749
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1750
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1751
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1752
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1753
+ ...extraAttributes,
1754
+ };
1755
+ return attributes;
1756
+ }
1757
+ /**
1758
+ * Create cloud URL from base URL, organization ID, and tenant ID
1759
+ */
1760
+ createCloudUrl() {
1761
+ const baseUrl = this.telemetryContext?.baseUrl;
1762
+ const orgId = this.telemetryContext?.orgName;
1763
+ const tenantId = this.telemetryContext?.tenantName;
1764
+ if (!baseUrl || !orgId || !tenantId) {
1765
+ return UNKNOWN;
1766
+ }
1767
+ return `${baseUrl}/${orgId}/${tenantId}`;
1768
+ }
1769
+ }
1770
+ // Export singleton instance
1771
+ const telemetryClient = TelemetryClient.getInstance();
1772
+
1773
+ /**
1774
+ * SDK Track decorator and function for telemetry
1775
+ */
1776
+ /**
1777
+ * Common tracking logic shared between method and function decorators
1778
+ */
1779
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1780
+ return function (...args) {
1781
+ // Determine if we should track this call
1782
+ let shouldTrack = true;
1783
+ if (opts.condition !== undefined) {
1784
+ if (typeof opts.condition === 'function') {
1785
+ shouldTrack = opts.condition.apply(this, args);
1786
+ }
1787
+ else {
1788
+ shouldTrack = opts.condition;
1789
+ }
1790
+ }
1791
+ // Track the event if enabled
1792
+ if (shouldTrack) {
1793
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
1794
+ const serviceMethod = nameOrOptions
1795
+ ;
1796
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
1797
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1798
+ }
1799
+ // Execute the original function
1800
+ return originalFunction.apply(this, args);
1801
+ };
1802
+ }
1803
+ /**
1804
+ * Track decorator that can be used to automatically track function calls
1805
+ *
1806
+ * Usage:
1807
+ * @track("Service.Method")
1808
+ * function myFunction() { ... }
1809
+ *
1810
+ * @track("Queue.GetAll")
1811
+ * async getAll() { ... }
1812
+ *
1813
+ * @track("Tasks.Create")
1814
+ * async create() { ... }
1815
+ *
1816
+ * @track("Assets.Update", { condition: false })
1817
+ * function myFunction() { ... }
1818
+ *
1819
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
1820
+ * function myFunction() { ... }
1821
+ */
1822
+ function track(nameOrOptions, options) {
1823
+ return function decorator(_target, propertyKey, descriptor) {
1824
+ const opts = {};
1825
+ if (descriptor && typeof descriptor.value === 'function') {
1826
+ // Method decorator
1827
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
1828
+ return descriptor;
1829
+ }
1830
+ // Function decorator
1831
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
1832
+ };
1833
+ }
1834
+
1835
+ /**
1836
+ * Service for interacting with UiPath Agent Feedback API
1837
+ */
1838
+ class FeedbackService extends BaseService {
1839
+ /**
1840
+ * Gets all feedback across all agents in the tenant, with optional filters.
1841
+ *
1842
+ * Retrieves a list of feedback entries, optionally filtered by agent, trace, span, status, or agent version.
1843
+ * 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.
1844
+ *
1845
+ * @param options - Optional query parameters for filtering and pagination
1846
+ * @returns Promise resolving to {@link NonPaginatedResponse} of {@link FeedbackGetResponse} without pagination options, or {@link PaginatedResponse} of {@link FeedbackGetResponse} when pagination options are used.
1847
+ * @example
1848
+ * ```typescript
1849
+ * import { Feedback, FeedbackStatus } from '@uipath/uipath-typescript/feedback';
1850
+ *
1851
+ * // Get all feedback (default pagination: returns first 50 items)
1852
+ * const allFeedback = await feedback.getAll();
1853
+ *
1854
+ * // Get the agentId from a feedback entry
1855
+ * const agentId = allFeedback.items[0].agentId;
1856
+ *
1857
+ * // Get feedback for a specific agent
1858
+ * const agentFeedback = await feedback.getAll({
1859
+ * agentId,
1860
+ * });
1861
+ *
1862
+ * // First page with pagination
1863
+ * const page1 = await feedback.getAll({ pageSize: 10 });
1864
+ *
1865
+ * // Navigate using cursor
1866
+ * if (page1.hasNextPage) {
1867
+ * const page2 = await feedback.getAll({ cursor: page1.nextCursor });
1868
+ * }
1869
+ *
1870
+ * // Filter by status
1871
+ * const activeFeedback = await feedback.getAll({
1872
+ * status: FeedbackStatus.Pending,
1873
+ * });
1874
+ * ```
1875
+ */
1876
+ async getAll(options) {
1877
+ const transformFeedbackResponse = (item) => transformData(item, FeedbackMap);
1878
+ return PaginationHelpers.getAll({
1879
+ serviceAccess: this.createPaginationServiceAccess(),
1880
+ getEndpoint: () => FEEDBACK_ENDPOINTS.GET_ALL,
1881
+ transformFn: transformFeedbackResponse,
1882
+ pagination: {
1883
+ paginationType: PaginationType.OFFSET,
1884
+ paginationParams: {
1885
+ pageSizeParam: FEEDBACK_OFFSET_PARAMS.PAGE_SIZE_PARAM,
1886
+ offsetParam: FEEDBACK_OFFSET_PARAMS.OFFSET_PARAM,
1887
+ countParam: FEEDBACK_OFFSET_PARAMS.COUNT_PARAM,
1888
+ },
1889
+ },
1890
+ excludeFromPrefix: Object.keys(options || {}),
1891
+ }, options);
1892
+ }
1893
+ }
1894
+ __decorate([
1895
+ track('Feedback.GetAll')
1896
+ ], FeedbackService.prototype, "getAll", null);
1897
+
1898
+ /**
1899
+ * Status of a feedback entry in the review workflow
1900
+ */
1901
+ exports.FeedbackStatus = void 0;
1902
+ (function (FeedbackStatus) {
1903
+ /** Feedback is awaiting review */
1904
+ FeedbackStatus[FeedbackStatus["Pending"] = 0] = "Pending";
1905
+ /** Feedback has been approved and confirmed */
1906
+ FeedbackStatus[FeedbackStatus["Approved"] = 1] = "Approved";
1907
+ /** Feedback has been dismissed */
1908
+ FeedbackStatus[FeedbackStatus["Dismissed"] = 2] = "Dismissed";
1909
+ })(exports.FeedbackStatus || (exports.FeedbackStatus = {}));
1910
+
1911
+ exports.Feedback = FeedbackService;