@uipath/uipath-typescript 1.0.0-beta.18 → 1.0.0

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