@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,2361 @@
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
+ * Bucket pagination constants for token-based pagination
888
+ */
889
+ const BUCKET_PAGINATION = {
890
+ /** Field name for items in bucket file metadata response */
891
+ ITEMS_FIELD: 'items',
892
+ /** Field name for continuation token in bucket file metadata response */
893
+ CONTINUATION_TOKEN_FIELD: 'continuationToken'
894
+ };
895
+ /**
896
+ * OData OFFSET pagination parameter names (ODATA-style)
897
+ */
898
+ const ODATA_OFFSET_PARAMS = {
899
+ /** OData page size parameter name */
900
+ PAGE_SIZE_PARAM: '$top',
901
+ /** OData offset parameter name */
902
+ OFFSET_PARAM: '$skip',
903
+ /** OData count parameter name */
904
+ COUNT_PARAM: '$count'
905
+ };
906
+ /**
907
+ * Bucket TOKEN pagination parameter names
908
+ */
909
+ const BUCKET_TOKEN_PARAMS = {
910
+ /** Bucket page size parameter name */
911
+ PAGE_SIZE_PARAM: 'takeHint',
912
+ /** Bucket token parameter name */
913
+ TOKEN_PARAM: 'continuationToken'
914
+ };
915
+
916
+ /**
917
+ * Transforms data by mapping fields according to the provided field mapping
918
+ * @param data The source data to transform
919
+ * @param fieldMapping Object mapping source field names to target field names
920
+ * @returns Transformed data with mapped field names
921
+ *
922
+ * @example
923
+ * ```typescript
924
+ * // Single object transformation
925
+ * const data = { id: '123', userName: 'john' };
926
+ * const mapping = { id: 'userId', userName: 'name' };
927
+ * const result = transformData(data, mapping);
928
+ * // result = { userId: '123', name: 'john' }
929
+ *
930
+ * // Array transformation
931
+ * const dataArray = [
932
+ * { id: '123', userName: 'john' },
933
+ * { id: '456', userName: 'jane' }
934
+ * ];
935
+ * const result = transformData(dataArray, mapping);
936
+ * // result = [
937
+ * // { userId: '123', name: 'john' },
938
+ * // { userId: '456', name: 'jane' }
939
+ * // ]
940
+ * ```
941
+ */
942
+ function transformData(data, fieldMapping) {
943
+ // Handle array of objects
944
+ if (Array.isArray(data)) {
945
+ return data.map(item => transformData(item, fieldMapping));
946
+ }
947
+ // Handle single object
948
+ const result = { ...data };
949
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
950
+ if (sourceField in result) {
951
+ const value = result[sourceField];
952
+ delete result[sourceField];
953
+ result[targetField] = value;
954
+ }
955
+ }
956
+ return result;
957
+ }
958
+ /**
959
+ * Converts a string from PascalCase to camelCase
960
+ * @param str The PascalCase string to convert
961
+ * @returns The camelCase version of the string
962
+ *
963
+ * @example
964
+ * ```typescript
965
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
966
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
967
+ * ```
968
+ */
969
+ function pascalToCamelCase(str) {
970
+ if (!str)
971
+ return str;
972
+ return str.charAt(0).toLowerCase() + str.slice(1);
973
+ }
974
+ /**
975
+ * Generic function to transform object keys using a provided case conversion function
976
+ * @param data The object to transform
977
+ * @param convertCase The function to convert each key
978
+ * @returns A new object with transformed keys
979
+ */
980
+ function transformCaseKeys(data, convertCase) {
981
+ // Handle array of objects
982
+ if (Array.isArray(data)) {
983
+ return data.map(item => {
984
+ // If the array element is a primitive (string, number, etc.), return it as is
985
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
986
+ return item;
987
+ }
988
+ // Only recursively transform if it's actually an object
989
+ return transformCaseKeys(item, convertCase);
990
+ });
991
+ }
992
+ const result = {};
993
+ for (const [key, value] of Object.entries(data)) {
994
+ const transformedKey = convertCase(key);
995
+ // Recursively transform nested objects and arrays
996
+ if (value !== null && typeof value === 'object') {
997
+ result[transformedKey] = transformCaseKeys(value, convertCase);
998
+ }
999
+ else {
1000
+ result[transformedKey] = value;
1001
+ }
1002
+ }
1003
+ return result;
1004
+ }
1005
+ /**
1006
+ * Transforms an object's keys from PascalCase to camelCase
1007
+ * @param data The object with PascalCase keys
1008
+ * @returns A new object with all keys converted to camelCase
1009
+ *
1010
+ * @example
1011
+ * ```typescript
1012
+ * // Simple object
1013
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
1014
+ * // Result: { id: "123", taskName: "Invoice" }
1015
+ *
1016
+ * // Nested object
1017
+ * pascalToCamelCaseKeys({
1018
+ * TaskId: "456",
1019
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
1020
+ * });
1021
+ * // Result: {
1022
+ * // taskId: "456",
1023
+ * // taskDetails: { assignedUser: "John", priority: "High" }
1024
+ * // }
1025
+ *
1026
+ * // Array of objects
1027
+ * pascalToCamelCaseKeys([
1028
+ * { Id: "1", IsComplete: false },
1029
+ * { Id: "2", IsComplete: true }
1030
+ * ]);
1031
+ * // Result: [
1032
+ * // { id: "1", isComplete: false },
1033
+ * // { id: "2", isComplete: true }
1034
+ * // ]
1035
+ * ```
1036
+ */
1037
+ function pascalToCamelCaseKeys(data) {
1038
+ return transformCaseKeys(data, pascalToCamelCase);
1039
+ }
1040
+ /**
1041
+ * Adds a prefix to specified keys in an object, returning a new object.
1042
+ * Only the provided keys are prefixed; all others are left unchanged.
1043
+ *
1044
+ * @param obj The source object
1045
+ * @param prefix The prefix to add (e.g., '$')
1046
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1047
+ * @returns A new object with specified keys prefixed
1048
+ *
1049
+ * @example
1050
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1051
+ */
1052
+ function addPrefixToKeys(obj, prefix, keys) {
1053
+ const result = {};
1054
+ for (const [key, value] of Object.entries(obj)) {
1055
+ if (keys.includes(key)) {
1056
+ result[`${prefix}${key}`] = value;
1057
+ }
1058
+ else {
1059
+ result[key] = value;
1060
+ }
1061
+ }
1062
+ return result;
1063
+ }
1064
+ /**
1065
+ * Transforms an array-based dictionary with separate keys and values arrays
1066
+ * into a standard JavaScript object/record
1067
+ *
1068
+ * @param dictionary Object containing keys and values arrays
1069
+ * @returns A standard record object with direct key-value mapping
1070
+ *
1071
+ * @example
1072
+ * ```typescript
1073
+ * const arrayDict = {
1074
+ * keys: ['Content-Type', 'x-ms-blob-type'],
1075
+ * values: ['application/json', 'BlockBlob']
1076
+ * };
1077
+ * const record = arrayDictionaryToRecord(arrayDict);
1078
+ * // result = {
1079
+ * // 'Content-Type': 'application/json',
1080
+ * // 'x-ms-blob-type': 'BlockBlob'
1081
+ * // }
1082
+ * ```
1083
+ */
1084
+ function arrayDictionaryToRecord(dictionary) {
1085
+ if (!dictionary || !dictionary.keys || !dictionary.values) {
1086
+ return {};
1087
+ }
1088
+ if (dictionary.keys.length !== dictionary.values.length) {
1089
+ console.warn('Keys and values arrays have different lengths');
1090
+ }
1091
+ const record = {};
1092
+ const length = Math.min(dictionary.keys.length, dictionary.values.length);
1093
+ for (let i = 0; i < length; i++) {
1094
+ record[dictionary.keys[i]] = dictionary.values[i];
1095
+ }
1096
+ return record;
1097
+ }
1098
+
1099
+ /**
1100
+ * Constants used throughout the pagination system
1101
+ */
1102
+ /** Maximum number of items that can be requested in a single page */
1103
+ const MAX_PAGE_SIZE = 1000;
1104
+ /** Default page size when jumpToPage is used without specifying pageSize */
1105
+ const DEFAULT_PAGE_SIZE = 50;
1106
+ /** Default field name for items in a paginated response */
1107
+ const DEFAULT_ITEMS_FIELD = 'value';
1108
+ /** Default field name for total count in a paginated response */
1109
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1110
+ /**
1111
+ * Limits the page size to the maximum allowed value
1112
+ * @param pageSize - Requested page size
1113
+ * @returns Limited page size value
1114
+ */
1115
+ function getLimitedPageSize(pageSize) {
1116
+ if (pageSize === undefined || pageSize === null) {
1117
+ return DEFAULT_PAGE_SIZE;
1118
+ }
1119
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1120
+ }
1121
+
1122
+ /**
1123
+ * Helper functions for pagination that can be used across services
1124
+ */
1125
+ class PaginationHelpers {
1126
+ /**
1127
+ * Checks if any pagination parameters are provided
1128
+ *
1129
+ * @param options - The options object to check
1130
+ * @returns True if any pagination parameter is defined, false otherwise
1131
+ */
1132
+ static hasPaginationParameters(options = {}) {
1133
+ const { cursor, pageSize, jumpToPage } = options;
1134
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1135
+ }
1136
+ /**
1137
+ * Parse a pagination cursor string into cursor data
1138
+ */
1139
+ static parseCursor(cursorString) {
1140
+ try {
1141
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1142
+ return cursorData;
1143
+ }
1144
+ catch {
1145
+ throw new Error('Invalid pagination cursor');
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Validates cursor format and structure
1150
+ *
1151
+ * @param paginationOptions - The pagination options containing the cursor
1152
+ * @param paginationType - Optional pagination type to validate against
1153
+ */
1154
+ static validateCursor(paginationOptions, paginationType) {
1155
+ if (paginationOptions.cursor !== undefined) {
1156
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1157
+ throw new Error('cursor must contain a valid cursor string');
1158
+ }
1159
+ try {
1160
+ // Try to parse the cursor to validate it
1161
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1162
+ // If type is provided, validate cursor contains expected type information
1163
+ if (paginationType) {
1164
+ if (!cursorData.type) {
1165
+ throw new Error('Invalid cursor: missing pagination type');
1166
+ }
1167
+ // Check pagination type compatibility
1168
+ if (cursorData.type !== paginationType) {
1169
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1170
+ }
1171
+ }
1172
+ }
1173
+ catch (error) {
1174
+ if (error instanceof Error) {
1175
+ // If it's already our error with specific message, pass it through
1176
+ if (error.message.startsWith('Invalid cursor') ||
1177
+ error.message.startsWith('Pagination type mismatch')) {
1178
+ throw error;
1179
+ }
1180
+ }
1181
+ throw new Error('Invalid pagination cursor format');
1182
+ }
1183
+ }
1184
+ }
1185
+ /**
1186
+ * Comprehensive validation for pagination options
1187
+ *
1188
+ * @param options - The pagination options to validate
1189
+ * @param paginationType - The pagination type these options will be used with
1190
+ * @returns Processed pagination parameters ready for use
1191
+ */
1192
+ static validatePaginationOptions(options, paginationType) {
1193
+ // Validate pageSize
1194
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1195
+ throw new Error('pageSize must be a positive number');
1196
+ }
1197
+ // Validate jumpToPage
1198
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1199
+ throw new Error('jumpToPage must be a positive number');
1200
+ }
1201
+ // Validate cursor
1202
+ PaginationHelpers.validateCursor(options, paginationType);
1203
+ // Validate service compatibility
1204
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1205
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1206
+ }
1207
+ // Get processed parameters
1208
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1209
+ }
1210
+ /**
1211
+ * Convert a unified pagination options to service-specific parameters
1212
+ */
1213
+ static getRequestParameters(options, paginationType) {
1214
+ // Handle jumpToPage
1215
+ if (options.jumpToPage !== undefined) {
1216
+ const jumpToPageOptions = {
1217
+ pageSize: options.pageSize,
1218
+ pageNumber: options.jumpToPage
1219
+ };
1220
+ return filterUndefined(jumpToPageOptions);
1221
+ }
1222
+ // If no cursor is provided, it's a first page request
1223
+ if (!options.cursor) {
1224
+ const firstPageOptions = {
1225
+ pageSize: options.pageSize,
1226
+ // Only set pageNumber for OFFSET pagination
1227
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1228
+ };
1229
+ return filterUndefined(firstPageOptions);
1230
+ }
1231
+ // Parse the cursor
1232
+ try {
1233
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1234
+ const cursorBasedOptions = {
1235
+ pageSize: cursorData.pageSize || options.pageSize,
1236
+ pageNumber: cursorData.pageNumber,
1237
+ continuationToken: cursorData.continuationToken,
1238
+ type: cursorData.type,
1239
+ };
1240
+ return filterUndefined(cursorBasedOptions);
1241
+ }
1242
+ catch {
1243
+ throw new Error('Invalid pagination cursor');
1244
+ }
1245
+ }
1246
+ /**
1247
+ * Helper method for paginated resource retrieval
1248
+ *
1249
+ * @param params - Parameters for pagination
1250
+ * @returns Promise resolving to a paginated result
1251
+ */
1252
+ static async getAllPaginated(params) {
1253
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1254
+ const endpoint = getEndpoint(folderId);
1255
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1256
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1257
+ headers,
1258
+ params: additionalParams,
1259
+ pagination: {
1260
+ paginationType: options.paginationType || PaginationType.OFFSET,
1261
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1262
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1263
+ continuationTokenField: options.continuationTokenField,
1264
+ paginationParams: options.paginationParams
1265
+ }
1266
+ });
1267
+ // Parse items - automatically handle JSON string responses
1268
+ const rawItems = paginatedResponse.items;
1269
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1270
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1271
+ return {
1272
+ ...paginatedResponse,
1273
+ items: transformedItems
1274
+ };
1275
+ }
1276
+ /**
1277
+ * Helper method for non-paginated resource retrieval
1278
+ *
1279
+ * @param params - Parameters for non-paginated resource retrieval
1280
+ * @returns Promise resolving to an object with data and totalCount
1281
+ */
1282
+ static async getAllNonPaginated(params) {
1283
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1284
+ // Set default field names
1285
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1286
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1287
+ // Determine endpoint and headers based on folderId
1288
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1289
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1290
+ // Make the API call based on method
1291
+ let response;
1292
+ if (method === HTTP_METHODS.POST) {
1293
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1294
+ }
1295
+ else {
1296
+ response = await serviceAccess.get(endpoint, {
1297
+ params: additionalParams,
1298
+ headers
1299
+ });
1300
+ }
1301
+ // Extract and transform items from response
1302
+ const rawItems = response.data?.[itemsField];
1303
+ const totalCount = response.data?.[totalCountField];
1304
+ // Parse items - automatically handle JSON string responses
1305
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1306
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1307
+ return {
1308
+ items,
1309
+ totalCount
1310
+ };
1311
+ }
1312
+ /**
1313
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1314
+ *
1315
+ * @param config - Configuration for the getAll operation
1316
+ * @param options - Request options including pagination parameters
1317
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1318
+ */
1319
+ static async getAll(config, options) {
1320
+ const optionsWithDefaults = options || {};
1321
+ const { folderId, ...restOptions } = optionsWithDefaults;
1322
+ const cursor = options?.cursor;
1323
+ const pageSize = options?.pageSize;
1324
+ const jumpToPage = options?.jumpToPage;
1325
+ // Determine if pagination is requested
1326
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1327
+ // Process parameters (custom processing if provided, otherwise default)
1328
+ let processedOptions = restOptions;
1329
+ if (config.processParametersFn) {
1330
+ processedOptions = config.processParametersFn(restOptions, folderId);
1331
+ }
1332
+ // Apply ODATA prefix to keys (excluding specified keys)
1333
+ const excludeKeys = config.excludeFromPrefix || [];
1334
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1335
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1336
+ // Default pagination options
1337
+ const paginationOptions = {
1338
+ paginationType: PaginationType.OFFSET,
1339
+ itemsField: DEFAULT_ITEMS_FIELD,
1340
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1341
+ ...config.pagination
1342
+ };
1343
+ // Paginated flow
1344
+ if (isPaginationRequested) {
1345
+ return PaginationHelpers.getAllPaginated({
1346
+ serviceAccess: config.serviceAccess,
1347
+ getEndpoint: config.getEndpoint,
1348
+ folderId,
1349
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1350
+ additionalParams: prefixedOptions,
1351
+ transformFn: config.transformFn,
1352
+ method: config.method,
1353
+ options: {
1354
+ ...paginationOptions,
1355
+ paginationParams: config.pagination?.paginationParams
1356
+ }
1357
+ }); // Type assertion needed due to conditional return
1358
+ }
1359
+ // Non-paginated flow
1360
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1361
+ return PaginationHelpers.getAllNonPaginated({
1362
+ serviceAccess: config.serviceAccess,
1363
+ getAllEndpoint: config.getEndpoint(),
1364
+ getByFolderEndpoint: byFolderEndpoint,
1365
+ folderId,
1366
+ additionalParams: prefixedOptions,
1367
+ transformFn: config.transformFn,
1368
+ method: config.method,
1369
+ options: {
1370
+ itemsField: paginationOptions.itemsField,
1371
+ totalCountField: paginationOptions.totalCountField
1372
+ }
1373
+ });
1374
+ }
1375
+ }
1376
+
1377
+ /**
1378
+ * SDK Internals Registry - Internal registry for SDK instances
1379
+ *
1380
+ * This class is NOT exported in the public API.
1381
+ * It provides a secure way to share SDK internals between
1382
+ * the UiPath class and service classes without exposing them publicly.
1383
+ *
1384
+ * @internal
1385
+ */
1386
+ // Global symbol key to ensure WeakMap is shared across module instances
1387
+ // This prevents issues when core and service modules are bundled separately
1388
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1389
+ // Get or create the global WeakMap store
1390
+ const getGlobalStore = () => {
1391
+ const globalObj = globalThis;
1392
+ if (!globalObj[REGISTRY_KEY]) {
1393
+ globalObj[REGISTRY_KEY] = new WeakMap();
1394
+ }
1395
+ return globalObj[REGISTRY_KEY];
1396
+ };
1397
+ /**
1398
+ * Internal registry for SDK private components.
1399
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1400
+ * garbage collected when the SDK instance is no longer referenced.
1401
+ *
1402
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1403
+ * across separately bundled modules (core, entities, tasks, etc.).
1404
+ *
1405
+ * @internal - Not exported in public API
1406
+ */
1407
+ class SDKInternalsRegistry {
1408
+ // Use global store to ensure sharing across module bundles
1409
+ static get store() {
1410
+ return getGlobalStore();
1411
+ }
1412
+ /**
1413
+ * Register SDK instance internals
1414
+ * Called by UiPath constructor
1415
+ */
1416
+ static set(instance, internals) {
1417
+ this.store.set(instance, internals);
1418
+ }
1419
+ /**
1420
+ * Retrieve SDK instance internals
1421
+ * Called by BaseService constructor
1422
+ */
1423
+ static get(instance) {
1424
+ const internals = this.store.get(instance);
1425
+ if (!internals) {
1426
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1427
+ }
1428
+ return internals;
1429
+ }
1430
+ }
1431
+
1432
+ var _BaseService_apiClient;
1433
+ /**
1434
+ * Base class for all UiPath SDK services.
1435
+ *
1436
+ * Provides common functionality for authentication, configuration, and API communication.
1437
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1438
+ *
1439
+ * This class implements the dependency injection pattern where services receive a configured
1440
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1441
+ * including authentication token management.
1442
+ *
1443
+ * @remarks
1444
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1445
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1446
+ *
1447
+ */
1448
+ class BaseService {
1449
+ /**
1450
+ * Creates a base service instance with dependency injection.
1451
+ *
1452
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1453
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1454
+ * and token management internally.
1455
+ *
1456
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1457
+ * Services receive this via dependency injection in the modular pattern.
1458
+ *
1459
+ * @example
1460
+ * ```typescript
1461
+ * // Services automatically call this via super()
1462
+ * export class EntityService extends BaseService {
1463
+ * constructor(instance: IUiPath) {
1464
+ * super(instance); // Initializes the internal ApiClient
1465
+ * }
1466
+ * }
1467
+ *
1468
+ * // Usage in modular pattern
1469
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1470
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1471
+ *
1472
+ * const sdk = new UiPath(config);
1473
+ * await sdk.initialize();
1474
+ * const entities = new Entities(sdk);
1475
+ * ```
1476
+ */
1477
+ constructor(instance) {
1478
+ // Private field - not visible via Object.keys() or any reflection
1479
+ _BaseService_apiClient.set(this, void 0);
1480
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1481
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1482
+ }
1483
+ /**
1484
+ * Gets a valid authentication token, refreshing if necessary.
1485
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1486
+ *
1487
+ * @returns Promise resolving to a valid access token string
1488
+ * @throws AuthenticationError if no token is available or refresh fails
1489
+ */
1490
+ async getValidAuthToken() {
1491
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1492
+ }
1493
+ /**
1494
+ * Creates a service accessor for pagination helpers
1495
+ * This allows pagination helpers to access protected methods without making them public
1496
+ */
1497
+ createPaginationServiceAccess() {
1498
+ return {
1499
+ get: (path, options) => this.get(path, options || {}),
1500
+ post: (path, body, options) => this.post(path, body, options || {}),
1501
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1502
+ };
1503
+ }
1504
+ async request(method, path, options = {}) {
1505
+ switch (method.toUpperCase()) {
1506
+ case 'GET':
1507
+ return this.get(path, options);
1508
+ case 'POST':
1509
+ return this.post(path, options.body, options);
1510
+ case 'PUT':
1511
+ return this.put(path, options.body, options);
1512
+ case 'PATCH':
1513
+ return this.patch(path, options.body, options);
1514
+ case 'DELETE':
1515
+ return this.delete(path, options);
1516
+ default:
1517
+ throw new Error(`Unsupported HTTP method: ${method}`);
1518
+ }
1519
+ }
1520
+ async requestWithSpec(spec) {
1521
+ if (!spec.method || !spec.url) {
1522
+ throw new Error('Request spec must include method and url');
1523
+ }
1524
+ return this.request(spec.method, spec.url, spec);
1525
+ }
1526
+ async get(path, options = {}) {
1527
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1528
+ return { data: response };
1529
+ }
1530
+ async post(path, data, options = {}) {
1531
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1532
+ return { data: response };
1533
+ }
1534
+ async put(path, data, options = {}) {
1535
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1536
+ return { data: response };
1537
+ }
1538
+ async patch(path, data, options = {}) {
1539
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1540
+ return { data: response };
1541
+ }
1542
+ async delete(path, options = {}) {
1543
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1544
+ return { data: response };
1545
+ }
1546
+ /**
1547
+ * Execute a request with cursor-based pagination
1548
+ */
1549
+ async requestWithPagination(method, path, paginationOptions, options) {
1550
+ const paginationType = options.pagination.paginationType;
1551
+ // Validate and prepare pagination parameters
1552
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1553
+ // Prepare request parameters based on pagination type
1554
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1555
+ // For POST requests, merge pagination params into body; for GET, use query params
1556
+ if (method.toUpperCase() === 'POST') {
1557
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1558
+ options.body = {
1559
+ ...existingBody,
1560
+ ...options.params,
1561
+ ...requestParams
1562
+ };
1563
+ }
1564
+ else {
1565
+ // Merge pagination parameters with existing parameters
1566
+ options.params = {
1567
+ ...options.params,
1568
+ ...requestParams
1569
+ };
1570
+ }
1571
+ // Make the request
1572
+ const response = await this.request(method, path, options);
1573
+ // Extract data from the response and create page result
1574
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1575
+ itemsField: options.pagination.itemsField,
1576
+ totalCountField: options.pagination.totalCountField,
1577
+ continuationTokenField: options.pagination.continuationTokenField
1578
+ });
1579
+ }
1580
+ /**
1581
+ * Validates and prepares pagination parameters from options
1582
+ */
1583
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1584
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1585
+ }
1586
+ /**
1587
+ * Prepares request parameters for pagination based on pagination type
1588
+ */
1589
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1590
+ const requestParams = {};
1591
+ let limitedPageSize;
1592
+ const paginationParams = paginationConfig?.paginationParams;
1593
+ switch (paginationType) {
1594
+ case PaginationType.OFFSET:
1595
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1596
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1597
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1598
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1599
+ requestParams[pageSizeParam] = limitedPageSize;
1600
+ if (params.pageNumber && params.pageNumber > 1) {
1601
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1602
+ }
1603
+ // Include total count for ODATA APIs
1604
+ {
1605
+ requestParams[countParam] = true;
1606
+ }
1607
+ break;
1608
+ case PaginationType.TOKEN:
1609
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1610
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1611
+ if (params.pageSize) {
1612
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1613
+ }
1614
+ if (params.continuationToken) {
1615
+ requestParams[tokenParam] = params.continuationToken;
1616
+ }
1617
+ break;
1618
+ }
1619
+ return requestParams;
1620
+ }
1621
+ /**
1622
+ * Creates a paginated response from API response
1623
+ */
1624
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1625
+ // Extract fields from response
1626
+ const itemsField = fields.itemsField ||
1627
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1628
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1629
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1630
+ // Extract items and metadata
1631
+ const items = response.data[itemsField] || [];
1632
+ const totalCount = response.data[totalCountField];
1633
+ const continuationToken = response.data[continuationTokenField];
1634
+ // Determine if there are more pages
1635
+ const hasMore = this.determineHasMorePages(paginationType, {
1636
+ totalCount,
1637
+ pageSize: params.pageSize,
1638
+ currentPage: params.pageNumber || 1,
1639
+ itemsCount: items.length,
1640
+ continuationToken
1641
+ });
1642
+ // Create and return the page result
1643
+ return PaginationManager.createPaginatedResponse({
1644
+ pageInfo: {
1645
+ hasMore,
1646
+ totalCount,
1647
+ currentPage: params.pageNumber,
1648
+ pageSize: params.pageSize,
1649
+ continuationToken
1650
+ },
1651
+ type: paginationType,
1652
+ }, items);
1653
+ }
1654
+ /**
1655
+ * Determines if there are more pages based on pagination type and metadata
1656
+ */
1657
+ determineHasMorePages(paginationType, info) {
1658
+ switch (paginationType) {
1659
+ case PaginationType.OFFSET:
1660
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1661
+ // If totalCount is available, use it for precise calculation
1662
+ if (info.totalCount !== undefined) {
1663
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1664
+ }
1665
+ // Fallback when totalCount is not available
1666
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1667
+ return info.itemsCount === effectivePageSize;
1668
+ case PaginationType.TOKEN:
1669
+ return !!info.continuationToken;
1670
+ default:
1671
+ return false;
1672
+ }
1673
+ }
1674
+ }
1675
+ _BaseService_apiClient = new WeakMap();
1676
+
1677
+ /**
1678
+ * Base service for services that need folder-specific functionality.
1679
+ *
1680
+ * Extends BaseService with additional methods for working with folder-scoped resources
1681
+ * in UiPath Orchestrator. Services that work with folders (Assets, Queues) extend this class.
1682
+ *
1683
+ * @remarks
1684
+ * This class provides helper methods for making folder-scoped API calls, handling folder IDs
1685
+ * in request headers, and managing cross-folder queries.
1686
+ */
1687
+ class FolderScopedService extends BaseService {
1688
+ /**
1689
+ * Gets resources in a folder with optional query parameters
1690
+ *
1691
+ * @param endpoint - API endpoint to call
1692
+ * @param folderId - required folder ID
1693
+ * @param options - Query options
1694
+ * @param transformFn - Optional function to transform the response data
1695
+ * @returns Promise resolving to an array of resources
1696
+ */
1697
+ async _getByFolder(endpoint, folderId, options = {}, transformFn) {
1698
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
1699
+ const keysToPrefix = Object.keys(options);
1700
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
1701
+ const response = await this.get(endpoint, {
1702
+ params: apiOptions,
1703
+ headers
1704
+ });
1705
+ if (transformFn) {
1706
+ return response.data?.value.map(transformFn);
1707
+ }
1708
+ return response.data?.value;
1709
+ }
1710
+ }
1711
+
1712
+ /**
1713
+ * API Endpoint Constants
1714
+ * Centralized location for all API endpoints used throughout the SDK
1715
+ */
1716
+ /**
1717
+ * Base path constants for different services
1718
+ */
1719
+ const ORCHESTRATOR_BASE = 'orchestrator_';
1720
+ /**
1721
+ * Orchestrator Bucket Endpoints
1722
+ */
1723
+ const BUCKET_ENDPOINTS = {
1724
+ GET_BY_FOLDER: `${ORCHESTRATOR_BASE}/odata/Buckets`,
1725
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/Buckets/UiPath.Server.Configuration.OData.GetBucketsAcrossFolders`,
1726
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Buckets(${id})`,
1727
+ GET_FILE_META_DATA: (id) => `${ORCHESTRATOR_BASE}/api/Buckets/${id}/ListFiles`,
1728
+ GET_READ_URI: (id) => `${ORCHESTRATOR_BASE}/odata/Buckets(${id})/UiPath.Server.Configuration.OData.GetReadUri`,
1729
+ GET_WRITE_URI: (id) => `${ORCHESTRATOR_BASE}/odata/Buckets(${id})/UiPath.Server.Configuration.OData.GetWriteUri`,
1730
+ };
1731
+
1732
+ /**
1733
+ * Maps fields for Bucket entities to ensure consistent naming
1734
+ */
1735
+ const BucketMap = {
1736
+ fullPath: 'path',
1737
+ items: 'blobItems',
1738
+ verb: 'httpMethod'
1739
+ };
1740
+
1741
+ /**
1742
+ * SDK Telemetry constants
1743
+ */
1744
+ // Connection string placeholder that will be replaced during build
1745
+ 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";
1746
+ // SDK Version placeholder
1747
+ const SDK_VERSION = "1.0.0";
1748
+ const VERSION = "Version";
1749
+ const SERVICE = "Service";
1750
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1751
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1752
+ const CLOUD_URL = "CloudUrl";
1753
+ const CLOUD_CLIENT_ID = "CloudClientId";
1754
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1755
+ const APP_NAME = "ApplicationName";
1756
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1757
+ // Service and logger names
1758
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1759
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1760
+ // Event names
1761
+ const SDK_RUN_EVENT = "Sdk.Run";
1762
+ // Default value for unknown/empty attributes
1763
+ const UNKNOWN = "";
1764
+
1765
+ /**
1766
+ * Log exporter that sends ALL logs as Application Insights custom events
1767
+ */
1768
+ class ApplicationInsightsEventExporter {
1769
+ constructor(connectionString) {
1770
+ this.connectionString = connectionString;
1771
+ }
1772
+ export(logs, resultCallback) {
1773
+ try {
1774
+ logs.forEach(logRecord => {
1775
+ this.sendAsCustomEvent(logRecord);
1776
+ });
1777
+ resultCallback({ code: 0 });
1778
+ }
1779
+ catch (error) {
1780
+ console.debug('Failed to export logs to Application Insights:', error);
1781
+ resultCallback({ code: 2, error });
1782
+ }
1783
+ }
1784
+ shutdown() {
1785
+ return Promise.resolve();
1786
+ }
1787
+ sendAsCustomEvent(logRecord) {
1788
+ // Get event name from body or attributes
1789
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1790
+ const payload = {
1791
+ name: 'Microsoft.ApplicationInsights.Event',
1792
+ time: new Date().toISOString(),
1793
+ iKey: this.extractInstrumentationKey(),
1794
+ data: {
1795
+ baseType: 'EventData',
1796
+ baseData: {
1797
+ ver: 2,
1798
+ name: eventName,
1799
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1800
+ }
1801
+ },
1802
+ tags: {
1803
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1804
+ 'ai.cloud.roleInstance': SDK_VERSION
1805
+ }
1806
+ };
1807
+ this.sendToApplicationInsights(payload);
1808
+ }
1809
+ extractInstrumentationKey() {
1810
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1811
+ return match ? match[1] : '';
1812
+ }
1813
+ convertAttributesToProperties(attributes) {
1814
+ const properties = {};
1815
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1816
+ properties[key] = String(value);
1817
+ });
1818
+ return properties;
1819
+ }
1820
+ async sendToApplicationInsights(payload) {
1821
+ try {
1822
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1823
+ if (!ingestionEndpoint) {
1824
+ console.debug('No ingestion endpoint found in connection string');
1825
+ return;
1826
+ }
1827
+ const url = `${ingestionEndpoint}/v2/track`;
1828
+ const response = await fetch(url, {
1829
+ method: 'POST',
1830
+ headers: {
1831
+ 'Content-Type': 'application/json',
1832
+ },
1833
+ body: JSON.stringify(payload)
1834
+ });
1835
+ if (!response.ok) {
1836
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1837
+ }
1838
+ }
1839
+ catch (error) {
1840
+ console.debug('Error sending event telemetry to Application Insights:', error);
1841
+ }
1842
+ }
1843
+ extractIngestionEndpoint() {
1844
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1845
+ return match ? match[1] : '';
1846
+ }
1847
+ }
1848
+ /**
1849
+ * Singleton telemetry client
1850
+ */
1851
+ class TelemetryClient {
1852
+ constructor() {
1853
+ this.isInitialized = false;
1854
+ }
1855
+ static getInstance() {
1856
+ if (!TelemetryClient.instance) {
1857
+ TelemetryClient.instance = new TelemetryClient();
1858
+ }
1859
+ return TelemetryClient.instance;
1860
+ }
1861
+ /**
1862
+ * Initialize telemetry
1863
+ */
1864
+ initialize(config) {
1865
+ if (this.isInitialized) {
1866
+ return;
1867
+ }
1868
+ this.isInitialized = true;
1869
+ if (config) {
1870
+ this.telemetryContext = config;
1871
+ }
1872
+ try {
1873
+ const connectionString = this.getConnectionString();
1874
+ if (!connectionString) {
1875
+ return;
1876
+ }
1877
+ this.setupTelemetryProvider(connectionString);
1878
+ }
1879
+ catch (error) {
1880
+ // Silent failure - telemetry errors shouldn't break functionality
1881
+ console.debug('Failed to initialize OpenTelemetry:', error);
1882
+ }
1883
+ }
1884
+ getConnectionString() {
1885
+ const connectionString = CONNECTION_STRING;
1886
+ return connectionString;
1887
+ }
1888
+ setupTelemetryProvider(connectionString) {
1889
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
1890
+ const processor = new BatchLogRecordProcessor(exporter);
1891
+ this.logProvider = new LoggerProvider({
1892
+ processors: [processor]
1893
+ });
1894
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1895
+ }
1896
+ /**
1897
+ * Track a telemetry event
1898
+ */
1899
+ track(eventName, name, extraAttributes = {}) {
1900
+ try {
1901
+ // Skip if logger not initialized
1902
+ if (!this.logger) {
1903
+ return;
1904
+ }
1905
+ const finalDisplayName = name || eventName;
1906
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1907
+ // Emit as log
1908
+ this.logger.emit({
1909
+ body: finalDisplayName,
1910
+ attributes: attributes,
1911
+ timestamp: Date.now(),
1912
+ });
1913
+ }
1914
+ catch (error) {
1915
+ // Silent failure
1916
+ console.debug('Failed to track telemetry event:', error);
1917
+ }
1918
+ }
1919
+ /**
1920
+ * Get enriched attributes for telemetry events
1921
+ */
1922
+ getEnrichedAttributes(extraAttributes, eventName) {
1923
+ const attributes = {
1924
+ ...extraAttributes,
1925
+ [APP_NAME]: SDK_SERVICE_NAME,
1926
+ [VERSION]: SDK_VERSION,
1927
+ [SERVICE]: eventName,
1928
+ [CLOUD_URL]: this.createCloudUrl(),
1929
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1930
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1931
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1932
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1933
+ };
1934
+ return attributes;
1935
+ }
1936
+ /**
1937
+ * Create cloud URL from base URL, organization ID, and tenant ID
1938
+ */
1939
+ createCloudUrl() {
1940
+ const baseUrl = this.telemetryContext?.baseUrl;
1941
+ const orgId = this.telemetryContext?.orgName;
1942
+ const tenantId = this.telemetryContext?.tenantName;
1943
+ if (!baseUrl || !orgId || !tenantId) {
1944
+ return UNKNOWN;
1945
+ }
1946
+ return `${baseUrl}/${orgId}/${tenantId}`;
1947
+ }
1948
+ }
1949
+ // Export singleton instance
1950
+ const telemetryClient = TelemetryClient.getInstance();
1951
+
1952
+ /**
1953
+ * SDK Track decorator and function for telemetry
1954
+ */
1955
+ /**
1956
+ * Common tracking logic shared between method and function decorators
1957
+ */
1958
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1959
+ return function (...args) {
1960
+ // Determine if we should track this call
1961
+ let shouldTrack = true;
1962
+ if (opts.condition !== undefined) {
1963
+ if (typeof opts.condition === 'function') {
1964
+ shouldTrack = opts.condition.apply(this, args);
1965
+ }
1966
+ else {
1967
+ shouldTrack = opts.condition;
1968
+ }
1969
+ }
1970
+ // Track the event if enabled
1971
+ if (shouldTrack) {
1972
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
1973
+ const serviceMethod = typeof nameOrOptions === 'string'
1974
+ ? nameOrOptions
1975
+ : fallbackName;
1976
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
1977
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1978
+ }
1979
+ // Execute the original function
1980
+ return originalFunction.apply(this, args);
1981
+ };
1982
+ }
1983
+ /**
1984
+ * Track decorator that can be used to automatically track function calls
1985
+ *
1986
+ * Usage:
1987
+ * @track("Service.Method")
1988
+ * function myFunction() { ... }
1989
+ *
1990
+ * @track("Queue.GetAll")
1991
+ * async getAll() { ... }
1992
+ *
1993
+ * @track("Tasks.Create")
1994
+ * async create() { ... }
1995
+ *
1996
+ * @track("Assets.Update", { condition: false })
1997
+ * function myFunction() { ... }
1998
+ *
1999
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
2000
+ * function myFunction() { ... }
2001
+ */
2002
+ function track(nameOrOptions, options) {
2003
+ return function decorator(_target, propertyKey, descriptor) {
2004
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
2005
+ if (descriptor && typeof descriptor.value === 'function') {
2006
+ // Method decorator
2007
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
2008
+ return descriptor;
2009
+ }
2010
+ // Function decorator
2011
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2012
+ };
2013
+ }
2014
+
2015
+ class BucketService extends FolderScopedService {
2016
+ /**
2017
+ * Gets a bucket by ID
2018
+ * @param bucketId - The ID of the bucket to retrieve
2019
+ * @param folderId - Folder ID for organization unit context
2020
+ * @param options - Optional query parameters (expand, select)
2021
+ * @returns Promise resolving to the bucket
2022
+ *
2023
+ * @example
2024
+ * ```typescript
2025
+ * import { Buckets } from '@uipath/uipath-typescript/buckets';
2026
+ *
2027
+ * const buckets = new Buckets(sdk);
2028
+ *
2029
+ * // Get bucket by ID
2030
+ * const bucket = await buckets.getById(123, 456);
2031
+ * ```
2032
+ */
2033
+ async getById(id, folderId, options = {}) {
2034
+ if (!id) {
2035
+ throw new ValidationError({ message: 'bucketId is required for getById' });
2036
+ }
2037
+ if (!folderId) {
2038
+ throw new ValidationError({ message: 'folderId is required for getById' });
2039
+ }
2040
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2041
+ // Prefix all keys in options with $ for OData
2042
+ const keysToPrefix = Object.keys(options);
2043
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
2044
+ const response = await this.get(BUCKET_ENDPOINTS.GET_BY_ID(id), {
2045
+ params: apiOptions,
2046
+ headers
2047
+ });
2048
+ // Transform response from PascalCase to camelCase
2049
+ return pascalToCamelCaseKeys(response.data);
2050
+ }
2051
+ /**
2052
+ * Gets all buckets across folders with optional filtering and folder scoping
2053
+ *
2054
+ * The method returns either:
2055
+ * - An array of buckets (when no pagination parameters are provided)
2056
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
2057
+ *
2058
+ * @param options - Query options including optional folderId
2059
+ * @returns Promise resolving to an array of buckets or paginated result
2060
+ *
2061
+ * @example
2062
+ * ```typescript
2063
+ * import { Buckets } from '@uipath/uipath-typescript/buckets';
2064
+ *
2065
+ * const buckets = new Buckets(sdk);
2066
+ *
2067
+ * // Get all buckets across folders
2068
+ * const allBuckets = await buckets.getAll();
2069
+ *
2070
+ * // Get buckets within a specific folder
2071
+ * const folderBuckets = await buckets.getAll({
2072
+ * folderId: 123
2073
+ * });
2074
+ *
2075
+ * // Get buckets with filtering
2076
+ * const filteredBuckets = await buckets.getAll({
2077
+ * filter: "name eq 'MyBucket'"
2078
+ * });
2079
+ *
2080
+ * // First page with pagination
2081
+ * const page1 = await buckets.getAll({ pageSize: 10 });
2082
+ *
2083
+ * // Navigate using cursor
2084
+ * if (page1.hasNextPage) {
2085
+ * const page2 = await buckets.getAll({ cursor: page1.nextCursor });
2086
+ * }
2087
+ *
2088
+ * // Jump to specific page
2089
+ * const page5 = await buckets.getAll({
2090
+ * jumpToPage: 5,
2091
+ * pageSize: 10
2092
+ * });
2093
+ * ```
2094
+ */
2095
+ async getAll(options) {
2096
+ // Transformation function for buckets
2097
+ const transformBucketResponse = (bucket) => pascalToCamelCaseKeys(bucket);
2098
+ return PaginationHelpers.getAll({
2099
+ serviceAccess: this.createPaginationServiceAccess(),
2100
+ getEndpoint: (folderId) => folderId ? BUCKET_ENDPOINTS.GET_BY_FOLDER : BUCKET_ENDPOINTS.GET_ALL,
2101
+ getByFolderEndpoint: BUCKET_ENDPOINTS.GET_BY_FOLDER,
2102
+ transformFn: transformBucketResponse,
2103
+ pagination: {
2104
+ paginationType: PaginationType.OFFSET,
2105
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2106
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2107
+ paginationParams: {
2108
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2109
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
2110
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
2111
+ }
2112
+ }
2113
+ }, options);
2114
+ }
2115
+ /**
2116
+ * Gets metadata for files in a bucket with optional filtering and pagination
2117
+ *
2118
+ * The method returns either:
2119
+ * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
2120
+ * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
2121
+ *
2122
+ * @param bucketId - The ID of the bucket to get file metadata from
2123
+ * @param folderId - Required folder ID for organization unit context
2124
+ * @param options - Optional parameters for filtering, pagination and access URL generation
2125
+ * @returns Promise resolving to the list of file metadata in the bucket or paginated result
2126
+ *
2127
+ * @example
2128
+ * ```typescript
2129
+ * import { Buckets } from '@uipath/uipath-typescript/buckets';
2130
+ *
2131
+ * const buckets = new Buckets(sdk);
2132
+ *
2133
+ * // Get metadata for all files in a bucket
2134
+ * const fileMetadata = await buckets.getFileMetaData(123, 456);
2135
+ *
2136
+ * // Get file metadata with a specific prefix
2137
+ * const fileMetadata = await buckets.getFileMetaData(123, 456, {
2138
+ * prefix: '/folder1'
2139
+ * });
2140
+ *
2141
+ * // First page with pagination
2142
+ * const page1 = await buckets.getFileMetaData(123, 456, { pageSize: 10 });
2143
+ *
2144
+ * // Navigate using cursor
2145
+ * if (page1.hasNextPage) {
2146
+ * const page2 = await buckets.getFileMetaData(123, 456, { cursor: page1.nextCursor });
2147
+ * }
2148
+ * ```
2149
+ */
2150
+ async getFileMetaData(bucketId, folderId, options) {
2151
+ if (!bucketId) {
2152
+ throw new ValidationError({ message: 'bucketId is required for getFileMetaData' });
2153
+ }
2154
+ if (!folderId) {
2155
+ throw new ValidationError({ message: 'folderId is required for getFileMetaData' });
2156
+ }
2157
+ // Transformation function for blob items
2158
+ const transformBlobItem = (item) => transformData(item, BucketMap);
2159
+ return PaginationHelpers.getAll({
2160
+ serviceAccess: this.createPaginationServiceAccess(),
2161
+ getEndpoint: () => BUCKET_ENDPOINTS.GET_FILE_META_DATA(bucketId),
2162
+ transformFn: transformBlobItem,
2163
+ pagination: {
2164
+ paginationType: PaginationType.TOKEN,
2165
+ itemsField: BUCKET_PAGINATION.ITEMS_FIELD,
2166
+ continuationTokenField: BUCKET_PAGINATION.CONTINUATION_TOKEN_FIELD,
2167
+ paginationParams: {
2168
+ pageSizeParam: BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM,
2169
+ tokenParam: BUCKET_TOKEN_PARAMS.TOKEN_PARAM
2170
+ }
2171
+ },
2172
+ excludeFromPrefix: ['prefix'] // Bucket-specific param, not OData
2173
+ }, { ...options, folderId });
2174
+ }
2175
+ /**
2176
+ * Uploads a file to a bucket
2177
+ *
2178
+ * @param options - Options for file upload including bucket ID, folder ID, path, content, and optional parameters
2179
+ * @returns Promise resolving to a response with success status and HTTP status code
2180
+ *
2181
+ * @example
2182
+ * ```typescript
2183
+ * import { Buckets } from '@uipath/uipath-typescript/buckets';
2184
+ *
2185
+ * const buckets = new Buckets(sdk);
2186
+ *
2187
+ * // Upload a file from browser
2188
+ * const file = new File(['file content'], 'example.txt');
2189
+ * const result = await buckets.uploadFile({
2190
+ * bucketId: 123,
2191
+ * folderId: 456,
2192
+ * path: '/folder/example.txt',
2193
+ * content: file
2194
+ * });
2195
+ *
2196
+ * // In Node env with Buffer
2197
+ * const buffer = Buffer.from('file content');
2198
+ * const result = await buckets.uploadFile({
2199
+ * bucketId: 123,
2200
+ * folderId: 456,
2201
+ * path: '/folder/example.txt',
2202
+ * content: buffer
2203
+ * });
2204
+ * ```
2205
+ */
2206
+ async uploadFile(options) {
2207
+ const { bucketId, folderId, path, content } = options;
2208
+ if (!bucketId) {
2209
+ throw new ValidationError({ message: 'bucketId is required for uploadFile' });
2210
+ }
2211
+ if (!folderId) {
2212
+ throw new ValidationError({ message: 'folderId is required for uploadFile' });
2213
+ }
2214
+ if (!path) {
2215
+ throw new ValidationError({ message: 'path is required for uploadFile' });
2216
+ }
2217
+ if (!content) {
2218
+ throw new ValidationError({ message: 'content is required for uploadFile' });
2219
+ }
2220
+ const uriResponse = await this._getWriteUri({
2221
+ bucketId,
2222
+ folderId,
2223
+ path,
2224
+ });
2225
+ // Upload file to the provided URI
2226
+ const response = await this._uploadToUri(uriResponse, content);
2227
+ return {
2228
+ success: response.status >= 200 && response.status < 300,
2229
+ statusCode: response.status
2230
+ };
2231
+ }
2232
+ /**
2233
+ * Gets a direct download URL for a file in the bucket
2234
+ *
2235
+ * @param options - Contains bucketId, folderId, file path and optional expiry time
2236
+ * @returns Promise resolving to blob file access information
2237
+ *
2238
+ * @example
2239
+ * ```typescript
2240
+ * import { Buckets } from '@uipath/uipath-typescript/buckets';
2241
+ *
2242
+ * const buckets = new Buckets(sdk);
2243
+ *
2244
+ * // Get download URL for a file
2245
+ * const fileAccess = await buckets.getReadUri({
2246
+ * bucketId: 123,
2247
+ * folderId: 456,
2248
+ * path: '/folder/file.pdf'
2249
+ * });
2250
+ * ```
2251
+ */
2252
+ async getReadUri(options) {
2253
+ const { bucketId, folderId, path, expiryInMinutes, ...restOptions } = options;
2254
+ const queryOptions = {
2255
+ expiryInMinutes,
2256
+ ...addPrefixToKeys(restOptions, ODATA_PREFIX, Object.keys(restOptions))
2257
+ };
2258
+ return this._getUri(BUCKET_ENDPOINTS.GET_READ_URI(bucketId), bucketId, folderId, path, queryOptions);
2259
+ }
2260
+ /**
2261
+ * Uploads content to the provided URI
2262
+ * @param uriResponse - Response from getWriteUri containing URL and headers
2263
+ * @param content - The content to upload
2264
+ * @returns The response from the upload request with status info
2265
+ */
2266
+ async _uploadToUri(uriResponse, content) {
2267
+ const { uri, headers = {}, requiresAuth } = uriResponse;
2268
+ if (!uri) {
2269
+ throw new ValidationError({ message: 'Upload URI not available', statusCode: HttpStatus.BAD_REQUEST });
2270
+ }
2271
+ // Create headers for the request
2272
+ let requestHeaders = { ...headers };
2273
+ // Add auth header if required
2274
+ if (requiresAuth) {
2275
+ const token = await this.getValidAuthToken();
2276
+ requestHeaders['Authorization'] = `Bearer ${token}`;
2277
+ }
2278
+ return fetch(uri, {
2279
+ method: 'PUT',
2280
+ body: content,
2281
+ headers: createHeaders(requestHeaders),
2282
+ });
2283
+ }
2284
+ /**
2285
+ * Private method to handle common URI request logic
2286
+ * @param endpoint - The API endpoint to call
2287
+ * @param bucketId - The bucket ID
2288
+ * @param folderId - The folder ID
2289
+ * @param path - The file path
2290
+ * @param queryOptions - Additional query parameters
2291
+ * @returns Promise resolving to blob file access information
2292
+ */
2293
+ async _getUri(endpoint, bucketId, folderId, path, queryOptions = {}) {
2294
+ if (!bucketId) {
2295
+ throw new ValidationError({ message: 'bucketId is required for getUri' });
2296
+ }
2297
+ if (!folderId) {
2298
+ throw new ValidationError({ message: 'folderId is required for getUri' });
2299
+ }
2300
+ if (!path) {
2301
+ throw new ValidationError({ message: 'path is required for getUri' });
2302
+ }
2303
+ // Create headers with required folder ID
2304
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2305
+ // Filter out undefined values and build query params
2306
+ const queryParams = filterUndefined({
2307
+ path,
2308
+ ...queryOptions
2309
+ });
2310
+ // Make the API call to get URI
2311
+ const response = await this.get(endpoint, {
2312
+ params: queryParams,
2313
+ headers
2314
+ });
2315
+ const transformedData = transformData(pascalToCamelCaseKeys(response.data), BucketMap);
2316
+ // Convert headers from array-based to record if needed
2317
+ if (transformedData.headers && 'keys' in transformedData.headers && 'values' in transformedData.headers) {
2318
+ transformedData.headers = arrayDictionaryToRecord(transformedData.headers);
2319
+ }
2320
+ return transformedData;
2321
+ }
2322
+ /**
2323
+ * Gets a direct upload URL for a file in the bucket
2324
+ *
2325
+ * @param options - Contains bucketId, folderId, file path, optional expiry time
2326
+ * @returns Promise resolving to blob file access information
2327
+ */
2328
+ async _getWriteUri(options) {
2329
+ const { bucketId, folderId, path, expiryInMinutes, ...restOptions } = options;
2330
+ const queryOptions = {
2331
+ expiryInMinutes,
2332
+ ...addPrefixToKeys(restOptions, ODATA_PREFIX, Object.keys(restOptions))
2333
+ };
2334
+ return this._getUri(BUCKET_ENDPOINTS.GET_WRITE_URI(bucketId), bucketId, folderId, path, queryOptions);
2335
+ }
2336
+ }
2337
+ __decorate([
2338
+ track('Buckets.GetById')
2339
+ ], BucketService.prototype, "getById", null);
2340
+ __decorate([
2341
+ track('Buckets.GetAll')
2342
+ ], BucketService.prototype, "getAll", null);
2343
+ __decorate([
2344
+ track('Buckets.GetFileMetaData')
2345
+ ], BucketService.prototype, "getFileMetaData", null);
2346
+ __decorate([
2347
+ track('Buckets.UploadFile')
2348
+ ], BucketService.prototype, "uploadFile", null);
2349
+ __decorate([
2350
+ track('Buckets.GetReadUri')
2351
+ ], BucketService.prototype, "getReadUri", null);
2352
+
2353
+ var BucketOptions;
2354
+ (function (BucketOptions) {
2355
+ BucketOptions["None"] = "None";
2356
+ BucketOptions["ReadOnly"] = "ReadOnly";
2357
+ BucketOptions["AuditReadAccess"] = "AuditReadAccess";
2358
+ BucketOptions["AccessDataThroughOrchestrator"] = "AccessDataThroughOrchestrator";
2359
+ })(BucketOptions || (BucketOptions = {}));
2360
+
2361
+ export { BucketOptions, BucketService, BucketService as Buckets };