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

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