@uipath/uipath-typescript 1.2.1 → 1.2.2

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 (40) hide show
  1. package/dist/assets/index.cjs +1 -1
  2. package/dist/assets/index.d.ts +2 -1
  3. package/dist/assets/index.mjs +1 -1
  4. package/dist/attachments/index.cjs +1944 -0
  5. package/dist/attachments/index.d.ts +399 -0
  6. package/dist/attachments/index.mjs +1941 -0
  7. package/dist/buckets/index.cjs +1 -1
  8. package/dist/buckets/index.d.ts +4 -2
  9. package/dist/buckets/index.mjs +1 -1
  10. package/dist/cases/index.cjs +95 -48
  11. package/dist/cases/index.d.ts +31 -2
  12. package/dist/cases/index.mjs +95 -48
  13. package/dist/conversational-agent/index.cjs +1 -1
  14. package/dist/conversational-agent/index.d.ts +10 -5
  15. package/dist/conversational-agent/index.mjs +1 -1
  16. package/dist/core/index.cjs +109 -17
  17. package/dist/core/index.d.ts +1 -1
  18. package/dist/core/index.mjs +109 -17
  19. package/dist/entities/index.cjs +1 -1
  20. package/dist/entities/index.d.ts +33 -21
  21. package/dist/entities/index.mjs +1 -1
  22. package/dist/index.cjs +569 -307
  23. package/dist/index.d.ts +468 -70
  24. package/dist/index.mjs +570 -308
  25. package/dist/index.umd.js +566 -304
  26. package/dist/jobs/index.cjs +2036 -0
  27. package/dist/jobs/index.d.ts +724 -0
  28. package/dist/jobs/index.mjs +2033 -0
  29. package/dist/maestro-processes/index.cjs +1 -1
  30. package/dist/maestro-processes/index.mjs +1 -1
  31. package/dist/processes/index.cjs +67 -1
  32. package/dist/processes/index.d.ts +80 -15
  33. package/dist/processes/index.mjs +68 -2
  34. package/dist/queues/index.cjs +1 -1
  35. package/dist/queues/index.d.ts +2 -1
  36. package/dist/queues/index.mjs +1 -1
  37. package/dist/tasks/index.cjs +1319 -1272
  38. package/dist/tasks/index.d.ts +331 -287
  39. package/dist/tasks/index.mjs +1319 -1272
  40. package/package.json +23 -2
@@ -0,0 +1,2033 @@
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
+ const token = await this.getValidToken();
548
+ return {
549
+ 'Authorization': `Bearer ${token}`,
550
+ 'Content-Type': CONTENT_TYPES.JSON,
551
+ ...this.defaultHeaders,
552
+ ...this.clientConfig.headers
553
+ };
554
+ }
555
+ async request(method, path, options = {}) {
556
+ // Ensure path starts with a forward slash
557
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
558
+ // Construct URL with org and tenant names
559
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
560
+ const isFormData = options.body instanceof FormData;
561
+ const defaultHeaders = await this.getDefaultHeaders();
562
+ if (isFormData) {
563
+ delete defaultHeaders['Content-Type'];
564
+ }
565
+ const headers = {
566
+ ...defaultHeaders,
567
+ ...options.headers
568
+ };
569
+ // Convert params to URLSearchParams
570
+ const searchParams = new URLSearchParams();
571
+ if (options.params) {
572
+ Object.entries(options.params).forEach(([key, value]) => {
573
+ searchParams.append(key, value.toString());
574
+ });
575
+ }
576
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
577
+ let body = undefined;
578
+ if (options.body) {
579
+ body = isFormData ? options.body : JSON.stringify(options.body);
580
+ }
581
+ try {
582
+ const response = await fetch(fullUrl, {
583
+ method,
584
+ headers,
585
+ body,
586
+ signal: options.signal
587
+ });
588
+ if (!response.ok) {
589
+ const errorInfo = await errorResponseParser.parse(response);
590
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
591
+ }
592
+ if (response.status === 204) {
593
+ return undefined;
594
+ }
595
+ // Handle blob response type for binary data (e.g., file downloads)
596
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
597
+ const blob = await response.blob();
598
+ return blob;
599
+ }
600
+ // Check if we're expecting XML
601
+ const acceptHeader = headers['Accept'] || headers['accept'];
602
+ if (acceptHeader === CONTENT_TYPES.XML) {
603
+ const text = await response.text();
604
+ return text;
605
+ }
606
+ return response.json();
607
+ }
608
+ catch (error) {
609
+ // If it's already one of our errors, re-throw it
610
+ if (error.type && error.type.includes('Error')) {
611
+ throw error;
612
+ }
613
+ // Otherwise, it's likely a network error
614
+ throw ErrorFactory.createNetworkError(error);
615
+ }
616
+ }
617
+ async get(path, options = {}) {
618
+ return this.request('GET', path, options);
619
+ }
620
+ async post(path, data, options = {}) {
621
+ return this.request('POST', path, { ...options, body: data });
622
+ }
623
+ async put(path, data, options = {}) {
624
+ return this.request('PUT', path, { ...options, body: data });
625
+ }
626
+ async patch(path, data, options = {}) {
627
+ return this.request('PATCH', path, { ...options, body: data });
628
+ }
629
+ async delete(path, options = {}) {
630
+ return this.request('DELETE', path, options);
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Pagination types supported by the SDK
636
+ */
637
+ var PaginationType;
638
+ (function (PaginationType) {
639
+ PaginationType["OFFSET"] = "offset";
640
+ PaginationType["TOKEN"] = "token";
641
+ })(PaginationType || (PaginationType = {}));
642
+
643
+ /**
644
+ * Collection of utility functions for working with objects
645
+ */
646
+ /**
647
+ * Filters out undefined values from an object
648
+ * @param obj The source object
649
+ * @returns A new object without undefined values
650
+ *
651
+ * @example
652
+ * ```typescript
653
+ * // Object with undefined values
654
+ * const options = {
655
+ * name: 'test',
656
+ * count: 5,
657
+ * prefix: undefined,
658
+ * suffix: null
659
+ * };
660
+ * const result = filterUndefined(options);
661
+ * // result = { name: 'test', count: 5, suffix: null }
662
+ * ```
663
+ */
664
+ function filterUndefined(obj) {
665
+ const result = {};
666
+ for (const [key, value] of Object.entries(obj)) {
667
+ if (value !== undefined) {
668
+ result[key] = value;
669
+ }
670
+ }
671
+ return result;
672
+ }
673
+
674
+ /**
675
+ * Utility functions for platform detection
676
+ */
677
+ /**
678
+ * Checks if code is running in a browser environment
679
+ */
680
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
681
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
682
+
683
+ /**
684
+ * Base64 encoding/decoding
685
+ */
686
+ /**
687
+ * Encodes a string to base64
688
+ * @param str - The string to encode
689
+ * @returns Base64 encoded string
690
+ */
691
+ function encodeBase64(str) {
692
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
693
+ const encoder = new TextEncoder();
694
+ const data = encoder.encode(str);
695
+ // Convert Uint8Array to base64
696
+ if (isBrowser) {
697
+ // Browser environment
698
+ // Convert Uint8Array to binary string then to base64
699
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
700
+ return btoa(binaryString);
701
+ }
702
+ else {
703
+ // Node.js environment
704
+ return Buffer.from(data).toString('base64');
705
+ }
706
+ }
707
+ /**
708
+ * Decodes a base64 string
709
+ * @param base64 - The base64 string to decode
710
+ * @returns Decoded string
711
+ */
712
+ function decodeBase64(base64) {
713
+ let bytes;
714
+ if (isBrowser) {
715
+ // Browser environment
716
+ const binaryString = atob(base64);
717
+ bytes = new Uint8Array(binaryString.length);
718
+ for (let i = 0; i < binaryString.length; i++) {
719
+ bytes[i] = binaryString.charCodeAt(i);
720
+ }
721
+ }
722
+ else {
723
+ // Node.js environment
724
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
725
+ }
726
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
727
+ const decoder = new TextDecoder();
728
+ return decoder.decode(bytes);
729
+ }
730
+
731
+ /**
732
+ * PaginationManager handles the conversion between uniform cursor-based pagination
733
+ * and the specific pagination type for each service
734
+ */
735
+ class PaginationManager {
736
+ /**
737
+ * Create a pagination cursor for subsequent page requests
738
+ */
739
+ static createCursor({ pageInfo, type }) {
740
+ if (!pageInfo.hasMore) {
741
+ return undefined;
742
+ }
743
+ const cursorData = {
744
+ type,
745
+ pageSize: pageInfo.pageSize,
746
+ };
747
+ switch (type) {
748
+ case PaginationType.OFFSET:
749
+ if (pageInfo.currentPage) {
750
+ cursorData.pageNumber = pageInfo.currentPage + 1;
751
+ }
752
+ break;
753
+ case PaginationType.TOKEN:
754
+ if (pageInfo.continuationToken) {
755
+ cursorData.continuationToken = pageInfo.continuationToken;
756
+ }
757
+ else {
758
+ return undefined; // No continuation token, can't continue
759
+ }
760
+ break;
761
+ }
762
+ return {
763
+ value: encodeBase64(JSON.stringify(cursorData))
764
+ };
765
+ }
766
+ /**
767
+ * Create a paginated response with navigation cursors
768
+ */
769
+ static createPaginatedResponse({ pageInfo, type }, items) {
770
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
771
+ // Create previous page cursor if applicable
772
+ let previousCursor = undefined;
773
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
774
+ const prevCursorData = {
775
+ type,
776
+ pageNumber: pageInfo.currentPage - 1,
777
+ pageSize: pageInfo.pageSize,
778
+ };
779
+ previousCursor = {
780
+ value: encodeBase64(JSON.stringify(prevCursorData))
781
+ };
782
+ }
783
+ // Calculate total pages if we have totalCount and pageSize
784
+ let totalPages = undefined;
785
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
786
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
787
+ }
788
+ // Determine if this pagination type supports page jumping
789
+ const supportsPageJump = type === PaginationType.OFFSET;
790
+ // Create the result object with all fields, then filter out undefined values
791
+ const result = filterUndefined({
792
+ items,
793
+ totalCount: pageInfo.totalCount,
794
+ hasNextPage: pageInfo.hasMore,
795
+ nextCursor: nextCursor,
796
+ previousCursor: previousCursor,
797
+ currentPage: pageInfo.currentPage,
798
+ totalPages,
799
+ supportsPageJump
800
+ });
801
+ return result;
802
+ }
803
+ }
804
+
805
+ /**
806
+ * Creates headers object from key-value pairs
807
+ * @param headersObj - Object containing header key-value pairs
808
+ * @returns Headers object with all values converted to strings
809
+ *
810
+ * @example
811
+ * ```typescript
812
+ * // Single header
813
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
814
+ *
815
+ * // Multiple headers
816
+ * const headers = createHeaders({
817
+ * 'X-UIPATH-FolderKey': '1234567890',
818
+ * 'X-UIPATH-OrganizationUnitId': 123,
819
+ * 'Accept': 'application/json'
820
+ * });
821
+ *
822
+ * // Using constants
823
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
824
+ * const headers = createHeaders({
825
+ * [FOLDER_KEY]: 'abc-123',
826
+ * [FOLDER_ID]: 456
827
+ * });
828
+ *
829
+ * // Empty headers
830
+ * const headers = createHeaders();
831
+ * ```
832
+ */
833
+ function createHeaders(headersObj) {
834
+ const headers = {};
835
+ for (const [key, value] of Object.entries(headersObj)) {
836
+ if (value !== undefined && value !== null) {
837
+ headers[key] = value.toString();
838
+ }
839
+ }
840
+ return headers;
841
+ }
842
+
843
+ /**
844
+ * Common constants used across the SDK
845
+ */
846
+ /**
847
+ * Prefix used for OData query parameters
848
+ */
849
+ const ODATA_PREFIX = '$';
850
+ /**
851
+ * HTTP methods
852
+ */
853
+ const HTTP_METHODS = {
854
+ GET: 'GET',
855
+ POST: 'POST'};
856
+ /**
857
+ * OData pagination constants
858
+ */
859
+ const ODATA_PAGINATION = {
860
+ /** Default field name for items in a paginated OData response */
861
+ ITEMS_FIELD: 'value',
862
+ /** Default field name for total count in a paginated OData response */
863
+ TOTAL_COUNT_FIELD: '@odata.count'
864
+ };
865
+ /**
866
+ * OData OFFSET pagination parameter names (ODATA-style)
867
+ */
868
+ const ODATA_OFFSET_PARAMS = {
869
+ /** OData page size parameter name */
870
+ PAGE_SIZE_PARAM: '$top',
871
+ /** OData offset parameter name */
872
+ OFFSET_PARAM: '$skip',
873
+ /** OData count parameter name */
874
+ COUNT_PARAM: '$count'
875
+ };
876
+ /**
877
+ * Bucket TOKEN pagination parameter names
878
+ */
879
+ const BUCKET_TOKEN_PARAMS = {
880
+ /** Bucket page size parameter name */
881
+ PAGE_SIZE_PARAM: 'takeHint',
882
+ /** Bucket token parameter name */
883
+ TOKEN_PARAM: 'continuationToken'
884
+ };
885
+
886
+ /**
887
+ * Transforms data by mapping fields according to the provided field mapping
888
+ * @param data The source data to transform
889
+ * @param fieldMapping Object mapping source field names to target field names
890
+ * @returns Transformed data with mapped field names
891
+ *
892
+ * @example
893
+ * ```typescript
894
+ * // Single object transformation
895
+ * const data = { id: '123', userName: 'john' };
896
+ * const mapping = { id: 'userId', userName: 'name' };
897
+ * const result = transformData(data, mapping);
898
+ * // result = { userId: '123', name: 'john' }
899
+ *
900
+ * // Array transformation
901
+ * const dataArray = [
902
+ * { id: '123', userName: 'john' },
903
+ * { id: '456', userName: 'jane' }
904
+ * ];
905
+ * const result = transformData(dataArray, mapping);
906
+ * // result = [
907
+ * // { userId: '123', name: 'john' },
908
+ * // { userId: '456', name: 'jane' }
909
+ * // ]
910
+ * ```
911
+ */
912
+ function transformData(data, fieldMapping) {
913
+ // Handle array of objects
914
+ if (Array.isArray(data)) {
915
+ return data.map(item => transformData(item, fieldMapping));
916
+ }
917
+ // Handle single object
918
+ const result = { ...data };
919
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
920
+ if (sourceField in result) {
921
+ const value = result[sourceField];
922
+ delete result[sourceField];
923
+ result[targetField] = value;
924
+ }
925
+ }
926
+ return result;
927
+ }
928
+ /**
929
+ * Converts a string from PascalCase to camelCase
930
+ * @param str The PascalCase string to convert
931
+ * @returns The camelCase version of the string
932
+ *
933
+ * @example
934
+ * ```typescript
935
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
936
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
937
+ * ```
938
+ */
939
+ function pascalToCamelCase(str) {
940
+ if (!str)
941
+ return str;
942
+ return str.charAt(0).toLowerCase() + str.slice(1);
943
+ }
944
+ /**
945
+ * Generic function to transform object keys using a provided case conversion function
946
+ * @param data The object to transform
947
+ * @param convertCase The function to convert each key
948
+ * @returns A new object with transformed keys
949
+ */
950
+ function transformCaseKeys(data, convertCase) {
951
+ // Handle array of objects
952
+ if (Array.isArray(data)) {
953
+ return data.map(item => {
954
+ // If the array element is a primitive (string, number, etc.), return it as is
955
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
956
+ return item;
957
+ }
958
+ // Only recursively transform if it's actually an object
959
+ return transformCaseKeys(item, convertCase);
960
+ });
961
+ }
962
+ const result = {};
963
+ for (const [key, value] of Object.entries(data)) {
964
+ const transformedKey = convertCase(key);
965
+ // Recursively transform nested objects and arrays
966
+ if (value !== null && typeof value === 'object') {
967
+ result[transformedKey] = transformCaseKeys(value, convertCase);
968
+ }
969
+ else {
970
+ result[transformedKey] = value;
971
+ }
972
+ }
973
+ return result;
974
+ }
975
+ /**
976
+ * Transforms an object's keys from PascalCase to camelCase
977
+ * @param data The object with PascalCase keys
978
+ * @returns A new object with all keys converted to camelCase
979
+ *
980
+ * @example
981
+ * ```typescript
982
+ * // Simple object
983
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
984
+ * // Result: { id: "123", taskName: "Invoice" }
985
+ *
986
+ * // Nested object
987
+ * pascalToCamelCaseKeys({
988
+ * TaskId: "456",
989
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
990
+ * });
991
+ * // Result: {
992
+ * // taskId: "456",
993
+ * // taskDetails: { assignedUser: "John", priority: "High" }
994
+ * // }
995
+ *
996
+ * // Array of objects
997
+ * pascalToCamelCaseKeys([
998
+ * { Id: "1", IsComplete: false },
999
+ * { Id: "2", IsComplete: true }
1000
+ * ]);
1001
+ * // Result: [
1002
+ * // { id: "1", isComplete: false },
1003
+ * // { id: "2", isComplete: true }
1004
+ * // ]
1005
+ * ```
1006
+ */
1007
+ function pascalToCamelCaseKeys(data) {
1008
+ return transformCaseKeys(data, pascalToCamelCase);
1009
+ }
1010
+ /**
1011
+ * Adds a prefix to specified keys in an object, returning a new object.
1012
+ * Only the provided keys are prefixed; all others are left unchanged.
1013
+ *
1014
+ * @param obj The source object
1015
+ * @param prefix The prefix to add (e.g., '$')
1016
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1017
+ * @returns A new object with specified keys prefixed
1018
+ *
1019
+ * @example
1020
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1021
+ */
1022
+ function addPrefixToKeys(obj, prefix, keys) {
1023
+ const result = {};
1024
+ for (const [key, value] of Object.entries(obj)) {
1025
+ if (keys.includes(key)) {
1026
+ result[`${prefix}${key}`] = value;
1027
+ }
1028
+ else {
1029
+ result[key] = value;
1030
+ }
1031
+ }
1032
+ return result;
1033
+ }
1034
+
1035
+ /**
1036
+ * Constants used throughout the pagination system
1037
+ */
1038
+ /** Maximum number of items that can be requested in a single page */
1039
+ const MAX_PAGE_SIZE = 1000;
1040
+ /** Default page size when jumpToPage is used without specifying pageSize */
1041
+ const DEFAULT_PAGE_SIZE = 50;
1042
+ /** Default field name for items in a paginated response */
1043
+ const DEFAULT_ITEMS_FIELD = 'value';
1044
+ /** Default field name for total count in a paginated response */
1045
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1046
+ /**
1047
+ * Limits the page size to the maximum allowed value
1048
+ * @param pageSize - Requested page size
1049
+ * @returns Limited page size value
1050
+ */
1051
+ function getLimitedPageSize(pageSize) {
1052
+ if (pageSize === undefined || pageSize === null) {
1053
+ return DEFAULT_PAGE_SIZE;
1054
+ }
1055
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1056
+ }
1057
+
1058
+ /**
1059
+ * Helper functions for pagination that can be used across services
1060
+ */
1061
+ class PaginationHelpers {
1062
+ /**
1063
+ * Checks if any pagination parameters are provided
1064
+ *
1065
+ * @param options - The options object to check
1066
+ * @returns True if any pagination parameter is defined, false otherwise
1067
+ */
1068
+ static hasPaginationParameters(options = {}) {
1069
+ const { cursor, pageSize, jumpToPage } = options;
1070
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1071
+ }
1072
+ /**
1073
+ * Parse a pagination cursor string into cursor data
1074
+ */
1075
+ static parseCursor(cursorString) {
1076
+ try {
1077
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1078
+ return cursorData;
1079
+ }
1080
+ catch {
1081
+ throw new Error('Invalid pagination cursor');
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Validates cursor format and structure
1086
+ *
1087
+ * @param paginationOptions - The pagination options containing the cursor
1088
+ * @param paginationType - Optional pagination type to validate against
1089
+ */
1090
+ static validateCursor(paginationOptions, paginationType) {
1091
+ if (paginationOptions.cursor !== undefined) {
1092
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1093
+ throw new Error('cursor must contain a valid cursor string');
1094
+ }
1095
+ try {
1096
+ // Try to parse the cursor to validate it
1097
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1098
+ // If type is provided, validate cursor contains expected type information
1099
+ if (paginationType) {
1100
+ if (!cursorData.type) {
1101
+ throw new Error('Invalid cursor: missing pagination type');
1102
+ }
1103
+ // Check pagination type compatibility
1104
+ if (cursorData.type !== paginationType) {
1105
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1106
+ }
1107
+ }
1108
+ }
1109
+ catch (error) {
1110
+ if (error instanceof Error) {
1111
+ // If it's already our error with specific message, pass it through
1112
+ if (error.message.startsWith('Invalid cursor') ||
1113
+ error.message.startsWith('Pagination type mismatch')) {
1114
+ throw error;
1115
+ }
1116
+ }
1117
+ throw new Error('Invalid pagination cursor format');
1118
+ }
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Comprehensive validation for pagination options
1123
+ *
1124
+ * @param options - The pagination options to validate
1125
+ * @param paginationType - The pagination type these options will be used with
1126
+ * @returns Processed pagination parameters ready for use
1127
+ */
1128
+ static validatePaginationOptions(options, paginationType) {
1129
+ // Validate pageSize
1130
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1131
+ throw new Error('pageSize must be a positive number');
1132
+ }
1133
+ // Validate jumpToPage
1134
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1135
+ throw new Error('jumpToPage must be a positive number');
1136
+ }
1137
+ // Validate cursor
1138
+ PaginationHelpers.validateCursor(options, paginationType);
1139
+ // Validate service compatibility
1140
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1141
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1142
+ }
1143
+ // Get processed parameters
1144
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1145
+ }
1146
+ /**
1147
+ * Convert a unified pagination options to service-specific parameters
1148
+ */
1149
+ static getRequestParameters(options, paginationType) {
1150
+ // Handle jumpToPage
1151
+ if (options.jumpToPage !== undefined) {
1152
+ const jumpToPageOptions = {
1153
+ pageSize: options.pageSize,
1154
+ pageNumber: options.jumpToPage
1155
+ };
1156
+ return filterUndefined(jumpToPageOptions);
1157
+ }
1158
+ // If no cursor is provided, it's a first page request
1159
+ if (!options.cursor) {
1160
+ const firstPageOptions = {
1161
+ pageSize: options.pageSize,
1162
+ // Only set pageNumber for OFFSET pagination
1163
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1164
+ };
1165
+ return filterUndefined(firstPageOptions);
1166
+ }
1167
+ // Parse the cursor
1168
+ try {
1169
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1170
+ const cursorBasedOptions = {
1171
+ pageSize: cursorData.pageSize || options.pageSize,
1172
+ pageNumber: cursorData.pageNumber,
1173
+ continuationToken: cursorData.continuationToken,
1174
+ type: cursorData.type,
1175
+ };
1176
+ return filterUndefined(cursorBasedOptions);
1177
+ }
1178
+ catch {
1179
+ throw new Error('Invalid pagination cursor');
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Helper method for paginated resource retrieval
1184
+ *
1185
+ * @param params - Parameters for pagination
1186
+ * @returns Promise resolving to a paginated result
1187
+ */
1188
+ static async getAllPaginated(params) {
1189
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1190
+ const endpoint = getEndpoint(folderId);
1191
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1192
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1193
+ headers,
1194
+ params: additionalParams,
1195
+ pagination: {
1196
+ paginationType: options.paginationType || PaginationType.OFFSET,
1197
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1198
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1199
+ continuationTokenField: options.continuationTokenField,
1200
+ paginationParams: options.paginationParams
1201
+ }
1202
+ });
1203
+ // Parse items - automatically handle JSON string responses
1204
+ const rawItems = paginatedResponse.items;
1205
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1206
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1207
+ return {
1208
+ ...paginatedResponse,
1209
+ items: transformedItems
1210
+ };
1211
+ }
1212
+ /**
1213
+ * Helper method for non-paginated resource retrieval
1214
+ *
1215
+ * @param params - Parameters for non-paginated resource retrieval
1216
+ * @returns Promise resolving to an object with data and totalCount
1217
+ */
1218
+ static async getAllNonPaginated(params) {
1219
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1220
+ // Set default field names
1221
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1222
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1223
+ // Determine endpoint and headers based on folderId
1224
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1225
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1226
+ // Make the API call based on method
1227
+ let response;
1228
+ if (method === HTTP_METHODS.POST) {
1229
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1230
+ }
1231
+ else {
1232
+ response = await serviceAccess.get(endpoint, {
1233
+ params: additionalParams,
1234
+ headers
1235
+ });
1236
+ }
1237
+ // Extract and transform items from response
1238
+ const rawItems = response.data?.[itemsField];
1239
+ const totalCount = response.data?.[totalCountField];
1240
+ // Parse items - automatically handle JSON string responses
1241
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1242
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1243
+ return {
1244
+ items,
1245
+ totalCount
1246
+ };
1247
+ }
1248
+ /**
1249
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1250
+ *
1251
+ * @param config - Configuration for the getAll operation
1252
+ * @param options - Request options including pagination parameters
1253
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1254
+ */
1255
+ static async getAll(config, options) {
1256
+ const optionsWithDefaults = options || {};
1257
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1258
+ // Determine if pagination is requested
1259
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1260
+ // Process parameters (custom processing if provided, otherwise default)
1261
+ let processedOptions = restOptions;
1262
+ if (config.processParametersFn) {
1263
+ processedOptions = config.processParametersFn(restOptions, folderId);
1264
+ }
1265
+ // Apply ODATA prefix to keys (excluding specified keys)
1266
+ const excludeKeys = config.excludeFromPrefix || [];
1267
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1268
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1269
+ // Default pagination options
1270
+ const paginationOptions = {
1271
+ paginationType: PaginationType.OFFSET,
1272
+ itemsField: DEFAULT_ITEMS_FIELD,
1273
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1274
+ ...config.pagination
1275
+ };
1276
+ // Paginated flow
1277
+ if (isPaginationRequested) {
1278
+ return PaginationHelpers.getAllPaginated({
1279
+ serviceAccess: config.serviceAccess,
1280
+ getEndpoint: config.getEndpoint,
1281
+ folderId,
1282
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1283
+ additionalParams: prefixedOptions,
1284
+ transformFn: config.transformFn,
1285
+ method: config.method,
1286
+ options: {
1287
+ ...paginationOptions,
1288
+ paginationParams: config.pagination?.paginationParams
1289
+ }
1290
+ }); // Type assertion needed due to conditional return
1291
+ }
1292
+ // Non-paginated flow
1293
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1294
+ return PaginationHelpers.getAllNonPaginated({
1295
+ serviceAccess: config.serviceAccess,
1296
+ getAllEndpoint: config.getEndpoint(),
1297
+ getByFolderEndpoint: byFolderEndpoint,
1298
+ folderId,
1299
+ additionalParams: prefixedOptions,
1300
+ transformFn: config.transformFn,
1301
+ method: config.method,
1302
+ options: {
1303
+ itemsField: paginationOptions.itemsField,
1304
+ totalCountField: paginationOptions.totalCountField
1305
+ }
1306
+ });
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * SDK Internals Registry - Internal registry for SDK instances
1312
+ *
1313
+ * This class is NOT exported in the public API.
1314
+ * It provides a secure way to share SDK internals between
1315
+ * the UiPath class and service classes without exposing them publicly.
1316
+ *
1317
+ * @internal
1318
+ */
1319
+ // Global symbol key to ensure WeakMap is shared across module instances
1320
+ // This prevents issues when core and service modules are bundled separately
1321
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1322
+ // Get or create the global WeakMap store
1323
+ const getGlobalStore = () => {
1324
+ const globalObj = globalThis;
1325
+ if (!globalObj[REGISTRY_KEY]) {
1326
+ globalObj[REGISTRY_KEY] = new WeakMap();
1327
+ }
1328
+ return globalObj[REGISTRY_KEY];
1329
+ };
1330
+ /**
1331
+ * Internal registry for SDK private components.
1332
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1333
+ * garbage collected when the SDK instance is no longer referenced.
1334
+ *
1335
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1336
+ * across separately bundled modules (core, entities, tasks, etc.).
1337
+ *
1338
+ * @internal - Not exported in public API
1339
+ */
1340
+ class SDKInternalsRegistry {
1341
+ // Use global store to ensure sharing across module bundles
1342
+ static get store() {
1343
+ return getGlobalStore();
1344
+ }
1345
+ /**
1346
+ * Register SDK instance internals
1347
+ * Called by UiPath constructor
1348
+ */
1349
+ static set(instance, internals) {
1350
+ this.store.set(instance, internals);
1351
+ }
1352
+ /**
1353
+ * Retrieve SDK instance internals
1354
+ * Called by BaseService constructor
1355
+ */
1356
+ static get(instance) {
1357
+ const internals = this.store.get(instance);
1358
+ if (!internals) {
1359
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1360
+ }
1361
+ return internals;
1362
+ }
1363
+ }
1364
+
1365
+ var _BaseService_apiClient;
1366
+ /**
1367
+ * Base class for all UiPath SDK services.
1368
+ *
1369
+ * Provides common functionality for authentication, configuration, and API communication.
1370
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1371
+ *
1372
+ * This class implements the dependency injection pattern where services receive a configured
1373
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1374
+ * including authentication token management.
1375
+ *
1376
+ * @remarks
1377
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1378
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1379
+ *
1380
+ */
1381
+ class BaseService {
1382
+ /**
1383
+ * Creates a base service instance with dependency injection.
1384
+ *
1385
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1386
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1387
+ * and token management internally.
1388
+ *
1389
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1390
+ * Services receive this via dependency injection in the modular pattern.
1391
+ *
1392
+ * @example
1393
+ * ```typescript
1394
+ * // Services automatically call this via super()
1395
+ * export class EntityService extends BaseService {
1396
+ * constructor(instance: IUiPath) {
1397
+ * super(instance); // Initializes the internal ApiClient
1398
+ * }
1399
+ * }
1400
+ *
1401
+ * // Usage in modular pattern
1402
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1403
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1404
+ *
1405
+ * const sdk = new UiPath(config);
1406
+ * await sdk.initialize();
1407
+ * const entities = new Entities(sdk);
1408
+ * ```
1409
+ */
1410
+ constructor(instance) {
1411
+ // Private field - not visible via Object.keys() or any reflection
1412
+ _BaseService_apiClient.set(this, void 0);
1413
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1414
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1415
+ }
1416
+ /**
1417
+ * Gets a valid authentication token, refreshing if necessary.
1418
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1419
+ *
1420
+ * @returns Promise resolving to a valid access token string
1421
+ * @throws AuthenticationError if no token is available or refresh fails
1422
+ */
1423
+ async getValidAuthToken() {
1424
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1425
+ }
1426
+ /**
1427
+ * Creates a service accessor for pagination helpers
1428
+ * This allows pagination helpers to access protected methods without making them public
1429
+ */
1430
+ createPaginationServiceAccess() {
1431
+ return {
1432
+ get: (path, options) => this.get(path, options || {}),
1433
+ post: (path, body, options) => this.post(path, body, options || {}),
1434
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1435
+ };
1436
+ }
1437
+ async request(method, path, options = {}) {
1438
+ switch (method.toUpperCase()) {
1439
+ case 'GET':
1440
+ return this.get(path, options);
1441
+ case 'POST':
1442
+ return this.post(path, options.body, options);
1443
+ case 'PUT':
1444
+ return this.put(path, options.body, options);
1445
+ case 'PATCH':
1446
+ return this.patch(path, options.body, options);
1447
+ case 'DELETE':
1448
+ return this.delete(path, options);
1449
+ default:
1450
+ throw new Error(`Unsupported HTTP method: ${method}`);
1451
+ }
1452
+ }
1453
+ async requestWithSpec(spec) {
1454
+ if (!spec.method || !spec.url) {
1455
+ throw new Error('Request spec must include method and url');
1456
+ }
1457
+ return this.request(spec.method, spec.url, spec);
1458
+ }
1459
+ async get(path, options = {}) {
1460
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1461
+ return { data: response };
1462
+ }
1463
+ async post(path, data, options = {}) {
1464
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1465
+ return { data: response };
1466
+ }
1467
+ async put(path, data, options = {}) {
1468
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1469
+ return { data: response };
1470
+ }
1471
+ async patch(path, data, options = {}) {
1472
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1473
+ return { data: response };
1474
+ }
1475
+ async delete(path, options = {}) {
1476
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1477
+ return { data: response };
1478
+ }
1479
+ /**
1480
+ * Execute a request with cursor-based pagination
1481
+ */
1482
+ async requestWithPagination(method, path, paginationOptions, options) {
1483
+ const paginationType = options.pagination.paginationType;
1484
+ // Validate and prepare pagination parameters
1485
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1486
+ // Prepare request parameters based on pagination type
1487
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1488
+ // For POST requests, merge pagination params into body; for GET, use query params
1489
+ if (method.toUpperCase() === 'POST') {
1490
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1491
+ options.body = {
1492
+ ...existingBody,
1493
+ ...options.params,
1494
+ ...requestParams
1495
+ };
1496
+ }
1497
+ else {
1498
+ // Merge pagination parameters with existing parameters
1499
+ options.params = {
1500
+ ...options.params,
1501
+ ...requestParams
1502
+ };
1503
+ }
1504
+ // Make the request
1505
+ const response = await this.request(method, path, options);
1506
+ // Extract data from the response and create page result
1507
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1508
+ itemsField: options.pagination.itemsField,
1509
+ totalCountField: options.pagination.totalCountField,
1510
+ continuationTokenField: options.pagination.continuationTokenField
1511
+ });
1512
+ }
1513
+ /**
1514
+ * Validates and prepares pagination parameters from options
1515
+ */
1516
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1517
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1518
+ }
1519
+ /**
1520
+ * Prepares request parameters for pagination based on pagination type
1521
+ */
1522
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1523
+ const requestParams = {};
1524
+ let limitedPageSize;
1525
+ const paginationParams = paginationConfig?.paginationParams;
1526
+ switch (paginationType) {
1527
+ case PaginationType.OFFSET:
1528
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1529
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1530
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1531
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1532
+ requestParams[pageSizeParam] = limitedPageSize;
1533
+ if (params.pageNumber && params.pageNumber > 1) {
1534
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1535
+ }
1536
+ // Include total count for ODATA APIs
1537
+ {
1538
+ requestParams[countParam] = true;
1539
+ }
1540
+ break;
1541
+ case PaginationType.TOKEN:
1542
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1543
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1544
+ if (params.pageSize) {
1545
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1546
+ }
1547
+ if (params.continuationToken) {
1548
+ requestParams[tokenParam] = params.continuationToken;
1549
+ }
1550
+ break;
1551
+ }
1552
+ return requestParams;
1553
+ }
1554
+ /**
1555
+ * Creates a paginated response from API response
1556
+ */
1557
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1558
+ // Extract fields from response
1559
+ const itemsField = fields.itemsField ||
1560
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1561
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1562
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1563
+ // Extract items and metadata
1564
+ const items = response.data[itemsField] || [];
1565
+ const totalCount = response.data[totalCountField];
1566
+ const continuationToken = response.data[continuationTokenField];
1567
+ // Determine if there are more pages
1568
+ const hasMore = this.determineHasMorePages(paginationType, {
1569
+ totalCount,
1570
+ pageSize: params.pageSize,
1571
+ currentPage: params.pageNumber || 1,
1572
+ itemsCount: items.length,
1573
+ continuationToken
1574
+ });
1575
+ // Create and return the page result
1576
+ return PaginationManager.createPaginatedResponse({
1577
+ pageInfo: {
1578
+ hasMore,
1579
+ totalCount,
1580
+ currentPage: params.pageNumber,
1581
+ pageSize: params.pageSize,
1582
+ continuationToken
1583
+ },
1584
+ type: paginationType,
1585
+ }, items);
1586
+ }
1587
+ /**
1588
+ * Determines if there are more pages based on pagination type and metadata
1589
+ */
1590
+ determineHasMorePages(paginationType, info) {
1591
+ switch (paginationType) {
1592
+ case PaginationType.OFFSET:
1593
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1594
+ // If totalCount is available, use it for precise calculation
1595
+ if (info.totalCount !== undefined) {
1596
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1597
+ }
1598
+ // Fallback when totalCount is not available
1599
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1600
+ return info.itemsCount === effectivePageSize;
1601
+ case PaginationType.TOKEN:
1602
+ return !!info.continuationToken;
1603
+ default:
1604
+ return false;
1605
+ }
1606
+ }
1607
+ }
1608
+ _BaseService_apiClient = new WeakMap();
1609
+
1610
+ /**
1611
+ * Base service for services that need folder-specific functionality.
1612
+ *
1613
+ * Extends BaseService with additional methods for working with folder-scoped resources
1614
+ * in UiPath Orchestrator. Services that work with folders (Assets, Queues) extend this class.
1615
+ *
1616
+ * @remarks
1617
+ * This class provides helper methods for making folder-scoped API calls, handling folder IDs
1618
+ * in request headers, and managing cross-folder queries.
1619
+ */
1620
+ class FolderScopedService extends BaseService {
1621
+ /**
1622
+ * Gets resources in a folder with optional query parameters
1623
+ *
1624
+ * @param endpoint - API endpoint to call
1625
+ * @param folderId - required folder ID
1626
+ * @param options - Query options
1627
+ * @param transformFn - Optional function to transform the response data
1628
+ * @returns Promise resolving to an array of resources
1629
+ */
1630
+ async _getByFolder(endpoint, folderId, options = {}, transformFn) {
1631
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
1632
+ const keysToPrefix = Object.keys(options);
1633
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
1634
+ const response = await this.get(endpoint, {
1635
+ params: apiOptions,
1636
+ headers
1637
+ });
1638
+ if (transformFn) {
1639
+ return response.data?.value.map(transformFn);
1640
+ }
1641
+ return response.data?.value;
1642
+ }
1643
+ }
1644
+
1645
+ /**
1646
+ * Base path constants for different services
1647
+ */
1648
+ const ORCHESTRATOR_BASE = 'orchestrator_';
1649
+
1650
+ /**
1651
+ * Orchestrator Service Endpoints
1652
+ */
1653
+ /**
1654
+ * Orchestrator Job Service Endpoints
1655
+ */
1656
+ const JOB_ENDPOINTS = {
1657
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/Jobs`,
1658
+ };
1659
+
1660
+ /**
1661
+ * Maps fields for Job entities to ensure consistent naming
1662
+ * Semantic renames only — case conversion handled by pascalToCamelCaseKeys()
1663
+ */
1664
+ const JobMap = {
1665
+ creationTime: 'createdTime',
1666
+ lastModificationTime: 'lastModifiedTime',
1667
+ organizationUnitId: 'folderId',
1668
+ organizationUnitFullyQualifiedName: 'folderName',
1669
+ releaseName: 'processName',
1670
+ releaseVersionId: 'processVersionId',
1671
+ processType: 'packageType',
1672
+ release: 'process',
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.2.2";
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 BatchLogRecordProcessor(exporter);
1825
+ this.logProvider = new 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 = nameOrOptions
1908
+ ;
1909
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
1910
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1911
+ }
1912
+ // Execute the original function
1913
+ return originalFunction.apply(this, args);
1914
+ };
1915
+ }
1916
+ /**
1917
+ * Track decorator that can be used to automatically track function calls
1918
+ *
1919
+ * Usage:
1920
+ * @track("Service.Method")
1921
+ * function myFunction() { ... }
1922
+ *
1923
+ * @track("Queue.GetAll")
1924
+ * async getAll() { ... }
1925
+ *
1926
+ * @track("Tasks.Create")
1927
+ * async create() { ... }
1928
+ *
1929
+ * @track("Assets.Update", { condition: false })
1930
+ * function myFunction() { ... }
1931
+ *
1932
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
1933
+ * function myFunction() { ... }
1934
+ */
1935
+ function track(nameOrOptions, options) {
1936
+ return function decorator(_target, propertyKey, descriptor) {
1937
+ const opts = {};
1938
+ if (descriptor && typeof descriptor.value === 'function') {
1939
+ // Method decorator
1940
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
1941
+ return descriptor;
1942
+ }
1943
+ // Function decorator
1944
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
1945
+ };
1946
+ }
1947
+
1948
+ /**
1949
+ * Service for interacting with UiPath Orchestrator Jobs API
1950
+ */
1951
+ class JobService extends FolderScopedService {
1952
+ /**
1953
+ * Gets all jobs across folders with optional filtering
1954
+ *
1955
+ * @param options - Query options including optional folderId and pagination options
1956
+ * @returns Promise resolving to array of jobs or paginated response
1957
+ *
1958
+ * @example
1959
+ * ```typescript
1960
+ * import { Jobs } from '@uipath/uipath-typescript/jobs';
1961
+ *
1962
+ * const jobs = new Jobs(sdk);
1963
+ *
1964
+ * // Get all jobs
1965
+ * const allJobs = await jobs.getAll();
1966
+ *
1967
+ * // Get all jobs in a specific folder
1968
+ * const folderJobs = await jobs.getAll({ folderId: 123 });
1969
+ *
1970
+ * // With filtering
1971
+ * const runningJobs = await jobs.getAll({
1972
+ * filter: "state eq 'Running'"
1973
+ * });
1974
+ *
1975
+ * // First page with pagination
1976
+ * const page1 = await jobs.getAll({ pageSize: 10 });
1977
+ *
1978
+ * // Navigate using cursor
1979
+ * if (page1.hasNextPage) {
1980
+ * const page2 = await jobs.getAll({ cursor: page1.nextCursor });
1981
+ * }
1982
+ * ```
1983
+ */
1984
+ async getAll(options) {
1985
+ const transformJobResponse = (job) => transformData(pascalToCamelCaseKeys(job), JobMap);
1986
+ return PaginationHelpers.getAll({
1987
+ serviceAccess: this.createPaginationServiceAccess(),
1988
+ getEndpoint: () => JOB_ENDPOINTS.GET_ALL,
1989
+ getByFolderEndpoint: JOB_ENDPOINTS.GET_ALL,
1990
+ transformFn: transformJobResponse,
1991
+ pagination: {
1992
+ paginationType: PaginationType.OFFSET,
1993
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
1994
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
1995
+ paginationParams: {
1996
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
1997
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
1998
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM,
1999
+ },
2000
+ },
2001
+ }, options);
2002
+ }
2003
+ }
2004
+ __decorate([
2005
+ track('Jobs.GetAll')
2006
+ ], JobService.prototype, "getAll", null);
2007
+
2008
+ /**
2009
+ * Enum for job sub-state
2010
+ */
2011
+ var JobSubState;
2012
+ (function (JobSubState) {
2013
+ JobSubState["WithFaults"] = "WITH_FAULTS";
2014
+ JobSubState["Manually"] = "MANUALLY";
2015
+ })(JobSubState || (JobSubState = {}));
2016
+ /**
2017
+ * Enum for serverless job type
2018
+ */
2019
+ var ServerlessJobType;
2020
+ (function (ServerlessJobType) {
2021
+ ServerlessJobType["RobotJob"] = "RobotJob";
2022
+ ServerlessJobType["WebApp"] = "WebApp";
2023
+ ServerlessJobType["LoadTest"] = "LoadTest";
2024
+ ServerlessJobType["StudioWebDesigner"] = "StudioWebDesigner";
2025
+ ServerlessJobType["PublishStudioProject"] = "PublishStudioProject";
2026
+ ServerlessJobType["JsApi"] = "JsApi";
2027
+ ServerlessJobType["PythonCodedAgent"] = "PythonCodedAgent";
2028
+ ServerlessJobType["MCPServer"] = "MCPServer";
2029
+ ServerlessJobType["PythonCodedSystemAgent"] = "PythonCodedSystemAgent";
2030
+ ServerlessJobType["PythonAgent"] = "PythonAgent";
2031
+ })(ServerlessJobType || (ServerlessJobType = {}));
2032
+
2033
+ export { JobService, JobSubState, JobService as Jobs, ServerlessJobType };