@uipath/uipath-typescript 1.0.0-beta.18 → 1.0.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.
@@ -0,0 +1,3487 @@
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
+ * Internal types for Maestro Cases
47
+ * These types are used internally by the cases service
48
+ */
49
+ /**
50
+ * Process type enum for filtering
51
+ */
52
+ var ProcessType;
53
+ (function (ProcessType) {
54
+ ProcessType["CaseManagement"] = "CaseManagement";
55
+ })(ProcessType || (ProcessType = {}));
56
+
57
+ /**
58
+ * Base error class for all UiPath SDK errors
59
+ * Pure TypeScript class with clean interface
60
+ */
61
+ class UiPathError {
62
+ constructor(type, params) {
63
+ this.type = type;
64
+ this.message = params.message;
65
+ this.statusCode = params.statusCode;
66
+ this.requestId = params.requestId;
67
+ this.timestamp = new Date();
68
+ // Capture stack trace for debugging
69
+ this.stack = (new Error()).stack;
70
+ }
71
+ /**
72
+ * Returns a clean JSON representation of the error
73
+ */
74
+ toJSON() {
75
+ return {
76
+ type: this.type,
77
+ message: this.message,
78
+ statusCode: this.statusCode,
79
+ requestId: this.requestId,
80
+ timestamp: this.timestamp
81
+ };
82
+ }
83
+ /**
84
+ * Returns detailed debug information including stack trace
85
+ */
86
+ getDebugInfo() {
87
+ return {
88
+ ...this.toJSON(),
89
+ stack: this.stack
90
+ };
91
+ }
92
+ }
93
+
94
+ /**
95
+ * HTTP status code constants for error handling
96
+ */
97
+ const HttpStatus = {
98
+ // Client errors (4xx)
99
+ BAD_REQUEST: 400,
100
+ UNAUTHORIZED: 401,
101
+ FORBIDDEN: 403,
102
+ NOT_FOUND: 404,
103
+ TOO_MANY_REQUESTS: 429,
104
+ // Server errors (5xx)
105
+ INTERNAL_SERVER_ERROR: 500,
106
+ BAD_GATEWAY: 502,
107
+ SERVICE_UNAVAILABLE: 503,
108
+ GATEWAY_TIMEOUT: 504
109
+ };
110
+ /**
111
+ * Error type constants for consistent error identification
112
+ */
113
+ const ErrorType = {
114
+ AUTHENTICATION: 'AuthenticationError',
115
+ AUTHORIZATION: 'AuthorizationError',
116
+ VALIDATION: 'ValidationError',
117
+ NOT_FOUND: 'NotFoundError',
118
+ RATE_LIMIT: 'RateLimitError',
119
+ SERVER: 'ServerError',
120
+ NETWORK: 'NetworkError'
121
+ };
122
+ /**
123
+ * HTTP header constants for error handling
124
+ */
125
+ const HttpHeaders = {
126
+ X_REQUEST_ID: 'x-request-id'
127
+ };
128
+ /**
129
+ * Standard error message constants
130
+ */
131
+ const ErrorMessages = {
132
+ // Authentication errors
133
+ AUTHENTICATION_FAILED: 'Authentication failed',
134
+ // Authorization errors
135
+ ACCESS_DENIED: 'Access denied',
136
+ // Validation errors
137
+ VALIDATION_FAILED: 'Validation failed',
138
+ // Not found errors
139
+ RESOURCE_NOT_FOUND: 'Resource not found',
140
+ // Rate limit errors
141
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
142
+ // Server errors
143
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
144
+ // Network errors
145
+ NETWORK_ERROR: 'Network error occurred',
146
+ REQUEST_TIMEOUT: 'Request timed out',
147
+ REQUEST_ABORTED: 'Request was aborted',
148
+ };
149
+ /**
150
+ * Error name constants for network error identification
151
+ */
152
+ const ErrorNames = {
153
+ ABORT_ERROR: 'AbortError'};
154
+
155
+ /**
156
+ * Error thrown when authentication fails (401 errors)
157
+ * Common scenarios:
158
+ * - Invalid credentials
159
+ * - Expired token
160
+ * - Missing authentication
161
+ */
162
+ class AuthenticationError extends UiPathError {
163
+ constructor(params = {}) {
164
+ super(ErrorType.AUTHENTICATION, {
165
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
166
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
167
+ requestId: params.requestId
168
+ });
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Error thrown when authorization fails (403 errors)
174
+ * Common scenarios:
175
+ * - Insufficient permissions
176
+ * - Access denied to resource
177
+ * - Invalid scope
178
+ */
179
+ class AuthorizationError extends UiPathError {
180
+ constructor(params = {}) {
181
+ super(ErrorType.AUTHORIZATION, {
182
+ message: params.message || ErrorMessages.ACCESS_DENIED,
183
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
184
+ requestId: params.requestId
185
+ });
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Error thrown when validation fails (400 errors or client-side validation)
191
+ * Common scenarios:
192
+ * - Invalid input parameters
193
+ * - Missing required fields
194
+ * - Invalid data format
195
+ */
196
+ class ValidationError extends UiPathError {
197
+ constructor(params = {}) {
198
+ super(ErrorType.VALIDATION, {
199
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
200
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
201
+ requestId: params.requestId
202
+ });
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Error thrown when a resource is not found (404 errors)
208
+ * Common scenarios:
209
+ * - Resource doesn't exist
210
+ * - Invalid ID provided
211
+ * - Resource deleted
212
+ */
213
+ class NotFoundError extends UiPathError {
214
+ constructor(params = {}) {
215
+ super(ErrorType.NOT_FOUND, {
216
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
217
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
218
+ requestId: params.requestId
219
+ });
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Error thrown when rate limit is exceeded (429 errors)
225
+ * Common scenarios:
226
+ * - Too many requests in a time window
227
+ * - API throttling
228
+ */
229
+ class RateLimitError extends UiPathError {
230
+ constructor(params = {}) {
231
+ super(ErrorType.RATE_LIMIT, {
232
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
233
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
234
+ requestId: params.requestId
235
+ });
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Error thrown when server encounters an error (5xx errors)
241
+ * Common scenarios:
242
+ * - Internal server error
243
+ * - Service unavailable
244
+ * - Gateway timeout
245
+ */
246
+ class ServerError extends UiPathError {
247
+ constructor(params = {}) {
248
+ super(ErrorType.SERVER, {
249
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
250
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
251
+ requestId: params.requestId
252
+ });
253
+ }
254
+ /**
255
+ * Checks if this is a temporary error that might succeed on retry
256
+ */
257
+ get isRetryable() {
258
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
259
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
260
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Error thrown when network/connection issues occur
266
+ * Common scenarios:
267
+ * - Connection timeout
268
+ * - DNS resolution failure
269
+ * - Network unreachable
270
+ * - Request aborted
271
+ */
272
+ class NetworkError extends UiPathError {
273
+ constructor(params = {}) {
274
+ super(ErrorType.NETWORK, {
275
+ message: params.message || ErrorMessages.NETWORK_ERROR,
276
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
277
+ requestId: params.requestId
278
+ });
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Type guards for error response types
284
+ */
285
+ function isOrchestratorError(error) {
286
+ return typeof error === 'object' &&
287
+ error !== null &&
288
+ 'message' in error &&
289
+ 'errorCode' in error &&
290
+ typeof error.message === 'string' &&
291
+ typeof error.errorCode === 'number';
292
+ }
293
+ function isEntityError(error) {
294
+ return typeof error === 'object' &&
295
+ error !== null &&
296
+ 'error' in error &&
297
+ typeof error.error === 'string';
298
+ }
299
+ function isPimsError(error) {
300
+ return typeof error === 'object' &&
301
+ error !== null &&
302
+ 'type' in error &&
303
+ 'title' in error &&
304
+ 'status' in error &&
305
+ typeof error.type === 'string' &&
306
+ typeof error.title === 'string' &&
307
+ typeof error.status === 'number';
308
+ }
309
+
310
+ /**
311
+ * Parser for Orchestrator/Task error format
312
+ */
313
+ class OrchestratorErrorParser {
314
+ canParse(errorBody) {
315
+ return isOrchestratorError(errorBody);
316
+ }
317
+ parse(errorBody, response) {
318
+ const error = errorBody;
319
+ return {
320
+ message: error.message,
321
+ code: response?.status?.toString(),
322
+ details: {
323
+ errorCode: error.errorCode,
324
+ traceId: error.traceId,
325
+ originalResponse: error
326
+ },
327
+ requestId: error.traceId
328
+ };
329
+ }
330
+ }
331
+ /**
332
+ * Parser for Entity (Data Fabric) error format
333
+ */
334
+ class EntityErrorParser {
335
+ canParse(errorBody) {
336
+ return isEntityError(errorBody);
337
+ }
338
+ parse(errorBody, response) {
339
+ const error = errorBody;
340
+ return {
341
+ message: error.error,
342
+ code: response?.status?.toString(),
343
+ details: {
344
+ error: error.error,
345
+ traceId: error.traceId,
346
+ originalResponse: error
347
+ },
348
+ requestId: error.traceId
349
+ };
350
+ }
351
+ }
352
+ /**
353
+ * Parser for PIMS error format
354
+ */
355
+ class PimsErrorParser {
356
+ canParse(errorBody) {
357
+ return isPimsError(errorBody);
358
+ }
359
+ parse(errorBody, response) {
360
+ const error = errorBody;
361
+ let message = error.title;
362
+ // If there are validation errors, append them to the message for better visibility
363
+ if (error.errors && Object.keys(error.errors).length > 0) {
364
+ const errorMessages = Object.entries(error.errors)
365
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
366
+ .join('; ');
367
+ message += `. Validation errors: ${errorMessages}`;
368
+ }
369
+ return {
370
+ message,
371
+ code: response?.status?.toString(),
372
+ details: {
373
+ type: error.type,
374
+ title: error.title,
375
+ status: error.status,
376
+ errors: error.errors,
377
+ traceId: error.traceId,
378
+ originalResponse: error
379
+ },
380
+ requestId: error.traceId
381
+ };
382
+ }
383
+ }
384
+ /**
385
+ * Fallback parser for unrecognized formats
386
+ */
387
+ class GenericErrorParser {
388
+ canParse(_errorBody) {
389
+ return true; // Always can parse as last resort
390
+ }
391
+ parse(errorBody, response) {
392
+ // For unknown error formats, just pass through the raw error with fallback message
393
+ const message = response?.statusText || 'An error occurred';
394
+ return {
395
+ message,
396
+ code: response?.status?.toString(),
397
+ details: {
398
+ originalResponse: errorBody
399
+ },
400
+ };
401
+ }
402
+ }
403
+ /**
404
+ * Main error response parser using Chain of Responsibility pattern
405
+ *
406
+ * This parser standardizes error responses from different UiPath services into a
407
+ * consistent format, regardless of the original error structure.
408
+ *
409
+ * Supported formats:
410
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
411
+ * 2. Entity (Data Fabric): { error, traceId }
412
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
413
+ * 4. Generic: Fallback for any other format
414
+ *
415
+ * @example
416
+ * const parser = new ErrorResponseParser();
417
+ * const errorInfo = await parser.parse(response);
418
+ * // errorInfo will have consistent structure regardless of service
419
+ */
420
+ class ErrorResponseParser {
421
+ constructor() {
422
+ this.strategies = [
423
+ new OrchestratorErrorParser(),
424
+ new EntityErrorParser(),
425
+ new PimsErrorParser(),
426
+ new GenericErrorParser() // Must be last
427
+ ];
428
+ }
429
+ /**
430
+ * Parses error response body into standardized format
431
+ * @param response - The HTTP response object
432
+ * @returns Standardized error information
433
+ */
434
+ async parse(response) {
435
+ try {
436
+ const errorBody = await response.json();
437
+ // Find the first strategy that can parse this error format
438
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
439
+ // GenericErrorParser always returns true, so this will never be null
440
+ return strategy.parse(errorBody, response);
441
+ }
442
+ catch {
443
+ // Handle non-JSON responses
444
+ const responseText = await response.text().catch(() => '');
445
+ return {
446
+ message: response.statusText,
447
+ code: response.status.toString(),
448
+ details: {
449
+ parseError: 'Failed to parse error response as JSON',
450
+ responseText
451
+ },
452
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
453
+ };
454
+ }
455
+ }
456
+ }
457
+ // Export singleton instance
458
+ const errorResponseParser = new ErrorResponseParser();
459
+
460
+ /**
461
+ * Factory for creating typed errors based on HTTP status codes
462
+ * Follows the Factory pattern for clean error instantiation
463
+ */
464
+ class ErrorFactory {
465
+ /**
466
+ * Creates appropriate error instance based on HTTP status code
467
+ */
468
+ static createFromHttpStatus(statusCode, errorInfo) {
469
+ const { message, requestId } = errorInfo;
470
+ // Map status codes to error types
471
+ switch (statusCode) {
472
+ case HttpStatus.BAD_REQUEST:
473
+ return new ValidationError({ message, statusCode, requestId });
474
+ case HttpStatus.UNAUTHORIZED:
475
+ return new AuthenticationError({ message, statusCode, requestId });
476
+ case HttpStatus.FORBIDDEN:
477
+ return new AuthorizationError({ message, statusCode, requestId });
478
+ case HttpStatus.NOT_FOUND:
479
+ return new NotFoundError({ message, statusCode, requestId });
480
+ case HttpStatus.TOO_MANY_REQUESTS:
481
+ return new RateLimitError({ message, statusCode, requestId });
482
+ default:
483
+ // For 5xx errors or any other status code
484
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
485
+ return new ServerError({ message, statusCode, requestId });
486
+ }
487
+ // For unknown client errors, treat as validation error
488
+ return new ValidationError({
489
+ message: `${message} (HTTP ${statusCode})`,
490
+ statusCode,
491
+ requestId
492
+ });
493
+ }
494
+ }
495
+ /**
496
+ * Creates a NetworkError from a fetch/network error
497
+ */
498
+ static createNetworkError(error) {
499
+ let message = ErrorMessages.NETWORK_ERROR;
500
+ if (error instanceof Error) {
501
+ if (error.name === ErrorNames.ABORT_ERROR) {
502
+ message = ErrorMessages.REQUEST_ABORTED;
503
+ }
504
+ else if (error.message.includes('timeout')) {
505
+ message = ErrorMessages.REQUEST_TIMEOUT;
506
+ }
507
+ else {
508
+ message = error.message;
509
+ }
510
+ }
511
+ return new NetworkError({ message });
512
+ }
513
+ }
514
+
515
+ const FOLDER_KEY = 'X-UIPATH-FolderKey';
516
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
517
+ /**
518
+ * Content type constants for HTTP requests/responses
519
+ */
520
+ const CONTENT_TYPES = {
521
+ JSON: 'application/json',
522
+ XML: 'application/xml',
523
+ OCTET_STREAM: 'application/octet-stream'
524
+ };
525
+ /**
526
+ * Response type constants for HTTP requests
527
+ */
528
+ const RESPONSE_TYPES = {
529
+ JSON: 'json',
530
+ TEXT: 'text',
531
+ BLOB: 'blob',
532
+ ARRAYBUFFER: 'arraybuffer'
533
+ };
534
+
535
+ class ApiClient {
536
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
537
+ this.defaultHeaders = {};
538
+ this.config = config;
539
+ this.executionContext = executionContext;
540
+ this.clientConfig = clientConfig;
541
+ this.tokenManager = tokenManager;
542
+ }
543
+ setDefaultHeaders(headers) {
544
+ this.defaultHeaders = { ...this.defaultHeaders, ...headers };
545
+ }
546
+ /**
547
+ * Gets a valid authentication token, refreshing if necessary.
548
+ * Used internally for API requests and exposed for services that need manual auth headers.
549
+ *
550
+ * @returns The valid token
551
+ * @throws AuthenticationError if no token available or refresh fails
552
+ */
553
+ async getValidToken() {
554
+ // Try to get token info from context
555
+ const tokenInfo = this.executionContext.get('tokenInfo');
556
+ if (!tokenInfo) {
557
+ throw new AuthenticationError({ message: 'No authentication token available. Make sure to initialize the SDK first.' });
558
+ }
559
+ // For secret-based tokens, they never expire
560
+ if (tokenInfo.type === 'secret') {
561
+ return tokenInfo.token;
562
+ }
563
+ // If token is not expired, return it
564
+ if (!this.tokenManager.isTokenExpired(tokenInfo)) {
565
+ return tokenInfo.token;
566
+ }
567
+ try {
568
+ const newToken = await this.tokenManager.refreshAccessToken();
569
+ return newToken.access_token;
570
+ }
571
+ catch (error) {
572
+ throw new AuthenticationError({
573
+ message: `Token refresh failed: ${error.message}. Please re-authenticate.`,
574
+ statusCode: HttpStatus.UNAUTHORIZED
575
+ });
576
+ }
577
+ }
578
+ async getDefaultHeaders() {
579
+ // Get headers from execution context first
580
+ const contextHeaders = this.executionContext.getHeaders();
581
+ // If Authorization header is already set in context, use that
582
+ if (contextHeaders['Authorization']) {
583
+ return {
584
+ ...contextHeaders,
585
+ 'Content-Type': CONTENT_TYPES.JSON,
586
+ ...this.defaultHeaders,
587
+ ...this.clientConfig.headers
588
+ };
589
+ }
590
+ const token = await this.getValidToken();
591
+ return {
592
+ ...contextHeaders,
593
+ 'Authorization': `Bearer ${token}`,
594
+ 'Content-Type': CONTENT_TYPES.JSON,
595
+ ...this.defaultHeaders,
596
+ ...this.clientConfig.headers
597
+ };
598
+ }
599
+ async request(method, path, options = {}) {
600
+ // Ensure path starts with a forward slash
601
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
602
+ // Construct URL with org and tenant names
603
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
604
+ const headers = {
605
+ ...await this.getDefaultHeaders(),
606
+ ...options.headers
607
+ };
608
+ // Convert params to URLSearchParams
609
+ const searchParams = new URLSearchParams();
610
+ if (options.params) {
611
+ Object.entries(options.params).forEach(([key, value]) => {
612
+ searchParams.append(key, value.toString());
613
+ });
614
+ }
615
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
616
+ try {
617
+ const response = await fetch(fullUrl, {
618
+ method,
619
+ headers,
620
+ body: options.body ? JSON.stringify(options.body) : undefined,
621
+ signal: options.signal
622
+ });
623
+ if (!response.ok) {
624
+ const errorInfo = await errorResponseParser.parse(response);
625
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
626
+ }
627
+ if (response.status === 204) {
628
+ return undefined;
629
+ }
630
+ // Handle blob response type for binary data (e.g., file downloads)
631
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
632
+ const blob = await response.blob();
633
+ return blob;
634
+ }
635
+ // Check if we're expecting XML
636
+ const acceptHeader = headers['Accept'] || headers['accept'];
637
+ if (acceptHeader === CONTENT_TYPES.XML) {
638
+ const text = await response.text();
639
+ return text;
640
+ }
641
+ return response.json();
642
+ }
643
+ catch (error) {
644
+ // If it's already one of our errors, re-throw it
645
+ if (error.type && error.type.includes('Error')) {
646
+ throw error;
647
+ }
648
+ // Otherwise, it's likely a network error
649
+ throw ErrorFactory.createNetworkError(error);
650
+ }
651
+ }
652
+ async get(path, options = {}) {
653
+ return this.request('GET', path, options);
654
+ }
655
+ async post(path, data, options = {}) {
656
+ return this.request('POST', path, { ...options, body: data });
657
+ }
658
+ async put(path, data, options = {}) {
659
+ return this.request('PUT', path, { ...options, body: data });
660
+ }
661
+ async patch(path, data, options = {}) {
662
+ return this.request('PATCH', path, { ...options, body: data });
663
+ }
664
+ async delete(path, options = {}) {
665
+ return this.request('DELETE', path, options);
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Pagination types supported by the SDK
671
+ */
672
+ var PaginationType;
673
+ (function (PaginationType) {
674
+ PaginationType["OFFSET"] = "offset";
675
+ PaginationType["TOKEN"] = "token";
676
+ })(PaginationType || (PaginationType = {}));
677
+
678
+ /**
679
+ * Collection of utility functions for working with objects
680
+ */
681
+ /**
682
+ * Filters out undefined values from an object
683
+ * @param obj The source object
684
+ * @returns A new object without undefined values
685
+ *
686
+ * @example
687
+ * ```typescript
688
+ * // Object with undefined values
689
+ * const options = {
690
+ * name: 'test',
691
+ * count: 5,
692
+ * prefix: undefined,
693
+ * suffix: null
694
+ * };
695
+ * const result = filterUndefined(options);
696
+ * // result = { name: 'test', count: 5, suffix: null }
697
+ * ```
698
+ */
699
+ function filterUndefined(obj) {
700
+ const result = {};
701
+ for (const [key, value] of Object.entries(obj)) {
702
+ if (value !== undefined) {
703
+ result[key] = value;
704
+ }
705
+ }
706
+ return result;
707
+ }
708
+ /**
709
+ * Helper function for OData responses that ALWAYS return 200 with array indication
710
+ * Empty array = success, Non-empty array = error
711
+ * Used for task assignment APIs that don't use HTTP status codes for errors
712
+ */
713
+ function processODataArrayResponse(oDataResponse, successData) {
714
+ // Empty array = success
715
+ if (oDataResponse.value.length === 0) {
716
+ return {
717
+ success: true,
718
+ data: successData
719
+ };
720
+ }
721
+ // Non-empty array = error details
722
+ return {
723
+ success: false,
724
+ data: oDataResponse.value
725
+ };
726
+ }
727
+
728
+ /**
729
+ * Utility functions for platform detection
730
+ */
731
+ /**
732
+ * Checks if code is running in a browser environment
733
+ */
734
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
735
+
736
+ /**
737
+ * Base64 encoding/decoding
738
+ */
739
+ /**
740
+ * Encodes a string to base64
741
+ * @param str - The string to encode
742
+ * @returns Base64 encoded string
743
+ */
744
+ function encodeBase64(str) {
745
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
746
+ const encoder = new TextEncoder();
747
+ const data = encoder.encode(str);
748
+ // Convert Uint8Array to base64
749
+ if (isBrowser) {
750
+ // Browser environment
751
+ // Convert Uint8Array to binary string then to base64
752
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
753
+ return btoa(binaryString);
754
+ }
755
+ else {
756
+ // Node.js environment
757
+ return Buffer.from(data).toString('base64');
758
+ }
759
+ }
760
+ /**
761
+ * Decodes a base64 string
762
+ * @param base64 - The base64 string to decode
763
+ * @returns Decoded string
764
+ */
765
+ function decodeBase64(base64) {
766
+ let bytes;
767
+ if (isBrowser) {
768
+ // Browser environment
769
+ const binaryString = atob(base64);
770
+ bytes = new Uint8Array(binaryString.length);
771
+ for (let i = 0; i < binaryString.length; i++) {
772
+ bytes[i] = binaryString.charCodeAt(i);
773
+ }
774
+ }
775
+ else {
776
+ // Node.js environment
777
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
778
+ }
779
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
780
+ const decoder = new TextDecoder();
781
+ return decoder.decode(bytes);
782
+ }
783
+
784
+ /**
785
+ * PaginationManager handles the conversion between uniform cursor-based pagination
786
+ * and the specific pagination type for each service
787
+ */
788
+ class PaginationManager {
789
+ /**
790
+ * Create a pagination cursor for subsequent page requests
791
+ */
792
+ static createCursor({ pageInfo, type }) {
793
+ if (!pageInfo.hasMore) {
794
+ return undefined;
795
+ }
796
+ const cursorData = {
797
+ type,
798
+ pageSize: pageInfo.pageSize,
799
+ };
800
+ switch (type) {
801
+ case PaginationType.OFFSET:
802
+ if (pageInfo.currentPage) {
803
+ cursorData.pageNumber = pageInfo.currentPage + 1;
804
+ }
805
+ break;
806
+ case PaginationType.TOKEN:
807
+ if (pageInfo.continuationToken) {
808
+ cursorData.continuationToken = pageInfo.continuationToken;
809
+ }
810
+ else {
811
+ return undefined; // No continuation token, can't continue
812
+ }
813
+ break;
814
+ }
815
+ return {
816
+ value: encodeBase64(JSON.stringify(cursorData))
817
+ };
818
+ }
819
+ /**
820
+ * Create a paginated response with navigation cursors
821
+ */
822
+ static createPaginatedResponse({ pageInfo, type }, items) {
823
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
824
+ // Create previous page cursor if applicable
825
+ let previousCursor = undefined;
826
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
827
+ const prevCursorData = {
828
+ type,
829
+ pageNumber: pageInfo.currentPage - 1,
830
+ pageSize: pageInfo.pageSize,
831
+ };
832
+ previousCursor = {
833
+ value: encodeBase64(JSON.stringify(prevCursorData))
834
+ };
835
+ }
836
+ // Calculate total pages if we have totalCount and pageSize
837
+ let totalPages = undefined;
838
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
839
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
840
+ }
841
+ // Determine if this pagination type supports page jumping
842
+ const supportsPageJump = type === PaginationType.OFFSET;
843
+ // Create the result object with all fields, then filter out undefined values
844
+ const result = filterUndefined({
845
+ items,
846
+ totalCount: pageInfo.totalCount,
847
+ hasNextPage: pageInfo.hasMore,
848
+ nextCursor: nextCursor,
849
+ previousCursor: previousCursor,
850
+ currentPage: pageInfo.currentPage,
851
+ totalPages,
852
+ supportsPageJump
853
+ });
854
+ return result;
855
+ }
856
+ }
857
+
858
+ /**
859
+ * Creates headers object from key-value pairs
860
+ * @param headersObj - Object containing header key-value pairs
861
+ * @returns Headers object with all values converted to strings
862
+ *
863
+ * @example
864
+ * ```typescript
865
+ * // Single header
866
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
867
+ *
868
+ * // Multiple headers
869
+ * const headers = createHeaders({
870
+ * 'X-UIPATH-FolderKey': '1234567890',
871
+ * 'X-UIPATH-OrganizationUnitId': 123,
872
+ * 'Accept': 'application/json'
873
+ * });
874
+ *
875
+ * // Using constants
876
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
877
+ * const headers = createHeaders({
878
+ * [FOLDER_KEY]: 'abc-123',
879
+ * [FOLDER_ID]: 456
880
+ * });
881
+ *
882
+ * // Empty headers
883
+ * const headers = createHeaders();
884
+ * ```
885
+ */
886
+ function createHeaders(headersObj) {
887
+ const headers = {};
888
+ for (const [key, value] of Object.entries(headersObj)) {
889
+ if (value !== undefined && value !== null) {
890
+ headers[key] = value.toString();
891
+ }
892
+ }
893
+ return headers;
894
+ }
895
+
896
+ /**
897
+ * Common constants used across the SDK
898
+ */
899
+ /**
900
+ * Prefix used for OData query parameters
901
+ */
902
+ const ODATA_PREFIX = '$';
903
+ /**
904
+ * HTTP methods
905
+ */
906
+ const HTTP_METHODS = {
907
+ GET: 'GET',
908
+ POST: 'POST'};
909
+ /**
910
+ * OData pagination constants
911
+ */
912
+ const ODATA_PAGINATION = {
913
+ /** Default field name for items in a paginated OData response */
914
+ ITEMS_FIELD: 'value',
915
+ /** Default field name for total count in a paginated OData response */
916
+ TOTAL_COUNT_FIELD: '@odata.count'
917
+ };
918
+ /**
919
+ * Process Instance pagination constants for token-based pagination
920
+ */
921
+ const PROCESS_INSTANCE_PAGINATION = {
922
+ /** Field name for items in process instance response */
923
+ ITEMS_FIELD: 'instances',
924
+ /** Field name for continuation token in process instance response */
925
+ CONTINUATION_TOKEN_FIELD: 'nextPage'
926
+ };
927
+ /**
928
+ * OData OFFSET pagination parameter names (ODATA-style)
929
+ */
930
+ const ODATA_OFFSET_PARAMS = {
931
+ /** OData page size parameter name */
932
+ PAGE_SIZE_PARAM: '$top',
933
+ /** OData offset parameter name */
934
+ OFFSET_PARAM: '$skip',
935
+ /** OData count parameter name */
936
+ COUNT_PARAM: '$count'
937
+ };
938
+ /**
939
+ * Bucket TOKEN pagination parameter names
940
+ */
941
+ const BUCKET_TOKEN_PARAMS = {
942
+ /** Bucket page size parameter name */
943
+ PAGE_SIZE_PARAM: 'takeHint',
944
+ /** Bucket token parameter name */
945
+ TOKEN_PARAM: 'continuationToken'
946
+ };
947
+ /**
948
+ * Process Instance TOKEN pagination parameter names
949
+ */
950
+ const PROCESS_INSTANCE_TOKEN_PARAMS = {
951
+ /** Process instance page size parameter name */
952
+ PAGE_SIZE_PARAM: 'pageSize',
953
+ /** Process instance token parameter name */
954
+ TOKEN_PARAM: 'nextPage'
955
+ };
956
+
957
+ /**
958
+ * Transforms data by mapping fields according to the provided field mapping
959
+ * @param data The source data to transform
960
+ * @param fieldMapping Object mapping source field names to target field names
961
+ * @returns Transformed data with mapped field names
962
+ *
963
+ * @example
964
+ * ```typescript
965
+ * // Single object transformation
966
+ * const data = { id: '123', userName: 'john' };
967
+ * const mapping = { id: 'userId', userName: 'name' };
968
+ * const result = transformData(data, mapping);
969
+ * // result = { userId: '123', name: 'john' }
970
+ *
971
+ * // Array transformation
972
+ * const dataArray = [
973
+ * { id: '123', userName: 'john' },
974
+ * { id: '456', userName: 'jane' }
975
+ * ];
976
+ * const result = transformData(dataArray, mapping);
977
+ * // result = [
978
+ * // { userId: '123', name: 'john' },
979
+ * // { userId: '456', name: 'jane' }
980
+ * // ]
981
+ * ```
982
+ */
983
+ function transformData(data, fieldMapping) {
984
+ // Handle array of objects
985
+ if (Array.isArray(data)) {
986
+ return data.map(item => transformData(item, fieldMapping));
987
+ }
988
+ // Handle single object
989
+ const result = { ...data };
990
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
991
+ if (sourceField in result) {
992
+ const value = result[sourceField];
993
+ delete result[sourceField];
994
+ result[targetField] = value;
995
+ }
996
+ }
997
+ return result;
998
+ }
999
+ /**
1000
+ * Converts a string from PascalCase to camelCase
1001
+ * @param str The PascalCase string to convert
1002
+ * @returns The camelCase version of the string
1003
+ *
1004
+ * @example
1005
+ * ```typescript
1006
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
1007
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
1008
+ * ```
1009
+ */
1010
+ function pascalToCamelCase(str) {
1011
+ if (!str)
1012
+ return str;
1013
+ return str.charAt(0).toLowerCase() + str.slice(1);
1014
+ }
1015
+ /**
1016
+ * Converts a string from camelCase to PascalCase
1017
+ * @param str The camelCase string to convert
1018
+ * @returns The PascalCase version of the string
1019
+ *
1020
+ * @example
1021
+ * ```typescript
1022
+ * camelToPascalCase('helloWorld'); // 'HelloWorld'
1023
+ * camelToPascalCase('taskAssignmentCriteria'); // 'TaskAssignmentCriteria'
1024
+ * ```
1025
+ */
1026
+ function camelToPascalCase(str) {
1027
+ if (!str)
1028
+ return str;
1029
+ return str.charAt(0).toUpperCase() + str.slice(1);
1030
+ }
1031
+ /**
1032
+ * Generic function to transform object keys using a provided case conversion function
1033
+ * @param data The object to transform
1034
+ * @param convertCase The function to convert each key
1035
+ * @returns A new object with transformed keys
1036
+ */
1037
+ function transformCaseKeys(data, convertCase) {
1038
+ // Handle array of objects
1039
+ if (Array.isArray(data)) {
1040
+ return data.map(item => {
1041
+ // If the array element is a primitive (string, number, etc.), return it as is
1042
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
1043
+ return item;
1044
+ }
1045
+ // Only recursively transform if it's actually an object
1046
+ return transformCaseKeys(item, convertCase);
1047
+ });
1048
+ }
1049
+ const result = {};
1050
+ for (const [key, value] of Object.entries(data)) {
1051
+ const transformedKey = convertCase(key);
1052
+ // Recursively transform nested objects and arrays
1053
+ if (value !== null && typeof value === 'object') {
1054
+ result[transformedKey] = transformCaseKeys(value, convertCase);
1055
+ }
1056
+ else {
1057
+ result[transformedKey] = value;
1058
+ }
1059
+ }
1060
+ return result;
1061
+ }
1062
+ /**
1063
+ * Transforms an object's keys from PascalCase to camelCase
1064
+ * @param data The object with PascalCase keys
1065
+ * @returns A new object with all keys converted to camelCase
1066
+ *
1067
+ * @example
1068
+ * ```typescript
1069
+ * // Simple object
1070
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
1071
+ * // Result: { id: "123", taskName: "Invoice" }
1072
+ *
1073
+ * // Nested object
1074
+ * pascalToCamelCaseKeys({
1075
+ * TaskId: "456",
1076
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
1077
+ * });
1078
+ * // Result: {
1079
+ * // taskId: "456",
1080
+ * // taskDetails: { assignedUser: "John", priority: "High" }
1081
+ * // }
1082
+ *
1083
+ * // Array of objects
1084
+ * pascalToCamelCaseKeys([
1085
+ * { Id: "1", IsComplete: false },
1086
+ * { Id: "2", IsComplete: true }
1087
+ * ]);
1088
+ * // Result: [
1089
+ * // { id: "1", isComplete: false },
1090
+ * // { id: "2", isComplete: true }
1091
+ * // ]
1092
+ * ```
1093
+ */
1094
+ function pascalToCamelCaseKeys(data) {
1095
+ return transformCaseKeys(data, pascalToCamelCase);
1096
+ }
1097
+ /**
1098
+ * Transforms an object's keys from camelCase to PascalCase
1099
+ * @param data The object with camelCase keys
1100
+ * @returns A new object with all keys converted to PascalCase
1101
+ *
1102
+ * @example
1103
+ * ```typescript
1104
+ * // Simple object
1105
+ * camelToPascalCaseKeys({ userId: "789", isActive: true });
1106
+ * // Result: { UserId: "789", IsActive: true }
1107
+ *
1108
+ * // Nested object
1109
+ * camelToPascalCaseKeys({
1110
+ * taskId: "ABC123",
1111
+ * submissionData: { customerName: "XYZ Corp" }
1112
+ * });
1113
+ * // Result: {
1114
+ * // TaskId: "ABC123",
1115
+ * // SubmissionData: { CustomerName: "XYZ Corp" }
1116
+ * // }
1117
+ *
1118
+ * // Array of objects
1119
+ * camelToPascalCaseKeys([
1120
+ * { userId: "u1", roleType: "admin" },
1121
+ * { userId: "u2", roleType: "user" }
1122
+ * ]);
1123
+ * // Result: [
1124
+ * // { UserId: "u1", RoleType: "admin" },
1125
+ * // { UserId: "u2", RoleType: "user" }
1126
+ * // ]
1127
+ * ```
1128
+ */
1129
+ function camelToPascalCaseKeys(data) {
1130
+ return transformCaseKeys(data, camelToPascalCase);
1131
+ }
1132
+ /**
1133
+ * Maps a field value in an object using a provided mapping object.
1134
+ * Returns a new object with the mapped field value.
1135
+ *
1136
+ * @param obj The object to map
1137
+ * @param field The field name to map
1138
+ * @param valueMap The mapping object (from input value to output value)
1139
+ * @returns A new object with the mapped field value
1140
+ *
1141
+ * @example
1142
+ * const statusMap = { 0: 'Unassigned', 1: 'Pending', 2: 'Completed' };
1143
+ * const task = { status: 1, id: 123 };
1144
+ * const mapped = mapFieldValue(task, 'status', statusMap);
1145
+ * // mapped = { status: 'Pending', id: 123 }
1146
+ */
1147
+ function _mapFieldValue(obj, field, valueMap) {
1148
+ const lookupKey = String(obj[field]);
1149
+ return {
1150
+ ...obj,
1151
+ [field]: lookupKey in valueMap
1152
+ ? valueMap[lookupKey]
1153
+ : obj[field],
1154
+ };
1155
+ }
1156
+ /**
1157
+ * General API response transformer with optional field value mapping.
1158
+ *
1159
+ * @param data - The API response data to transform
1160
+ * @param options - Optional mapping options:
1161
+ * - field: The field name to map (optional)
1162
+ * - valueMap: The mapping object for the field (optional)
1163
+ * - transform: A function to further transform the data (optional)
1164
+ * @returns The transformed data, with field value mapped if specified
1165
+ *
1166
+ * @example
1167
+ * // Just transform
1168
+ * const result = applyDataTransforms(data);
1169
+ *
1170
+ * // Map a field value, then transform
1171
+ * const result = applyDataTransforms(data, { field: 'status', valueMap: StatusMap });
1172
+ *
1173
+ * // Map a field value, then apply a custom transform
1174
+ * const result = applyDataTransforms(data, { field: 'status', valueMap: StatusMap, transform: customTransform });
1175
+ */
1176
+ function applyDataTransforms(data, options) {
1177
+ let result = data;
1178
+ if (options?.field && options?.valueMap) {
1179
+ result = _mapFieldValue(result, options.field, options.valueMap);
1180
+ }
1181
+ if (options?.transform) {
1182
+ result = options.transform(result);
1183
+ }
1184
+ return result;
1185
+ }
1186
+ /**
1187
+ * Adds a prefix to specified keys in an object, returning a new object.
1188
+ * Only the provided keys are prefixed; all others are left unchanged.
1189
+ *
1190
+ * @param obj The source object
1191
+ * @param prefix The prefix to add (e.g., '$')
1192
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1193
+ * @returns A new object with specified keys prefixed
1194
+ *
1195
+ * @example
1196
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1197
+ */
1198
+ function addPrefixToKeys(obj, prefix, keys) {
1199
+ const result = {};
1200
+ for (const [key, value] of Object.entries(obj)) {
1201
+ if (keys.includes(key)) {
1202
+ result[`${prefix}${key}`] = value;
1203
+ }
1204
+ else {
1205
+ result[key] = value;
1206
+ }
1207
+ }
1208
+ return result;
1209
+ }
1210
+
1211
+ /**
1212
+ * Constants used throughout the pagination system
1213
+ */
1214
+ /** Maximum number of items that can be requested in a single page */
1215
+ const MAX_PAGE_SIZE = 1000;
1216
+ /** Default page size when jumpToPage is used without specifying pageSize */
1217
+ const DEFAULT_PAGE_SIZE = 50;
1218
+ /** Default field name for items in a paginated response */
1219
+ const DEFAULT_ITEMS_FIELD = 'value';
1220
+ /** Default field name for total count in a paginated response */
1221
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1222
+ /**
1223
+ * Limits the page size to the maximum allowed value
1224
+ * @param pageSize - Requested page size
1225
+ * @returns Limited page size value
1226
+ */
1227
+ function getLimitedPageSize(pageSize) {
1228
+ if (pageSize === undefined || pageSize === null) {
1229
+ return DEFAULT_PAGE_SIZE;
1230
+ }
1231
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1232
+ }
1233
+
1234
+ /**
1235
+ * Helper functions for pagination that can be used across services
1236
+ */
1237
+ class PaginationHelpers {
1238
+ /**
1239
+ * Checks if any pagination parameters are provided
1240
+ *
1241
+ * @param options - The options object to check
1242
+ * @returns True if any pagination parameter is defined, false otherwise
1243
+ */
1244
+ static hasPaginationParameters(options = {}) {
1245
+ const { cursor, pageSize, jumpToPage } = options;
1246
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1247
+ }
1248
+ /**
1249
+ * Parse a pagination cursor string into cursor data
1250
+ */
1251
+ static parseCursor(cursorString) {
1252
+ try {
1253
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1254
+ return cursorData;
1255
+ }
1256
+ catch {
1257
+ throw new Error('Invalid pagination cursor');
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Validates cursor format and structure
1262
+ *
1263
+ * @param paginationOptions - The pagination options containing the cursor
1264
+ * @param paginationType - Optional pagination type to validate against
1265
+ */
1266
+ static validateCursor(paginationOptions, paginationType) {
1267
+ if (paginationOptions.cursor !== undefined) {
1268
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1269
+ throw new Error('cursor must contain a valid cursor string');
1270
+ }
1271
+ try {
1272
+ // Try to parse the cursor to validate it
1273
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1274
+ // If type is provided, validate cursor contains expected type information
1275
+ if (paginationType) {
1276
+ if (!cursorData.type) {
1277
+ throw new Error('Invalid cursor: missing pagination type');
1278
+ }
1279
+ // Check pagination type compatibility
1280
+ if (cursorData.type !== paginationType) {
1281
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1282
+ }
1283
+ }
1284
+ }
1285
+ catch (error) {
1286
+ if (error instanceof Error) {
1287
+ // If it's already our error with specific message, pass it through
1288
+ if (error.message.startsWith('Invalid cursor') ||
1289
+ error.message.startsWith('Pagination type mismatch')) {
1290
+ throw error;
1291
+ }
1292
+ }
1293
+ throw new Error('Invalid pagination cursor format');
1294
+ }
1295
+ }
1296
+ }
1297
+ /**
1298
+ * Comprehensive validation for pagination options
1299
+ *
1300
+ * @param options - The pagination options to validate
1301
+ * @param paginationType - The pagination type these options will be used with
1302
+ * @returns Processed pagination parameters ready for use
1303
+ */
1304
+ static validatePaginationOptions(options, paginationType) {
1305
+ // Validate pageSize
1306
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1307
+ throw new Error('pageSize must be a positive number');
1308
+ }
1309
+ // Validate jumpToPage
1310
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1311
+ throw new Error('jumpToPage must be a positive number');
1312
+ }
1313
+ // Validate cursor
1314
+ PaginationHelpers.validateCursor(options, paginationType);
1315
+ // Validate service compatibility
1316
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1317
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1318
+ }
1319
+ // Get processed parameters
1320
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1321
+ }
1322
+ /**
1323
+ * Convert a unified pagination options to service-specific parameters
1324
+ */
1325
+ static getRequestParameters(options, paginationType) {
1326
+ // Handle jumpToPage
1327
+ if (options.jumpToPage !== undefined) {
1328
+ const jumpToPageOptions = {
1329
+ pageSize: options.pageSize,
1330
+ pageNumber: options.jumpToPage
1331
+ };
1332
+ return filterUndefined(jumpToPageOptions);
1333
+ }
1334
+ // If no cursor is provided, it's a first page request
1335
+ if (!options.cursor) {
1336
+ const firstPageOptions = {
1337
+ pageSize: options.pageSize,
1338
+ // Only set pageNumber for OFFSET pagination
1339
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1340
+ };
1341
+ return filterUndefined(firstPageOptions);
1342
+ }
1343
+ // Parse the cursor
1344
+ try {
1345
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1346
+ const cursorBasedOptions = {
1347
+ pageSize: cursorData.pageSize || options.pageSize,
1348
+ pageNumber: cursorData.pageNumber,
1349
+ continuationToken: cursorData.continuationToken,
1350
+ type: cursorData.type,
1351
+ };
1352
+ return filterUndefined(cursorBasedOptions);
1353
+ }
1354
+ catch {
1355
+ throw new Error('Invalid pagination cursor');
1356
+ }
1357
+ }
1358
+ /**
1359
+ * Helper method for paginated resource retrieval
1360
+ *
1361
+ * @param params - Parameters for pagination
1362
+ * @returns Promise resolving to a paginated result
1363
+ */
1364
+ static async getAllPaginated(params) {
1365
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1366
+ const endpoint = getEndpoint(folderId);
1367
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1368
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1369
+ headers,
1370
+ params: additionalParams,
1371
+ pagination: {
1372
+ paginationType: options.paginationType || PaginationType.OFFSET,
1373
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1374
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1375
+ continuationTokenField: options.continuationTokenField,
1376
+ paginationParams: options.paginationParams
1377
+ }
1378
+ });
1379
+ // Parse items - automatically handle JSON string responses
1380
+ const rawItems = paginatedResponse.items;
1381
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1382
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1383
+ return {
1384
+ ...paginatedResponse,
1385
+ items: transformedItems
1386
+ };
1387
+ }
1388
+ /**
1389
+ * Helper method for non-paginated resource retrieval
1390
+ *
1391
+ * @param params - Parameters for non-paginated resource retrieval
1392
+ * @returns Promise resolving to an object with data and totalCount
1393
+ */
1394
+ static async getAllNonPaginated(params) {
1395
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1396
+ // Set default field names
1397
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1398
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1399
+ // Determine endpoint and headers based on folderId
1400
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1401
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1402
+ // Make the API call based on method
1403
+ let response;
1404
+ if (method === HTTP_METHODS.POST) {
1405
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1406
+ }
1407
+ else {
1408
+ response = await serviceAccess.get(endpoint, {
1409
+ params: additionalParams,
1410
+ headers
1411
+ });
1412
+ }
1413
+ // Extract and transform items from response
1414
+ const rawItems = response.data?.[itemsField];
1415
+ const totalCount = response.data?.[totalCountField];
1416
+ // Parse items - automatically handle JSON string responses
1417
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1418
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1419
+ return {
1420
+ items,
1421
+ totalCount
1422
+ };
1423
+ }
1424
+ /**
1425
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1426
+ *
1427
+ * @param config - Configuration for the getAll operation
1428
+ * @param options - Request options including pagination parameters
1429
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1430
+ */
1431
+ static async getAll(config, options) {
1432
+ const optionsWithDefaults = options || {};
1433
+ const { folderId, ...restOptions } = optionsWithDefaults;
1434
+ const cursor = options?.cursor;
1435
+ const pageSize = options?.pageSize;
1436
+ const jumpToPage = options?.jumpToPage;
1437
+ // Determine if pagination is requested
1438
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1439
+ // Process parameters (custom processing if provided, otherwise default)
1440
+ let processedOptions = restOptions;
1441
+ if (config.processParametersFn) {
1442
+ processedOptions = config.processParametersFn(restOptions, folderId);
1443
+ }
1444
+ // Apply ODATA prefix to keys (excluding specified keys)
1445
+ const excludeKeys = config.excludeFromPrefix || [];
1446
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1447
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1448
+ // Default pagination options
1449
+ const paginationOptions = {
1450
+ paginationType: PaginationType.OFFSET,
1451
+ itemsField: DEFAULT_ITEMS_FIELD,
1452
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1453
+ ...config.pagination
1454
+ };
1455
+ // Paginated flow
1456
+ if (isPaginationRequested) {
1457
+ return PaginationHelpers.getAllPaginated({
1458
+ serviceAccess: config.serviceAccess,
1459
+ getEndpoint: config.getEndpoint,
1460
+ folderId,
1461
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1462
+ additionalParams: prefixedOptions,
1463
+ transformFn: config.transformFn,
1464
+ method: config.method,
1465
+ options: {
1466
+ ...paginationOptions,
1467
+ paginationParams: config.pagination?.paginationParams
1468
+ }
1469
+ }); // Type assertion needed due to conditional return
1470
+ }
1471
+ // Non-paginated flow
1472
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1473
+ return PaginationHelpers.getAllNonPaginated({
1474
+ serviceAccess: config.serviceAccess,
1475
+ getAllEndpoint: config.getEndpoint(),
1476
+ getByFolderEndpoint: byFolderEndpoint,
1477
+ folderId,
1478
+ additionalParams: prefixedOptions,
1479
+ transformFn: config.transformFn,
1480
+ method: config.method,
1481
+ options: {
1482
+ itemsField: paginationOptions.itemsField,
1483
+ totalCountField: paginationOptions.totalCountField
1484
+ }
1485
+ });
1486
+ }
1487
+ }
1488
+
1489
+ /**
1490
+ * SDK Internals Registry - Internal registry for SDK instances
1491
+ *
1492
+ * This class is NOT exported in the public API.
1493
+ * It provides a secure way to share SDK internals between
1494
+ * the UiPath class and service classes without exposing them publicly.
1495
+ *
1496
+ * @internal
1497
+ */
1498
+ // Global symbol key to ensure WeakMap is shared across module instances
1499
+ // This prevents issues when core and service modules are bundled separately
1500
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1501
+ // Get or create the global WeakMap store
1502
+ const getGlobalStore = () => {
1503
+ const globalObj = globalThis;
1504
+ if (!globalObj[REGISTRY_KEY]) {
1505
+ globalObj[REGISTRY_KEY] = new WeakMap();
1506
+ }
1507
+ return globalObj[REGISTRY_KEY];
1508
+ };
1509
+ /**
1510
+ * Internal registry for SDK private components.
1511
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1512
+ * garbage collected when the SDK instance is no longer referenced.
1513
+ *
1514
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1515
+ * across separately bundled modules (core, entities, tasks, etc.).
1516
+ *
1517
+ * @internal - Not exported in public API
1518
+ */
1519
+ class SDKInternalsRegistry {
1520
+ // Use global store to ensure sharing across module bundles
1521
+ static get store() {
1522
+ return getGlobalStore();
1523
+ }
1524
+ /**
1525
+ * Register SDK instance internals
1526
+ * Called by UiPath constructor
1527
+ */
1528
+ static set(instance, internals) {
1529
+ this.store.set(instance, internals);
1530
+ }
1531
+ /**
1532
+ * Retrieve SDK instance internals
1533
+ * Called by BaseService constructor
1534
+ */
1535
+ static get(instance) {
1536
+ const internals = this.store.get(instance);
1537
+ if (!internals) {
1538
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1539
+ }
1540
+ return internals;
1541
+ }
1542
+ }
1543
+
1544
+ var _BaseService_apiClient;
1545
+ /**
1546
+ * Base class for all UiPath SDK services.
1547
+ *
1548
+ * Provides common functionality for authentication, configuration, and API communication.
1549
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1550
+ *
1551
+ * This class implements the dependency injection pattern where services receive a configured
1552
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1553
+ * including authentication token management.
1554
+ *
1555
+ * @remarks
1556
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1557
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1558
+ *
1559
+ */
1560
+ class BaseService {
1561
+ /**
1562
+ * Creates a base service instance with dependency injection.
1563
+ *
1564
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1565
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1566
+ * and token management internally.
1567
+ *
1568
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1569
+ * Services receive this via dependency injection in the modular pattern.
1570
+ *
1571
+ * @example
1572
+ * ```typescript
1573
+ * // Services automatically call this via super()
1574
+ * export class EntityService extends BaseService {
1575
+ * constructor(instance: IUiPath) {
1576
+ * super(instance); // Initializes the internal ApiClient
1577
+ * }
1578
+ * }
1579
+ *
1580
+ * // Usage in modular pattern
1581
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1582
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1583
+ *
1584
+ * const sdk = new UiPath(config);
1585
+ * await sdk.initialize();
1586
+ * const entities = new Entities(sdk);
1587
+ * ```
1588
+ */
1589
+ constructor(instance) {
1590
+ // Private field - not visible via Object.keys() or any reflection
1591
+ _BaseService_apiClient.set(this, void 0);
1592
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1593
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1594
+ }
1595
+ /**
1596
+ * Gets a valid authentication token, refreshing if necessary.
1597
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1598
+ *
1599
+ * @returns Promise resolving to a valid access token string
1600
+ * @throws AuthenticationError if no token is available or refresh fails
1601
+ */
1602
+ async getValidAuthToken() {
1603
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1604
+ }
1605
+ /**
1606
+ * Creates a service accessor for pagination helpers
1607
+ * This allows pagination helpers to access protected methods without making them public
1608
+ */
1609
+ createPaginationServiceAccess() {
1610
+ return {
1611
+ get: (path, options) => this.get(path, options || {}),
1612
+ post: (path, body, options) => this.post(path, body, options || {}),
1613
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1614
+ };
1615
+ }
1616
+ async request(method, path, options = {}) {
1617
+ switch (method.toUpperCase()) {
1618
+ case 'GET':
1619
+ return this.get(path, options);
1620
+ case 'POST':
1621
+ return this.post(path, options.body, options);
1622
+ case 'PUT':
1623
+ return this.put(path, options.body, options);
1624
+ case 'PATCH':
1625
+ return this.patch(path, options.body, options);
1626
+ case 'DELETE':
1627
+ return this.delete(path, options);
1628
+ default:
1629
+ throw new Error(`Unsupported HTTP method: ${method}`);
1630
+ }
1631
+ }
1632
+ async requestWithSpec(spec) {
1633
+ if (!spec.method || !spec.url) {
1634
+ throw new Error('Request spec must include method and url');
1635
+ }
1636
+ return this.request(spec.method, spec.url, spec);
1637
+ }
1638
+ async get(path, options = {}) {
1639
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1640
+ return { data: response };
1641
+ }
1642
+ async post(path, data, options = {}) {
1643
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1644
+ return { data: response };
1645
+ }
1646
+ async put(path, data, options = {}) {
1647
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1648
+ return { data: response };
1649
+ }
1650
+ async patch(path, data, options = {}) {
1651
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1652
+ return { data: response };
1653
+ }
1654
+ async delete(path, options = {}) {
1655
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1656
+ return { data: response };
1657
+ }
1658
+ /**
1659
+ * Execute a request with cursor-based pagination
1660
+ */
1661
+ async requestWithPagination(method, path, paginationOptions, options) {
1662
+ const paginationType = options.pagination.paginationType;
1663
+ // Validate and prepare pagination parameters
1664
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1665
+ // Prepare request parameters based on pagination type
1666
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1667
+ // For POST requests, merge pagination params into body; for GET, use query params
1668
+ if (method.toUpperCase() === 'POST') {
1669
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1670
+ options.body = {
1671
+ ...existingBody,
1672
+ ...options.params,
1673
+ ...requestParams
1674
+ };
1675
+ }
1676
+ else {
1677
+ // Merge pagination parameters with existing parameters
1678
+ options.params = {
1679
+ ...options.params,
1680
+ ...requestParams
1681
+ };
1682
+ }
1683
+ // Make the request
1684
+ const response = await this.request(method, path, options);
1685
+ // Extract data from the response and create page result
1686
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1687
+ itemsField: options.pagination.itemsField,
1688
+ totalCountField: options.pagination.totalCountField,
1689
+ continuationTokenField: options.pagination.continuationTokenField
1690
+ });
1691
+ }
1692
+ /**
1693
+ * Validates and prepares pagination parameters from options
1694
+ */
1695
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1696
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1697
+ }
1698
+ /**
1699
+ * Prepares request parameters for pagination based on pagination type
1700
+ */
1701
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1702
+ const requestParams = {};
1703
+ let limitedPageSize;
1704
+ const paginationParams = paginationConfig?.paginationParams;
1705
+ switch (paginationType) {
1706
+ case PaginationType.OFFSET:
1707
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1708
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1709
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1710
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1711
+ requestParams[pageSizeParam] = limitedPageSize;
1712
+ if (params.pageNumber && params.pageNumber > 1) {
1713
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1714
+ }
1715
+ // Include total count for ODATA APIs
1716
+ {
1717
+ requestParams[countParam] = true;
1718
+ }
1719
+ break;
1720
+ case PaginationType.TOKEN:
1721
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1722
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1723
+ if (params.pageSize) {
1724
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1725
+ }
1726
+ if (params.continuationToken) {
1727
+ requestParams[tokenParam] = params.continuationToken;
1728
+ }
1729
+ break;
1730
+ }
1731
+ return requestParams;
1732
+ }
1733
+ /**
1734
+ * Creates a paginated response from API response
1735
+ */
1736
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1737
+ // Extract fields from response
1738
+ const itemsField = fields.itemsField ||
1739
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1740
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1741
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1742
+ // Extract items and metadata
1743
+ const items = response.data[itemsField] || [];
1744
+ const totalCount = response.data[totalCountField];
1745
+ const continuationToken = response.data[continuationTokenField];
1746
+ // Determine if there are more pages
1747
+ const hasMore = this.determineHasMorePages(paginationType, {
1748
+ totalCount,
1749
+ pageSize: params.pageSize,
1750
+ currentPage: params.pageNumber || 1,
1751
+ itemsCount: items.length,
1752
+ continuationToken
1753
+ });
1754
+ // Create and return the page result
1755
+ return PaginationManager.createPaginatedResponse({
1756
+ pageInfo: {
1757
+ hasMore,
1758
+ totalCount,
1759
+ currentPage: params.pageNumber,
1760
+ pageSize: params.pageSize,
1761
+ continuationToken
1762
+ },
1763
+ type: paginationType,
1764
+ }, items);
1765
+ }
1766
+ /**
1767
+ * Determines if there are more pages based on pagination type and metadata
1768
+ */
1769
+ determineHasMorePages(paginationType, info) {
1770
+ switch (paginationType) {
1771
+ case PaginationType.OFFSET:
1772
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1773
+ // If totalCount is available, use it for precise calculation
1774
+ if (info.totalCount !== undefined) {
1775
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1776
+ }
1777
+ // Fallback when totalCount is not available
1778
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1779
+ return info.itemsCount === effectivePageSize;
1780
+ case PaginationType.TOKEN:
1781
+ return !!info.continuationToken;
1782
+ default:
1783
+ return false;
1784
+ }
1785
+ }
1786
+ }
1787
+ _BaseService_apiClient = new WeakMap();
1788
+
1789
+ /**
1790
+ * API Endpoint Constants
1791
+ * Centralized location for all API endpoints used throughout the SDK
1792
+ */
1793
+ /**
1794
+ * Base path constants for different services
1795
+ */
1796
+ const ORCHESTRATOR_BASE = 'orchestrator_';
1797
+ const PIMS_BASE = 'pims_';
1798
+ /**
1799
+ * Maestro Process Service Endpoints
1800
+ */
1801
+ const MAESTRO_ENDPOINTS = {
1802
+ PROCESSES: {
1803
+ GET_ALL: `${PIMS_BASE}/api/v1/processes/summary`,
1804
+ GET_SETTINGS: (processKey) => `${PIMS_BASE}/api/v1/processes/${processKey}/settings`,
1805
+ },
1806
+ INSTANCES: {
1807
+ GET_ALL: `${PIMS_BASE}/api/v1/instances`,
1808
+ GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
1809
+ GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
1810
+ GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
1811
+ GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
1812
+ CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
1813
+ PAUSE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/pause`,
1814
+ RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
1815
+ },
1816
+ INCIDENTS: {
1817
+ GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
1818
+ GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
1819
+ GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
1820
+ },
1821
+ CASES: {
1822
+ GET_CASE_JSON: (instanceId) => `${PIMS_BASE}/api/v1/cases/${instanceId}/case-json`,
1823
+ GET_ELEMENT_EXECUTIONS: (instanceId) => `${PIMS_BASE}/api/v1/element-executions/case-instances/${instanceId}`,
1824
+ REOPEN: (instanceId) => `${PIMS_BASE}/api/v1/cases/${instanceId}/reopen`,
1825
+ },
1826
+ };
1827
+ /**
1828
+ * Task Service (Action Center) Endpoints
1829
+ */
1830
+ const TASK_ENDPOINTS = {
1831
+ CREATE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CreateTask`,
1832
+ GET_TASK_USERS: (folderId) => `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTaskUsers(organizationUnitId=${folderId})`,
1833
+ GET_TASKS_ACROSS_FOLDERS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFolders`,
1834
+ GET_TASKS_ACROSS_FOLDERS_ADMIN: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFoldersForAdmin`,
1835
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Tasks(${id})`,
1836
+ ASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.AssignTasks`,
1837
+ REASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.ReassignTasks`,
1838
+ UNASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.UnassignTasks`,
1839
+ COMPLETE_FORM_TASK: `${ORCHESTRATOR_BASE}/forms/TaskForms/CompleteTask`,
1840
+ COMPLETE_APP_TASK: `${ORCHESTRATOR_BASE}/tasks/AppTasks/CompleteAppTask`,
1841
+ COMPLETE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CompleteTask`,
1842
+ GET_TASK_FORM_BY_ID: `${ORCHESTRATOR_BASE}/forms/TaskForms/GetTaskFormById`,
1843
+ };
1844
+
1845
+ /**
1846
+ * SDK Telemetry constants
1847
+ */
1848
+ // Connection string placeholder that will be replaced during build
1849
+ 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";
1850
+ // SDK Version placeholder
1851
+ const SDK_VERSION = "1.0.0";
1852
+ const VERSION = "Version";
1853
+ const SERVICE = "Service";
1854
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1855
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1856
+ const CLOUD_URL = "CloudUrl";
1857
+ const CLOUD_CLIENT_ID = "CloudClientId";
1858
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1859
+ const APP_NAME = "ApplicationName";
1860
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1861
+ // Service and logger names
1862
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1863
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1864
+ // Event names
1865
+ const SDK_RUN_EVENT = "Sdk.Run";
1866
+ // Default value for unknown/empty attributes
1867
+ const UNKNOWN = "";
1868
+
1869
+ /**
1870
+ * Log exporter that sends ALL logs as Application Insights custom events
1871
+ */
1872
+ class ApplicationInsightsEventExporter {
1873
+ constructor(connectionString) {
1874
+ this.connectionString = connectionString;
1875
+ }
1876
+ export(logs, resultCallback) {
1877
+ try {
1878
+ logs.forEach(logRecord => {
1879
+ this.sendAsCustomEvent(logRecord);
1880
+ });
1881
+ resultCallback({ code: 0 });
1882
+ }
1883
+ catch (error) {
1884
+ console.debug('Failed to export logs to Application Insights:', error);
1885
+ resultCallback({ code: 2, error });
1886
+ }
1887
+ }
1888
+ shutdown() {
1889
+ return Promise.resolve();
1890
+ }
1891
+ sendAsCustomEvent(logRecord) {
1892
+ // Get event name from body or attributes
1893
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1894
+ const payload = {
1895
+ name: 'Microsoft.ApplicationInsights.Event',
1896
+ time: new Date().toISOString(),
1897
+ iKey: this.extractInstrumentationKey(),
1898
+ data: {
1899
+ baseType: 'EventData',
1900
+ baseData: {
1901
+ ver: 2,
1902
+ name: eventName,
1903
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1904
+ }
1905
+ },
1906
+ tags: {
1907
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1908
+ 'ai.cloud.roleInstance': SDK_VERSION
1909
+ }
1910
+ };
1911
+ this.sendToApplicationInsights(payload);
1912
+ }
1913
+ extractInstrumentationKey() {
1914
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1915
+ return match ? match[1] : '';
1916
+ }
1917
+ convertAttributesToProperties(attributes) {
1918
+ const properties = {};
1919
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1920
+ properties[key] = String(value);
1921
+ });
1922
+ return properties;
1923
+ }
1924
+ async sendToApplicationInsights(payload) {
1925
+ try {
1926
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1927
+ if (!ingestionEndpoint) {
1928
+ console.debug('No ingestion endpoint found in connection string');
1929
+ return;
1930
+ }
1931
+ const url = `${ingestionEndpoint}/v2/track`;
1932
+ const response = await fetch(url, {
1933
+ method: 'POST',
1934
+ headers: {
1935
+ 'Content-Type': 'application/json',
1936
+ },
1937
+ body: JSON.stringify(payload)
1938
+ });
1939
+ if (!response.ok) {
1940
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1941
+ }
1942
+ }
1943
+ catch (error) {
1944
+ console.debug('Error sending event telemetry to Application Insights:', error);
1945
+ }
1946
+ }
1947
+ extractIngestionEndpoint() {
1948
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1949
+ return match ? match[1] : '';
1950
+ }
1951
+ }
1952
+ /**
1953
+ * Singleton telemetry client
1954
+ */
1955
+ class TelemetryClient {
1956
+ constructor() {
1957
+ this.isInitialized = false;
1958
+ }
1959
+ static getInstance() {
1960
+ if (!TelemetryClient.instance) {
1961
+ TelemetryClient.instance = new TelemetryClient();
1962
+ }
1963
+ return TelemetryClient.instance;
1964
+ }
1965
+ /**
1966
+ * Initialize telemetry
1967
+ */
1968
+ initialize(config) {
1969
+ if (this.isInitialized) {
1970
+ return;
1971
+ }
1972
+ this.isInitialized = true;
1973
+ if (config) {
1974
+ this.telemetryContext = config;
1975
+ }
1976
+ try {
1977
+ const connectionString = this.getConnectionString();
1978
+ if (!connectionString) {
1979
+ return;
1980
+ }
1981
+ this.setupTelemetryProvider(connectionString);
1982
+ }
1983
+ catch (error) {
1984
+ // Silent failure - telemetry errors shouldn't break functionality
1985
+ console.debug('Failed to initialize OpenTelemetry:', error);
1986
+ }
1987
+ }
1988
+ getConnectionString() {
1989
+ const connectionString = CONNECTION_STRING;
1990
+ return connectionString;
1991
+ }
1992
+ setupTelemetryProvider(connectionString) {
1993
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
1994
+ const processor = new BatchLogRecordProcessor(exporter);
1995
+ this.logProvider = new LoggerProvider({
1996
+ processors: [processor]
1997
+ });
1998
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1999
+ }
2000
+ /**
2001
+ * Track a telemetry event
2002
+ */
2003
+ track(eventName, name, extraAttributes = {}) {
2004
+ try {
2005
+ // Skip if logger not initialized
2006
+ if (!this.logger) {
2007
+ return;
2008
+ }
2009
+ const finalDisplayName = name || eventName;
2010
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
2011
+ // Emit as log
2012
+ this.logger.emit({
2013
+ body: finalDisplayName,
2014
+ attributes: attributes,
2015
+ timestamp: Date.now(),
2016
+ });
2017
+ }
2018
+ catch (error) {
2019
+ // Silent failure
2020
+ console.debug('Failed to track telemetry event:', error);
2021
+ }
2022
+ }
2023
+ /**
2024
+ * Get enriched attributes for telemetry events
2025
+ */
2026
+ getEnrichedAttributes(extraAttributes, eventName) {
2027
+ const attributes = {
2028
+ ...extraAttributes,
2029
+ [APP_NAME]: SDK_SERVICE_NAME,
2030
+ [VERSION]: SDK_VERSION,
2031
+ [SERVICE]: eventName,
2032
+ [CLOUD_URL]: this.createCloudUrl(),
2033
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
2034
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
2035
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
2036
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
2037
+ };
2038
+ return attributes;
2039
+ }
2040
+ /**
2041
+ * Create cloud URL from base URL, organization ID, and tenant ID
2042
+ */
2043
+ createCloudUrl() {
2044
+ const baseUrl = this.telemetryContext?.baseUrl;
2045
+ const orgId = this.telemetryContext?.orgName;
2046
+ const tenantId = this.telemetryContext?.tenantName;
2047
+ if (!baseUrl || !orgId || !tenantId) {
2048
+ return UNKNOWN;
2049
+ }
2050
+ return `${baseUrl}/${orgId}/${tenantId}`;
2051
+ }
2052
+ }
2053
+ // Export singleton instance
2054
+ const telemetryClient = TelemetryClient.getInstance();
2055
+
2056
+ /**
2057
+ * SDK Track decorator and function for telemetry
2058
+ */
2059
+ /**
2060
+ * Common tracking logic shared between method and function decorators
2061
+ */
2062
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
2063
+ return function (...args) {
2064
+ // Determine if we should track this call
2065
+ let shouldTrack = true;
2066
+ if (opts.condition !== undefined) {
2067
+ if (typeof opts.condition === 'function') {
2068
+ shouldTrack = opts.condition.apply(this, args);
2069
+ }
2070
+ else {
2071
+ shouldTrack = opts.condition;
2072
+ }
2073
+ }
2074
+ // Track the event if enabled
2075
+ if (shouldTrack) {
2076
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
2077
+ const serviceMethod = typeof nameOrOptions === 'string'
2078
+ ? nameOrOptions
2079
+ : fallbackName;
2080
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
2081
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
2082
+ }
2083
+ // Execute the original function
2084
+ return originalFunction.apply(this, args);
2085
+ };
2086
+ }
2087
+ /**
2088
+ * Track decorator that can be used to automatically track function calls
2089
+ *
2090
+ * Usage:
2091
+ * @track("Service.Method")
2092
+ * function myFunction() { ... }
2093
+ *
2094
+ * @track("Queue.GetAll")
2095
+ * async getAll() { ... }
2096
+ *
2097
+ * @track("Tasks.Create")
2098
+ * async create() { ... }
2099
+ *
2100
+ * @track("Assets.Update", { condition: false })
2101
+ * function myFunction() { ... }
2102
+ *
2103
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
2104
+ * function myFunction() { ... }
2105
+ */
2106
+ function track(nameOrOptions, options) {
2107
+ return function decorator(_target, propertyKey, descriptor) {
2108
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
2109
+ if (descriptor && typeof descriptor.value === 'function') {
2110
+ // Method decorator
2111
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
2112
+ return descriptor;
2113
+ }
2114
+ // Function decorator
2115
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2116
+ };
2117
+ }
2118
+
2119
+ /**
2120
+ * Creates query parameters object from key-value pairs, filtering out undefined values
2121
+ * @param paramsObj - Object containing parameter key-value pairs
2122
+ * @returns Parameters object with undefined values filtered out
2123
+ *
2124
+ * @example
2125
+ * ```typescript
2126
+ * // Entity service parameters
2127
+ * const params = createParams({
2128
+ * start: 0,
2129
+ * limit: 10,
2130
+ * expansionLevel: 1
2131
+ * });
2132
+ *
2133
+ * // With optional/undefined values (automatically filtered)
2134
+ * const params = createParams({
2135
+ * start: options.start, // Could be undefined
2136
+ * limit: options.limit, // Could be undefined
2137
+ * expansionLevel: options.expansionLevel // Could be undefined
2138
+ * });
2139
+ *
2140
+ * // Empty params
2141
+ * const params = createParams();
2142
+ * ```
2143
+ */
2144
+ function createParams(paramsObj = {}) {
2145
+ const params = {};
2146
+ for (const [key, value] of Object.entries(paramsObj)) {
2147
+ if (value !== undefined && value !== null) {
2148
+ params[key] = value;
2149
+ }
2150
+ }
2151
+ return params;
2152
+ }
2153
+
2154
+ /**
2155
+ * Service for interacting with UiPath Maestro Cases
2156
+ */
2157
+ class CasesService extends BaseService {
2158
+ /**
2159
+ * Get all case management processes with their instance statistics
2160
+ * @returns Promise resolving to array of Case objects
2161
+ *
2162
+ * @example
2163
+ * ```typescript
2164
+ * import { Cases } from '@uipath/uipath-typescript/cases';
2165
+ *
2166
+ * const cases = new Cases(sdk);
2167
+ * const allCases = await cases.getAll();
2168
+ *
2169
+ * // Access case information
2170
+ * for (const caseProcess of allCases) {
2171
+ * console.log(`Case Process: ${caseProcess.processKey}`);
2172
+ * console.log(`Running instances: ${caseProcess.runningCount}`);
2173
+ * console.log(`Completed instances: ${caseProcess.completedCount}`);
2174
+ * }
2175
+ * ```
2176
+ */
2177
+ async getAll() {
2178
+ const params = createParams({
2179
+ processType: ProcessType.CaseManagement
2180
+ });
2181
+ const response = await this.get(MAESTRO_ENDPOINTS.PROCESSES.GET_ALL, { params });
2182
+ // Extract processes array from response data and add name field
2183
+ const cases = response.data?.processes || [];
2184
+ return cases.map(caseItem => ({
2185
+ ...caseItem,
2186
+ name: this.extractCaseName(caseItem.packageId)
2187
+ }));
2188
+ }
2189
+ /**
2190
+ * Extract a readable case name from the packageId
2191
+ * @param packageId - The full package identifier
2192
+ * @returns A human-readable case name
2193
+ * @private
2194
+ */
2195
+ extractCaseName(packageId) {
2196
+ // Check if packageId contains "CaseManagement."
2197
+ const caseManagementIndex = packageId.indexOf('CaseManagement.');
2198
+ if (caseManagementIndex !== -1) {
2199
+ // Extract everything after "CaseManagement."
2200
+ const afterCaseManagement = packageId.substring(caseManagementIndex + 'CaseManagement.'.length);
2201
+ // Replace hyphens with spaces for better readability
2202
+ return afterCaseManagement.replace(/-/g, ' ');
2203
+ }
2204
+ // If no "CaseManagement.", return the whole packageId
2205
+ return packageId;
2206
+ }
2207
+ }
2208
+ __decorate([
2209
+ track('Cases.GetAll')
2210
+ ], CasesService.prototype, "getAll", null);
2211
+
2212
+ /**
2213
+ * Process Incident Status
2214
+ */
2215
+ var ProcessIncidentStatus;
2216
+ (function (ProcessIncidentStatus) {
2217
+ ProcessIncidentStatus["Open"] = "Open";
2218
+ ProcessIncidentStatus["Closed"] = "Closed";
2219
+ })(ProcessIncidentStatus || (ProcessIncidentStatus = {}));
2220
+ /**
2221
+ * Process Incident Type
2222
+ */
2223
+ var ProcessIncidentType;
2224
+ (function (ProcessIncidentType) {
2225
+ ProcessIncidentType["System"] = "System";
2226
+ ProcessIncidentType["User"] = "User";
2227
+ ProcessIncidentType["Deployment"] = "Deployment";
2228
+ })(ProcessIncidentType || (ProcessIncidentType = {}));
2229
+ /**
2230
+ * Process Incident Severity
2231
+ */
2232
+ var ProcessIncidentSeverity;
2233
+ (function (ProcessIncidentSeverity) {
2234
+ ProcessIncidentSeverity["Error"] = "Error";
2235
+ ProcessIncidentSeverity["Warning"] = "Warning";
2236
+ })(ProcessIncidentSeverity || (ProcessIncidentSeverity = {}));
2237
+ /**
2238
+ * Process Incident Debug Mode
2239
+ */
2240
+ var DebugMode;
2241
+ (function (DebugMode) {
2242
+ DebugMode["None"] = "None";
2243
+ DebugMode["Default"] = "Default";
2244
+ DebugMode["StepByStep"] = "StepByStep";
2245
+ DebugMode["SingleStep"] = "SingleStep";
2246
+ })(DebugMode || (DebugMode = {}));
2247
+
2248
+ /**
2249
+ * Case Instance Types
2250
+ * Types and interfaces for Maestro case instance management
2251
+ */
2252
+ /**
2253
+ * Case stage task type
2254
+ */
2255
+ var StageTaskType;
2256
+ (function (StageTaskType) {
2257
+ StageTaskType["EXTERNAL_AGENT"] = "external-agent";
2258
+ StageTaskType["RPA"] = "rpa";
2259
+ StageTaskType["AGENTIC_PROCESS"] = "process";
2260
+ StageTaskType["AGENT"] = "agent";
2261
+ StageTaskType["ACTION"] = "action";
2262
+ StageTaskType["API_WORKFLOW"] = "api-workflow";
2263
+ })(StageTaskType || (StageTaskType = {}));
2264
+ /**
2265
+ * Escalation recipient scope
2266
+ */
2267
+ var EscalationRecipientScope;
2268
+ (function (EscalationRecipientScope) {
2269
+ EscalationRecipientScope["USER"] = "user";
2270
+ EscalationRecipientScope["USER_GROUP"] = "usergroup";
2271
+ })(EscalationRecipientScope || (EscalationRecipientScope = {}));
2272
+ /**
2273
+ * Escalation action type
2274
+ */
2275
+ var EscalationActionType;
2276
+ (function (EscalationActionType) {
2277
+ EscalationActionType["NOTIFICATION"] = "notification";
2278
+ })(EscalationActionType || (EscalationActionType = {}));
2279
+ /**
2280
+ * Escalation rule trigger type
2281
+ */
2282
+ var EscalationTriggerType;
2283
+ (function (EscalationTriggerType) {
2284
+ EscalationTriggerType["SLA_BREACHED"] = "sla-breached";
2285
+ EscalationTriggerType["AT_RISK"] = "at-risk";
2286
+ })(EscalationTriggerType || (EscalationTriggerType = {}));
2287
+ /**
2288
+ * SLA duration unit
2289
+ */
2290
+ var SLADurationUnit;
2291
+ (function (SLADurationUnit) {
2292
+ SLADurationUnit["HOURS"] = "h";
2293
+ SLADurationUnit["DAYS"] = "d";
2294
+ SLADurationUnit["WEEKS"] = "w";
2295
+ SLADurationUnit["MONTHS"] = "m";
2296
+ })(SLADurationUnit || (SLADurationUnit = {}));
2297
+
2298
+ /**
2299
+ * Creates methods for a case instance
2300
+ *
2301
+ * @param instanceData - The case instance data (response from API)
2302
+ * @param service - The case instance service instance
2303
+ * @returns Object containing case instance methods
2304
+ */
2305
+ function createCaseInstanceMethods(instanceData, service) {
2306
+ return {
2307
+ async close(options) {
2308
+ if (!instanceData.instanceId)
2309
+ throw new Error('Case instance ID is undefined');
2310
+ if (!instanceData.folderKey)
2311
+ throw new Error('Case instance folder key is undefined');
2312
+ return service.close(instanceData.instanceId, instanceData.folderKey, options);
2313
+ },
2314
+ async pause(options) {
2315
+ if (!instanceData.instanceId)
2316
+ throw new Error('Case instance ID is undefined');
2317
+ if (!instanceData.folderKey)
2318
+ throw new Error('Case instance folder key is undefined');
2319
+ return service.pause(instanceData.instanceId, instanceData.folderKey, options);
2320
+ },
2321
+ async reopen(options) {
2322
+ if (!instanceData.instanceId)
2323
+ throw new Error('Case instance ID is undefined');
2324
+ if (!instanceData.folderKey)
2325
+ throw new Error('Case instance folder key is undefined');
2326
+ return service.reopen(instanceData.instanceId, instanceData.folderKey, options);
2327
+ },
2328
+ async resume(options) {
2329
+ if (!instanceData.instanceId)
2330
+ throw new Error('Case instance ID is undefined');
2331
+ if (!instanceData.folderKey)
2332
+ throw new Error('Case instance folder key is undefined');
2333
+ return service.resume(instanceData.instanceId, instanceData.folderKey, options);
2334
+ },
2335
+ async getExecutionHistory() {
2336
+ if (!instanceData.instanceId)
2337
+ throw new Error('Case instance ID is undefined');
2338
+ if (!instanceData.folderKey)
2339
+ throw new Error('Case instance folder key is undefined');
2340
+ return service.getExecutionHistory(instanceData.instanceId, instanceData.folderKey);
2341
+ },
2342
+ async getStages() {
2343
+ if (!instanceData.instanceId)
2344
+ throw new Error('Case instance ID is undefined');
2345
+ if (!instanceData.folderKey)
2346
+ throw new Error('Case instance folder key is undefined');
2347
+ return service.getStages(instanceData.instanceId, instanceData.folderKey);
2348
+ },
2349
+ async getActionTasks(options) {
2350
+ if (!instanceData.instanceId)
2351
+ throw new Error('Case instance ID is undefined');
2352
+ return service.getActionTasks(instanceData.instanceId, options);
2353
+ }
2354
+ };
2355
+ }
2356
+ /**
2357
+ * Creates an actionable case instance by combining API case instance data with operational methods.
2358
+ *
2359
+ * @param instanceData - The case instance data from API
2360
+ * @param service - The case instance service instance
2361
+ * @returns A case instance object with added methods
2362
+ */
2363
+ function createCaseInstanceWithMethods(instanceData, service) {
2364
+ const methods = createCaseInstanceMethods(instanceData, service);
2365
+ return Object.assign({}, instanceData, methods);
2366
+ }
2367
+
2368
+ /**
2369
+ * Maps fields for Case Instance entities to ensure consistent naming
2370
+ */
2371
+ const CaseInstanceMap = {
2372
+ startedTimeUtc: 'startedTime',
2373
+ completedTimeUtc: 'completedTime',
2374
+ expiryTimeUtc: 'expiredTime',
2375
+ createdAt: 'createdTime',
2376
+ updatedAt: 'updatedTime',
2377
+ externalId: 'caseId',
2378
+ };
2379
+ /**
2380
+ * Maps fields for Case App Config
2381
+ */
2382
+ const CaseAppConfigMap = {
2383
+ sections: 'overview',
2384
+ };
2385
+ /**
2386
+ * Maps fields for Stage SLA configuration
2387
+ */
2388
+ const StageSLAMap = {
2389
+ count: 'length',
2390
+ unit: 'duration',
2391
+ };
2392
+ /**
2393
+ * Maps UTC time fields to simpler field names
2394
+ * Used for transforming execution history responses
2395
+ */
2396
+ const TimeFieldTransformMap = {
2397
+ startedTimeUtc: 'startedTime',
2398
+ completedTimeUtc: 'completedTime',
2399
+ };
2400
+ /**
2401
+ * Constants for case instance stage processing
2402
+ */
2403
+ const CASE_STAGE_CONSTANTS = {
2404
+ TRIGGER_NODE_TYPE: 'case-management:Trigger',
2405
+ UNDEFINED_VALUE: 'Undefined',
2406
+ NOT_STARTED_STATUS: 'Not Started'
2407
+ };
2408
+ /**
2409
+ * Function to generate case instance task filter by case instance ID
2410
+ */
2411
+ const CASE_INSTANCE_TASK_FILTER = (caseInstanceId) => `Tags/any(tags:tags/DisplayName eq '${caseInstanceId}') and (IsDeleted eq false)`;
2412
+ /**
2413
+ * Default expand parameters for case instance tasks
2414
+ */
2415
+ const CASE_INSTANCE_TASK_EXPAND = 'AssignedToUser,Activities';
2416
+
2417
+ var TaskType;
2418
+ (function (TaskType) {
2419
+ TaskType["Form"] = "FormTask";
2420
+ TaskType["External"] = "ExternalTask";
2421
+ TaskType["App"] = "AppTask";
2422
+ })(TaskType || (TaskType = {}));
2423
+ var TaskPriority;
2424
+ (function (TaskPriority) {
2425
+ TaskPriority["Low"] = "Low";
2426
+ TaskPriority["Medium"] = "Medium";
2427
+ TaskPriority["High"] = "High";
2428
+ TaskPriority["Critical"] = "Critical";
2429
+ })(TaskPriority || (TaskPriority = {}));
2430
+ var TaskStatus;
2431
+ (function (TaskStatus) {
2432
+ TaskStatus["Unassigned"] = "Unassigned";
2433
+ TaskStatus["Pending"] = "Pending";
2434
+ TaskStatus["Completed"] = "Completed";
2435
+ })(TaskStatus || (TaskStatus = {}));
2436
+ var TaskSlaCriteria;
2437
+ (function (TaskSlaCriteria) {
2438
+ TaskSlaCriteria["TaskCreated"] = "TaskCreated";
2439
+ TaskSlaCriteria["TaskAssigned"] = "TaskAssigned";
2440
+ TaskSlaCriteria["TaskCompleted"] = "TaskCompleted";
2441
+ })(TaskSlaCriteria || (TaskSlaCriteria = {}));
2442
+ var TaskSlaStatus;
2443
+ (function (TaskSlaStatus) {
2444
+ TaskSlaStatus["OverdueLater"] = "OverdueLater";
2445
+ TaskSlaStatus["OverdueSoon"] = "OverdueSoon";
2446
+ TaskSlaStatus["Overdue"] = "Overdue";
2447
+ TaskSlaStatus["CompletedInTime"] = "CompletedInTime";
2448
+ })(TaskSlaStatus || (TaskSlaStatus = {}));
2449
+ var TaskSourceName;
2450
+ (function (TaskSourceName) {
2451
+ TaskSourceName["Agent"] = "Agent";
2452
+ TaskSourceName["Workflow"] = "Workflow";
2453
+ TaskSourceName["Maestro"] = "Maestro";
2454
+ TaskSourceName["Default"] = "Default";
2455
+ })(TaskSourceName || (TaskSourceName = {}));
2456
+ /**
2457
+ * Task activity types
2458
+ */
2459
+ var TaskActivityType;
2460
+ (function (TaskActivityType) {
2461
+ TaskActivityType["Created"] = "Created";
2462
+ TaskActivityType["Assigned"] = "Assigned";
2463
+ TaskActivityType["Reassigned"] = "Reassigned";
2464
+ TaskActivityType["Unassigned"] = "Unassigned";
2465
+ TaskActivityType["Saved"] = "Saved";
2466
+ TaskActivityType["Forwarded"] = "Forwarded";
2467
+ TaskActivityType["Completed"] = "Completed";
2468
+ TaskActivityType["Commented"] = "Commented";
2469
+ TaskActivityType["Deleted"] = "Deleted";
2470
+ TaskActivityType["BulkSaved"] = "BulkSaved";
2471
+ TaskActivityType["BulkCompleted"] = "BulkCompleted";
2472
+ TaskActivityType["FirstOpened"] = "FirstOpened";
2473
+ })(TaskActivityType || (TaskActivityType = {}));
2474
+
2475
+ /**
2476
+ * Creates methods for a task
2477
+ *
2478
+ * @param taskData - The task data (response from API)
2479
+ * @param service - The task service instance
2480
+ * @returns Object containing task methods
2481
+ */
2482
+ function createTaskMethods(taskData, service) {
2483
+ return {
2484
+ async assign(options) {
2485
+ if (!taskData.id)
2486
+ throw new Error('Task ID is undefined');
2487
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
2488
+ ? { taskId: taskData.id, userId: options.userId }
2489
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
2490
+ return service.assign(assignmentOptions);
2491
+ },
2492
+ async reassign(options) {
2493
+ if (!taskData.id)
2494
+ throw new Error('Task ID is undefined');
2495
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
2496
+ ? { taskId: taskData.id, userId: options.userId }
2497
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
2498
+ return service.reassign(assignmentOptions);
2499
+ },
2500
+ async unassign() {
2501
+ if (!taskData.id)
2502
+ throw new Error('Task ID is undefined');
2503
+ return service.unassign(taskData.id);
2504
+ },
2505
+ async complete(options) {
2506
+ if (!taskData.id)
2507
+ throw new Error('Task ID is undefined');
2508
+ const folderId = taskData.folderId;
2509
+ if (!folderId)
2510
+ throw new Error('Folder ID is required');
2511
+ return service.complete({
2512
+ type: options.type,
2513
+ taskId: taskData.id,
2514
+ data: options.data,
2515
+ action: options.action
2516
+ }, folderId);
2517
+ }
2518
+ };
2519
+ }
2520
+ /**
2521
+ * Creates an actionable task by combining API task data with operational methods.
2522
+ *
2523
+ * @param taskData - The task data from API
2524
+ * @param service - The task service instance
2525
+ * @returns A task object with added methods
2526
+ */
2527
+ function createTaskWithMethods(taskData, service) {
2528
+ const methods = createTaskMethods(taskData, service);
2529
+ return Object.assign({}, taskData, methods);
2530
+ }
2531
+
2532
+ /**
2533
+ * Maps numeric TaskStatus values (from API) to TaskStatus enum values.
2534
+ * Extend this file with additional field mappings as needed.
2535
+ */
2536
+ const TaskStatusMap = {
2537
+ 0: TaskStatus.Unassigned,
2538
+ 1: TaskStatus.Pending,
2539
+ 2: TaskStatus.Completed,
2540
+ };
2541
+ // Field mapping for time-related fields to ensure consistent naming
2542
+ const TaskMap = {
2543
+ completionTime: 'completedTime',
2544
+ deletionTime: 'deletedTime',
2545
+ lastModificationTime: 'lastModifiedTime',
2546
+ creationTime: 'createdTime',
2547
+ organizationUnitId: 'folderId'
2548
+ };
2549
+ /**
2550
+ * Default expand parameters
2551
+ */
2552
+ const DEFAULT_TASK_EXPAND = 'AssignedToUser,CreatorUser,LastModifierUser';
2553
+
2554
+ /**
2555
+ * Service for interacting with UiPath Tasks API
2556
+ */
2557
+ class TaskService extends BaseService {
2558
+ constructor() {
2559
+ super(...arguments);
2560
+ /**
2561
+ * Process parameters for task queries with folder filtering
2562
+ * @param options - The REST API options to process
2563
+ * @param folderId - Optional folder ID to filter by
2564
+ * @returns Processed options with folder filtering applied if needed
2565
+ * @private
2566
+ */
2567
+ this.processTaskParameters = (options, folderId) => {
2568
+ // Add default expand parameters
2569
+ const processedOptions = this.addDefaultExpand(options);
2570
+ if (folderId) {
2571
+ // Create or add to existing filter for folder-specific queries
2572
+ if (processedOptions.filter) {
2573
+ processedOptions.filter = `${processedOptions.filter} and organizationUnitId eq ${folderId}`;
2574
+ }
2575
+ else {
2576
+ processedOptions.filter = `organizationUnitId eq ${folderId}`;
2577
+ }
2578
+ }
2579
+ return processedOptions;
2580
+ };
2581
+ }
2582
+ /**
2583
+ * Creates a new task
2584
+ * @param task - The task to be created
2585
+ * @param folderId - Required folder ID
2586
+ * @returns Promise resolving to the created task
2587
+ *
2588
+ * @example
2589
+ * ```typescript
2590
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2591
+ *
2592
+ * const tasks = new Tasks(sdk);
2593
+ * const task = await tasks.create({
2594
+ * title: "My Task",
2595
+ * priority: TaskPriority.Medium,
2596
+ * data: { key: "value" }
2597
+ * }, 123); // folderId is required
2598
+ * ```
2599
+ */
2600
+ async create(task, folderId) {
2601
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2602
+ const externalTask = {
2603
+ ...task,
2604
+ type: TaskType.External //currently only external task is supported
2605
+ };
2606
+ const response = await this.post(TASK_ENDPOINTS.CREATE_GENERIC_TASK, externalTask, { headers });
2607
+ // Transform time fields for consistency
2608
+ const normalizedData = transformData(response.data, TaskMap);
2609
+ const transformedData = applyDataTransforms(normalizedData, { field: 'status', valueMap: TaskStatusMap });
2610
+ return createTaskWithMethods(transformedData, this);
2611
+ }
2612
+ /**
2613
+ * Gets users in the given folder who have Tasks.View and Tasks.Edit permissions
2614
+ *
2615
+ * The method returns either:
2616
+ * - An array of users (when no pagination parameters are provided)
2617
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
2618
+ *
2619
+ * @param folderId - The folder ID to get users from
2620
+ * @param options - Optional query and pagination parameters
2621
+ * @returns Promise resolving to an array of users or paginated result
2622
+ *
2623
+ * @example
2624
+ * ```typescript
2625
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2626
+ *
2627
+ * const tasks = new Tasks(sdk);
2628
+ *
2629
+ * // Standard array return
2630
+ * const users = await tasks.getUsers(123);
2631
+ *
2632
+ * // Get users with filtering
2633
+ * const users = await tasks.getUsers(123, {
2634
+ * filter: "name eq 'abc'"
2635
+ * });
2636
+ *
2637
+ * // First page with pagination
2638
+ * const page1 = await tasks.getUsers(123, { pageSize: 10 });
2639
+ *
2640
+ * // Navigate using cursor
2641
+ * if (page1.hasNextPage) {
2642
+ * const page2 = await tasks.getUsers(123, { cursor: page1.nextCursor });
2643
+ * }
2644
+ *
2645
+ * // Jump to specific page
2646
+ * const page5 = await tasks.getUsers(123, {
2647
+ * jumpToPage: 5,
2648
+ * pageSize: 10
2649
+ * });
2650
+ * ```
2651
+ */
2652
+ async getUsers(folderId, options) {
2653
+ // Transformation function for users
2654
+ const transformUserResponse = (user) => pascalToCamelCaseKeys(user);
2655
+ // Add folderId to options so the centralized helper can handle it properly
2656
+ const optionsWithFolder = { ...options, folderId };
2657
+ return PaginationHelpers.getAll({
2658
+ serviceAccess: this.createPaginationServiceAccess(),
2659
+ getEndpoint: (folderId) => TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use folderId from centralized helper
2660
+ getByFolderEndpoint: TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use the passed folderId
2661
+ transformFn: transformUserResponse,
2662
+ pagination: {
2663
+ paginationType: PaginationType.OFFSET,
2664
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2665
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2666
+ paginationParams: {
2667
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2668
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
2669
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
2670
+ }
2671
+ }
2672
+ }, optionsWithFolder);
2673
+ }
2674
+ /**
2675
+ * Gets tasks across folders with optional filtering and folder scoping
2676
+ *
2677
+ * The method returns either:
2678
+ * - An array of tasks (when no pagination parameters are provided)
2679
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
2680
+ *
2681
+ * @param options - Query options including optional folderId, asTaskAdmin flag and pagination options
2682
+ * @returns Promise resolving to an array of tasks or paginated result
2683
+ *
2684
+ * @example
2685
+ * ```typescript
2686
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2687
+ *
2688
+ * const tasks = new Tasks(sdk);
2689
+ *
2690
+ * // Standard array return
2691
+ * const allTasks = await tasks.getAll();
2692
+ *
2693
+ * // Get tasks within a specific folder
2694
+ * const folderTasks = await tasks.getAll({
2695
+ * folderId: 123
2696
+ * });
2697
+ *
2698
+ * // Get tasks with admin permissions
2699
+ * const adminTasks = await tasks.getAll({
2700
+ * asTaskAdmin: true
2701
+ * });
2702
+ *
2703
+ * // First page with pagination
2704
+ * const page1 = await tasks.getAll({ pageSize: 10 });
2705
+ *
2706
+ * // Navigate using cursor
2707
+ * if (page1.hasNextPage) {
2708
+ * const page2 = await tasks.getAll({ cursor: page1.nextCursor });
2709
+ * }
2710
+ *
2711
+ * // Jump to specific page
2712
+ * const page5 = await tasks.getAll({
2713
+ * jumpToPage: 5,
2714
+ * pageSize: 10
2715
+ * });
2716
+ * ```
2717
+ */
2718
+ async getAll(options) {
2719
+ // Determine which endpoint to use based on asTaskAdmin flag
2720
+ const endpoint = options?.asTaskAdmin
2721
+ ? TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS_ADMIN
2722
+ : TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS;
2723
+ // Transformation function for tasks
2724
+ const transformTaskResponse = (task) => {
2725
+ const transformedTask = transformData(pascalToCamelCaseKeys(task), TaskMap);
2726
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
2727
+ };
2728
+ return PaginationHelpers.getAll({
2729
+ serviceAccess: this.createPaginationServiceAccess(),
2730
+ getEndpoint: () => endpoint,
2731
+ transformFn: transformTaskResponse,
2732
+ processParametersFn: this.processTaskParameters,
2733
+ excludeFromPrefix: ['event'], // Exclude 'event' key from ODATA prefix transformation
2734
+ pagination: {
2735
+ paginationType: PaginationType.OFFSET,
2736
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2737
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2738
+ paginationParams: {
2739
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM, // OData OFFSET parameter
2740
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM, // OData OFFSET parameter
2741
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM // OData OFFSET parameter
2742
+ }
2743
+ }
2744
+ }, options);
2745
+ }
2746
+ /**
2747
+ * Gets a task by ID
2748
+ * IMPORTANT: For form tasks, folderId must be provided.
2749
+ *
2750
+ * @param id - The ID of the task to retrieve
2751
+ * @param options - Optional query parameters
2752
+ * @param folderId - Optional folder ID (REQUIRED for form tasks)
2753
+ * @returns Promise resolving to the task (form tasks will return form-specific data)
2754
+ *
2755
+ * @example
2756
+ * ```typescript
2757
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2758
+ *
2759
+ * const tasks = new Tasks(sdk);
2760
+ *
2761
+ * // Get task by ID
2762
+ * const task = await tasks.getById(123);
2763
+ *
2764
+ * // If the task is a form task, it will automatically return form-specific data
2765
+ * ```
2766
+ */
2767
+ async getById(id, options = {}, folderId) {
2768
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2769
+ // Add default expand parameters
2770
+ const modifiedOptions = this.addDefaultExpand(options);
2771
+ // prefix all keys in options
2772
+ const keysToPrefix = Object.keys(modifiedOptions);
2773
+ const apiOptions = addPrefixToKeys(modifiedOptions, ODATA_PREFIX, keysToPrefix);
2774
+ const response = await this.get(TASK_ENDPOINTS.GET_BY_ID(id), {
2775
+ params: apiOptions,
2776
+ headers
2777
+ });
2778
+ // Transform response from PascalCase to camelCase and normalize time fields
2779
+ const transformedTask = transformData(pascalToCamelCaseKeys(response.data), TaskMap);
2780
+ // Check if this is a form task and get form-specific data if it is
2781
+ if (transformedTask.type === TaskType.Form) {
2782
+ const formOptions = { expandOnFormLayout: true };
2783
+ return this.getFormTaskById(id, folderId || transformedTask.folderId, formOptions);
2784
+ }
2785
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
2786
+ }
2787
+ /**
2788
+ * Assigns tasks to users
2789
+ *
2790
+ * @param taskAssignments - Single task assignment or array of task assignments
2791
+ * @returns Promise resolving to array of task assignment results
2792
+ *
2793
+ * @example
2794
+ * ```typescript
2795
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2796
+ *
2797
+ * const tasks = new Tasks(sdk);
2798
+ *
2799
+ * // Assign a single task to a user by ID
2800
+ * const result = await tasks.assign({
2801
+ * taskId: 123,
2802
+ * userId: 456
2803
+ * });
2804
+ *
2805
+ * // Assign a single task to a user by email
2806
+ * const result = await tasks.assign({
2807
+ * taskId: 123,
2808
+ * userNameOrEmail: "user@example.com"
2809
+ * });
2810
+ *
2811
+ * // Assign multiple tasks
2812
+ * const result = await tasks.assign([
2813
+ * {
2814
+ * taskId: 123,
2815
+ * userId: 456
2816
+ * },
2817
+ * {
2818
+ * taskId: 789,
2819
+ * userNameOrEmail: "user@example.com"
2820
+ * }
2821
+ * ]);
2822
+ * ```
2823
+ */
2824
+ async assign(taskAssignments) {
2825
+ // Normalize input to array
2826
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
2827
+ const options = {
2828
+ taskAssignments: assignmentArray
2829
+ };
2830
+ // Convert options to PascalCase for API
2831
+ const pascalOptions = camelToPascalCaseKeys(options);
2832
+ const response = await this.post(TASK_ENDPOINTS.ASSIGN_TASKS, pascalOptions);
2833
+ // Transform response from PascalCase to camelCase
2834
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2835
+ // Process OData array response - empty array = success, non-empty = error
2836
+ return processODataArrayResponse(transformedResponse, assignmentArray);
2837
+ }
2838
+ /**
2839
+ * Reassigns tasks to new users
2840
+ *
2841
+ * @param taskAssignments - Single task assignment or array of task assignments
2842
+ * @returns Promise resolving to array of task assignment results
2843
+ *
2844
+ * @example
2845
+ * ```typescript
2846
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2847
+ *
2848
+ * const tasks = new Tasks(sdk);
2849
+ *
2850
+ * // Reassign a single task to a user by ID
2851
+ * const result = await tasks.reassign({
2852
+ * taskId: 123,
2853
+ * userId: 456
2854
+ * });
2855
+ *
2856
+ * // Reassign a single task to a user by email
2857
+ * const result = await tasks.reassign({
2858
+ * taskId: 123,
2859
+ * userNameOrEmail: "user@example.com"
2860
+ * });
2861
+ *
2862
+ * // Reassign multiple tasks
2863
+ * const result = await tasks.reassign([
2864
+ * {
2865
+ * taskId: 123,
2866
+ * userId: 456
2867
+ * },
2868
+ * {
2869
+ * taskId: 789,
2870
+ * userNameOrEmail: "user@example.com"
2871
+ * }
2872
+ * ]);
2873
+ * ```
2874
+ */
2875
+ async reassign(taskAssignments) {
2876
+ // Normalize input to array
2877
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
2878
+ const options = {
2879
+ taskAssignments: assignmentArray
2880
+ };
2881
+ // Convert options to PascalCase for API
2882
+ const pascalOptions = camelToPascalCaseKeys(options);
2883
+ const response = await this.post(TASK_ENDPOINTS.REASSIGN_TASKS, pascalOptions);
2884
+ // Transform response from PascalCase to camelCase
2885
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2886
+ // Process OData array response - empty array = success, non-empty = error
2887
+ return processODataArrayResponse(transformedResponse, assignmentArray);
2888
+ }
2889
+ /**
2890
+ * Unassigns tasks (removes current assignees)
2891
+ *
2892
+ * @param taskIds - Single task ID or array of task IDs to unassign
2893
+ * @returns Promise resolving to array of task assignment results
2894
+ *
2895
+ * @example
2896
+ * ```typescript
2897
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2898
+ *
2899
+ * const tasks = new Tasks(sdk);
2900
+ *
2901
+ * // Unassign a single task
2902
+ * const result = await tasks.unassign(123);
2903
+ *
2904
+ * // Unassign multiple tasks
2905
+ * const result = await tasks.unassign([123, 456, 789]);
2906
+ * ```
2907
+ */
2908
+ async unassign(taskIds) {
2909
+ // Normalize input to array
2910
+ const taskIdArray = Array.isArray(taskIds) ? taskIds : [taskIds];
2911
+ const options = {
2912
+ taskIds: taskIdArray
2913
+ };
2914
+ const response = await this.post(TASK_ENDPOINTS.UNASSIGN_TASKS, options);
2915
+ // Transform response from PascalCase to camelCase
2916
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2917
+ // Process OData array response - empty array = success, non-empty = error
2918
+ // Return the task IDs that were unassigned
2919
+ return processODataArrayResponse(transformedResponse, taskIdArray.map(id => ({ taskId: id })));
2920
+ }
2921
+ /**
2922
+ * Completes a task with the specified type and data
2923
+ *
2924
+ * @param options - The completion options including task type, taskId, data, and action
2925
+ * @param folderId - Required folder ID
2926
+ * @returns Promise resolving to completion result
2927
+ *
2928
+ * @example
2929
+ * ```typescript
2930
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2931
+ *
2932
+ * const tasks = new Tasks(sdk);
2933
+ *
2934
+ * // Complete an app task
2935
+ * await tasks.complete({
2936
+ * type: TaskType.App,
2937
+ * taskId: 456,
2938
+ * data: {},
2939
+ * action: "submit"
2940
+ * }, 123); // folderId is required
2941
+ *
2942
+ * // Complete an external task
2943
+ * await tasks.complete({
2944
+ * type: TaskType.External,
2945
+ * taskId: 789
2946
+ * }, 123); // folderId is required
2947
+ * ```
2948
+ */
2949
+ async complete(options, folderId) {
2950
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2951
+ let endpoint;
2952
+ switch (options.type) {
2953
+ case TaskType.Form:
2954
+ endpoint = TASK_ENDPOINTS.COMPLETE_FORM_TASK;
2955
+ break;
2956
+ case TaskType.App:
2957
+ endpoint = TASK_ENDPOINTS.COMPLETE_APP_TASK;
2958
+ break;
2959
+ default:
2960
+ endpoint = TASK_ENDPOINTS.COMPLETE_GENERIC_TASK;
2961
+ break;
2962
+ }
2963
+ // CompleteAppTask returns 204 no content
2964
+ await this.post(endpoint, options, { headers });
2965
+ // Return success with the request context data
2966
+ return {
2967
+ success: true,
2968
+ data: options
2969
+ };
2970
+ }
2971
+ /**
2972
+ * Gets a form task by ID (private method)
2973
+ *
2974
+ * @param id - The ID of the form task to retrieve
2975
+ * @param folderId - Required folder ID
2976
+ * @param options - Optional query parameters
2977
+ * @returns Promise resolving to the form task
2978
+ */
2979
+ async getFormTaskById(id, folderId, options = {}) {
2980
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2981
+ const response = await this.get(TASK_ENDPOINTS.GET_TASK_FORM_BY_ID, {
2982
+ params: {
2983
+ taskId: id,
2984
+ ...options
2985
+ },
2986
+ headers
2987
+ });
2988
+ const transformedFormTask = transformData(response.data, TaskMap);
2989
+ return createTaskWithMethods(applyDataTransforms(transformedFormTask, { field: 'status', valueMap: TaskStatusMap }), this);
2990
+ }
2991
+ /**
2992
+ * Adds default expand parameters to options
2993
+ * @param options - The options object to add default expand to
2994
+ * @returns Options with default expand parameters added
2995
+ * @private
2996
+ */
2997
+ addDefaultExpand(options) {
2998
+ const processedOptions = { ...options };
2999
+ processedOptions.expand = processedOptions.expand
3000
+ ? `${DEFAULT_TASK_EXPAND},${processedOptions.expand}`
3001
+ : DEFAULT_TASK_EXPAND;
3002
+ return processedOptions;
3003
+ }
3004
+ }
3005
+ __decorate([
3006
+ track('Tasks.Create')
3007
+ ], TaskService.prototype, "create", null);
3008
+ __decorate([
3009
+ track('Tasks.GetUsers')
3010
+ ], TaskService.prototype, "getUsers", null);
3011
+ __decorate([
3012
+ track('Tasks.GetAll')
3013
+ ], TaskService.prototype, "getAll", null);
3014
+ __decorate([
3015
+ track('Tasks.GetById')
3016
+ ], TaskService.prototype, "getById", null);
3017
+ __decorate([
3018
+ track('Tasks.Assign')
3019
+ ], TaskService.prototype, "assign", null);
3020
+ __decorate([
3021
+ track('Tasks.Reassign')
3022
+ ], TaskService.prototype, "reassign", null);
3023
+ __decorate([
3024
+ track('Tasks.Unassign')
3025
+ ], TaskService.prototype, "unassign", null);
3026
+ __decorate([
3027
+ track('Tasks.Complete')
3028
+ ], TaskService.prototype, "complete", null);
3029
+
3030
+ class CaseInstancesService extends BaseService {
3031
+ /**
3032
+ * Creates an instance of the Case Instances service.
3033
+ *
3034
+ * @param instance - UiPath SDK instance providing authentication and configuration
3035
+ */
3036
+ constructor(instance) {
3037
+ super(instance);
3038
+ this.taskService = new TaskService(instance);
3039
+ }
3040
+ /**
3041
+ * Get all case instances with optional filtering and pagination
3042
+ *
3043
+ * The method returns either:
3044
+ * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
3045
+ * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
3046
+ *
3047
+ * @param options -Query parameters for filtering instances and pagination
3048
+ * @returns Promise resolving to case instances or paginated result
3049
+ *
3050
+ * @example
3051
+ * ```typescript
3052
+ * import { CaseInstances } from '@uipath/uipath-typescript/cases';
3053
+ *
3054
+ * const caseInstances = new CaseInstances(sdk);
3055
+ *
3056
+ * // Get all case instances (non-paginated)
3057
+ * const instances = await caseInstances.getAll();
3058
+ *
3059
+ * // Close faulted instances using methods directly on instances
3060
+ * for (const instance of instances.items) {
3061
+ * if (instance.latestRunStatus === 'Faulted') {
3062
+ * await instance.close({ comment: 'Closing faulted case instance' });
3063
+ * }
3064
+ * }
3065
+ *
3066
+ * // With filtering
3067
+ * const filtered = await caseInstances.getAll({
3068
+ * processKey: 'MyCaseProcess'
3069
+ * });
3070
+ *
3071
+ * // First page with pagination
3072
+ * const page1 = await caseInstances.getAll({ pageSize: 10 });
3073
+ *
3074
+ * // Navigate using cursor
3075
+ * if (page1.hasNextPage) {
3076
+ * const page2 = await caseInstances.getAll({ cursor: page1.nextCursor });
3077
+ * }
3078
+ * ```
3079
+ */
3080
+ async getAll(options) {
3081
+ // Add processType filter to only get case management instances
3082
+ const enhancedOptions = {
3083
+ ...options,
3084
+ processType: ProcessType.CaseManagement
3085
+ };
3086
+ // Base transformation function for case instances (synchronous)
3087
+ const transformCaseInstance = (item) => {
3088
+ const rawInstance = transformData(item, CaseInstanceMap);
3089
+ return createCaseInstanceWithMethods(rawInstance, this);
3090
+ };
3091
+ // Get the paginated result with basic transformation
3092
+ const result = await PaginationHelpers.getAll({
3093
+ serviceAccess: this.createPaginationServiceAccess(),
3094
+ getEndpoint: () => MAESTRO_ENDPOINTS.INSTANCES.GET_ALL,
3095
+ transformFn: transformCaseInstance,
3096
+ pagination: {
3097
+ paginationType: PaginationType.TOKEN,
3098
+ itemsField: PROCESS_INSTANCE_PAGINATION.ITEMS_FIELD,
3099
+ continuationTokenField: PROCESS_INSTANCE_PAGINATION.CONTINUATION_TOKEN_FIELD,
3100
+ paginationParams: {
3101
+ pageSizeParam: PROCESS_INSTANCE_TOKEN_PARAMS.PAGE_SIZE_PARAM,
3102
+ tokenParam: PROCESS_INSTANCE_TOKEN_PARAMS.TOKEN_PARAM
3103
+ }
3104
+ },
3105
+ excludeFromPrefix: Object.keys(enhancedOptions || {})
3106
+ }, enhancedOptions);
3107
+ // Enhance instances with case JSON data if requested
3108
+ if (result.items && result.items.length > 0) {
3109
+ const enhancedItems = await this.enhanceInstancesWithCaseJson(result.items);
3110
+ return {
3111
+ ...result,
3112
+ items: enhancedItems
3113
+ };
3114
+ }
3115
+ return result;
3116
+ }
3117
+ /**
3118
+ * Get a case instance by ID with operation methods (close, pause, resume, reopen)
3119
+ * @param instanceId - The ID of the instance to retrieve
3120
+ * @param folderKey - Required folder key
3121
+ * @returns Promise<CaseInstanceGetResponse>
3122
+ */
3123
+ async getById(instanceId, folderKey) {
3124
+ const response = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_BY_ID(instanceId), {
3125
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3126
+ });
3127
+ const transformedInstance = transformData(response.data, CaseInstanceMap);
3128
+ const instanceWithMethods = createCaseInstanceWithMethods(transformedInstance, this);
3129
+ // Enhance with case JSON data
3130
+ return this.enhanceInstanceWithCaseJson(instanceWithMethods);
3131
+ }
3132
+ /**
3133
+ * Enhance a single case instance with case JSON data
3134
+ * @param instance - The case instance to enhance
3135
+ * @returns Promise resolving to enhanced instance
3136
+ * @private
3137
+ */
3138
+ async enhanceInstanceWithCaseJson(instance) {
3139
+ if (!instance.folderKey) {
3140
+ return instance;
3141
+ }
3142
+ try {
3143
+ const caseJson = await this.getCaseJson(instance.instanceId, instance.folderKey);
3144
+ if (caseJson && caseJson.root) {
3145
+ // Transform caseAppConfig
3146
+ const transformedCaseAppConfig = caseJson.root.caseAppConfig ? (() => {
3147
+ const transformed = transformData(caseJson.root.caseAppConfig, CaseAppConfigMap);
3148
+ // Remove id field from each overview item
3149
+ if (transformed.overview) {
3150
+ transformed.overview = transformed.overview.map(({ id: _, ...rest }) => rest);
3151
+ }
3152
+ return transformed;
3153
+ })() : undefined;
3154
+ return {
3155
+ ...instance,
3156
+ ...(transformedCaseAppConfig && { caseAppConfig: transformedCaseAppConfig }),
3157
+ ...(caseJson.root.name && { caseType: caseJson.root.name }),
3158
+ ...(caseJson.root.description && { caseTitle: caseJson.root.description })
3159
+ };
3160
+ }
3161
+ }
3162
+ catch (error) {
3163
+ console.debug(`Failed to fetch case JSON for instance ${instance.instanceId}:`, error);
3164
+ }
3165
+ return instance;
3166
+ }
3167
+ /**
3168
+ * Enhance multiple case instances with case JSON data
3169
+ * @param instances - Array of case instances to enhance
3170
+ * @returns Promise resolving to array of enhanced instances
3171
+ * @private
3172
+ */
3173
+ async enhanceInstancesWithCaseJson(instances) {
3174
+ return Promise.all(instances.map(instance => this.enhanceInstanceWithCaseJson(instance)));
3175
+ }
3176
+ /**
3177
+ * Get case JSON for a specific instance
3178
+ * @param instanceId - The case instance ID
3179
+ * @param folderKey - Required folder key
3180
+ * @returns Promise resolving to case JSON data
3181
+ * @private
3182
+ */
3183
+ async getCaseJson(instanceId, folderKey) {
3184
+ try {
3185
+ const response = await this.get(MAESTRO_ENDPOINTS.CASES.GET_CASE_JSON(instanceId), {
3186
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3187
+ });
3188
+ return response.data;
3189
+ }
3190
+ catch {
3191
+ // Return null if the case JSON is not available
3192
+ return null;
3193
+ }
3194
+ }
3195
+ /**
3196
+ * Close a case instance
3197
+ * @param instanceId - The ID of the instance to cancel
3198
+ * @param folderKey - Required folder key
3199
+ * @param options - Optional cancellation options with comment
3200
+ * @returns Promise resolving to operation result with updated instance data
3201
+ */
3202
+ async close(instanceId, folderKey, options) {
3203
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.CANCEL(instanceId), options || {}, {
3204
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3205
+ });
3206
+ return {
3207
+ success: true,
3208
+ data: response.data
3209
+ };
3210
+ }
3211
+ /**
3212
+ * Pause a case instance
3213
+ * @param instanceId - The ID of the instance to pause
3214
+ * @param folderKey - Required folder key
3215
+ * @param options - Optional pause options with comment
3216
+ * @returns Promise resolving to operation result with updated instance data
3217
+ */
3218
+ async pause(instanceId, folderKey, options) {
3219
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.PAUSE(instanceId), options || {}, {
3220
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3221
+ });
3222
+ return {
3223
+ success: true,
3224
+ data: response.data
3225
+ };
3226
+ }
3227
+ /**
3228
+ * Reopen a case instance from a specified element
3229
+ * @param instanceId - The ID of the case instance to reopen
3230
+ * @param folderKey - Required folder key
3231
+ * @param options - Reopen options containing stageId (the stage ID to resume from) and an optional comment
3232
+ * @returns Promise resolving to operation result with updated instance data
3233
+ */
3234
+ async reopen(instanceId, folderKey, options) {
3235
+ // Transform SDK options to API request format
3236
+ const requestBody = {
3237
+ StartElementId: options.stageId,
3238
+ ...(options.comment && { Comment: options.comment })
3239
+ };
3240
+ const response = await this.post(MAESTRO_ENDPOINTS.CASES.REOPEN(instanceId), requestBody, {
3241
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3242
+ });
3243
+ return {
3244
+ success: true,
3245
+ data: response.data
3246
+ };
3247
+ }
3248
+ /**
3249
+ * Resume a case instance
3250
+ * @param instanceId - The ID of the instance to resume
3251
+ * @param folderKey - Required folder key
3252
+ * @param options - Optional resume options with comment
3253
+ * @returns Promise resolving to operation result with updated instance data
3254
+ */
3255
+ async resume(instanceId, folderKey, options) {
3256
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.RESUME(instanceId), options || {}, {
3257
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3258
+ });
3259
+ return {
3260
+ success: true,
3261
+ data: response.data
3262
+ };
3263
+ }
3264
+ /**
3265
+ * Get execution history for a case instance
3266
+ * @param instanceId - The ID of the case instance
3267
+ * @param folderKey - Required folder key
3268
+ * @returns Promise resolving to instance execution history
3269
+ * @example
3270
+ * ```typescript
3271
+ * import { CaseInstances } from '@uipath/uipath-typescript/cases';
3272
+ *
3273
+ * const caseInstances = new CaseInstances(sdk);
3274
+ * const history = await caseInstances.getExecutionHistory(
3275
+ * 'instance-id',
3276
+ * 'folder-key'
3277
+ * );
3278
+ * ```
3279
+ */
3280
+ async getExecutionHistory(instanceId, folderKey) {
3281
+ const response = await this.get(MAESTRO_ENDPOINTS.CASES.GET_ELEMENT_EXECUTIONS(instanceId), {
3282
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3283
+ });
3284
+ // Transform the main response
3285
+ const transformedResponse = transformData(response.data, TimeFieldTransformMap);
3286
+ // Transform each element execution and its nested element runs
3287
+ if (transformedResponse.elementExecutions && Array.isArray(transformedResponse.elementExecutions)) {
3288
+ transformedResponse.elementExecutions = transformedResponse.elementExecutions.map((execution) => {
3289
+ // Transform the element execution itself
3290
+ const transformedExecution = transformData(execution, TimeFieldTransformMap);
3291
+ // Transform nested element runs if they exist
3292
+ if (transformedExecution.elementRuns && Array.isArray(transformedExecution.elementRuns)) {
3293
+ transformedExecution.elementRuns = transformedExecution.elementRuns.map((run) => transformData(run, TimeFieldTransformMap));
3294
+ }
3295
+ return transformedExecution;
3296
+ });
3297
+ }
3298
+ return transformedResponse;
3299
+ }
3300
+ /**
3301
+ * Get case stages with their associated tasks and execution status
3302
+ * @param caseInstanceId - The ID of the case instance
3303
+ * @param folderKey - Required folder key
3304
+ * @returns Promise resolving to an array of case stages, each containing their tasks with execution details
3305
+ */
3306
+ async getStages(caseInstanceId, folderKey) {
3307
+ // Fetch both execution history and case JSON in parallel, but handle execution failures gracefully
3308
+ const [executionHistoryResponse, caseJsonResponse] = await Promise.allSettled([
3309
+ this.getExecutionHistory(caseInstanceId, folderKey),
3310
+ this.getCaseJson(caseInstanceId, folderKey)
3311
+ ]);
3312
+ // Extract execution history if successful, otherwise use null
3313
+ const executionHistory = executionHistoryResponse.status === 'fulfilled'
3314
+ ? executionHistoryResponse.value
3315
+ : null;
3316
+ // Extract case JSON - the null check below will handle failures
3317
+ const caseJson = caseJsonResponse.status === 'fulfilled'
3318
+ ? caseJsonResponse.value
3319
+ : null;
3320
+ if (!caseJson || !caseJson.nodes) {
3321
+ return [];
3322
+ }
3323
+ // Create lookup maps for efficient data access
3324
+ const executionMap = this.createExecutionMap(executionHistory);
3325
+ const bindingsMap = this.createBindingsMap(caseJson);
3326
+ // Process nodes to extract stages (exclude triggers)
3327
+ const stages = caseJson.nodes
3328
+ .filter((node) => node.type !== CASE_STAGE_CONSTANTS.TRIGGER_NODE_TYPE)
3329
+ .map((node) => this.createStageFromNode(node, executionMap, bindingsMap));
3330
+ return stages;
3331
+ }
3332
+ /**
3333
+ * Create a map of element ID to execution data
3334
+ * @param executionHistory - The execution history response
3335
+ * @returns Map of elementId to execution metadata
3336
+ * @private
3337
+ */
3338
+ createExecutionMap(executionHistory) {
3339
+ const executionMap = new Map();
3340
+ if (executionHistory?.elementExecutions) {
3341
+ for (const execution of executionHistory.elementExecutions) {
3342
+ executionMap.set(execution.elementId, execution);
3343
+ }
3344
+ }
3345
+ return executionMap;
3346
+ }
3347
+ /**
3348
+ * Create a map of binding IDs to their values
3349
+ * @param caseJsonResponse - The case JSON response
3350
+ * @returns Map of binding ID to binding object
3351
+ * @private
3352
+ */
3353
+ createBindingsMap(caseJsonResponse) {
3354
+ const bindingsMap = new Map();
3355
+ if (caseJsonResponse?.root?.data?.uipath?.bindings) {
3356
+ for (const binding of caseJsonResponse.root.data.uipath.bindings) {
3357
+ if (binding.id) {
3358
+ bindingsMap.set(binding.id, binding);
3359
+ }
3360
+ }
3361
+ }
3362
+ return bindingsMap;
3363
+ }
3364
+ /**
3365
+ * Resolve binding values from binding expressions
3366
+ * @param value - The value that may contain binding references
3367
+ * @param bindingsMap - Map of binding IDs to binding objects
3368
+ * @returns Resolved value
3369
+ * @private
3370
+ */
3371
+ resolveBinding(value, bindingsMap) {
3372
+ if (typeof value === 'string' && value.startsWith('=bindings.')) {
3373
+ const bindingId = value.substring('=bindings.'.length);
3374
+ const binding = bindingsMap.get(bindingId);
3375
+ return binding?.default || binding?.name || value;
3376
+ }
3377
+ return value;
3378
+ }
3379
+ /**
3380
+ * Process tasks for a stage node
3381
+ * @param node - The stage node containing tasks
3382
+ * @param executionMap - Map of element IDs to execution data
3383
+ * @param bindingsMap - Map of binding IDs to binding objects
3384
+ * @returns Processed tasks array
3385
+ * @private
3386
+ */
3387
+ processTasks(node, executionMap, bindingsMap) {
3388
+ if (!node.data?.tasks || !Array.isArray(node.data.tasks)) {
3389
+ return [];
3390
+ }
3391
+ return node.data.tasks.map((taskGroup) => {
3392
+ if (Array.isArray(taskGroup)) {
3393
+ return taskGroup.map((task) => {
3394
+ const taskId = task.id;
3395
+ // Find the execution data using the task's id
3396
+ const taskExecution = taskId ? executionMap.get(taskId) : undefined;
3397
+ // Resolve task name from bindings
3398
+ let taskName = task.displayName;
3399
+ if (!taskName && task.data?.name) {
3400
+ taskName = this.resolveBinding(task.data.name, bindingsMap);
3401
+ }
3402
+ const stageTask = {
3403
+ id: taskId || task.elementId || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
3404
+ name: taskName || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
3405
+ completedTime: taskExecution?.completedTime || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
3406
+ startedTime: taskExecution?.startedTime || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
3407
+ status: taskExecution?.status || CASE_STAGE_CONSTANTS.NOT_STARTED_STATUS,
3408
+ type: task.type || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE
3409
+ };
3410
+ return stageTask;
3411
+ });
3412
+ }
3413
+ return [];
3414
+ });
3415
+ }
3416
+ /**
3417
+ * Create a stage from a case node
3418
+ * @param node - The case node to process
3419
+ * @param executionMap - Map of element IDs to execution data
3420
+ * @param bindingsMap - Map of binding IDs to binding objects
3421
+ * @returns CaseGetStageResponse object
3422
+ * @private
3423
+ */
3424
+ createStageFromNode(node, executionMap, bindingsMap) {
3425
+ const execution = executionMap.get(node.id);
3426
+ const stage = {
3427
+ id: node.id,
3428
+ name: node.data?.label || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
3429
+ sla: node.data?.sla ? transformData(node.data.sla, StageSLAMap) : undefined,
3430
+ status: execution?.status || CASE_STAGE_CONSTANTS.NOT_STARTED_STATUS,
3431
+ tasks: this.processTasks(node, executionMap, bindingsMap)
3432
+ };
3433
+ return stage;
3434
+ }
3435
+ /**
3436
+ * Get human in the loop tasks associated with a case instance
3437
+ * @param caseInstanceId - The ID of the case instance
3438
+ * @param options - Optional filtering and pagination options
3439
+ * @returns Promise resolving to human in the loop tasks associated with the case instance
3440
+ */
3441
+ async getActionTasks(caseInstanceId, options) {
3442
+ // Build filter to match tasks by case instance ID using tags
3443
+ const tagFilter = CASE_INSTANCE_TASK_FILTER(caseInstanceId);
3444
+ // Combine with any existing filter
3445
+ const filter = options?.filter
3446
+ ? `(${tagFilter}) and (${options.filter})`
3447
+ : tagFilter;
3448
+ // Add expand to include AssignedToUser and Activities
3449
+ const expand = CASE_INSTANCE_TASK_EXPAND;
3450
+ // Prepare the enhanced options with proper typing
3451
+ const enhancedOptions = {
3452
+ ...options,
3453
+ filter,
3454
+ expand
3455
+ };
3456
+ return await this.taskService.getAll(enhancedOptions);
3457
+ }
3458
+ }
3459
+ __decorate([
3460
+ track('CaseInstances.GetAll')
3461
+ ], CaseInstancesService.prototype, "getAll", null);
3462
+ __decorate([
3463
+ track('CaseInstances.GetById')
3464
+ ], CaseInstancesService.prototype, "getById", null);
3465
+ __decorate([
3466
+ track('CaseInstances.Close')
3467
+ ], CaseInstancesService.prototype, "close", null);
3468
+ __decorate([
3469
+ track('CaseInstances.Pause')
3470
+ ], CaseInstancesService.prototype, "pause", null);
3471
+ __decorate([
3472
+ track('CaseInstances.Reopen')
3473
+ ], CaseInstancesService.prototype, "reopen", null);
3474
+ __decorate([
3475
+ track('CaseInstances.Resume')
3476
+ ], CaseInstancesService.prototype, "resume", null);
3477
+ __decorate([
3478
+ track('CaseInstances.GetExecutionHistory')
3479
+ ], CaseInstancesService.prototype, "getExecutionHistory", null);
3480
+ __decorate([
3481
+ track('CaseInstances.GetStages')
3482
+ ], CaseInstancesService.prototype, "getStages", null);
3483
+ __decorate([
3484
+ track('CaseInstances.GetActionTasks')
3485
+ ], CaseInstancesService.prototype, "getActionTasks", null);
3486
+
3487
+ export { CaseInstancesService as CaseInstances, CaseInstancesService, CasesService as Cases, CasesService, EscalationActionType, EscalationRecipientScope, EscalationTriggerType, SLADurationUnit, StageTaskType, createCaseInstanceWithMethods };