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