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