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