@uipath/uipath-typescript 1.2.1 → 1.3.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 (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 +11 -27
  20. package/dist/entities/index.d.ts +38 -26
  21. package/dist/entities/index.mjs +11 -27
  22. package/dist/index.cjs +683 -284
  23. package/dist/index.d.ts +549 -75
  24. package/dist/index.mjs +683 -285
  25. package/dist/index.umd.js +680 -281
  26. package/dist/jobs/index.cjs +2264 -0
  27. package/dist/jobs/index.d.ts +860 -0
  28. package/dist/jobs/index.mjs +2260 -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,2264 @@
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
+ const token = await this.getValidToken();
550
+ return {
551
+ 'Authorization': `Bearer ${token}`,
552
+ 'Content-Type': CONTENT_TYPES.JSON,
553
+ ...this.defaultHeaders,
554
+ ...this.clientConfig.headers
555
+ };
556
+ }
557
+ async request(method, path, options = {}) {
558
+ // Ensure path starts with a forward slash
559
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
560
+ // Construct URL with org and tenant names
561
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
562
+ const isFormData = options.body instanceof FormData;
563
+ const defaultHeaders = await this.getDefaultHeaders();
564
+ if (isFormData) {
565
+ delete defaultHeaders['Content-Type'];
566
+ }
567
+ const headers = {
568
+ ...defaultHeaders,
569
+ ...options.headers
570
+ };
571
+ // Convert params to URLSearchParams
572
+ const searchParams = new URLSearchParams();
573
+ if (options.params) {
574
+ Object.entries(options.params).forEach(([key, value]) => {
575
+ searchParams.append(key, value.toString());
576
+ });
577
+ }
578
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
579
+ let body = undefined;
580
+ if (options.body) {
581
+ body = isFormData ? options.body : JSON.stringify(options.body);
582
+ }
583
+ try {
584
+ const response = await fetch(fullUrl, {
585
+ method,
586
+ headers,
587
+ body,
588
+ signal: options.signal
589
+ });
590
+ if (!response.ok) {
591
+ const errorInfo = await errorResponseParser.parse(response);
592
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
593
+ }
594
+ if (response.status === 204) {
595
+ return undefined;
596
+ }
597
+ // Handle blob response type for binary data (e.g., file downloads)
598
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
599
+ const blob = await response.blob();
600
+ return blob;
601
+ }
602
+ // Check if we're expecting XML
603
+ const acceptHeader = headers['Accept'] || headers['accept'];
604
+ if (acceptHeader === CONTENT_TYPES.XML) {
605
+ const text = await response.text();
606
+ return text;
607
+ }
608
+ return response.json();
609
+ }
610
+ catch (error) {
611
+ // If it's already one of our errors, re-throw it
612
+ if (error.type && error.type.includes('Error')) {
613
+ throw error;
614
+ }
615
+ // Otherwise, it's likely a network error
616
+ throw ErrorFactory.createNetworkError(error);
617
+ }
618
+ }
619
+ async get(path, options = {}) {
620
+ return this.request('GET', path, options);
621
+ }
622
+ async post(path, data, options = {}) {
623
+ return this.request('POST', path, { ...options, body: data });
624
+ }
625
+ async put(path, data, options = {}) {
626
+ return this.request('PUT', path, { ...options, body: data });
627
+ }
628
+ async patch(path, data, options = {}) {
629
+ return this.request('PATCH', path, { ...options, body: data });
630
+ }
631
+ async delete(path, options = {}) {
632
+ return this.request('DELETE', path, options);
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Pagination types supported by the SDK
638
+ */
639
+ var PaginationType;
640
+ (function (PaginationType) {
641
+ PaginationType["OFFSET"] = "offset";
642
+ PaginationType["TOKEN"] = "token";
643
+ })(PaginationType || (PaginationType = {}));
644
+
645
+ /**
646
+ * Collection of utility functions for working with objects
647
+ */
648
+ /**
649
+ * Filters out undefined values from an object
650
+ * @param obj The source object
651
+ * @returns A new object without undefined values
652
+ *
653
+ * @example
654
+ * ```typescript
655
+ * // Object with undefined values
656
+ * const options = {
657
+ * name: 'test',
658
+ * count: 5,
659
+ * prefix: undefined,
660
+ * suffix: null
661
+ * };
662
+ * const result = filterUndefined(options);
663
+ * // result = { name: 'test', count: 5, suffix: null }
664
+ * ```
665
+ */
666
+ function filterUndefined(obj) {
667
+ const result = {};
668
+ for (const [key, value] of Object.entries(obj)) {
669
+ if (value !== undefined) {
670
+ result[key] = value;
671
+ }
672
+ }
673
+ return result;
674
+ }
675
+
676
+ /**
677
+ * Utility functions for platform detection
678
+ */
679
+ /**
680
+ * Checks if code is running in a browser environment
681
+ */
682
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
683
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
684
+
685
+ /**
686
+ * Base64 encoding/decoding
687
+ */
688
+ /**
689
+ * Encodes a string to base64
690
+ * @param str - The string to encode
691
+ * @returns Base64 encoded string
692
+ */
693
+ function encodeBase64(str) {
694
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
695
+ const encoder = new TextEncoder();
696
+ const data = encoder.encode(str);
697
+ // Convert Uint8Array to base64
698
+ if (isBrowser) {
699
+ // Browser environment
700
+ // Convert Uint8Array to binary string then to base64
701
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
702
+ return btoa(binaryString);
703
+ }
704
+ else {
705
+ // Node.js environment
706
+ return Buffer.from(data).toString('base64');
707
+ }
708
+ }
709
+ /**
710
+ * Decodes a base64 string
711
+ * @param base64 - The base64 string to decode
712
+ * @returns Decoded string
713
+ */
714
+ function decodeBase64(base64) {
715
+ let bytes;
716
+ if (isBrowser) {
717
+ // Browser environment
718
+ const binaryString = atob(base64);
719
+ bytes = new Uint8Array(binaryString.length);
720
+ for (let i = 0; i < binaryString.length; i++) {
721
+ bytes[i] = binaryString.charCodeAt(i);
722
+ }
723
+ }
724
+ else {
725
+ // Node.js environment
726
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
727
+ }
728
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
729
+ const decoder = new TextDecoder();
730
+ return decoder.decode(bytes);
731
+ }
732
+
733
+ /**
734
+ * PaginationManager handles the conversion between uniform cursor-based pagination
735
+ * and the specific pagination type for each service
736
+ */
737
+ class PaginationManager {
738
+ /**
739
+ * Create a pagination cursor for subsequent page requests
740
+ */
741
+ static createCursor({ pageInfo, type }) {
742
+ if (!pageInfo.hasMore) {
743
+ return undefined;
744
+ }
745
+ const cursorData = {
746
+ type,
747
+ pageSize: pageInfo.pageSize,
748
+ };
749
+ switch (type) {
750
+ case PaginationType.OFFSET:
751
+ if (pageInfo.currentPage) {
752
+ cursorData.pageNumber = pageInfo.currentPage + 1;
753
+ }
754
+ break;
755
+ case PaginationType.TOKEN:
756
+ if (pageInfo.continuationToken) {
757
+ cursorData.continuationToken = pageInfo.continuationToken;
758
+ }
759
+ else {
760
+ return undefined; // No continuation token, can't continue
761
+ }
762
+ break;
763
+ }
764
+ return {
765
+ value: encodeBase64(JSON.stringify(cursorData))
766
+ };
767
+ }
768
+ /**
769
+ * Create a paginated response with navigation cursors
770
+ */
771
+ static createPaginatedResponse({ pageInfo, type }, items) {
772
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
773
+ // Create previous page cursor if applicable
774
+ let previousCursor = undefined;
775
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
776
+ const prevCursorData = {
777
+ type,
778
+ pageNumber: pageInfo.currentPage - 1,
779
+ pageSize: pageInfo.pageSize,
780
+ };
781
+ previousCursor = {
782
+ value: encodeBase64(JSON.stringify(prevCursorData))
783
+ };
784
+ }
785
+ // Calculate total pages if we have totalCount and pageSize
786
+ let totalPages = undefined;
787
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
788
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
789
+ }
790
+ // Determine if this pagination type supports page jumping
791
+ const supportsPageJump = type === PaginationType.OFFSET;
792
+ // Create the result object with all fields, then filter out undefined values
793
+ const result = filterUndefined({
794
+ items,
795
+ totalCount: pageInfo.totalCount,
796
+ hasNextPage: pageInfo.hasMore,
797
+ nextCursor: nextCursor,
798
+ previousCursor: previousCursor,
799
+ currentPage: pageInfo.currentPage,
800
+ totalPages,
801
+ supportsPageJump
802
+ });
803
+ return result;
804
+ }
805
+ }
806
+
807
+ /**
808
+ * Creates headers object from key-value pairs
809
+ * @param headersObj - Object containing header key-value pairs
810
+ * @returns Headers object with all values converted to strings
811
+ *
812
+ * @example
813
+ * ```typescript
814
+ * // Single header
815
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
816
+ *
817
+ * // Multiple headers
818
+ * const headers = createHeaders({
819
+ * 'X-UIPATH-FolderKey': '1234567890',
820
+ * 'X-UIPATH-OrganizationUnitId': 123,
821
+ * 'Accept': 'application/json'
822
+ * });
823
+ *
824
+ * // Using constants
825
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
826
+ * const headers = createHeaders({
827
+ * [FOLDER_KEY]: 'abc-123',
828
+ * [FOLDER_ID]: 456
829
+ * });
830
+ *
831
+ * // Empty headers
832
+ * const headers = createHeaders();
833
+ * ```
834
+ */
835
+ function createHeaders(headersObj) {
836
+ const headers = {};
837
+ for (const [key, value] of Object.entries(headersObj)) {
838
+ if (value !== undefined && value !== null) {
839
+ headers[key] = value.toString();
840
+ }
841
+ }
842
+ return headers;
843
+ }
844
+
845
+ /**
846
+ * Common constants used across the SDK
847
+ */
848
+ /**
849
+ * Prefix used for OData query parameters
850
+ */
851
+ const ODATA_PREFIX = '$';
852
+ /**
853
+ * HTTP methods
854
+ */
855
+ const HTTP_METHODS = {
856
+ GET: 'GET',
857
+ POST: 'POST'};
858
+ /**
859
+ * OData pagination constants
860
+ */
861
+ const ODATA_PAGINATION = {
862
+ /** Default field name for items in a paginated OData response */
863
+ ITEMS_FIELD: 'value',
864
+ /** Default field name for total count in a paginated OData response */
865
+ TOTAL_COUNT_FIELD: '@odata.count'
866
+ };
867
+ /**
868
+ * OData OFFSET pagination parameter names (ODATA-style)
869
+ */
870
+ const ODATA_OFFSET_PARAMS = {
871
+ /** OData page size parameter name */
872
+ PAGE_SIZE_PARAM: '$top',
873
+ /** OData offset parameter name */
874
+ OFFSET_PARAM: '$skip',
875
+ /** OData count parameter name */
876
+ COUNT_PARAM: '$count'
877
+ };
878
+ /**
879
+ * Bucket TOKEN pagination parameter names
880
+ */
881
+ const BUCKET_TOKEN_PARAMS = {
882
+ /** Bucket page size parameter name */
883
+ PAGE_SIZE_PARAM: 'takeHint',
884
+ /** Bucket token parameter name */
885
+ TOKEN_PARAM: 'continuationToken'
886
+ };
887
+
888
+ /**
889
+ * Transforms data by mapping fields according to the provided field mapping
890
+ * @param data The source data to transform
891
+ * @param fieldMapping Object mapping source field names to target field names
892
+ * @returns Transformed data with mapped field names
893
+ *
894
+ * @example
895
+ * ```typescript
896
+ * // Single object transformation
897
+ * const data = { id: '123', userName: 'john' };
898
+ * const mapping = { id: 'userId', userName: 'name' };
899
+ * const result = transformData(data, mapping);
900
+ * // result = { userId: '123', name: 'john' }
901
+ *
902
+ * // Array transformation
903
+ * const dataArray = [
904
+ * { id: '123', userName: 'john' },
905
+ * { id: '456', userName: 'jane' }
906
+ * ];
907
+ * const result = transformData(dataArray, mapping);
908
+ * // result = [
909
+ * // { userId: '123', name: 'john' },
910
+ * // { userId: '456', name: 'jane' }
911
+ * // ]
912
+ * ```
913
+ */
914
+ function transformData(data, fieldMapping) {
915
+ // Handle array of objects
916
+ if (Array.isArray(data)) {
917
+ return data.map(item => transformData(item, fieldMapping));
918
+ }
919
+ // Handle single object
920
+ const result = { ...data };
921
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
922
+ if (sourceField in result) {
923
+ const value = result[sourceField];
924
+ delete result[sourceField];
925
+ result[targetField] = value;
926
+ }
927
+ }
928
+ return result;
929
+ }
930
+ /**
931
+ * Converts a string from PascalCase to camelCase
932
+ * @param str The PascalCase string to convert
933
+ * @returns The camelCase version of the string
934
+ *
935
+ * @example
936
+ * ```typescript
937
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
938
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
939
+ * ```
940
+ */
941
+ function pascalToCamelCase(str) {
942
+ if (!str)
943
+ return str;
944
+ return str.charAt(0).toLowerCase() + str.slice(1);
945
+ }
946
+ /**
947
+ * Generic function to transform object keys using a provided case conversion function
948
+ * @param data The object to transform
949
+ * @param convertCase The function to convert each key
950
+ * @returns A new object with transformed keys
951
+ */
952
+ function transformCaseKeys(data, convertCase) {
953
+ // Handle array of objects
954
+ if (Array.isArray(data)) {
955
+ return data.map(item => {
956
+ // If the array element is a primitive (string, number, etc.), return it as is
957
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
958
+ return item;
959
+ }
960
+ // Only recursively transform if it's actually an object
961
+ return transformCaseKeys(item, convertCase);
962
+ });
963
+ }
964
+ const result = {};
965
+ for (const [key, value] of Object.entries(data)) {
966
+ const transformedKey = convertCase(key);
967
+ // Recursively transform nested objects and arrays
968
+ if (value !== null && typeof value === 'object') {
969
+ result[transformedKey] = transformCaseKeys(value, convertCase);
970
+ }
971
+ else {
972
+ result[transformedKey] = value;
973
+ }
974
+ }
975
+ return result;
976
+ }
977
+ /**
978
+ * Transforms an object's keys from PascalCase to camelCase
979
+ * @param data The object with PascalCase keys
980
+ * @returns A new object with all keys converted to camelCase
981
+ *
982
+ * @example
983
+ * ```typescript
984
+ * // Simple object
985
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
986
+ * // Result: { id: "123", taskName: "Invoice" }
987
+ *
988
+ * // Nested object
989
+ * pascalToCamelCaseKeys({
990
+ * TaskId: "456",
991
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
992
+ * });
993
+ * // Result: {
994
+ * // taskId: "456",
995
+ * // taskDetails: { assignedUser: "John", priority: "High" }
996
+ * // }
997
+ *
998
+ * // Array of objects
999
+ * pascalToCamelCaseKeys([
1000
+ * { Id: "1", IsComplete: false },
1001
+ * { Id: "2", IsComplete: true }
1002
+ * ]);
1003
+ * // Result: [
1004
+ * // { id: "1", isComplete: false },
1005
+ * // { id: "2", isComplete: true }
1006
+ * // ]
1007
+ * ```
1008
+ */
1009
+ function pascalToCamelCaseKeys(data) {
1010
+ return transformCaseKeys(data, pascalToCamelCase);
1011
+ }
1012
+ /**
1013
+ * Adds a prefix to specified keys in an object, returning a new object.
1014
+ * Only the provided keys are prefixed; all others are left unchanged.
1015
+ *
1016
+ * @param obj The source object
1017
+ * @param prefix The prefix to add (e.g., '$')
1018
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1019
+ * @returns A new object with specified keys prefixed
1020
+ *
1021
+ * @example
1022
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1023
+ */
1024
+ function addPrefixToKeys(obj, prefix, keys) {
1025
+ const result = {};
1026
+ for (const [key, value] of Object.entries(obj)) {
1027
+ if (keys.includes(key)) {
1028
+ result[`${prefix}${key}`] = value;
1029
+ }
1030
+ else {
1031
+ result[key] = value;
1032
+ }
1033
+ }
1034
+ return result;
1035
+ }
1036
+
1037
+ /**
1038
+ * Constants used throughout the pagination system
1039
+ */
1040
+ /** Maximum number of items that can be requested in a single page */
1041
+ const MAX_PAGE_SIZE = 1000;
1042
+ /** Default page size when jumpToPage is used without specifying pageSize */
1043
+ const DEFAULT_PAGE_SIZE = 50;
1044
+ /** Default field name for items in a paginated response */
1045
+ const DEFAULT_ITEMS_FIELD = 'value';
1046
+ /** Default field name for total count in a paginated response */
1047
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1048
+ /**
1049
+ * Limits the page size to the maximum allowed value
1050
+ * @param pageSize - Requested page size
1051
+ * @returns Limited page size value
1052
+ */
1053
+ function getLimitedPageSize(pageSize) {
1054
+ if (pageSize === undefined || pageSize === null) {
1055
+ return DEFAULT_PAGE_SIZE;
1056
+ }
1057
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1058
+ }
1059
+
1060
+ /**
1061
+ * Helper functions for pagination that can be used across services
1062
+ */
1063
+ class PaginationHelpers {
1064
+ /**
1065
+ * Checks if any pagination parameters are provided
1066
+ *
1067
+ * @param options - The options object to check
1068
+ * @returns True if any pagination parameter is defined, false otherwise
1069
+ */
1070
+ static hasPaginationParameters(options = {}) {
1071
+ const { cursor, pageSize, jumpToPage } = options;
1072
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1073
+ }
1074
+ /**
1075
+ * Parse a pagination cursor string into cursor data
1076
+ */
1077
+ static parseCursor(cursorString) {
1078
+ try {
1079
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1080
+ return cursorData;
1081
+ }
1082
+ catch {
1083
+ throw new Error('Invalid pagination cursor');
1084
+ }
1085
+ }
1086
+ /**
1087
+ * Validates cursor format and structure
1088
+ *
1089
+ * @param paginationOptions - The pagination options containing the cursor
1090
+ * @param paginationType - Optional pagination type to validate against
1091
+ */
1092
+ static validateCursor(paginationOptions, paginationType) {
1093
+ if (paginationOptions.cursor !== undefined) {
1094
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1095
+ throw new Error('cursor must contain a valid cursor string');
1096
+ }
1097
+ try {
1098
+ // Try to parse the cursor to validate it
1099
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1100
+ // If type is provided, validate cursor contains expected type information
1101
+ if (paginationType) {
1102
+ if (!cursorData.type) {
1103
+ throw new Error('Invalid cursor: missing pagination type');
1104
+ }
1105
+ // Check pagination type compatibility
1106
+ if (cursorData.type !== paginationType) {
1107
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1108
+ }
1109
+ }
1110
+ }
1111
+ catch (error) {
1112
+ if (error instanceof Error) {
1113
+ // If it's already our error with specific message, pass it through
1114
+ if (error.message.startsWith('Invalid cursor') ||
1115
+ error.message.startsWith('Pagination type mismatch')) {
1116
+ throw error;
1117
+ }
1118
+ }
1119
+ throw new Error('Invalid pagination cursor format');
1120
+ }
1121
+ }
1122
+ }
1123
+ /**
1124
+ * Comprehensive validation for pagination options
1125
+ *
1126
+ * @param options - The pagination options to validate
1127
+ * @param paginationType - The pagination type these options will be used with
1128
+ * @returns Processed pagination parameters ready for use
1129
+ */
1130
+ static validatePaginationOptions(options, paginationType) {
1131
+ // Validate pageSize
1132
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1133
+ throw new Error('pageSize must be a positive number');
1134
+ }
1135
+ // Validate jumpToPage
1136
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1137
+ throw new Error('jumpToPage must be a positive number');
1138
+ }
1139
+ // Validate cursor
1140
+ PaginationHelpers.validateCursor(options, paginationType);
1141
+ // Validate service compatibility
1142
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1143
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1144
+ }
1145
+ // Get processed parameters
1146
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1147
+ }
1148
+ /**
1149
+ * Convert a unified pagination options to service-specific parameters
1150
+ */
1151
+ static getRequestParameters(options, paginationType) {
1152
+ // Handle jumpToPage
1153
+ if (options.jumpToPage !== undefined) {
1154
+ const jumpToPageOptions = {
1155
+ pageSize: options.pageSize,
1156
+ pageNumber: options.jumpToPage
1157
+ };
1158
+ return filterUndefined(jumpToPageOptions);
1159
+ }
1160
+ // If no cursor is provided, it's a first page request
1161
+ if (!options.cursor) {
1162
+ const firstPageOptions = {
1163
+ pageSize: options.pageSize,
1164
+ // Only set pageNumber for OFFSET pagination
1165
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1166
+ };
1167
+ return filterUndefined(firstPageOptions);
1168
+ }
1169
+ // Parse the cursor
1170
+ try {
1171
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1172
+ const cursorBasedOptions = {
1173
+ pageSize: cursorData.pageSize || options.pageSize,
1174
+ pageNumber: cursorData.pageNumber,
1175
+ continuationToken: cursorData.continuationToken,
1176
+ type: cursorData.type,
1177
+ };
1178
+ return filterUndefined(cursorBasedOptions);
1179
+ }
1180
+ catch {
1181
+ throw new Error('Invalid pagination cursor');
1182
+ }
1183
+ }
1184
+ /**
1185
+ * Helper method for paginated resource retrieval
1186
+ *
1187
+ * @param params - Parameters for pagination
1188
+ * @returns Promise resolving to a paginated result
1189
+ */
1190
+ static async getAllPaginated(params) {
1191
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1192
+ const endpoint = getEndpoint(folderId);
1193
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1194
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1195
+ headers,
1196
+ params: additionalParams,
1197
+ pagination: {
1198
+ paginationType: options.paginationType || PaginationType.OFFSET,
1199
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1200
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1201
+ continuationTokenField: options.continuationTokenField,
1202
+ paginationParams: options.paginationParams
1203
+ }
1204
+ });
1205
+ // Parse items - automatically handle JSON string responses
1206
+ const rawItems = paginatedResponse.items;
1207
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1208
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1209
+ return {
1210
+ ...paginatedResponse,
1211
+ items: transformedItems
1212
+ };
1213
+ }
1214
+ /**
1215
+ * Helper method for non-paginated resource retrieval
1216
+ *
1217
+ * @param params - Parameters for non-paginated resource retrieval
1218
+ * @returns Promise resolving to an object with data and totalCount
1219
+ */
1220
+ static async getAllNonPaginated(params) {
1221
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1222
+ // Set default field names
1223
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1224
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1225
+ // Determine endpoint and headers based on folderId
1226
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1227
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1228
+ // Make the API call based on method
1229
+ let response;
1230
+ if (method === HTTP_METHODS.POST) {
1231
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1232
+ }
1233
+ else {
1234
+ response = await serviceAccess.get(endpoint, {
1235
+ params: additionalParams,
1236
+ headers
1237
+ });
1238
+ }
1239
+ // Extract and transform items from response
1240
+ const rawItems = response.data?.[itemsField];
1241
+ const totalCount = response.data?.[totalCountField];
1242
+ // Parse items - automatically handle JSON string responses
1243
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1244
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1245
+ return {
1246
+ items,
1247
+ totalCount
1248
+ };
1249
+ }
1250
+ /**
1251
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1252
+ *
1253
+ * @param config - Configuration for the getAll operation
1254
+ * @param options - Request options including pagination parameters
1255
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1256
+ */
1257
+ static async getAll(config, options) {
1258
+ const optionsWithDefaults = options || {};
1259
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1260
+ // Determine if pagination is requested
1261
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1262
+ // Process parameters (custom processing if provided, otherwise default)
1263
+ let processedOptions = restOptions;
1264
+ if (config.processParametersFn) {
1265
+ processedOptions = config.processParametersFn(restOptions, folderId);
1266
+ }
1267
+ // Apply ODATA prefix to keys (excluding specified keys)
1268
+ const excludeKeys = config.excludeFromPrefix || [];
1269
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1270
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1271
+ // Default pagination options
1272
+ const paginationOptions = {
1273
+ paginationType: PaginationType.OFFSET,
1274
+ itemsField: DEFAULT_ITEMS_FIELD,
1275
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1276
+ ...config.pagination
1277
+ };
1278
+ // Paginated flow
1279
+ if (isPaginationRequested) {
1280
+ return PaginationHelpers.getAllPaginated({
1281
+ serviceAccess: config.serviceAccess,
1282
+ getEndpoint: config.getEndpoint,
1283
+ folderId,
1284
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1285
+ additionalParams: prefixedOptions,
1286
+ transformFn: config.transformFn,
1287
+ method: config.method,
1288
+ options: {
1289
+ ...paginationOptions,
1290
+ paginationParams: config.pagination?.paginationParams
1291
+ }
1292
+ }); // Type assertion needed due to conditional return
1293
+ }
1294
+ // Non-paginated flow
1295
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1296
+ return PaginationHelpers.getAllNonPaginated({
1297
+ serviceAccess: config.serviceAccess,
1298
+ getAllEndpoint: config.getEndpoint(),
1299
+ getByFolderEndpoint: byFolderEndpoint,
1300
+ folderId,
1301
+ additionalParams: prefixedOptions,
1302
+ transformFn: config.transformFn,
1303
+ method: config.method,
1304
+ options: {
1305
+ itemsField: paginationOptions.itemsField,
1306
+ totalCountField: paginationOptions.totalCountField
1307
+ }
1308
+ });
1309
+ }
1310
+ }
1311
+
1312
+ /**
1313
+ * SDK Internals Registry - Internal registry for SDK instances
1314
+ *
1315
+ * This class is NOT exported in the public API.
1316
+ * It provides a secure way to share SDK internals between
1317
+ * the UiPath class and service classes without exposing them publicly.
1318
+ *
1319
+ * @internal
1320
+ */
1321
+ // Global symbol key to ensure WeakMap is shared across module instances
1322
+ // This prevents issues when core and service modules are bundled separately
1323
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1324
+ // Get or create the global WeakMap store
1325
+ const getGlobalStore = () => {
1326
+ const globalObj = globalThis;
1327
+ if (!globalObj[REGISTRY_KEY]) {
1328
+ globalObj[REGISTRY_KEY] = new WeakMap();
1329
+ }
1330
+ return globalObj[REGISTRY_KEY];
1331
+ };
1332
+ /**
1333
+ * Internal registry for SDK private components.
1334
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1335
+ * garbage collected when the SDK instance is no longer referenced.
1336
+ *
1337
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1338
+ * across separately bundled modules (core, entities, tasks, etc.).
1339
+ *
1340
+ * @internal - Not exported in public API
1341
+ */
1342
+ class SDKInternalsRegistry {
1343
+ // Use global store to ensure sharing across module bundles
1344
+ static get store() {
1345
+ return getGlobalStore();
1346
+ }
1347
+ /**
1348
+ * Register SDK instance internals
1349
+ * Called by UiPath constructor
1350
+ */
1351
+ static set(instance, internals) {
1352
+ this.store.set(instance, internals);
1353
+ }
1354
+ /**
1355
+ * Retrieve SDK instance internals
1356
+ * Called by BaseService constructor
1357
+ */
1358
+ static get(instance) {
1359
+ const internals = this.store.get(instance);
1360
+ if (!internals) {
1361
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1362
+ }
1363
+ return internals;
1364
+ }
1365
+ }
1366
+
1367
+ var _BaseService_apiClient;
1368
+ /**
1369
+ * Base class for all UiPath SDK services.
1370
+ *
1371
+ * Provides common functionality for authentication, configuration, and API communication.
1372
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1373
+ *
1374
+ * This class implements the dependency injection pattern where services receive a configured
1375
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1376
+ * including authentication token management.
1377
+ *
1378
+ * @remarks
1379
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1380
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1381
+ *
1382
+ */
1383
+ class BaseService {
1384
+ /**
1385
+ * Creates a base service instance with dependency injection.
1386
+ *
1387
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1388
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1389
+ * and token management internally.
1390
+ *
1391
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1392
+ * Services receive this via dependency injection in the modular pattern.
1393
+ *
1394
+ * @example
1395
+ * ```typescript
1396
+ * // Services automatically call this via super()
1397
+ * export class EntityService extends BaseService {
1398
+ * constructor(instance: IUiPath) {
1399
+ * super(instance); // Initializes the internal ApiClient
1400
+ * }
1401
+ * }
1402
+ *
1403
+ * // Usage in modular pattern
1404
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1405
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1406
+ *
1407
+ * const sdk = new UiPath(config);
1408
+ * await sdk.initialize();
1409
+ * const entities = new Entities(sdk);
1410
+ * ```
1411
+ */
1412
+ constructor(instance) {
1413
+ // Private field - not visible via Object.keys() or any reflection
1414
+ _BaseService_apiClient.set(this, void 0);
1415
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1416
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1417
+ }
1418
+ /**
1419
+ * Gets a valid authentication token, refreshing if necessary.
1420
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1421
+ *
1422
+ * @returns Promise resolving to a valid access token string
1423
+ * @throws AuthenticationError if no token is available or refresh fails
1424
+ */
1425
+ async getValidAuthToken() {
1426
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1427
+ }
1428
+ /**
1429
+ * Creates a service accessor for pagination helpers
1430
+ * This allows pagination helpers to access protected methods without making them public
1431
+ */
1432
+ createPaginationServiceAccess() {
1433
+ return {
1434
+ get: (path, options) => this.get(path, options || {}),
1435
+ post: (path, body, options) => this.post(path, body, options || {}),
1436
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1437
+ };
1438
+ }
1439
+ async request(method, path, options = {}) {
1440
+ switch (method.toUpperCase()) {
1441
+ case 'GET':
1442
+ return this.get(path, options);
1443
+ case 'POST':
1444
+ return this.post(path, options.body, options);
1445
+ case 'PUT':
1446
+ return this.put(path, options.body, options);
1447
+ case 'PATCH':
1448
+ return this.patch(path, options.body, options);
1449
+ case 'DELETE':
1450
+ return this.delete(path, options);
1451
+ default:
1452
+ throw new Error(`Unsupported HTTP method: ${method}`);
1453
+ }
1454
+ }
1455
+ async requestWithSpec(spec) {
1456
+ if (!spec.method || !spec.url) {
1457
+ throw new Error('Request spec must include method and url');
1458
+ }
1459
+ return this.request(spec.method, spec.url, spec);
1460
+ }
1461
+ async get(path, options = {}) {
1462
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1463
+ return { data: response };
1464
+ }
1465
+ async post(path, data, options = {}) {
1466
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1467
+ return { data: response };
1468
+ }
1469
+ async put(path, data, options = {}) {
1470
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1471
+ return { data: response };
1472
+ }
1473
+ async patch(path, data, options = {}) {
1474
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1475
+ return { data: response };
1476
+ }
1477
+ async delete(path, options = {}) {
1478
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1479
+ return { data: response };
1480
+ }
1481
+ /**
1482
+ * Execute a request with cursor-based pagination
1483
+ */
1484
+ async requestWithPagination(method, path, paginationOptions, options) {
1485
+ const paginationType = options.pagination.paginationType;
1486
+ // Validate and prepare pagination parameters
1487
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1488
+ // Prepare request parameters based on pagination type
1489
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1490
+ // For POST requests, merge pagination params into body; for GET, use query params
1491
+ if (method.toUpperCase() === 'POST') {
1492
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1493
+ options.body = {
1494
+ ...existingBody,
1495
+ ...options.params,
1496
+ ...requestParams
1497
+ };
1498
+ }
1499
+ else {
1500
+ // Merge pagination parameters with existing parameters
1501
+ options.params = {
1502
+ ...options.params,
1503
+ ...requestParams
1504
+ };
1505
+ }
1506
+ // Make the request
1507
+ const response = await this.request(method, path, options);
1508
+ // Extract data from the response and create page result
1509
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1510
+ itemsField: options.pagination.itemsField,
1511
+ totalCountField: options.pagination.totalCountField,
1512
+ continuationTokenField: options.pagination.continuationTokenField
1513
+ });
1514
+ }
1515
+ /**
1516
+ * Validates and prepares pagination parameters from options
1517
+ */
1518
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1519
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1520
+ }
1521
+ /**
1522
+ * Prepares request parameters for pagination based on pagination type
1523
+ */
1524
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1525
+ const requestParams = {};
1526
+ let limitedPageSize;
1527
+ const paginationParams = paginationConfig?.paginationParams;
1528
+ switch (paginationType) {
1529
+ case PaginationType.OFFSET:
1530
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1531
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1532
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1533
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1534
+ requestParams[pageSizeParam] = limitedPageSize;
1535
+ if (params.pageNumber && params.pageNumber > 1) {
1536
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1537
+ }
1538
+ // Include total count for ODATA APIs
1539
+ {
1540
+ requestParams[countParam] = true;
1541
+ }
1542
+ break;
1543
+ case PaginationType.TOKEN:
1544
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1545
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1546
+ if (params.pageSize) {
1547
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1548
+ }
1549
+ if (params.continuationToken) {
1550
+ requestParams[tokenParam] = params.continuationToken;
1551
+ }
1552
+ break;
1553
+ }
1554
+ return requestParams;
1555
+ }
1556
+ /**
1557
+ * Creates a paginated response from API response
1558
+ */
1559
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1560
+ // Extract fields from response
1561
+ const itemsField = fields.itemsField ||
1562
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1563
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1564
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1565
+ // Extract items and metadata
1566
+ const items = response.data[itemsField] || [];
1567
+ const totalCount = response.data[totalCountField];
1568
+ const continuationToken = response.data[continuationTokenField];
1569
+ // Determine if there are more pages
1570
+ const hasMore = this.determineHasMorePages(paginationType, {
1571
+ totalCount,
1572
+ pageSize: params.pageSize,
1573
+ currentPage: params.pageNumber || 1,
1574
+ itemsCount: items.length,
1575
+ continuationToken
1576
+ });
1577
+ // Create and return the page result
1578
+ return PaginationManager.createPaginatedResponse({
1579
+ pageInfo: {
1580
+ hasMore,
1581
+ totalCount,
1582
+ currentPage: params.pageNumber,
1583
+ pageSize: params.pageSize,
1584
+ continuationToken
1585
+ },
1586
+ type: paginationType,
1587
+ }, items);
1588
+ }
1589
+ /**
1590
+ * Determines if there are more pages based on pagination type and metadata
1591
+ */
1592
+ determineHasMorePages(paginationType, info) {
1593
+ switch (paginationType) {
1594
+ case PaginationType.OFFSET:
1595
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1596
+ // If totalCount is available, use it for precise calculation
1597
+ if (info.totalCount !== undefined) {
1598
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1599
+ }
1600
+ // Fallback when totalCount is not available
1601
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1602
+ return info.itemsCount === effectivePageSize;
1603
+ case PaginationType.TOKEN:
1604
+ return !!info.continuationToken;
1605
+ default:
1606
+ return false;
1607
+ }
1608
+ }
1609
+ }
1610
+ _BaseService_apiClient = new WeakMap();
1611
+
1612
+ /**
1613
+ * Base service for services that need folder-specific functionality.
1614
+ *
1615
+ * Extends BaseService with additional methods for working with folder-scoped resources
1616
+ * in UiPath Orchestrator. Services that work with folders (Assets, Queues) extend this class.
1617
+ *
1618
+ * @remarks
1619
+ * This class provides helper methods for making folder-scoped API calls, handling folder IDs
1620
+ * in request headers, and managing cross-folder queries.
1621
+ */
1622
+ class FolderScopedService extends BaseService {
1623
+ /**
1624
+ * Gets resources in a folder with optional query parameters
1625
+ *
1626
+ * @param endpoint - API endpoint to call
1627
+ * @param folderId - required folder ID
1628
+ * @param options - Query options
1629
+ * @param transformFn - Optional function to transform the response data
1630
+ * @returns Promise resolving to an array of resources
1631
+ */
1632
+ async _getByFolder(endpoint, folderId, options = {}, transformFn) {
1633
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
1634
+ const keysToPrefix = Object.keys(options);
1635
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
1636
+ const response = await this.get(endpoint, {
1637
+ params: apiOptions,
1638
+ headers
1639
+ });
1640
+ if (transformFn) {
1641
+ return response.data?.value.map(transformFn);
1642
+ }
1643
+ return response.data?.value;
1644
+ }
1645
+ }
1646
+
1647
+ /**
1648
+ * Creates methods for a job response object.
1649
+ *
1650
+ * @param jobData - The raw job data from API
1651
+ * @param service - The job service instance
1652
+ * @returns Object containing job methods
1653
+ */
1654
+ function createJobMethods(jobData, service) {
1655
+ return {
1656
+ async getOutput() {
1657
+ if (!jobData.key)
1658
+ throw new Error('Job key is undefined');
1659
+ if (!jobData.folderId)
1660
+ throw new Error('Job folderId is undefined');
1661
+ return service.getOutput(jobData.key, jobData.folderId);
1662
+ },
1663
+ };
1664
+ }
1665
+ /**
1666
+ * Creates a job response with bound methods.
1667
+ *
1668
+ * @param jobData - The raw job data from API
1669
+ * @param service - The job service instance
1670
+ * @returns A job object with added methods
1671
+ */
1672
+ function createJobWithMethods(jobData, service) {
1673
+ const methods = createJobMethods(jobData, service);
1674
+ return Object.assign({}, jobData, methods);
1675
+ }
1676
+
1677
+ /**
1678
+ * Base path constants for different services
1679
+ */
1680
+ const ORCHESTRATOR_BASE = 'orchestrator_';
1681
+
1682
+ /**
1683
+ * Orchestrator Service Endpoints
1684
+ */
1685
+ /**
1686
+ * Orchestrator Job Service Endpoints
1687
+ */
1688
+ const JOB_ENDPOINTS = {
1689
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/Jobs`,
1690
+ GET_BY_KEY: (identifier) => `${ORCHESTRATOR_BASE}/odata/Jobs/UiPath.Server.Configuration.OData.GetByKey(identifier=${identifier})`,
1691
+ };
1692
+ /**
1693
+ * Orchestrator Attachment Service Endpoints
1694
+ */
1695
+ const ORCHESTRATOR_ATTACHMENT_ENDPOINTS = {
1696
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Attachments(${id})`,
1697
+ };
1698
+
1699
+ /**
1700
+ * Maps fields for Job entities to ensure consistent naming
1701
+ * Semantic renames only — case conversion handled by pascalToCamelCaseKeys()
1702
+ */
1703
+ const JobMap = {
1704
+ creationTime: 'createdTime',
1705
+ lastModificationTime: 'lastModifiedTime',
1706
+ organizationUnitId: 'folderId',
1707
+ organizationUnitFullyQualifiedName: 'folderName',
1708
+ releaseName: 'processName',
1709
+ releaseVersionId: 'processVersionId',
1710
+ processType: 'packageType',
1711
+ release: 'process',
1712
+ };
1713
+
1714
+ /**
1715
+ * SDK Telemetry constants
1716
+ */
1717
+ // Connection string placeholder that will be replaced during build
1718
+ 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";
1719
+ // SDK Version placeholder
1720
+ const SDK_VERSION = "1.3.0";
1721
+ const VERSION = "Version";
1722
+ const SERVICE = "Service";
1723
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1724
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1725
+ const CLOUD_URL = "CloudUrl";
1726
+ const CLOUD_CLIENT_ID = "CloudClientId";
1727
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1728
+ const APP_NAME = "ApplicationName";
1729
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1730
+ // Service and logger names
1731
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1732
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1733
+ // Event names
1734
+ const SDK_RUN_EVENT = "Sdk.Run";
1735
+ // Default value for unknown/empty attributes
1736
+ const UNKNOWN = "";
1737
+
1738
+ /**
1739
+ * Log exporter that sends ALL logs as Application Insights custom events
1740
+ */
1741
+ class ApplicationInsightsEventExporter {
1742
+ constructor(connectionString) {
1743
+ this.connectionString = connectionString;
1744
+ }
1745
+ export(logs, resultCallback) {
1746
+ try {
1747
+ logs.forEach(logRecord => {
1748
+ this.sendAsCustomEvent(logRecord);
1749
+ });
1750
+ resultCallback({ code: 0 });
1751
+ }
1752
+ catch (error) {
1753
+ console.debug('Failed to export logs to Application Insights:', error);
1754
+ resultCallback({ code: 2, error });
1755
+ }
1756
+ }
1757
+ shutdown() {
1758
+ return Promise.resolve();
1759
+ }
1760
+ sendAsCustomEvent(logRecord) {
1761
+ // Get event name from body or attributes
1762
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1763
+ const payload = {
1764
+ name: 'Microsoft.ApplicationInsights.Event',
1765
+ time: new Date().toISOString(),
1766
+ iKey: this.extractInstrumentationKey(),
1767
+ data: {
1768
+ baseType: 'EventData',
1769
+ baseData: {
1770
+ ver: 2,
1771
+ name: eventName,
1772
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1773
+ }
1774
+ },
1775
+ tags: {
1776
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1777
+ 'ai.cloud.roleInstance': SDK_VERSION
1778
+ }
1779
+ };
1780
+ this.sendToApplicationInsights(payload);
1781
+ }
1782
+ extractInstrumentationKey() {
1783
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1784
+ return match ? match[1] : '';
1785
+ }
1786
+ convertAttributesToProperties(attributes) {
1787
+ const properties = {};
1788
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1789
+ properties[key] = String(value);
1790
+ });
1791
+ return properties;
1792
+ }
1793
+ async sendToApplicationInsights(payload) {
1794
+ try {
1795
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1796
+ if (!ingestionEndpoint) {
1797
+ console.debug('No ingestion endpoint found in connection string');
1798
+ return;
1799
+ }
1800
+ const url = `${ingestionEndpoint}/v2/track`;
1801
+ const response = await fetch(url, {
1802
+ method: 'POST',
1803
+ headers: {
1804
+ 'Content-Type': 'application/json',
1805
+ },
1806
+ body: JSON.stringify(payload)
1807
+ });
1808
+ if (!response.ok) {
1809
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1810
+ }
1811
+ }
1812
+ catch (error) {
1813
+ console.debug('Error sending event telemetry to Application Insights:', error);
1814
+ }
1815
+ }
1816
+ extractIngestionEndpoint() {
1817
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1818
+ return match ? match[1] : '';
1819
+ }
1820
+ }
1821
+ /**
1822
+ * Singleton telemetry client
1823
+ */
1824
+ class TelemetryClient {
1825
+ constructor() {
1826
+ this.isInitialized = false;
1827
+ }
1828
+ static getInstance() {
1829
+ if (!TelemetryClient.instance) {
1830
+ TelemetryClient.instance = new TelemetryClient();
1831
+ }
1832
+ return TelemetryClient.instance;
1833
+ }
1834
+ /**
1835
+ * Initialize telemetry
1836
+ */
1837
+ initialize(config) {
1838
+ if (this.isInitialized) {
1839
+ return;
1840
+ }
1841
+ this.isInitialized = true;
1842
+ if (config) {
1843
+ this.telemetryContext = config;
1844
+ }
1845
+ try {
1846
+ const connectionString = this.getConnectionString();
1847
+ if (!connectionString) {
1848
+ return;
1849
+ }
1850
+ this.setupTelemetryProvider(connectionString);
1851
+ }
1852
+ catch (error) {
1853
+ // Silent failure - telemetry errors shouldn't break functionality
1854
+ console.debug('Failed to initialize OpenTelemetry:', error);
1855
+ }
1856
+ }
1857
+ getConnectionString() {
1858
+ const connectionString = CONNECTION_STRING;
1859
+ return connectionString;
1860
+ }
1861
+ setupTelemetryProvider(connectionString) {
1862
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
1863
+ const processor = new sdkLogs.BatchLogRecordProcessor(exporter);
1864
+ this.logProvider = new sdkLogs.LoggerProvider({
1865
+ processors: [processor]
1866
+ });
1867
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1868
+ }
1869
+ /**
1870
+ * Track a telemetry event
1871
+ */
1872
+ track(eventName, name, extraAttributes = {}) {
1873
+ try {
1874
+ // Skip if logger not initialized
1875
+ if (!this.logger) {
1876
+ return;
1877
+ }
1878
+ const finalDisplayName = name || eventName;
1879
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1880
+ // Emit as log
1881
+ this.logger.emit({
1882
+ body: finalDisplayName,
1883
+ attributes: attributes,
1884
+ timestamp: Date.now(),
1885
+ });
1886
+ }
1887
+ catch (error) {
1888
+ // Silent failure
1889
+ console.debug('Failed to track telemetry event:', error);
1890
+ }
1891
+ }
1892
+ /**
1893
+ * Get enriched attributes for telemetry events
1894
+ */
1895
+ getEnrichedAttributes(extraAttributes, eventName) {
1896
+ const attributes = {
1897
+ [APP_NAME]: SDK_SERVICE_NAME,
1898
+ [VERSION]: SDK_VERSION,
1899
+ [SERVICE]: eventName,
1900
+ [CLOUD_URL]: this.createCloudUrl(),
1901
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1902
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1903
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1904
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1905
+ ...extraAttributes,
1906
+ };
1907
+ return attributes;
1908
+ }
1909
+ /**
1910
+ * Create cloud URL from base URL, organization ID, and tenant ID
1911
+ */
1912
+ createCloudUrl() {
1913
+ const baseUrl = this.telemetryContext?.baseUrl;
1914
+ const orgId = this.telemetryContext?.orgName;
1915
+ const tenantId = this.telemetryContext?.tenantName;
1916
+ if (!baseUrl || !orgId || !tenantId) {
1917
+ return UNKNOWN;
1918
+ }
1919
+ return `${baseUrl}/${orgId}/${tenantId}`;
1920
+ }
1921
+ }
1922
+ // Export singleton instance
1923
+ const telemetryClient = TelemetryClient.getInstance();
1924
+
1925
+ /**
1926
+ * SDK Track decorator and function for telemetry
1927
+ */
1928
+ /**
1929
+ * Common tracking logic shared between method and function decorators
1930
+ */
1931
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1932
+ return function (...args) {
1933
+ // Determine if we should track this call
1934
+ let shouldTrack = true;
1935
+ if (opts.condition !== undefined) {
1936
+ if (typeof opts.condition === 'function') {
1937
+ shouldTrack = opts.condition.apply(this, args);
1938
+ }
1939
+ else {
1940
+ shouldTrack = opts.condition;
1941
+ }
1942
+ }
1943
+ // Track the event if enabled
1944
+ if (shouldTrack) {
1945
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
1946
+ const serviceMethod = typeof nameOrOptions === 'string'
1947
+ ? nameOrOptions
1948
+ : fallbackName;
1949
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
1950
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1951
+ }
1952
+ // Execute the original function
1953
+ return originalFunction.apply(this, args);
1954
+ };
1955
+ }
1956
+ /**
1957
+ * Track decorator that can be used to automatically track function calls
1958
+ *
1959
+ * Usage:
1960
+ * @track("Service.Method")
1961
+ * function myFunction() { ... }
1962
+ *
1963
+ * @track("Queue.GetAll")
1964
+ * async getAll() { ... }
1965
+ *
1966
+ * @track("Tasks.Create")
1967
+ * async create() { ... }
1968
+ *
1969
+ * @track("Assets.Update", { condition: false })
1970
+ * function myFunction() { ... }
1971
+ *
1972
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
1973
+ * function myFunction() { ... }
1974
+ */
1975
+ function track(nameOrOptions, options) {
1976
+ return function decorator(_target, propertyKey, descriptor) {
1977
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
1978
+ if (descriptor && typeof descriptor.value === 'function') {
1979
+ // Method decorator
1980
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
1981
+ return descriptor;
1982
+ }
1983
+ // Function decorator
1984
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
1985
+ };
1986
+ }
1987
+
1988
+ /**
1989
+ * Maps fields for Attachment entities to ensure consistent naming
1990
+ */
1991
+ const AttachmentsMap = {
1992
+ creationTime: 'createdTime',
1993
+ lastModificationTime: 'lastModifiedTime'
1994
+ };
1995
+
1996
+ /**
1997
+ * Maps fields for Bucket entities to ensure consistent naming
1998
+ */
1999
+ const BucketMap = {
2000
+ fullPath: 'path',
2001
+ items: 'blobItems',
2002
+ verb: 'httpMethod'
2003
+ };
2004
+
2005
+ class AttachmentService extends BaseService {
2006
+ /**
2007
+ * Gets an attachment by ID
2008
+ * @param id - The UUID of the attachment to retrieve
2009
+ * @param options - Optional query parameters (expand, select)
2010
+ * @returns Promise resolving to the attachment
2011
+ *
2012
+ * @example
2013
+ * ```typescript
2014
+ * import { Attachments } from '@uipath/uipath-typescript/attachments';
2015
+ *
2016
+ * const attachments = new Attachments(sdk);
2017
+ * const attachment = await attachments.getById('12345678-1234-1234-1234-123456789abc');
2018
+ * ```
2019
+ */
2020
+ async getById(id, options = {}) {
2021
+ if (!id) {
2022
+ throw new ValidationError({ message: 'id is required for getById' });
2023
+ }
2024
+ // Prefix all keys in options with $ for OData
2025
+ const keysToPrefix = Object.keys(options);
2026
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
2027
+ const response = await this.get(ORCHESTRATOR_ATTACHMENT_ENDPOINTS.GET_BY_ID(id), {
2028
+ params: apiOptions,
2029
+ });
2030
+ // Transform response from PascalCase to camelCase, then apply field maps
2031
+ const camelCased = pascalToCamelCaseKeys(response.data);
2032
+ camelCased.blobFileAccess = transformData(camelCased.blobFileAccess, BucketMap);
2033
+ return transformData(camelCased, AttachmentsMap);
2034
+ }
2035
+ }
2036
+ __decorate([
2037
+ track('Attachments.GetById')
2038
+ ], AttachmentService.prototype, "getById", null);
2039
+
2040
+ /**
2041
+ * Service for interacting with UiPath Orchestrator Jobs API
2042
+ */
2043
+ class JobService extends FolderScopedService {
2044
+ /**
2045
+ * Creates an instance of the Jobs service.
2046
+ *
2047
+ * @param instance - UiPath SDK instance providing authentication and configuration
2048
+ */
2049
+ constructor(instance) {
2050
+ super(instance);
2051
+ this.attachmentService = new AttachmentService(instance);
2052
+ }
2053
+ /**
2054
+ * Gets all jobs across folders with optional filtering and pagination.
2055
+ *
2056
+ * Returns jobs with full details including state, timing, and input/output arguments.
2057
+ * Pass `folderId` to scope the query to a specific folder.
2058
+ *
2059
+ * !!! info "Input and output fields are not included in `getAll` responses"
2060
+ * The `inputArguments`, `inputFile`, `outputArguments`, and `outputFile` fields will always be `null` in the `getAll` response. To retrieve a job's output, use the {@link getOutput} method with the job's `key` and `folderId`.
2061
+ *
2062
+ * @param options - Query options including optional folderId, filtering, and pagination options
2063
+ * @returns Promise resolving to either an array of jobs {@link NonPaginatedResponse}<{@link JobGetResponse}> or a {@link PaginatedResponse}<{@link JobGetResponse}> when pagination options are used.
2064
+ * {@link JobGetResponse}
2065
+ * @example
2066
+ * ```typescript
2067
+ * // Get all jobs
2068
+ * const allJobs = await jobs.getAll();
2069
+ *
2070
+ * // Get all jobs in a specific folder
2071
+ * const folderJobs = await jobs.getAll({ folderId: <folderId> });
2072
+ *
2073
+ * // With filtering
2074
+ * const runningJobs = await jobs.getAll({
2075
+ * filter: "state eq 'Running'"
2076
+ * });
2077
+ *
2078
+ * // First page with pagination
2079
+ * const page1 = await jobs.getAll({ pageSize: 10 });
2080
+ *
2081
+ * // Navigate using cursor
2082
+ * if (page1.hasNextPage) {
2083
+ * const page2 = await jobs.getAll({ cursor: page1.nextCursor });
2084
+ * }
2085
+ *
2086
+ * // Jump to specific page
2087
+ * const page5 = await jobs.getAll({
2088
+ * jumpToPage: 5,
2089
+ * pageSize: 10
2090
+ * });
2091
+ * ```
2092
+ */
2093
+ async getAll(options) {
2094
+ const transformJobResponse = (job) => {
2095
+ const rawJob = transformData(pascalToCamelCaseKeys(job), JobMap);
2096
+ return createJobWithMethods(rawJob, this);
2097
+ };
2098
+ return PaginationHelpers.getAll({
2099
+ serviceAccess: this.createPaginationServiceAccess(),
2100
+ getEndpoint: () => JOB_ENDPOINTS.GET_ALL,
2101
+ getByFolderEndpoint: JOB_ENDPOINTS.GET_ALL,
2102
+ transformFn: transformJobResponse,
2103
+ pagination: {
2104
+ paginationType: PaginationType.OFFSET,
2105
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2106
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2107
+ paginationParams: {
2108
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2109
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
2110
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM,
2111
+ },
2112
+ },
2113
+ }, options);
2114
+ }
2115
+ /**
2116
+ * Gets the output of a completed job.
2117
+ *
2118
+ * Retrieves the job's output arguments, handling both inline output (stored directly on the job
2119
+ * as a JSON string in `outputArguments`) and file-based output (stored as a blob attachment for
2120
+ * large outputs). Returns the parsed JSON output or `null` if the job has no output.
2121
+ *
2122
+ * @param jobKey - The unique key (GUID) of the job to retrieve output from
2123
+ * @param folderId - The folder ID where the job resides
2124
+ * @returns Promise resolving to the parsed output as `Record<string, unknown>`, or `null` if no output exists
2125
+ *
2126
+ * @example
2127
+ * ```typescript
2128
+ * // Get output from a completed job
2129
+ * const output = await jobs.getOutput(<jobKey>, <folderId>);
2130
+ *
2131
+ * if (output) {
2132
+ * console.log('Job output:', output);
2133
+ * }
2134
+ * ```
2135
+ *
2136
+ * @example
2137
+ * ```typescript
2138
+ * // Get output using bound method (jobKey and folderId are taken from the job object)
2139
+ * const allJobs = await jobs.getAll();
2140
+ * const completedJob = allJobs.items.find(j => j.state === JobState.Successful);
2141
+ *
2142
+ * if (completedJob) {
2143
+ * const output = await completedJob.getOutput();
2144
+ * }
2145
+ * ```
2146
+ */
2147
+ async getOutput(jobKey, folderId) {
2148
+ if (!jobKey) {
2149
+ throw new ValidationError({ message: 'jobKey is required for getOutput' });
2150
+ }
2151
+ const job = await this.fetchJobByKey(jobKey, folderId);
2152
+ if (job.OutputArguments) {
2153
+ try {
2154
+ return JSON.parse(job.OutputArguments);
2155
+ }
2156
+ catch {
2157
+ throw new ServerError({ message: 'Failed to parse job output arguments as JSON' });
2158
+ }
2159
+ }
2160
+ if (job.OutputFile) {
2161
+ return this.downloadOutputFile(job.OutputFile);
2162
+ }
2163
+ return null;
2164
+ }
2165
+ /**
2166
+ * Fetches a job by its Key (GUID) using the GetByKey endpoint.
2167
+ * Only selects fields needed for output extraction.
2168
+ */
2169
+ async fetchJobByKey(jobKey, folderId) {
2170
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2171
+ const response = await this.get(JOB_ENDPOINTS.GET_BY_KEY(jobKey), {
2172
+ params: {
2173
+ $select: 'OutputArguments,OutputFile',
2174
+ },
2175
+ headers,
2176
+ });
2177
+ return response.data;
2178
+ }
2179
+ /**
2180
+ * Downloads the output file content via the Attachments API.
2181
+ * 1. Fetches blob access info from the attachment using AttachmentService
2182
+ * 2. Downloads content from the presigned blob URI
2183
+ * 3. Parses and returns the JSON content
2184
+ */
2185
+ async downloadOutputFile(outputFileKey) {
2186
+ const attachment = await this.attachmentService.getById(outputFileKey);
2187
+ const blobAccess = attachment.blobFileAccess;
2188
+ if (!blobAccess?.uri) {
2189
+ return null;
2190
+ }
2191
+ const blobHeaders = { ...blobAccess.headers };
2192
+ // Add auth header if the blob URI requires authenticated access
2193
+ if (blobAccess.requiresAuth) {
2194
+ const token = await this.getValidAuthToken();
2195
+ blobHeaders['Authorization'] = `Bearer ${token}`;
2196
+ }
2197
+ const blobResponse = await fetch(blobAccess.uri, {
2198
+ method: 'GET',
2199
+ headers: blobHeaders,
2200
+ });
2201
+ if (!blobResponse.ok) {
2202
+ const errorInfo = await errorResponseParser.parse(blobResponse);
2203
+ throw ErrorFactory.createFromHttpStatus(blobResponse.status, errorInfo);
2204
+ }
2205
+ const content = await blobResponse.text();
2206
+ try {
2207
+ return JSON.parse(content);
2208
+ }
2209
+ catch {
2210
+ throw new ServerError({ message: 'Failed to parse job output file as JSON' });
2211
+ }
2212
+ }
2213
+ }
2214
+ __decorate([
2215
+ track('Jobs.GetAll')
2216
+ ], JobService.prototype, "getAll", null);
2217
+ __decorate([
2218
+ track('Jobs.GetOutput')
2219
+ ], JobService.prototype, "getOutput", null);
2220
+
2221
+ /**
2222
+ * Enum for job sub-state
2223
+ */
2224
+ exports.JobSubState = void 0;
2225
+ (function (JobSubState) {
2226
+ JobSubState["WithFaults"] = "WITH_FAULTS";
2227
+ JobSubState["Manually"] = "MANUALLY";
2228
+ })(exports.JobSubState || (exports.JobSubState = {}));
2229
+ /**
2230
+ * Enum for serverless job type
2231
+ */
2232
+ exports.ServerlessJobType = void 0;
2233
+ (function (ServerlessJobType) {
2234
+ ServerlessJobType["RobotJob"] = "RobotJob";
2235
+ ServerlessJobType["WebApp"] = "WebApp";
2236
+ ServerlessJobType["LoadTest"] = "LoadTest";
2237
+ ServerlessJobType["StudioWebDesigner"] = "StudioWebDesigner";
2238
+ ServerlessJobType["PublishStudioProject"] = "PublishStudioProject";
2239
+ ServerlessJobType["JsApi"] = "JsApi";
2240
+ ServerlessJobType["PythonCodedAgent"] = "PythonCodedAgent";
2241
+ ServerlessJobType["MCPServer"] = "MCPServer";
2242
+ ServerlessJobType["PythonCodedSystemAgent"] = "PythonCodedSystemAgent";
2243
+ ServerlessJobType["PythonAgent"] = "PythonAgent";
2244
+ })(exports.ServerlessJobType || (exports.ServerlessJobType = {}));
2245
+
2246
+ /**
2247
+ * Common enum for job state used across services
2248
+ */
2249
+ exports.JobState = void 0;
2250
+ (function (JobState) {
2251
+ JobState["Pending"] = "Pending";
2252
+ JobState["Running"] = "Running";
2253
+ JobState["Stopping"] = "Stopping";
2254
+ JobState["Terminating"] = "Terminating";
2255
+ JobState["Faulted"] = "Faulted";
2256
+ JobState["Successful"] = "Successful";
2257
+ JobState["Stopped"] = "Stopped";
2258
+ JobState["Suspended"] = "Suspended";
2259
+ JobState["Resumed"] = "Resumed";
2260
+ })(exports.JobState || (exports.JobState = {}));
2261
+
2262
+ exports.JobService = JobService;
2263
+ exports.Jobs = JobService;
2264
+ exports.createJobWithMethods = createJobWithMethods;