@uipath/uipath-typescript 1.0.0-beta.18 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +100 -40
  3. package/dist/assets/index.cjs +2068 -0
  4. package/dist/assets/index.d.ts +513 -0
  5. package/dist/assets/index.mjs +2065 -0
  6. package/dist/buckets/index.cjs +2342 -0
  7. package/dist/buckets/index.d.ts +819 -0
  8. package/dist/buckets/index.mjs +2339 -0
  9. package/dist/cases/index.cjs +3475 -0
  10. package/dist/cases/index.d.ts +1397 -0
  11. package/dist/cases/index.mjs +3469 -0
  12. package/dist/conversational-agent/index.cjs +6622 -0
  13. package/dist/conversational-agent/index.d.ts +6579 -0
  14. package/dist/conversational-agent/index.mjs +6575 -0
  15. package/dist/core/index.cjs +5305 -0
  16. package/dist/core/index.d.ts +398 -0
  17. package/dist/core/index.mjs +5279 -0
  18. package/dist/entities/index.cjs +2727 -0
  19. package/dist/entities/index.d.ts +1513 -0
  20. package/dist/entities/index.mjs +2721 -0
  21. package/dist/index.cjs +3651 -2935
  22. package/dist/index.d.ts +5341 -590
  23. package/dist/index.mjs +3644 -2935
  24. package/dist/index.umd.js +8118 -11244
  25. package/dist/maestro-processes/index.cjs +2587 -0
  26. package/dist/maestro-processes/index.d.ts +1127 -0
  27. package/dist/maestro-processes/index.mjs +2578 -0
  28. package/dist/processes/index.cjs +2247 -0
  29. package/dist/processes/index.d.ts +800 -0
  30. package/dist/processes/index.mjs +2244 -0
  31. package/dist/queues/index.cjs +2053 -0
  32. package/dist/queues/index.d.ts +504 -0
  33. package/dist/queues/index.mjs +2050 -0
  34. package/dist/tasks/index.cjs +2653 -0
  35. package/dist/tasks/index.d.ts +1122 -0
  36. package/dist/tasks/index.mjs +2649 -0
  37. package/package.json +118 -6
  38. package/dist/index.d.cts +0 -5463
  39. package/dist/index.d.mts +0 -5463
@@ -0,0 +1,2578 @@
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_KEY = 'X-UIPATH-FolderKey';
507
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
508
+ /**
509
+ * Content type constants for HTTP requests/responses
510
+ */
511
+ const CONTENT_TYPES = {
512
+ JSON: 'application/json',
513
+ XML: 'application/xml',
514
+ OCTET_STREAM: 'application/octet-stream'
515
+ };
516
+ /**
517
+ * Response type constants for HTTP requests
518
+ */
519
+ const RESPONSE_TYPES = {
520
+ JSON: 'json',
521
+ TEXT: 'text',
522
+ BLOB: 'blob',
523
+ ARRAYBUFFER: 'arraybuffer'
524
+ };
525
+
526
+ class ApiClient {
527
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
528
+ this.defaultHeaders = {};
529
+ this.config = config;
530
+ this.executionContext = executionContext;
531
+ this.clientConfig = clientConfig;
532
+ this.tokenManager = tokenManager;
533
+ }
534
+ setDefaultHeaders(headers) {
535
+ this.defaultHeaders = { ...this.defaultHeaders, ...headers };
536
+ }
537
+ /**
538
+ * Gets a valid authentication token, refreshing if necessary.
539
+ * Used internally for API requests and exposed for services that need manual auth headers.
540
+ *
541
+ * @returns The valid token
542
+ * @throws AuthenticationError if no token available or refresh fails
543
+ */
544
+ async getValidToken() {
545
+ return this.tokenManager.getValidToken();
546
+ }
547
+ async getDefaultHeaders() {
548
+ // Get headers from execution context first
549
+ const contextHeaders = this.executionContext.getHeaders();
550
+ // If Authorization header is already set in context, use that
551
+ if (contextHeaders['Authorization']) {
552
+ return {
553
+ ...contextHeaders,
554
+ 'Content-Type': CONTENT_TYPES.JSON,
555
+ ...this.defaultHeaders,
556
+ ...this.clientConfig.headers
557
+ };
558
+ }
559
+ const token = await this.getValidToken();
560
+ return {
561
+ ...contextHeaders,
562
+ 'Authorization': `Bearer ${token}`,
563
+ 'Content-Type': CONTENT_TYPES.JSON,
564
+ ...this.defaultHeaders,
565
+ ...this.clientConfig.headers
566
+ };
567
+ }
568
+ async request(method, path, options = {}) {
569
+ // Ensure path starts with a forward slash
570
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
571
+ // Construct URL with org and tenant names
572
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
573
+ const headers = {
574
+ ...await this.getDefaultHeaders(),
575
+ ...options.headers
576
+ };
577
+ // Convert params to URLSearchParams
578
+ const searchParams = new URLSearchParams();
579
+ if (options.params) {
580
+ Object.entries(options.params).forEach(([key, value]) => {
581
+ searchParams.append(key, value.toString());
582
+ });
583
+ }
584
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
585
+ try {
586
+ const response = await fetch(fullUrl, {
587
+ method,
588
+ headers,
589
+ body: options.body ? JSON.stringify(options.body) : undefined,
590
+ signal: options.signal
591
+ });
592
+ if (!response.ok) {
593
+ const errorInfo = await errorResponseParser.parse(response);
594
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
595
+ }
596
+ if (response.status === 204) {
597
+ return undefined;
598
+ }
599
+ // Handle blob response type for binary data (e.g., file downloads)
600
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
601
+ const blob = await response.blob();
602
+ return blob;
603
+ }
604
+ // Check if we're expecting XML
605
+ const acceptHeader = headers['Accept'] || headers['accept'];
606
+ if (acceptHeader === CONTENT_TYPES.XML) {
607
+ const text = await response.text();
608
+ return text;
609
+ }
610
+ return response.json();
611
+ }
612
+ catch (error) {
613
+ // If it's already one of our errors, re-throw it
614
+ if (error.type && error.type.includes('Error')) {
615
+ throw error;
616
+ }
617
+ // Otherwise, it's likely a network error
618
+ throw ErrorFactory.createNetworkError(error);
619
+ }
620
+ }
621
+ async get(path, options = {}) {
622
+ return this.request('GET', path, options);
623
+ }
624
+ async post(path, data, options = {}) {
625
+ return this.request('POST', path, { ...options, body: data });
626
+ }
627
+ async put(path, data, options = {}) {
628
+ return this.request('PUT', path, { ...options, body: data });
629
+ }
630
+ async patch(path, data, options = {}) {
631
+ return this.request('PATCH', path, { ...options, body: data });
632
+ }
633
+ async delete(path, options = {}) {
634
+ return this.request('DELETE', path, options);
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Pagination types supported by the SDK
640
+ */
641
+ var PaginationType;
642
+ (function (PaginationType) {
643
+ PaginationType["OFFSET"] = "offset";
644
+ PaginationType["TOKEN"] = "token";
645
+ })(PaginationType || (PaginationType = {}));
646
+
647
+ /**
648
+ * Collection of utility functions for working with objects
649
+ */
650
+ /**
651
+ * Filters out undefined values from an object
652
+ * @param obj The source object
653
+ * @returns A new object without undefined values
654
+ *
655
+ * @example
656
+ * ```typescript
657
+ * // Object with undefined values
658
+ * const options = {
659
+ * name: 'test',
660
+ * count: 5,
661
+ * prefix: undefined,
662
+ * suffix: null
663
+ * };
664
+ * const result = filterUndefined(options);
665
+ * // result = { name: 'test', count: 5, suffix: null }
666
+ * ```
667
+ */
668
+ function filterUndefined(obj) {
669
+ const result = {};
670
+ for (const [key, value] of Object.entries(obj)) {
671
+ if (value !== undefined) {
672
+ result[key] = value;
673
+ }
674
+ }
675
+ return result;
676
+ }
677
+
678
+ /**
679
+ * Utility functions for platform detection
680
+ */
681
+ /**
682
+ * Checks if code is running in a browser environment
683
+ */
684
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
685
+
686
+ /**
687
+ * Base64 encoding/decoding
688
+ */
689
+ /**
690
+ * Encodes a string to base64
691
+ * @param str - The string to encode
692
+ * @returns Base64 encoded string
693
+ */
694
+ function encodeBase64(str) {
695
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
696
+ const encoder = new TextEncoder();
697
+ const data = encoder.encode(str);
698
+ // Convert Uint8Array to base64
699
+ if (isBrowser) {
700
+ // Browser environment
701
+ // Convert Uint8Array to binary string then to base64
702
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
703
+ return btoa(binaryString);
704
+ }
705
+ else {
706
+ // Node.js environment
707
+ return Buffer.from(data).toString('base64');
708
+ }
709
+ }
710
+ /**
711
+ * Decodes a base64 string
712
+ * @param base64 - The base64 string to decode
713
+ * @returns Decoded string
714
+ */
715
+ function decodeBase64(base64) {
716
+ let bytes;
717
+ if (isBrowser) {
718
+ // Browser environment
719
+ const binaryString = atob(base64);
720
+ bytes = new Uint8Array(binaryString.length);
721
+ for (let i = 0; i < binaryString.length; i++) {
722
+ bytes[i] = binaryString.charCodeAt(i);
723
+ }
724
+ }
725
+ else {
726
+ // Node.js environment
727
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
728
+ }
729
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
730
+ const decoder = new TextDecoder();
731
+ return decoder.decode(bytes);
732
+ }
733
+
734
+ /**
735
+ * PaginationManager handles the conversion between uniform cursor-based pagination
736
+ * and the specific pagination type for each service
737
+ */
738
+ class PaginationManager {
739
+ /**
740
+ * Create a pagination cursor for subsequent page requests
741
+ */
742
+ static createCursor({ pageInfo, type }) {
743
+ if (!pageInfo.hasMore) {
744
+ return undefined;
745
+ }
746
+ const cursorData = {
747
+ type,
748
+ pageSize: pageInfo.pageSize,
749
+ };
750
+ switch (type) {
751
+ case PaginationType.OFFSET:
752
+ if (pageInfo.currentPage) {
753
+ cursorData.pageNumber = pageInfo.currentPage + 1;
754
+ }
755
+ break;
756
+ case PaginationType.TOKEN:
757
+ if (pageInfo.continuationToken) {
758
+ cursorData.continuationToken = pageInfo.continuationToken;
759
+ }
760
+ else {
761
+ return undefined; // No continuation token, can't continue
762
+ }
763
+ break;
764
+ }
765
+ return {
766
+ value: encodeBase64(JSON.stringify(cursorData))
767
+ };
768
+ }
769
+ /**
770
+ * Create a paginated response with navigation cursors
771
+ */
772
+ static createPaginatedResponse({ pageInfo, type }, items) {
773
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
774
+ // Create previous page cursor if applicable
775
+ let previousCursor = undefined;
776
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
777
+ const prevCursorData = {
778
+ type,
779
+ pageNumber: pageInfo.currentPage - 1,
780
+ pageSize: pageInfo.pageSize,
781
+ };
782
+ previousCursor = {
783
+ value: encodeBase64(JSON.stringify(prevCursorData))
784
+ };
785
+ }
786
+ // Calculate total pages if we have totalCount and pageSize
787
+ let totalPages = undefined;
788
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
789
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
790
+ }
791
+ // Determine if this pagination type supports page jumping
792
+ const supportsPageJump = type === PaginationType.OFFSET;
793
+ // Create the result object with all fields, then filter out undefined values
794
+ const result = filterUndefined({
795
+ items,
796
+ totalCount: pageInfo.totalCount,
797
+ hasNextPage: pageInfo.hasMore,
798
+ nextCursor: nextCursor,
799
+ previousCursor: previousCursor,
800
+ currentPage: pageInfo.currentPage,
801
+ totalPages,
802
+ supportsPageJump
803
+ });
804
+ return result;
805
+ }
806
+ }
807
+
808
+ /**
809
+ * Creates headers object from key-value pairs
810
+ * @param headersObj - Object containing header key-value pairs
811
+ * @returns Headers object with all values converted to strings
812
+ *
813
+ * @example
814
+ * ```typescript
815
+ * // Single header
816
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
817
+ *
818
+ * // Multiple headers
819
+ * const headers = createHeaders({
820
+ * 'X-UIPATH-FolderKey': '1234567890',
821
+ * 'X-UIPATH-OrganizationUnitId': 123,
822
+ * 'Accept': 'application/json'
823
+ * });
824
+ *
825
+ * // Using constants
826
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
827
+ * const headers = createHeaders({
828
+ * [FOLDER_KEY]: 'abc-123',
829
+ * [FOLDER_ID]: 456
830
+ * });
831
+ *
832
+ * // Empty headers
833
+ * const headers = createHeaders();
834
+ * ```
835
+ */
836
+ function createHeaders(headersObj) {
837
+ const headers = {};
838
+ for (const [key, value] of Object.entries(headersObj)) {
839
+ if (value !== undefined && value !== null) {
840
+ headers[key] = value.toString();
841
+ }
842
+ }
843
+ return headers;
844
+ }
845
+
846
+ /**
847
+ * Common constants used across the SDK
848
+ */
849
+ /**
850
+ * Prefix used for OData query parameters
851
+ */
852
+ const ODATA_PREFIX = '$';
853
+ const UNKNOWN$1 = 'Unknown';
854
+ const NO_INSTANCE = 'no-instance';
855
+ /**
856
+ * HTTP methods
857
+ */
858
+ const HTTP_METHODS = {
859
+ GET: 'GET',
860
+ POST: 'POST'};
861
+ /**
862
+ * Process Instance pagination constants for token-based pagination
863
+ */
864
+ const PROCESS_INSTANCE_PAGINATION = {
865
+ /** Field name for items in process instance response */
866
+ ITEMS_FIELD: 'instances',
867
+ /** Field name for continuation token in process instance response */
868
+ CONTINUATION_TOKEN_FIELD: 'nextPage'
869
+ };
870
+ /**
871
+ * OData OFFSET pagination parameter names (ODATA-style)
872
+ */
873
+ const ODATA_OFFSET_PARAMS = {
874
+ /** OData page size parameter name */
875
+ PAGE_SIZE_PARAM: '$top',
876
+ /** OData offset parameter name */
877
+ OFFSET_PARAM: '$skip',
878
+ /** OData count parameter name */
879
+ COUNT_PARAM: '$count'
880
+ };
881
+ /**
882
+ * Bucket TOKEN pagination parameter names
883
+ */
884
+ const BUCKET_TOKEN_PARAMS = {
885
+ /** Bucket page size parameter name */
886
+ PAGE_SIZE_PARAM: 'takeHint',
887
+ /** Bucket token parameter name */
888
+ TOKEN_PARAM: 'continuationToken'
889
+ };
890
+ /**
891
+ * Process Instance TOKEN pagination parameter names
892
+ */
893
+ const PROCESS_INSTANCE_TOKEN_PARAMS = {
894
+ /** Process instance page size parameter name */
895
+ PAGE_SIZE_PARAM: 'pageSize',
896
+ /** Process instance token parameter name */
897
+ TOKEN_PARAM: 'nextPage'
898
+ };
899
+
900
+ /**
901
+ * Transforms data by mapping fields according to the provided field mapping
902
+ * @param data The source data to transform
903
+ * @param fieldMapping Object mapping source field names to target field names
904
+ * @returns Transformed data with mapped field names
905
+ *
906
+ * @example
907
+ * ```typescript
908
+ * // Single object transformation
909
+ * const data = { id: '123', userName: 'john' };
910
+ * const mapping = { id: 'userId', userName: 'name' };
911
+ * const result = transformData(data, mapping);
912
+ * // result = { userId: '123', name: 'john' }
913
+ *
914
+ * // Array transformation
915
+ * const dataArray = [
916
+ * { id: '123', userName: 'john' },
917
+ * { id: '456', userName: 'jane' }
918
+ * ];
919
+ * const result = transformData(dataArray, mapping);
920
+ * // result = [
921
+ * // { userId: '123', name: 'john' },
922
+ * // { userId: '456', name: 'jane' }
923
+ * // ]
924
+ * ```
925
+ */
926
+ function transformData(data, fieldMapping) {
927
+ // Handle array of objects
928
+ if (Array.isArray(data)) {
929
+ return data.map(item => transformData(item, fieldMapping));
930
+ }
931
+ // Handle single object
932
+ const result = { ...data };
933
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
934
+ if (sourceField in result) {
935
+ const value = result[sourceField];
936
+ delete result[sourceField];
937
+ result[targetField] = value;
938
+ }
939
+ }
940
+ return result;
941
+ }
942
+ /**
943
+ * Adds a prefix to specified keys in an object, returning a new object.
944
+ * Only the provided keys are prefixed; all others are left unchanged.
945
+ *
946
+ * @param obj The source object
947
+ * @param prefix The prefix to add (e.g., '$')
948
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
949
+ * @returns A new object with specified keys prefixed
950
+ *
951
+ * @example
952
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
953
+ */
954
+ function addPrefixToKeys(obj, prefix, keys) {
955
+ const result = {};
956
+ for (const [key, value] of Object.entries(obj)) {
957
+ if (keys.includes(key)) {
958
+ result[`${prefix}${key}`] = value;
959
+ }
960
+ else {
961
+ result[key] = value;
962
+ }
963
+ }
964
+ return result;
965
+ }
966
+
967
+ /**
968
+ * Constants used throughout the pagination system
969
+ */
970
+ /** Maximum number of items that can be requested in a single page */
971
+ const MAX_PAGE_SIZE = 1000;
972
+ /** Default page size when jumpToPage is used without specifying pageSize */
973
+ const DEFAULT_PAGE_SIZE = 50;
974
+ /** Default field name for items in a paginated response */
975
+ const DEFAULT_ITEMS_FIELD = 'value';
976
+ /** Default field name for total count in a paginated response */
977
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
978
+ /**
979
+ * Limits the page size to the maximum allowed value
980
+ * @param pageSize - Requested page size
981
+ * @returns Limited page size value
982
+ */
983
+ function getLimitedPageSize(pageSize) {
984
+ if (pageSize === undefined || pageSize === null) {
985
+ return DEFAULT_PAGE_SIZE;
986
+ }
987
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
988
+ }
989
+
990
+ /**
991
+ * Helper functions for pagination that can be used across services
992
+ */
993
+ class PaginationHelpers {
994
+ /**
995
+ * Checks if any pagination parameters are provided
996
+ *
997
+ * @param options - The options object to check
998
+ * @returns True if any pagination parameter is defined, false otherwise
999
+ */
1000
+ static hasPaginationParameters(options = {}) {
1001
+ const { cursor, pageSize, jumpToPage } = options;
1002
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1003
+ }
1004
+ /**
1005
+ * Parse a pagination cursor string into cursor data
1006
+ */
1007
+ static parseCursor(cursorString) {
1008
+ try {
1009
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1010
+ return cursorData;
1011
+ }
1012
+ catch {
1013
+ throw new Error('Invalid pagination cursor');
1014
+ }
1015
+ }
1016
+ /**
1017
+ * Validates cursor format and structure
1018
+ *
1019
+ * @param paginationOptions - The pagination options containing the cursor
1020
+ * @param paginationType - Optional pagination type to validate against
1021
+ */
1022
+ static validateCursor(paginationOptions, paginationType) {
1023
+ if (paginationOptions.cursor !== undefined) {
1024
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1025
+ throw new Error('cursor must contain a valid cursor string');
1026
+ }
1027
+ try {
1028
+ // Try to parse the cursor to validate it
1029
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1030
+ // If type is provided, validate cursor contains expected type information
1031
+ if (paginationType) {
1032
+ if (!cursorData.type) {
1033
+ throw new Error('Invalid cursor: missing pagination type');
1034
+ }
1035
+ // Check pagination type compatibility
1036
+ if (cursorData.type !== paginationType) {
1037
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1038
+ }
1039
+ }
1040
+ }
1041
+ catch (error) {
1042
+ if (error instanceof Error) {
1043
+ // If it's already our error with specific message, pass it through
1044
+ if (error.message.startsWith('Invalid cursor') ||
1045
+ error.message.startsWith('Pagination type mismatch')) {
1046
+ throw error;
1047
+ }
1048
+ }
1049
+ throw new Error('Invalid pagination cursor format');
1050
+ }
1051
+ }
1052
+ }
1053
+ /**
1054
+ * Comprehensive validation for pagination options
1055
+ *
1056
+ * @param options - The pagination options to validate
1057
+ * @param paginationType - The pagination type these options will be used with
1058
+ * @returns Processed pagination parameters ready for use
1059
+ */
1060
+ static validatePaginationOptions(options, paginationType) {
1061
+ // Validate pageSize
1062
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1063
+ throw new Error('pageSize must be a positive number');
1064
+ }
1065
+ // Validate jumpToPage
1066
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1067
+ throw new Error('jumpToPage must be a positive number');
1068
+ }
1069
+ // Validate cursor
1070
+ PaginationHelpers.validateCursor(options, paginationType);
1071
+ // Validate service compatibility
1072
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1073
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1074
+ }
1075
+ // Get processed parameters
1076
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1077
+ }
1078
+ /**
1079
+ * Convert a unified pagination options to service-specific parameters
1080
+ */
1081
+ static getRequestParameters(options, paginationType) {
1082
+ // Handle jumpToPage
1083
+ if (options.jumpToPage !== undefined) {
1084
+ const jumpToPageOptions = {
1085
+ pageSize: options.pageSize,
1086
+ pageNumber: options.jumpToPage
1087
+ };
1088
+ return filterUndefined(jumpToPageOptions);
1089
+ }
1090
+ // If no cursor is provided, it's a first page request
1091
+ if (!options.cursor) {
1092
+ const firstPageOptions = {
1093
+ pageSize: options.pageSize,
1094
+ // Only set pageNumber for OFFSET pagination
1095
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1096
+ };
1097
+ return filterUndefined(firstPageOptions);
1098
+ }
1099
+ // Parse the cursor
1100
+ try {
1101
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1102
+ const cursorBasedOptions = {
1103
+ pageSize: cursorData.pageSize || options.pageSize,
1104
+ pageNumber: cursorData.pageNumber,
1105
+ continuationToken: cursorData.continuationToken,
1106
+ type: cursorData.type,
1107
+ };
1108
+ return filterUndefined(cursorBasedOptions);
1109
+ }
1110
+ catch {
1111
+ throw new Error('Invalid pagination cursor');
1112
+ }
1113
+ }
1114
+ /**
1115
+ * Helper method for paginated resource retrieval
1116
+ *
1117
+ * @param params - Parameters for pagination
1118
+ * @returns Promise resolving to a paginated result
1119
+ */
1120
+ static async getAllPaginated(params) {
1121
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1122
+ const endpoint = getEndpoint(folderId);
1123
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1124
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1125
+ headers,
1126
+ params: additionalParams,
1127
+ pagination: {
1128
+ paginationType: options.paginationType || PaginationType.OFFSET,
1129
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1130
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1131
+ continuationTokenField: options.continuationTokenField,
1132
+ paginationParams: options.paginationParams
1133
+ }
1134
+ });
1135
+ // Parse items - automatically handle JSON string responses
1136
+ const rawItems = paginatedResponse.items;
1137
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1138
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1139
+ return {
1140
+ ...paginatedResponse,
1141
+ items: transformedItems
1142
+ };
1143
+ }
1144
+ /**
1145
+ * Helper method for non-paginated resource retrieval
1146
+ *
1147
+ * @param params - Parameters for non-paginated resource retrieval
1148
+ * @returns Promise resolving to an object with data and totalCount
1149
+ */
1150
+ static async getAllNonPaginated(params) {
1151
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1152
+ // Set default field names
1153
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1154
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1155
+ // Determine endpoint and headers based on folderId
1156
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1157
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1158
+ // Make the API call based on method
1159
+ let response;
1160
+ if (method === HTTP_METHODS.POST) {
1161
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1162
+ }
1163
+ else {
1164
+ response = await serviceAccess.get(endpoint, {
1165
+ params: additionalParams,
1166
+ headers
1167
+ });
1168
+ }
1169
+ // Extract and transform items from response
1170
+ const rawItems = response.data?.[itemsField];
1171
+ const totalCount = response.data?.[totalCountField];
1172
+ // Parse items - automatically handle JSON string responses
1173
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1174
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1175
+ return {
1176
+ items,
1177
+ totalCount
1178
+ };
1179
+ }
1180
+ /**
1181
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1182
+ *
1183
+ * @param config - Configuration for the getAll operation
1184
+ * @param options - Request options including pagination parameters
1185
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1186
+ */
1187
+ static async getAll(config, options) {
1188
+ const optionsWithDefaults = options || {};
1189
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1190
+ // Determine if pagination is requested
1191
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1192
+ // Process parameters (custom processing if provided, otherwise default)
1193
+ let processedOptions = restOptions;
1194
+ if (config.processParametersFn) {
1195
+ processedOptions = config.processParametersFn(restOptions, folderId);
1196
+ }
1197
+ // Apply ODATA prefix to keys (excluding specified keys)
1198
+ const excludeKeys = config.excludeFromPrefix || [];
1199
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1200
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1201
+ // Default pagination options
1202
+ const paginationOptions = {
1203
+ paginationType: PaginationType.OFFSET,
1204
+ itemsField: DEFAULT_ITEMS_FIELD,
1205
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1206
+ ...config.pagination
1207
+ };
1208
+ // Paginated flow
1209
+ if (isPaginationRequested) {
1210
+ return PaginationHelpers.getAllPaginated({
1211
+ serviceAccess: config.serviceAccess,
1212
+ getEndpoint: config.getEndpoint,
1213
+ folderId,
1214
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1215
+ additionalParams: prefixedOptions,
1216
+ transformFn: config.transformFn,
1217
+ method: config.method,
1218
+ options: {
1219
+ ...paginationOptions,
1220
+ paginationParams: config.pagination?.paginationParams
1221
+ }
1222
+ }); // Type assertion needed due to conditional return
1223
+ }
1224
+ // Non-paginated flow
1225
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1226
+ return PaginationHelpers.getAllNonPaginated({
1227
+ serviceAccess: config.serviceAccess,
1228
+ getAllEndpoint: config.getEndpoint(),
1229
+ getByFolderEndpoint: byFolderEndpoint,
1230
+ folderId,
1231
+ additionalParams: prefixedOptions,
1232
+ transformFn: config.transformFn,
1233
+ method: config.method,
1234
+ options: {
1235
+ itemsField: paginationOptions.itemsField,
1236
+ totalCountField: paginationOptions.totalCountField
1237
+ }
1238
+ });
1239
+ }
1240
+ }
1241
+
1242
+ /**
1243
+ * SDK Internals Registry - Internal registry for SDK instances
1244
+ *
1245
+ * This class is NOT exported in the public API.
1246
+ * It provides a secure way to share SDK internals between
1247
+ * the UiPath class and service classes without exposing them publicly.
1248
+ *
1249
+ * @internal
1250
+ */
1251
+ // Global symbol key to ensure WeakMap is shared across module instances
1252
+ // This prevents issues when core and service modules are bundled separately
1253
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1254
+ // Get or create the global WeakMap store
1255
+ const getGlobalStore = () => {
1256
+ const globalObj = globalThis;
1257
+ if (!globalObj[REGISTRY_KEY]) {
1258
+ globalObj[REGISTRY_KEY] = new WeakMap();
1259
+ }
1260
+ return globalObj[REGISTRY_KEY];
1261
+ };
1262
+ /**
1263
+ * Internal registry for SDK private components.
1264
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1265
+ * garbage collected when the SDK instance is no longer referenced.
1266
+ *
1267
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1268
+ * across separately bundled modules (core, entities, tasks, etc.).
1269
+ *
1270
+ * @internal - Not exported in public API
1271
+ */
1272
+ class SDKInternalsRegistry {
1273
+ // Use global store to ensure sharing across module bundles
1274
+ static get store() {
1275
+ return getGlobalStore();
1276
+ }
1277
+ /**
1278
+ * Register SDK instance internals
1279
+ * Called by UiPath constructor
1280
+ */
1281
+ static set(instance, internals) {
1282
+ this.store.set(instance, internals);
1283
+ }
1284
+ /**
1285
+ * Retrieve SDK instance internals
1286
+ * Called by BaseService constructor
1287
+ */
1288
+ static get(instance) {
1289
+ const internals = this.store.get(instance);
1290
+ if (!internals) {
1291
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1292
+ }
1293
+ return internals;
1294
+ }
1295
+ }
1296
+
1297
+ var _BaseService_apiClient;
1298
+ /**
1299
+ * Base class for all UiPath SDK services.
1300
+ *
1301
+ * Provides common functionality for authentication, configuration, and API communication.
1302
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1303
+ *
1304
+ * This class implements the dependency injection pattern where services receive a configured
1305
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1306
+ * including authentication token management.
1307
+ *
1308
+ * @remarks
1309
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1310
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1311
+ *
1312
+ */
1313
+ class BaseService {
1314
+ /**
1315
+ * Creates a base service instance with dependency injection.
1316
+ *
1317
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1318
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1319
+ * and token management internally.
1320
+ *
1321
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1322
+ * Services receive this via dependency injection in the modular pattern.
1323
+ *
1324
+ * @example
1325
+ * ```typescript
1326
+ * // Services automatically call this via super()
1327
+ * export class EntityService extends BaseService {
1328
+ * constructor(instance: IUiPath) {
1329
+ * super(instance); // Initializes the internal ApiClient
1330
+ * }
1331
+ * }
1332
+ *
1333
+ * // Usage in modular pattern
1334
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1335
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1336
+ *
1337
+ * const sdk = new UiPath(config);
1338
+ * await sdk.initialize();
1339
+ * const entities = new Entities(sdk);
1340
+ * ```
1341
+ */
1342
+ constructor(instance) {
1343
+ // Private field - not visible via Object.keys() or any reflection
1344
+ _BaseService_apiClient.set(this, void 0);
1345
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1346
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1347
+ }
1348
+ /**
1349
+ * Gets a valid authentication token, refreshing if necessary.
1350
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1351
+ *
1352
+ * @returns Promise resolving to a valid access token string
1353
+ * @throws AuthenticationError if no token is available or refresh fails
1354
+ */
1355
+ async getValidAuthToken() {
1356
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1357
+ }
1358
+ /**
1359
+ * Creates a service accessor for pagination helpers
1360
+ * This allows pagination helpers to access protected methods without making them public
1361
+ */
1362
+ createPaginationServiceAccess() {
1363
+ return {
1364
+ get: (path, options) => this.get(path, options || {}),
1365
+ post: (path, body, options) => this.post(path, body, options || {}),
1366
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1367
+ };
1368
+ }
1369
+ async request(method, path, options = {}) {
1370
+ switch (method.toUpperCase()) {
1371
+ case 'GET':
1372
+ return this.get(path, options);
1373
+ case 'POST':
1374
+ return this.post(path, options.body, options);
1375
+ case 'PUT':
1376
+ return this.put(path, options.body, options);
1377
+ case 'PATCH':
1378
+ return this.patch(path, options.body, options);
1379
+ case 'DELETE':
1380
+ return this.delete(path, options);
1381
+ default:
1382
+ throw new Error(`Unsupported HTTP method: ${method}`);
1383
+ }
1384
+ }
1385
+ async requestWithSpec(spec) {
1386
+ if (!spec.method || !spec.url) {
1387
+ throw new Error('Request spec must include method and url');
1388
+ }
1389
+ return this.request(spec.method, spec.url, spec);
1390
+ }
1391
+ async get(path, options = {}) {
1392
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1393
+ return { data: response };
1394
+ }
1395
+ async post(path, data, options = {}) {
1396
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1397
+ return { data: response };
1398
+ }
1399
+ async put(path, data, options = {}) {
1400
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1401
+ return { data: response };
1402
+ }
1403
+ async patch(path, data, options = {}) {
1404
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1405
+ return { data: response };
1406
+ }
1407
+ async delete(path, options = {}) {
1408
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1409
+ return { data: response };
1410
+ }
1411
+ /**
1412
+ * Execute a request with cursor-based pagination
1413
+ */
1414
+ async requestWithPagination(method, path, paginationOptions, options) {
1415
+ const paginationType = options.pagination.paginationType;
1416
+ // Validate and prepare pagination parameters
1417
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1418
+ // Prepare request parameters based on pagination type
1419
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1420
+ // For POST requests, merge pagination params into body; for GET, use query params
1421
+ if (method.toUpperCase() === 'POST') {
1422
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1423
+ options.body = {
1424
+ ...existingBody,
1425
+ ...options.params,
1426
+ ...requestParams
1427
+ };
1428
+ }
1429
+ else {
1430
+ // Merge pagination parameters with existing parameters
1431
+ options.params = {
1432
+ ...options.params,
1433
+ ...requestParams
1434
+ };
1435
+ }
1436
+ // Make the request
1437
+ const response = await this.request(method, path, options);
1438
+ // Extract data from the response and create page result
1439
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1440
+ itemsField: options.pagination.itemsField,
1441
+ totalCountField: options.pagination.totalCountField,
1442
+ continuationTokenField: options.pagination.continuationTokenField
1443
+ });
1444
+ }
1445
+ /**
1446
+ * Validates and prepares pagination parameters from options
1447
+ */
1448
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1449
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1450
+ }
1451
+ /**
1452
+ * Prepares request parameters for pagination based on pagination type
1453
+ */
1454
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1455
+ const requestParams = {};
1456
+ let limitedPageSize;
1457
+ const paginationParams = paginationConfig?.paginationParams;
1458
+ switch (paginationType) {
1459
+ case PaginationType.OFFSET:
1460
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1461
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1462
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1463
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1464
+ requestParams[pageSizeParam] = limitedPageSize;
1465
+ if (params.pageNumber && params.pageNumber > 1) {
1466
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1467
+ }
1468
+ // Include total count for ODATA APIs
1469
+ {
1470
+ requestParams[countParam] = true;
1471
+ }
1472
+ break;
1473
+ case PaginationType.TOKEN:
1474
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1475
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1476
+ if (params.pageSize) {
1477
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1478
+ }
1479
+ if (params.continuationToken) {
1480
+ requestParams[tokenParam] = params.continuationToken;
1481
+ }
1482
+ break;
1483
+ }
1484
+ return requestParams;
1485
+ }
1486
+ /**
1487
+ * Creates a paginated response from API response
1488
+ */
1489
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1490
+ // Extract fields from response
1491
+ const itemsField = fields.itemsField ||
1492
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1493
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1494
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1495
+ // Extract items and metadata
1496
+ const items = response.data[itemsField] || [];
1497
+ const totalCount = response.data[totalCountField];
1498
+ const continuationToken = response.data[continuationTokenField];
1499
+ // Determine if there are more pages
1500
+ const hasMore = this.determineHasMorePages(paginationType, {
1501
+ totalCount,
1502
+ pageSize: params.pageSize,
1503
+ currentPage: params.pageNumber || 1,
1504
+ itemsCount: items.length,
1505
+ continuationToken
1506
+ });
1507
+ // Create and return the page result
1508
+ return PaginationManager.createPaginatedResponse({
1509
+ pageInfo: {
1510
+ hasMore,
1511
+ totalCount,
1512
+ currentPage: params.pageNumber,
1513
+ pageSize: params.pageSize,
1514
+ continuationToken
1515
+ },
1516
+ type: paginationType,
1517
+ }, items);
1518
+ }
1519
+ /**
1520
+ * Determines if there are more pages based on pagination type and metadata
1521
+ */
1522
+ determineHasMorePages(paginationType, info) {
1523
+ switch (paginationType) {
1524
+ case PaginationType.OFFSET:
1525
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1526
+ // If totalCount is available, use it for precise calculation
1527
+ if (info.totalCount !== undefined) {
1528
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1529
+ }
1530
+ // Fallback when totalCount is not available
1531
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1532
+ return info.itemsCount === effectivePageSize;
1533
+ case PaginationType.TOKEN:
1534
+ return !!info.continuationToken;
1535
+ default:
1536
+ return false;
1537
+ }
1538
+ }
1539
+ }
1540
+ _BaseService_apiClient = new WeakMap();
1541
+
1542
+ /**
1543
+ * Base path constants for different services
1544
+ */
1545
+ const PIMS_BASE = 'pims_';
1546
+
1547
+ /**
1548
+ * Maestro Service Endpoints
1549
+ */
1550
+ /**
1551
+ * Maestro Process Service Endpoints
1552
+ */
1553
+ const MAESTRO_ENDPOINTS = {
1554
+ PROCESSES: {
1555
+ GET_ALL: `${PIMS_BASE}/api/v1/processes/summary`},
1556
+ INSTANCES: {
1557
+ GET_ALL: `${PIMS_BASE}/api/v1/instances`,
1558
+ GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
1559
+ GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
1560
+ GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
1561
+ GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
1562
+ CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
1563
+ PAUSE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/pause`,
1564
+ RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
1565
+ },
1566
+ INCIDENTS: {
1567
+ GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
1568
+ GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
1569
+ GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
1570
+ }};
1571
+
1572
+ /**
1573
+ * Maestro Process Models
1574
+ * Model classes for Maestro processes
1575
+ */
1576
+ /**
1577
+ * Creates methods for a process object
1578
+ *
1579
+ * @param processData - The process data (response from API)
1580
+ * @param service - The process service instance
1581
+ * @returns Object containing process methods
1582
+ */
1583
+ function createProcessMethods(processData, service) {
1584
+ return {
1585
+ async getIncidents() {
1586
+ if (!processData.processKey)
1587
+ throw new Error('Process key is undefined');
1588
+ if (!processData.folderKey)
1589
+ throw new Error('Folder key is undefined');
1590
+ return service.getIncidents(processData.processKey, processData.folderKey);
1591
+ }
1592
+ };
1593
+ }
1594
+ /**
1595
+ * Creates an actionable process by combining API process data with operational methods.
1596
+ *
1597
+ * @param processData - The process data from API
1598
+ * @param service - The process service instance
1599
+ * @returns A process object with added methods
1600
+ */
1601
+ function createProcessWithMethods(processData, service) {
1602
+ const methods = createProcessMethods(processData, service);
1603
+ return Object.assign({}, processData, methods);
1604
+ }
1605
+
1606
+ /**
1607
+ * Maps fields for Incident entities
1608
+ */
1609
+ const ProcessIncidentMap = {
1610
+ errorTimeUtc: 'errorTime'
1611
+ };
1612
+ /**
1613
+ * Maps fields for Incident Summary entities
1614
+ */
1615
+ const ProcessIncidentSummaryMap = {
1616
+ firstTimeUtc: 'firstOccuranceTime'
1617
+ };
1618
+
1619
+ /**
1620
+ * Helpers for fetching BPMN XML and extracting element details used to annotate responses
1621
+ */
1622
+ class BpmnHelpers {
1623
+ /**
1624
+ * Parse BPMN XML and extract element id → {name,type} used for incidents
1625
+ */
1626
+ static parseBpmnElementsForIncidents(bpmnXml) {
1627
+ const elementInfo = {};
1628
+ try {
1629
+ // Find <bpmn:...> start tags and capture the element type.
1630
+ // Then read 'id' and 'name' attributes from each tag.
1631
+ const bpmnOpenTagRegex = /<bpmn:([A-Za-z][\w.-]*)\b[^>]*>/g;
1632
+ for (const tagMatch of bpmnXml.matchAll(bpmnOpenTagRegex)) {
1633
+ const [fullTag, elementType] = tagMatch;
1634
+ // Extract attributes from the current tag text.
1635
+ const idMatch = /\bid\s*=\s*"([^"]*)"/.exec(fullTag);
1636
+ if (!idMatch) {
1637
+ continue;
1638
+ }
1639
+ const elementId = idMatch[1];
1640
+ const nameMatch = /\bname\s*=\s*"([^"]*)"/.exec(fullTag);
1641
+ const name = nameMatch ? nameMatch[1] : '';
1642
+ // Convert BPMN element type to human-readable format
1643
+ const activityType = this.formatActivityTypeForIncidents(elementType);
1644
+ const activityName = name || elementId;
1645
+ elementInfo[elementId] = {
1646
+ type: activityType,
1647
+ name: activityName
1648
+ };
1649
+ }
1650
+ }
1651
+ catch (error) {
1652
+ console.warn('Failed to parse BPMN XML for incidents:', error);
1653
+ }
1654
+ return elementInfo;
1655
+ }
1656
+ /**
1657
+ * Format BPMN element type to human-readable activity type for incidents
1658
+ */
1659
+ static formatActivityTypeForIncidents(elementType) {
1660
+ // Convert camelCase BPMN element types to human-readable format
1661
+ // e.g., "serviceTask" -> "Service Task", "exclusiveGateway" -> "Exclusive Gateway"
1662
+ return elementType
1663
+ .replace(/([A-Z])/g, ' $1') // Add space before uppercase letters
1664
+ .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
1665
+ .trim(); // Remove any leading/trailing spaces
1666
+ }
1667
+ /**
1668
+ * Fetch BPMN via getBpmn and add element name/type to each incident
1669
+ */
1670
+ static async enrichIncidentsWithBpmnData(incidents, folderKey, service) {
1671
+ // Check if all incidents have the same instanceId
1672
+ const uniqueInstanceIds = [...new Set(incidents.map(i => i.instanceId))];
1673
+ if (uniqueInstanceIds.length === 1) {
1674
+ // Single instance optimization (in case of process instance incidents)
1675
+ const elementInfo = await this.getBpmnElementInfo(uniqueInstanceIds[0], folderKey, service);
1676
+ return incidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
1677
+ }
1678
+ else {
1679
+ // Multiple instances optimization (in case of process incidents)
1680
+ return this.enrichMultipleInstanceIncidents(incidents, folderKey, service);
1681
+ }
1682
+ }
1683
+ /**
1684
+ * When incidents span multiple instances, fetch BPMN per instance and annotate
1685
+ */
1686
+ static async enrichMultipleInstanceIncidents(incidents, folderKey, service) {
1687
+ const groups = incidents.reduce((acc, incident) => {
1688
+ const id = incident.instanceId || NO_INSTANCE;
1689
+ (acc[id] = acc[id] || []).push(incident);
1690
+ return acc;
1691
+ }, {});
1692
+ const results = await Promise.all(Object.entries(groups).map(async (entry) => {
1693
+ const [instanceId, groupIncidents] = entry;
1694
+ const elementInfo = await this.getBpmnElementInfo(instanceId, folderKey, service);
1695
+ return groupIncidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
1696
+ }));
1697
+ return results.flat();
1698
+ }
1699
+ /**
1700
+ * Retrieve BPMN XML for an instance and derive element id → {name,type}
1701
+ */
1702
+ static async getBpmnElementInfo(instanceId, folderKey, service) {
1703
+ if (!instanceId || instanceId === NO_INSTANCE) {
1704
+ return {};
1705
+ }
1706
+ try {
1707
+ const bpmnXml = await service.getBpmn(instanceId, folderKey);
1708
+ return this.parseBpmnElementsForIncidents(bpmnXml);
1709
+ }
1710
+ catch (error) {
1711
+ console.warn(`Failed to get BPMN for instance ${instanceId}:`, error);
1712
+ return {};
1713
+ }
1714
+ }
1715
+ /**
1716
+ * Transform a raw incident by attaching element name/type from BPMN
1717
+ */
1718
+ static transformIncidentWithBpmn(incident, elementInfo) {
1719
+ const element = elementInfo[incident.elementId];
1720
+ const transformed = transformData(incident, ProcessIncidentMap);
1721
+ return {
1722
+ ...transformed,
1723
+ incidentElementActivityType: element?.type || UNKNOWN$1,
1724
+ incidentElementActivityName: element?.name || UNKNOWN$1
1725
+ };
1726
+ }
1727
+ }
1728
+
1729
+ /**
1730
+ * SDK Telemetry constants
1731
+ */
1732
+ // Connection string placeholder that will be replaced during build
1733
+ 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";
1734
+ // SDK Version placeholder
1735
+ const SDK_VERSION = "1.1.0";
1736
+ const VERSION = "Version";
1737
+ const SERVICE = "Service";
1738
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1739
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1740
+ const CLOUD_URL = "CloudUrl";
1741
+ const CLOUD_CLIENT_ID = "CloudClientId";
1742
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1743
+ const APP_NAME = "ApplicationName";
1744
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1745
+ // Service and logger names
1746
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1747
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1748
+ // Event names
1749
+ const SDK_RUN_EVENT = "Sdk.Run";
1750
+ // Default value for unknown/empty attributes
1751
+ const UNKNOWN = "";
1752
+
1753
+ /**
1754
+ * Log exporter that sends ALL logs as Application Insights custom events
1755
+ */
1756
+ class ApplicationInsightsEventExporter {
1757
+ constructor(connectionString) {
1758
+ this.connectionString = connectionString;
1759
+ }
1760
+ export(logs, resultCallback) {
1761
+ try {
1762
+ logs.forEach(logRecord => {
1763
+ this.sendAsCustomEvent(logRecord);
1764
+ });
1765
+ resultCallback({ code: 0 });
1766
+ }
1767
+ catch (error) {
1768
+ console.debug('Failed to export logs to Application Insights:', error);
1769
+ resultCallback({ code: 2, error });
1770
+ }
1771
+ }
1772
+ shutdown() {
1773
+ return Promise.resolve();
1774
+ }
1775
+ sendAsCustomEvent(logRecord) {
1776
+ // Get event name from body or attributes
1777
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1778
+ const payload = {
1779
+ name: 'Microsoft.ApplicationInsights.Event',
1780
+ time: new Date().toISOString(),
1781
+ iKey: this.extractInstrumentationKey(),
1782
+ data: {
1783
+ baseType: 'EventData',
1784
+ baseData: {
1785
+ ver: 2,
1786
+ name: eventName,
1787
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1788
+ }
1789
+ },
1790
+ tags: {
1791
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1792
+ 'ai.cloud.roleInstance': SDK_VERSION
1793
+ }
1794
+ };
1795
+ this.sendToApplicationInsights(payload);
1796
+ }
1797
+ extractInstrumentationKey() {
1798
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1799
+ return match ? match[1] : '';
1800
+ }
1801
+ convertAttributesToProperties(attributes) {
1802
+ const properties = {};
1803
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1804
+ properties[key] = String(value);
1805
+ });
1806
+ return properties;
1807
+ }
1808
+ async sendToApplicationInsights(payload) {
1809
+ try {
1810
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1811
+ if (!ingestionEndpoint) {
1812
+ console.debug('No ingestion endpoint found in connection string');
1813
+ return;
1814
+ }
1815
+ const url = `${ingestionEndpoint}/v2/track`;
1816
+ const response = await fetch(url, {
1817
+ method: 'POST',
1818
+ headers: {
1819
+ 'Content-Type': 'application/json',
1820
+ },
1821
+ body: JSON.stringify(payload)
1822
+ });
1823
+ if (!response.ok) {
1824
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1825
+ }
1826
+ }
1827
+ catch (error) {
1828
+ console.debug('Error sending event telemetry to Application Insights:', error);
1829
+ }
1830
+ }
1831
+ extractIngestionEndpoint() {
1832
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1833
+ return match ? match[1] : '';
1834
+ }
1835
+ }
1836
+ /**
1837
+ * Singleton telemetry client
1838
+ */
1839
+ class TelemetryClient {
1840
+ constructor() {
1841
+ this.isInitialized = false;
1842
+ }
1843
+ static getInstance() {
1844
+ if (!TelemetryClient.instance) {
1845
+ TelemetryClient.instance = new TelemetryClient();
1846
+ }
1847
+ return TelemetryClient.instance;
1848
+ }
1849
+ /**
1850
+ * Initialize telemetry
1851
+ */
1852
+ initialize(config) {
1853
+ if (this.isInitialized) {
1854
+ return;
1855
+ }
1856
+ this.isInitialized = true;
1857
+ if (config) {
1858
+ this.telemetryContext = config;
1859
+ }
1860
+ try {
1861
+ const connectionString = this.getConnectionString();
1862
+ if (!connectionString) {
1863
+ return;
1864
+ }
1865
+ this.setupTelemetryProvider(connectionString);
1866
+ }
1867
+ catch (error) {
1868
+ // Silent failure - telemetry errors shouldn't break functionality
1869
+ console.debug('Failed to initialize OpenTelemetry:', error);
1870
+ }
1871
+ }
1872
+ getConnectionString() {
1873
+ const connectionString = CONNECTION_STRING;
1874
+ return connectionString;
1875
+ }
1876
+ setupTelemetryProvider(connectionString) {
1877
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
1878
+ const processor = new BatchLogRecordProcessor(exporter);
1879
+ this.logProvider = new LoggerProvider({
1880
+ processors: [processor]
1881
+ });
1882
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1883
+ }
1884
+ /**
1885
+ * Track a telemetry event
1886
+ */
1887
+ track(eventName, name, extraAttributes = {}) {
1888
+ try {
1889
+ // Skip if logger not initialized
1890
+ if (!this.logger) {
1891
+ return;
1892
+ }
1893
+ const finalDisplayName = name || eventName;
1894
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1895
+ // Emit as log
1896
+ this.logger.emit({
1897
+ body: finalDisplayName,
1898
+ attributes: attributes,
1899
+ timestamp: Date.now(),
1900
+ });
1901
+ }
1902
+ catch (error) {
1903
+ // Silent failure
1904
+ console.debug('Failed to track telemetry event:', error);
1905
+ }
1906
+ }
1907
+ /**
1908
+ * Get enriched attributes for telemetry events
1909
+ */
1910
+ getEnrichedAttributes(extraAttributes, eventName) {
1911
+ const attributes = {
1912
+ [APP_NAME]: SDK_SERVICE_NAME,
1913
+ [VERSION]: SDK_VERSION,
1914
+ [SERVICE]: eventName,
1915
+ [CLOUD_URL]: this.createCloudUrl(),
1916
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1917
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1918
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1919
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1920
+ ...extraAttributes,
1921
+ };
1922
+ return attributes;
1923
+ }
1924
+ /**
1925
+ * Create cloud URL from base URL, organization ID, and tenant ID
1926
+ */
1927
+ createCloudUrl() {
1928
+ const baseUrl = this.telemetryContext?.baseUrl;
1929
+ const orgId = this.telemetryContext?.orgName;
1930
+ const tenantId = this.telemetryContext?.tenantName;
1931
+ if (!baseUrl || !orgId || !tenantId) {
1932
+ return UNKNOWN;
1933
+ }
1934
+ return `${baseUrl}/${orgId}/${tenantId}`;
1935
+ }
1936
+ }
1937
+ // Export singleton instance
1938
+ const telemetryClient = TelemetryClient.getInstance();
1939
+
1940
+ /**
1941
+ * SDK Track decorator and function for telemetry
1942
+ */
1943
+ /**
1944
+ * Common tracking logic shared between method and function decorators
1945
+ */
1946
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1947
+ return function (...args) {
1948
+ // Determine if we should track this call
1949
+ let shouldTrack = true;
1950
+ if (opts.condition !== undefined) {
1951
+ if (typeof opts.condition === 'function') {
1952
+ shouldTrack = opts.condition.apply(this, args);
1953
+ }
1954
+ else {
1955
+ shouldTrack = opts.condition;
1956
+ }
1957
+ }
1958
+ // Track the event if enabled
1959
+ if (shouldTrack) {
1960
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
1961
+ const serviceMethod = typeof nameOrOptions === 'string'
1962
+ ? nameOrOptions
1963
+ : fallbackName;
1964
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
1965
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1966
+ }
1967
+ // Execute the original function
1968
+ return originalFunction.apply(this, args);
1969
+ };
1970
+ }
1971
+ /**
1972
+ * Track decorator that can be used to automatically track function calls
1973
+ *
1974
+ * Usage:
1975
+ * @track("Service.Method")
1976
+ * function myFunction() { ... }
1977
+ *
1978
+ * @track("Queue.GetAll")
1979
+ * async getAll() { ... }
1980
+ *
1981
+ * @track("Tasks.Create")
1982
+ * async create() { ... }
1983
+ *
1984
+ * @track("Assets.Update", { condition: false })
1985
+ * function myFunction() { ... }
1986
+ *
1987
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
1988
+ * function myFunction() { ... }
1989
+ */
1990
+ function track(nameOrOptions, options) {
1991
+ return function decorator(_target, propertyKey, descriptor) {
1992
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
1993
+ if (descriptor && typeof descriptor.value === 'function') {
1994
+ // Method decorator
1995
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
1996
+ return descriptor;
1997
+ }
1998
+ // Function decorator
1999
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2000
+ };
2001
+ }
2002
+
2003
+ /**
2004
+ * Creates methods for a process instance
2005
+ *
2006
+ * @param instanceData - The process instance data (response from API)
2007
+ * @param service - The process instance service instance
2008
+ * @returns Object containing process instance methods
2009
+ */
2010
+ function createProcessInstanceMethods(instanceData, service) {
2011
+ return {
2012
+ async cancel(options) {
2013
+ if (!instanceData.instanceId)
2014
+ throw new Error('Process instance ID is undefined');
2015
+ if (!instanceData.folderKey)
2016
+ throw new Error('Process instance folder key is undefined');
2017
+ return service.cancel(instanceData.instanceId, instanceData.folderKey, options);
2018
+ },
2019
+ async pause(options) {
2020
+ if (!instanceData.instanceId)
2021
+ throw new Error('Process instance ID is undefined');
2022
+ if (!instanceData.folderKey)
2023
+ throw new Error('Process instance folder key is undefined');
2024
+ return service.pause(instanceData.instanceId, instanceData.folderKey, options);
2025
+ },
2026
+ async resume(options) {
2027
+ if (!instanceData.instanceId)
2028
+ throw new Error('Process instance ID is undefined');
2029
+ if (!instanceData.folderKey)
2030
+ throw new Error('Process instance folder key is undefined');
2031
+ return service.resume(instanceData.instanceId, instanceData.folderKey, options);
2032
+ },
2033
+ async getIncidents() {
2034
+ if (!instanceData.instanceId)
2035
+ throw new Error('Process instance ID is undefined');
2036
+ if (!instanceData.folderKey)
2037
+ throw new Error('Process instance folder key is undefined');
2038
+ return service.getIncidents(instanceData.instanceId, instanceData.folderKey);
2039
+ },
2040
+ async getExecutionHistory() {
2041
+ if (!instanceData.instanceId)
2042
+ throw new Error('Process instance ID is undefined');
2043
+ return service.getExecutionHistory(instanceData.instanceId);
2044
+ },
2045
+ async getBpmn() {
2046
+ if (!instanceData.instanceId)
2047
+ throw new Error('Process instance ID is undefined');
2048
+ if (!instanceData.folderKey)
2049
+ throw new Error('Process instance folder key is undefined');
2050
+ return service.getBpmn(instanceData.instanceId, instanceData.folderKey);
2051
+ },
2052
+ async getVariables(options) {
2053
+ if (!instanceData.instanceId)
2054
+ throw new Error('Process instance ID is undefined');
2055
+ if (!instanceData.folderKey)
2056
+ throw new Error('Process instance folder key is undefined');
2057
+ return service.getVariables(instanceData.instanceId, instanceData.folderKey, options);
2058
+ }
2059
+ };
2060
+ }
2061
+ /**
2062
+ * Creates an actionable process instance by combining API process instance data with operational methods.
2063
+ *
2064
+ * @param instanceData - The process instance data from API
2065
+ * @param service - The process instance service instance
2066
+ * @returns A process instance object with added methods
2067
+ */
2068
+ function createProcessInstanceWithMethods(instanceData, service) {
2069
+ const methods = createProcessInstanceMethods(instanceData, service);
2070
+ return Object.assign({}, instanceData, methods);
2071
+ }
2072
+
2073
+ /**
2074
+ * Process Incident Status
2075
+ */
2076
+ var ProcessIncidentStatus;
2077
+ (function (ProcessIncidentStatus) {
2078
+ ProcessIncidentStatus["Open"] = "Open";
2079
+ ProcessIncidentStatus["Closed"] = "Closed";
2080
+ })(ProcessIncidentStatus || (ProcessIncidentStatus = {}));
2081
+ /**
2082
+ * Process Incident Type
2083
+ */
2084
+ var ProcessIncidentType;
2085
+ (function (ProcessIncidentType) {
2086
+ ProcessIncidentType["System"] = "System";
2087
+ ProcessIncidentType["User"] = "User";
2088
+ ProcessIncidentType["Deployment"] = "Deployment";
2089
+ })(ProcessIncidentType || (ProcessIncidentType = {}));
2090
+ /**
2091
+ * Process Incident Severity
2092
+ */
2093
+ var ProcessIncidentSeverity;
2094
+ (function (ProcessIncidentSeverity) {
2095
+ ProcessIncidentSeverity["Error"] = "Error";
2096
+ ProcessIncidentSeverity["Warning"] = "Warning";
2097
+ })(ProcessIncidentSeverity || (ProcessIncidentSeverity = {}));
2098
+ /**
2099
+ * Process Incident Debug Mode
2100
+ */
2101
+ var DebugMode;
2102
+ (function (DebugMode) {
2103
+ DebugMode["None"] = "None";
2104
+ DebugMode["Default"] = "Default";
2105
+ DebugMode["StepByStep"] = "StepByStep";
2106
+ DebugMode["SingleStep"] = "SingleStep";
2107
+ })(DebugMode || (DebugMode = {}));
2108
+
2109
+ /**
2110
+ * Case Instance Types
2111
+ * Types and interfaces for Maestro case instance management
2112
+ */
2113
+ /**
2114
+ * Case stage task type
2115
+ */
2116
+ var StageTaskType;
2117
+ (function (StageTaskType) {
2118
+ StageTaskType["EXTERNAL_AGENT"] = "external-agent";
2119
+ StageTaskType["RPA"] = "rpa";
2120
+ StageTaskType["AGENTIC_PROCESS"] = "process";
2121
+ StageTaskType["AGENT"] = "agent";
2122
+ StageTaskType["ACTION"] = "action";
2123
+ StageTaskType["API_WORKFLOW"] = "api-workflow";
2124
+ })(StageTaskType || (StageTaskType = {}));
2125
+ /**
2126
+ * Escalation recipient scope
2127
+ */
2128
+ var EscalationRecipientScope;
2129
+ (function (EscalationRecipientScope) {
2130
+ EscalationRecipientScope["USER"] = "user";
2131
+ EscalationRecipientScope["USER_GROUP"] = "usergroup";
2132
+ })(EscalationRecipientScope || (EscalationRecipientScope = {}));
2133
+ /**
2134
+ * Escalation action type
2135
+ */
2136
+ var EscalationActionType;
2137
+ (function (EscalationActionType) {
2138
+ EscalationActionType["NOTIFICATION"] = "notification";
2139
+ })(EscalationActionType || (EscalationActionType = {}));
2140
+ /**
2141
+ * Escalation rule trigger type
2142
+ */
2143
+ var EscalationTriggerType;
2144
+ (function (EscalationTriggerType) {
2145
+ EscalationTriggerType["SLA_BREACHED"] = "sla-breached";
2146
+ EscalationTriggerType["AT_RISK"] = "at-risk";
2147
+ })(EscalationTriggerType || (EscalationTriggerType = {}));
2148
+ /**
2149
+ * SLA duration unit
2150
+ */
2151
+ var SLADurationUnit;
2152
+ (function (SLADurationUnit) {
2153
+ SLADurationUnit["HOURS"] = "h";
2154
+ SLADurationUnit["DAYS"] = "d";
2155
+ SLADurationUnit["WEEKS"] = "w";
2156
+ SLADurationUnit["MONTHS"] = "m";
2157
+ })(SLADurationUnit || (SLADurationUnit = {}));
2158
+
2159
+ /**
2160
+ * Maps fields for Process Instance entities to ensure consistent naming
2161
+ */
2162
+ const ProcessInstanceMap = {
2163
+ startedTimeUtc: 'startedTime',
2164
+ completedTimeUtc: 'completedTime',
2165
+ expiryTimeUtc: 'expiredTime',
2166
+ createdAt: 'createdTime',
2167
+ updatedAt: 'updatedTime'
2168
+ };
2169
+ /**
2170
+ * Maps fields for Process Instance Execution History to ensure consistent naming
2171
+ */
2172
+ const ProcessInstanceExecutionHistoryMap = {
2173
+ startTime: 'startedTime'
2174
+ };
2175
+
2176
+ class ProcessInstancesService extends BaseService {
2177
+ /**
2178
+ * Get all process instances with optional filtering and pagination
2179
+ *
2180
+ * The method returns either:
2181
+ * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
2182
+ * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
2183
+ *
2184
+ * @param options Query parameters for filtering instances and pagination
2185
+ * @returns Promise resolving to process instances or paginated result
2186
+ *
2187
+ * @example
2188
+ * ```typescript
2189
+ * import { ProcessInstances } from '@uipath/uipath-typescript/maestro-processes';
2190
+ *
2191
+ * const processInstances = new ProcessInstances(sdk);
2192
+ *
2193
+ * // Get all instances (non-paginated)
2194
+ * const instances = await processInstances.getAll();
2195
+ *
2196
+ * // Cancel faulted instances using methods directly on instances
2197
+ * for (const instance of instances.items) {
2198
+ * if (instance.latestRunStatus === 'Faulted') {
2199
+ * await instance.cancel({ comment: 'Cancelling faulted instance' });
2200
+ * }
2201
+ * }
2202
+ *
2203
+ * // With filtering
2204
+ * const filtered = await processInstances.getAll({
2205
+ * processKey: 'MyProcess'
2206
+ * });
2207
+ *
2208
+ * // First page with pagination
2209
+ * const page1 = await processInstances.getAll({ pageSize: 10 });
2210
+ *
2211
+ * // Navigate using cursor
2212
+ * if (page1.hasNextPage) {
2213
+ * const page2 = await processInstances.getAll({ cursor: page1.nextCursor });
2214
+ * }
2215
+ * ```
2216
+ */
2217
+ async getAll(options) {
2218
+ // Transformation function for process instances
2219
+ const transformProcessInstance = (item) => {
2220
+ const rawInstance = transformData(item, ProcessInstanceMap);
2221
+ return createProcessInstanceWithMethods(rawInstance, this);
2222
+ };
2223
+ return PaginationHelpers.getAll({
2224
+ serviceAccess: this.createPaginationServiceAccess(),
2225
+ getEndpoint: () => MAESTRO_ENDPOINTS.INSTANCES.GET_ALL,
2226
+ transformFn: transformProcessInstance,
2227
+ pagination: {
2228
+ paginationType: PaginationType.TOKEN,
2229
+ itemsField: PROCESS_INSTANCE_PAGINATION.ITEMS_FIELD,
2230
+ continuationTokenField: PROCESS_INSTANCE_PAGINATION.CONTINUATION_TOKEN_FIELD,
2231
+ paginationParams: {
2232
+ pageSizeParam: PROCESS_INSTANCE_TOKEN_PARAMS.PAGE_SIZE_PARAM,
2233
+ tokenParam: PROCESS_INSTANCE_TOKEN_PARAMS.TOKEN_PARAM
2234
+ }
2235
+ },
2236
+ excludeFromPrefix: Object.keys(options || {}) // All process instance params are not OData
2237
+ }, options);
2238
+ }
2239
+ /**
2240
+ * Get a process instance by ID with operation methods (cancel, pause, resume)
2241
+ * @param id The ID of the instance to retrieve
2242
+ * @param folderKey The folder key for authorization
2243
+ * @returns Promise<ProcessInstanceGetResponse>
2244
+ */
2245
+ async getById(id, folderKey) {
2246
+ const response = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_BY_ID(id), {
2247
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
2248
+ });
2249
+ const rawInstance = transformData(response.data, ProcessInstanceMap);
2250
+ return createProcessInstanceWithMethods(rawInstance, this);
2251
+ }
2252
+ /**
2253
+ * Get execution history (spans) for a process instance
2254
+ * @param instanceId The ID of the instance to get history for
2255
+ * @returns Promise<ProcessInstanceExecutionHistoryResponse[]>
2256
+ */
2257
+ async getExecutionHistory(instanceId) {
2258
+ const response = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_EXECUTION_HISTORY(instanceId));
2259
+ return response.data.map(historyItem => transformData(historyItem, ProcessInstanceExecutionHistoryMap));
2260
+ }
2261
+ /**
2262
+ * Get BPMN XML file for a process instance
2263
+ * @param instanceId The ID of the instance to get BPMN for
2264
+ * @param folderKey The folder key for authorization
2265
+ * @returns Promise<BpmnXmlString> The BPMN XML contents as a string
2266
+ */
2267
+ async getBpmn(instanceId, folderKey) {
2268
+ const response = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_BPMN(instanceId), {
2269
+ headers: createHeaders({
2270
+ [FOLDER_KEY]: folderKey,
2271
+ 'Accept': CONTENT_TYPES.XML
2272
+ })
2273
+ });
2274
+ return response.data;
2275
+ }
2276
+ /**
2277
+ * Cancel a process instance
2278
+ * @param instanceId The ID of the instance to cancel
2279
+ * @param folderKey The folder key for authorization
2280
+ * @param options Optional cancellation options with comment
2281
+ * @returns Promise resolving to operation result with updated instance data
2282
+ */
2283
+ async cancel(instanceId, folderKey, options) {
2284
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.CANCEL(instanceId), options || {}, {
2285
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
2286
+ });
2287
+ return {
2288
+ success: true,
2289
+ data: response.data
2290
+ };
2291
+ }
2292
+ /**
2293
+ * Pause a process instance
2294
+ * @param instanceId The ID of the instance to pause
2295
+ * @param folderKey The folder key for authorization
2296
+ * @param options Optional pause options with comment
2297
+ * @returns Promise resolving to operation result with updated instance data
2298
+ */
2299
+ async pause(instanceId, folderKey, options) {
2300
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.PAUSE(instanceId), options || {}, {
2301
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
2302
+ });
2303
+ return {
2304
+ success: true,
2305
+ data: response.data
2306
+ };
2307
+ }
2308
+ /**
2309
+ * Resume a process instance
2310
+ * @param instanceId The ID of the instance to resume
2311
+ * @param folderKey The folder key for authorization
2312
+ * @param options Optional resume options with comment
2313
+ * @returns Promise resolving to operation result with updated instance data
2314
+ */
2315
+ async resume(instanceId, folderKey, options) {
2316
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.RESUME(instanceId), options || {}, {
2317
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
2318
+ });
2319
+ return {
2320
+ success: true,
2321
+ data: response.data
2322
+ };
2323
+ }
2324
+ /**
2325
+ * Parses BPMN XML to extract variable metadata from uipath:inputOutput elements
2326
+ * @private
2327
+ * @param bpmnXml The BPMN XML string
2328
+ * @returns Map of variable ID to metadata
2329
+ */
2330
+ parseBpmnVariables(bpmnXml) {
2331
+ const variableMap = new Map();
2332
+ const variableSourceMap = this.getVariableSource(bpmnXml);
2333
+ // Match both self-closing and content-bearing uipath:inputOutput elements
2334
+ // Handles: <uipath:inputOutput .../> and <uipath:inputOutput ...>content</uipath:inputOutput>
2335
+ const inputOutputRegex = /<uipath:inputOutput\s+([^/]+?)(?:\/(?:>)?|>[\s\S]*?<\/uipath:inputOutput>)/g;
2336
+ const inputOutputMatches = bpmnXml.matchAll(inputOutputRegex);
2337
+ for (const match of inputOutputMatches) {
2338
+ const attributes = match[1];
2339
+ // Extract attributes from the inputOutput element
2340
+ const idMatch = attributes.match(/id="([^"]+)"/);
2341
+ const nameMatch = attributes.match(/name="([^"]+)"/);
2342
+ const typeMatch = attributes.match(/type="([^"]+)"/);
2343
+ const elementIdMatch = attributes.match(/elementId="([^"]+)"/);
2344
+ if (idMatch && nameMatch && typeMatch && elementIdMatch) {
2345
+ const elementId = elementIdMatch[1];
2346
+ const sourceName = variableSourceMap.get(elementId) || elementId;
2347
+ const metadata = {
2348
+ id: idMatch[1],
2349
+ name: nameMatch[1],
2350
+ type: typeMatch[1],
2351
+ elementId: elementId,
2352
+ source: sourceName
2353
+ };
2354
+ variableMap.set(metadata.id, metadata);
2355
+ }
2356
+ }
2357
+ return variableMap;
2358
+ }
2359
+ /**
2360
+ * Extracts element names from BPMN XML and maps them to their element IDs
2361
+ * @private
2362
+ * @param bpmnXml The BPMN XML string
2363
+ * @returns Map of elementId to element name
2364
+ */
2365
+ getVariableSource(bpmnXml) {
2366
+ const elementNameMap = new Map();
2367
+ // Regex to match any BPMN element with both id and name attributes
2368
+ const elementRegex = /<bpmn:\w+\s+([^>]*id="([^"]+)"[^>]*name="([^"]+)"[^>]*)/g;
2369
+ const elementMatches = bpmnXml.matchAll(elementRegex);
2370
+ for (const match of elementMatches) {
2371
+ const elementId = match[2];
2372
+ const elementName = match[3];
2373
+ if (elementId && elementName) {
2374
+ elementNameMap.set(elementId, elementName);
2375
+ }
2376
+ }
2377
+ return elementNameMap;
2378
+ }
2379
+ /**
2380
+ * Enriches global variables with metadata from BPMN
2381
+ * @private
2382
+ * @param globals The raw globals object from API response
2383
+ * @param variableMetadata The parsed BPMN variable metadata
2384
+ * @returns Array of global variables
2385
+ */
2386
+ transformGlobalVariables(globals, variableMetadata) {
2387
+ const enrichedGlobalVariables = [];
2388
+ if (globals && typeof globals === 'object') {
2389
+ for (const [variableId, value] of Object.entries(globals)) {
2390
+ const metadata = variableMetadata.get(variableId);
2391
+ if (metadata) {
2392
+ enrichedGlobalVariables.push({
2393
+ id: metadata.id,
2394
+ name: metadata.name,
2395
+ type: metadata.type,
2396
+ elementId: metadata.elementId,
2397
+ source: metadata.source,
2398
+ value: value
2399
+ });
2400
+ }
2401
+ }
2402
+ }
2403
+ return enrichedGlobalVariables;
2404
+ }
2405
+ /**
2406
+ * Get global variables for a process instance
2407
+ * @param instanceId The ID of the instance to get variables for
2408
+ * @param folderKey The folder key for authorization
2409
+ * @param options Optional options including parentElementId to filter by parent element
2410
+ * @returns Promise<ProcessInstanceGetVariablesResponse>
2411
+ */
2412
+ async getVariables(instanceId, folderKey, options) {
2413
+ // Fetch the BPMN XML to get variable metadata
2414
+ let variableMetadata = new Map();
2415
+ try {
2416
+ const bpmnXml = await this.getBpmn(instanceId, folderKey);
2417
+ variableMetadata = this.parseBpmnVariables(bpmnXml);
2418
+ }
2419
+ catch (error) {
2420
+ // Log warning
2421
+ console.warn(`Failed to fetch BPMN metadata for instance ${instanceId} :`, error);
2422
+ }
2423
+ // Fetch the variables
2424
+ const queryParams = options?.parentElementId ? { parentElementId: options.parentElementId } : undefined;
2425
+ const response = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_VARIABLES(instanceId), {
2426
+ headers: createHeaders({ [FOLDER_KEY]: folderKey }),
2427
+ params: queryParams
2428
+ });
2429
+ // Transform the globals object to include metadata from BPMN
2430
+ const enrichedGlobalVariables = this.transformGlobalVariables(response.data.globals, variableMetadata);
2431
+ const variablesResponse = {
2432
+ elements: response.data.elements,
2433
+ globalVariables: enrichedGlobalVariables,
2434
+ instanceId: response.data.instanceId,
2435
+ parentElementId: response.data.parentElementId
2436
+ };
2437
+ return variablesResponse;
2438
+ }
2439
+ /**
2440
+ * Get incidents for a process instance
2441
+ * @param instanceId The ID of the instance to get incidents for
2442
+ * @param folderKey The folder key for authorization
2443
+ * @returns Promise<ProcessIncidentGetResponse[]>
2444
+ */
2445
+ async getIncidents(instanceId, folderKey) {
2446
+ const rawResponse = await this.get(MAESTRO_ENDPOINTS.INCIDENTS.GET_BY_INSTANCE(instanceId), {
2447
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
2448
+ });
2449
+ // Filter out excluded fields and transform response, then enrich with BPMN data
2450
+ return BpmnHelpers.enrichIncidentsWithBpmnData(rawResponse.data || [], folderKey, this);
2451
+ }
2452
+ }
2453
+ __decorate([
2454
+ track('ProcessInstances.GetAll')
2455
+ ], ProcessInstancesService.prototype, "getAll", null);
2456
+ __decorate([
2457
+ track('ProcessInstances.GetById')
2458
+ ], ProcessInstancesService.prototype, "getById", null);
2459
+ __decorate([
2460
+ track('ProcessInstances.GetExecutionHistory')
2461
+ ], ProcessInstancesService.prototype, "getExecutionHistory", null);
2462
+ __decorate([
2463
+ track('ProcessInstances.GetBpmn')
2464
+ ], ProcessInstancesService.prototype, "getBpmn", null);
2465
+ __decorate([
2466
+ track('ProcessInstances.Cancel')
2467
+ ], ProcessInstancesService.prototype, "cancel", null);
2468
+ __decorate([
2469
+ track('ProcessInstances.Pause')
2470
+ ], ProcessInstancesService.prototype, "pause", null);
2471
+ __decorate([
2472
+ track('ProcessInstances.Resume')
2473
+ ], ProcessInstancesService.prototype, "resume", null);
2474
+ __decorate([
2475
+ track('ProcessInstances.GetVariables')
2476
+ ], ProcessInstancesService.prototype, "getVariables", null);
2477
+ __decorate([
2478
+ track('ProcessInstances.GetIncidents')
2479
+ ], ProcessInstancesService.prototype, "getIncidents", null);
2480
+
2481
+ /**
2482
+ * Service for interacting with Maestro Processes
2483
+ */
2484
+ class MaestroProcessesService extends BaseService {
2485
+ /**
2486
+ * Creates an instance of the Maestro Processes service.
2487
+ *
2488
+ * @param instance - UiPath SDK instance providing authentication and configuration
2489
+ */
2490
+ constructor(instance) {
2491
+ super(instance);
2492
+ this.processInstancesService = new ProcessInstancesService(instance);
2493
+ }
2494
+ /**
2495
+ * Get all processes with their instance statistics
2496
+ * @returns Promise resolving to array of MaestroProcess objects
2497
+ *
2498
+ * @example
2499
+ * ```typescript
2500
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
2501
+ *
2502
+ * const maestroProcesses = new MaestroProcesses(sdk);
2503
+ * const processes = await maestroProcesses.getAll();
2504
+ *
2505
+ * // Access process information
2506
+ * for (const process of processes) {
2507
+ * console.log(`Process: ${process.processKey}`);
2508
+ * console.log(`Running instances: ${process.runningCount}`);
2509
+ * console.log(`Faulted instances: ${process.faultedCount}`);
2510
+ * }
2511
+ * ```
2512
+ */
2513
+ async getAll() {
2514
+ const response = await this.get(MAESTRO_ENDPOINTS.PROCESSES.GET_ALL);
2515
+ // Extract processes array from response data and add name field
2516
+ const processes = response.data?.processes || [];
2517
+ const processesWithName = processes.map(process => ({
2518
+ ...process,
2519
+ name: process.packageId
2520
+ }));
2521
+ // Add methods to each process
2522
+ return processesWithName.map(process => createProcessWithMethods(process, this));
2523
+ }
2524
+ /**
2525
+ * Get incidents for a specific process
2526
+ */
2527
+ async getIncidents(processKey, folderKey) {
2528
+ const rawResponse = await this.get(MAESTRO_ENDPOINTS.INCIDENTS.GET_BY_PROCESS(processKey), {
2529
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
2530
+ });
2531
+ // Fetch BPMN XML and add element name/type to each incident
2532
+ return BpmnHelpers.enrichIncidentsWithBpmnData(rawResponse.data || [], folderKey, this.processInstancesService);
2533
+ }
2534
+ }
2535
+ __decorate([
2536
+ track('MaestroProcesses.GetAll')
2537
+ ], MaestroProcessesService.prototype, "getAll", null);
2538
+ __decorate([
2539
+ track('MaestroProcesses.GetIncidents')
2540
+ ], MaestroProcessesService.prototype, "getIncidents", null);
2541
+
2542
+ /**
2543
+ * Service class for Maestro Process Incidents
2544
+ */
2545
+ class ProcessIncidentsService extends BaseService {
2546
+ /**
2547
+ * Get all process incidents across all folders
2548
+ *
2549
+ * @returns Promise resolving to array of process incident
2550
+ * {@link ProcessIncidentGetAllResponse}
2551
+ * @example
2552
+ * ```typescript
2553
+ * import { ProcessIncidents } from '@uipath/uipath-typescript/maestro-processes';
2554
+ *
2555
+ * const processIncidents = new ProcessIncidents(sdk);
2556
+ * const incidents = await processIncidents.getAll();
2557
+ *
2558
+ * // Access process incident information
2559
+ * for (const incident of incidents) {
2560
+ * console.log(`Process: ${incident.processKey}`);
2561
+ * console.log(`Error: ${incident.errorMessage}`);
2562
+ * console.log(`Count: ${incident.count}`);
2563
+ * console.log(`First occurrence: ${incident.firstOccuranceTime}`);
2564
+ * }
2565
+ * ```
2566
+ */
2567
+ async getAll() {
2568
+ const rawResponse = await this.get(MAESTRO_ENDPOINTS.INCIDENTS.GET_ALL);
2569
+ // Transform field names
2570
+ const data = rawResponse.data || [];
2571
+ return data.map(incident => transformData(incident, ProcessIncidentSummaryMap));
2572
+ }
2573
+ }
2574
+ __decorate([
2575
+ track('ProcessIncidents.getAll')
2576
+ ], ProcessIncidentsService.prototype, "getAll", null);
2577
+
2578
+ export { DebugMode, MaestroProcessesService as MaestroProcesses, MaestroProcessesService, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, ProcessIncidentsService as ProcessIncidents, ProcessIncidentsService, ProcessInstancesService as ProcessInstances, ProcessInstancesService, createProcessInstanceWithMethods, createProcessWithMethods };