@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,2649 @@
1
+ import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+
20
+ function __decorate(decorators, target, key, desc) {
21
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
23
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
24
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
25
+ }
26
+
27
+ function __classPrivateFieldGet(receiver, state, kind, f) {
28
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
29
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
30
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
31
+ }
32
+
33
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
34
+ if (kind === "m") throw new TypeError("Private method is not writable");
35
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
36
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
37
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
38
+ }
39
+
40
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
41
+ var e = new Error(message);
42
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
43
+ };
44
+
45
+ /**
46
+ * Type guards for error response types
47
+ */
48
+ function isOrchestratorError(error) {
49
+ return typeof error === 'object' &&
50
+ error !== null &&
51
+ 'message' in error &&
52
+ 'errorCode' in error &&
53
+ typeof error.message === 'string' &&
54
+ typeof error.errorCode === 'number';
55
+ }
56
+ function isEntityError(error) {
57
+ return typeof error === 'object' &&
58
+ error !== null &&
59
+ 'error' in error &&
60
+ typeof error.error === 'string';
61
+ }
62
+ function isPimsError(error) {
63
+ return typeof error === 'object' &&
64
+ error !== null &&
65
+ 'type' in error &&
66
+ 'title' in error &&
67
+ 'status' in error &&
68
+ typeof error.type === 'string' &&
69
+ typeof error.title === 'string' &&
70
+ typeof error.status === 'number';
71
+ }
72
+
73
+ /**
74
+ * HTTP status code constants for error handling
75
+ */
76
+ const HttpStatus = {
77
+ // Client errors (4xx)
78
+ BAD_REQUEST: 400,
79
+ UNAUTHORIZED: 401,
80
+ FORBIDDEN: 403,
81
+ NOT_FOUND: 404,
82
+ TOO_MANY_REQUESTS: 429,
83
+ // Server errors (5xx)
84
+ INTERNAL_SERVER_ERROR: 500,
85
+ BAD_GATEWAY: 502,
86
+ SERVICE_UNAVAILABLE: 503,
87
+ GATEWAY_TIMEOUT: 504
88
+ };
89
+ /**
90
+ * Error type constants for consistent error identification
91
+ */
92
+ const ErrorType = {
93
+ AUTHENTICATION: 'AuthenticationError',
94
+ AUTHORIZATION: 'AuthorizationError',
95
+ VALIDATION: 'ValidationError',
96
+ NOT_FOUND: 'NotFoundError',
97
+ RATE_LIMIT: 'RateLimitError',
98
+ SERVER: 'ServerError',
99
+ NETWORK: 'NetworkError'
100
+ };
101
+ /**
102
+ * HTTP header constants for error handling
103
+ */
104
+ const HttpHeaders = {
105
+ X_REQUEST_ID: 'x-request-id'
106
+ };
107
+ /**
108
+ * Standard error message constants
109
+ */
110
+ const ErrorMessages = {
111
+ // Authentication errors
112
+ AUTHENTICATION_FAILED: 'Authentication failed',
113
+ // Authorization errors
114
+ ACCESS_DENIED: 'Access denied',
115
+ // Validation errors
116
+ VALIDATION_FAILED: 'Validation failed',
117
+ // Not found errors
118
+ RESOURCE_NOT_FOUND: 'Resource not found',
119
+ // Rate limit errors
120
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
121
+ // Server errors
122
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
123
+ // Network errors
124
+ NETWORK_ERROR: 'Network error occurred',
125
+ REQUEST_TIMEOUT: 'Request timed out',
126
+ REQUEST_ABORTED: 'Request was aborted',
127
+ };
128
+ /**
129
+ * Error name constants for network error identification
130
+ */
131
+ const ErrorNames = {
132
+ ABORT_ERROR: 'AbortError'};
133
+
134
+ /**
135
+ * Parser for Orchestrator/Task error format
136
+ */
137
+ class OrchestratorErrorParser {
138
+ canParse(errorBody) {
139
+ return isOrchestratorError(errorBody);
140
+ }
141
+ parse(errorBody, response) {
142
+ const error = errorBody;
143
+ return {
144
+ message: error.message,
145
+ code: response?.status?.toString(),
146
+ details: {
147
+ errorCode: error.errorCode,
148
+ traceId: error.traceId,
149
+ originalResponse: error
150
+ },
151
+ requestId: error.traceId
152
+ };
153
+ }
154
+ }
155
+ /**
156
+ * Parser for Entity (Data Fabric) error format
157
+ */
158
+ class EntityErrorParser {
159
+ canParse(errorBody) {
160
+ return isEntityError(errorBody);
161
+ }
162
+ parse(errorBody, response) {
163
+ const error = errorBody;
164
+ return {
165
+ message: error.error,
166
+ code: response?.status?.toString(),
167
+ details: {
168
+ error: error.error,
169
+ traceId: error.traceId,
170
+ originalResponse: error
171
+ },
172
+ requestId: error.traceId
173
+ };
174
+ }
175
+ }
176
+ /**
177
+ * Parser for PIMS error format
178
+ */
179
+ class PimsErrorParser {
180
+ canParse(errorBody) {
181
+ return isPimsError(errorBody);
182
+ }
183
+ parse(errorBody, response) {
184
+ const error = errorBody;
185
+ let message = error.title;
186
+ // If there are validation errors, append them to the message for better visibility
187
+ if (error.errors && Object.keys(error.errors).length > 0) {
188
+ const errorMessages = Object.entries(error.errors)
189
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
190
+ .join('; ');
191
+ message += `. Validation errors: ${errorMessages}`;
192
+ }
193
+ return {
194
+ message,
195
+ code: response?.status?.toString(),
196
+ details: {
197
+ type: error.type,
198
+ title: error.title,
199
+ status: error.status,
200
+ errors: error.errors,
201
+ traceId: error.traceId,
202
+ originalResponse: error
203
+ },
204
+ requestId: error.traceId
205
+ };
206
+ }
207
+ }
208
+ /**
209
+ * Fallback parser for unrecognized formats
210
+ */
211
+ class GenericErrorParser {
212
+ canParse(_errorBody) {
213
+ return true; // Always can parse as last resort
214
+ }
215
+ parse(errorBody, response) {
216
+ // For unknown error formats, just pass through the raw error with fallback message
217
+ const message = response?.statusText || 'An error occurred';
218
+ return {
219
+ message,
220
+ code: response?.status?.toString(),
221
+ details: {
222
+ originalResponse: errorBody
223
+ },
224
+ };
225
+ }
226
+ }
227
+ /**
228
+ * Main error response parser using Chain of Responsibility pattern
229
+ *
230
+ * This parser standardizes error responses from different UiPath services into a
231
+ * consistent format, regardless of the original error structure.
232
+ *
233
+ * Supported formats:
234
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
235
+ * 2. Entity (Data Fabric): { error, traceId }
236
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
237
+ * 4. Generic: Fallback for any other format
238
+ *
239
+ * @example
240
+ * const parser = new ErrorResponseParser();
241
+ * const errorInfo = await parser.parse(response);
242
+ * // errorInfo will have consistent structure regardless of service
243
+ */
244
+ class ErrorResponseParser {
245
+ constructor() {
246
+ this.strategies = [
247
+ new OrchestratorErrorParser(),
248
+ new EntityErrorParser(),
249
+ new PimsErrorParser(),
250
+ new GenericErrorParser() // Must be last
251
+ ];
252
+ }
253
+ /**
254
+ * Parses error response body into standardized format
255
+ * @param response - The HTTP response object
256
+ * @returns Standardized error information
257
+ */
258
+ async parse(response) {
259
+ try {
260
+ const errorBody = await response.json();
261
+ // Find the first strategy that can parse this error format
262
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
263
+ // GenericErrorParser always returns true, so this will never be null
264
+ return strategy.parse(errorBody, response);
265
+ }
266
+ catch {
267
+ // Handle non-JSON responses
268
+ const responseText = await response.text().catch(() => '');
269
+ return {
270
+ message: response.statusText,
271
+ code: response.status.toString(),
272
+ details: {
273
+ parseError: 'Failed to parse error response as JSON',
274
+ responseText
275
+ },
276
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
277
+ };
278
+ }
279
+ }
280
+ }
281
+ // Export singleton instance
282
+ const errorResponseParser = new ErrorResponseParser();
283
+
284
+ /**
285
+ * Base error class for all UiPath SDK errors
286
+ * Extends Error for standard error handling compatibility
287
+ */
288
+ class UiPathError extends Error {
289
+ constructor(type, params) {
290
+ super(params.message);
291
+ this.name = type;
292
+ this.type = type;
293
+ this.statusCode = params.statusCode;
294
+ this.requestId = params.requestId;
295
+ this.timestamp = new Date();
296
+ // Maintains proper stack trace for where our error was thrown
297
+ if (Error.captureStackTrace) {
298
+ Error.captureStackTrace(this, this.constructor);
299
+ }
300
+ }
301
+ /**
302
+ * Returns a clean JSON representation of the error
303
+ */
304
+ toJSON() {
305
+ return {
306
+ type: this.type,
307
+ message: this.message,
308
+ statusCode: this.statusCode,
309
+ requestId: this.requestId,
310
+ timestamp: this.timestamp
311
+ };
312
+ }
313
+ /**
314
+ * Returns detailed debug information including stack trace
315
+ */
316
+ getDebugInfo() {
317
+ return {
318
+ ...this.toJSON(),
319
+ stack: this.stack
320
+ };
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Error thrown when authentication fails (401 errors)
326
+ * Common scenarios:
327
+ * - Invalid credentials
328
+ * - Expired token
329
+ * - Missing authentication
330
+ */
331
+ class AuthenticationError extends UiPathError {
332
+ constructor(params = {}) {
333
+ super(ErrorType.AUTHENTICATION, {
334
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
335
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
336
+ requestId: params.requestId
337
+ });
338
+ }
339
+ }
340
+
341
+ /**
342
+ * Error thrown when authorization fails (403 errors)
343
+ * Common scenarios:
344
+ * - Insufficient permissions
345
+ * - Access denied to resource
346
+ * - Invalid scope
347
+ */
348
+ class AuthorizationError extends UiPathError {
349
+ constructor(params = {}) {
350
+ super(ErrorType.AUTHORIZATION, {
351
+ message: params.message || ErrorMessages.ACCESS_DENIED,
352
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
353
+ requestId: params.requestId
354
+ });
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Error thrown when validation fails (400 errors or client-side validation)
360
+ * Common scenarios:
361
+ * - Invalid input parameters
362
+ * - Missing required fields
363
+ * - Invalid data format
364
+ */
365
+ class ValidationError extends UiPathError {
366
+ constructor(params = {}) {
367
+ super(ErrorType.VALIDATION, {
368
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
369
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
370
+ requestId: params.requestId
371
+ });
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Error thrown when a resource is not found (404 errors)
377
+ * Common scenarios:
378
+ * - Resource doesn't exist
379
+ * - Invalid ID provided
380
+ * - Resource deleted
381
+ */
382
+ class NotFoundError extends UiPathError {
383
+ constructor(params = {}) {
384
+ super(ErrorType.NOT_FOUND, {
385
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
386
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
387
+ requestId: params.requestId
388
+ });
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Error thrown when rate limit is exceeded (429 errors)
394
+ * Common scenarios:
395
+ * - Too many requests in a time window
396
+ * - API throttling
397
+ */
398
+ class RateLimitError extends UiPathError {
399
+ constructor(params = {}) {
400
+ super(ErrorType.RATE_LIMIT, {
401
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
402
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
403
+ requestId: params.requestId
404
+ });
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Error thrown when server encounters an error (5xx errors)
410
+ * Common scenarios:
411
+ * - Internal server error
412
+ * - Service unavailable
413
+ * - Gateway timeout
414
+ */
415
+ class ServerError extends UiPathError {
416
+ constructor(params = {}) {
417
+ super(ErrorType.SERVER, {
418
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
419
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
420
+ requestId: params.requestId
421
+ });
422
+ }
423
+ /**
424
+ * Checks if this is a temporary error that might succeed on retry
425
+ */
426
+ get isRetryable() {
427
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
428
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
429
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Error thrown when network/connection issues occur
435
+ * Common scenarios:
436
+ * - Connection timeout
437
+ * - DNS resolution failure
438
+ * - Network unreachable
439
+ * - Request aborted
440
+ */
441
+ class NetworkError extends UiPathError {
442
+ constructor(params = {}) {
443
+ super(ErrorType.NETWORK, {
444
+ message: params.message || ErrorMessages.NETWORK_ERROR,
445
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
446
+ requestId: params.requestId
447
+ });
448
+ }
449
+ }
450
+
451
+ /**
452
+ * Factory for creating typed errors based on HTTP status codes
453
+ * Follows the Factory pattern for clean error instantiation
454
+ */
455
+ class ErrorFactory {
456
+ /**
457
+ * Creates appropriate error instance based on HTTP status code
458
+ */
459
+ static createFromHttpStatus(statusCode, errorInfo) {
460
+ const { message, requestId } = errorInfo;
461
+ // Map status codes to error types
462
+ switch (statusCode) {
463
+ case HttpStatus.BAD_REQUEST:
464
+ return new ValidationError({ message, statusCode, requestId });
465
+ case HttpStatus.UNAUTHORIZED:
466
+ return new AuthenticationError({ message, statusCode, requestId });
467
+ case HttpStatus.FORBIDDEN:
468
+ return new AuthorizationError({ message, statusCode, requestId });
469
+ case HttpStatus.NOT_FOUND:
470
+ return new NotFoundError({ message, statusCode, requestId });
471
+ case HttpStatus.TOO_MANY_REQUESTS:
472
+ return new RateLimitError({ message, statusCode, requestId });
473
+ default:
474
+ // For 5xx errors or any other status code
475
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
476
+ return new ServerError({ message, statusCode, requestId });
477
+ }
478
+ // For unknown client errors, treat as validation error
479
+ return new ValidationError({
480
+ message: `${message} (HTTP ${statusCode})`,
481
+ statusCode,
482
+ requestId
483
+ });
484
+ }
485
+ }
486
+ /**
487
+ * Creates a NetworkError from a fetch/network error
488
+ */
489
+ static createNetworkError(error) {
490
+ let message = ErrorMessages.NETWORK_ERROR;
491
+ if (error instanceof Error) {
492
+ if (error.name === ErrorNames.ABORT_ERROR) {
493
+ message = ErrorMessages.REQUEST_ABORTED;
494
+ }
495
+ else if (error.message.includes('timeout')) {
496
+ message = ErrorMessages.REQUEST_TIMEOUT;
497
+ }
498
+ else {
499
+ message = error.message;
500
+ }
501
+ }
502
+ return new NetworkError({ message });
503
+ }
504
+ }
505
+
506
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
507
+ /**
508
+ * Content type constants for HTTP requests/responses
509
+ */
510
+ const CONTENT_TYPES = {
511
+ JSON: 'application/json',
512
+ XML: 'application/xml',
513
+ OCTET_STREAM: 'application/octet-stream'
514
+ };
515
+ /**
516
+ * Response type constants for HTTP requests
517
+ */
518
+ const RESPONSE_TYPES = {
519
+ JSON: 'json',
520
+ TEXT: 'text',
521
+ BLOB: 'blob',
522
+ ARRAYBUFFER: 'arraybuffer'
523
+ };
524
+
525
+ class ApiClient {
526
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
527
+ this.defaultHeaders = {};
528
+ this.config = config;
529
+ this.executionContext = executionContext;
530
+ this.clientConfig = clientConfig;
531
+ this.tokenManager = tokenManager;
532
+ }
533
+ setDefaultHeaders(headers) {
534
+ this.defaultHeaders = { ...this.defaultHeaders, ...headers };
535
+ }
536
+ /**
537
+ * Gets a valid authentication token, refreshing if necessary.
538
+ * Used internally for API requests and exposed for services that need manual auth headers.
539
+ *
540
+ * @returns The valid token
541
+ * @throws AuthenticationError if no token available or refresh fails
542
+ */
543
+ async getValidToken() {
544
+ return this.tokenManager.getValidToken();
545
+ }
546
+ async getDefaultHeaders() {
547
+ // Get headers from execution context first
548
+ const contextHeaders = this.executionContext.getHeaders();
549
+ // If Authorization header is already set in context, use that
550
+ if (contextHeaders['Authorization']) {
551
+ return {
552
+ ...contextHeaders,
553
+ 'Content-Type': CONTENT_TYPES.JSON,
554
+ ...this.defaultHeaders,
555
+ ...this.clientConfig.headers
556
+ };
557
+ }
558
+ const token = await this.getValidToken();
559
+ return {
560
+ ...contextHeaders,
561
+ 'Authorization': `Bearer ${token}`,
562
+ 'Content-Type': CONTENT_TYPES.JSON,
563
+ ...this.defaultHeaders,
564
+ ...this.clientConfig.headers
565
+ };
566
+ }
567
+ async request(method, path, options = {}) {
568
+ // Ensure path starts with a forward slash
569
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
570
+ // Construct URL with org and tenant names
571
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
572
+ const headers = {
573
+ ...await this.getDefaultHeaders(),
574
+ ...options.headers
575
+ };
576
+ // Convert params to URLSearchParams
577
+ const searchParams = new URLSearchParams();
578
+ if (options.params) {
579
+ Object.entries(options.params).forEach(([key, value]) => {
580
+ searchParams.append(key, value.toString());
581
+ });
582
+ }
583
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
584
+ try {
585
+ const response = await fetch(fullUrl, {
586
+ method,
587
+ headers,
588
+ body: options.body ? JSON.stringify(options.body) : undefined,
589
+ signal: options.signal
590
+ });
591
+ if (!response.ok) {
592
+ const errorInfo = await errorResponseParser.parse(response);
593
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
594
+ }
595
+ if (response.status === 204) {
596
+ return undefined;
597
+ }
598
+ // Handle blob response type for binary data (e.g., file downloads)
599
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
600
+ const blob = await response.blob();
601
+ return blob;
602
+ }
603
+ // Check if we're expecting XML
604
+ const acceptHeader = headers['Accept'] || headers['accept'];
605
+ if (acceptHeader === CONTENT_TYPES.XML) {
606
+ const text = await response.text();
607
+ return text;
608
+ }
609
+ return response.json();
610
+ }
611
+ catch (error) {
612
+ // If it's already one of our errors, re-throw it
613
+ if (error.type && error.type.includes('Error')) {
614
+ throw error;
615
+ }
616
+ // Otherwise, it's likely a network error
617
+ throw ErrorFactory.createNetworkError(error);
618
+ }
619
+ }
620
+ async get(path, options = {}) {
621
+ return this.request('GET', path, options);
622
+ }
623
+ async post(path, data, options = {}) {
624
+ return this.request('POST', path, { ...options, body: data });
625
+ }
626
+ async put(path, data, options = {}) {
627
+ return this.request('PUT', path, { ...options, body: data });
628
+ }
629
+ async patch(path, data, options = {}) {
630
+ return this.request('PATCH', path, { ...options, body: data });
631
+ }
632
+ async delete(path, options = {}) {
633
+ return this.request('DELETE', path, options);
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Pagination types supported by the SDK
639
+ */
640
+ var PaginationType;
641
+ (function (PaginationType) {
642
+ PaginationType["OFFSET"] = "offset";
643
+ PaginationType["TOKEN"] = "token";
644
+ })(PaginationType || (PaginationType = {}));
645
+
646
+ /**
647
+ * Collection of utility functions for working with objects
648
+ */
649
+ /**
650
+ * Filters out undefined values from an object
651
+ * @param obj The source object
652
+ * @returns A new object without undefined values
653
+ *
654
+ * @example
655
+ * ```typescript
656
+ * // Object with undefined values
657
+ * const options = {
658
+ * name: 'test',
659
+ * count: 5,
660
+ * prefix: undefined,
661
+ * suffix: null
662
+ * };
663
+ * const result = filterUndefined(options);
664
+ * // result = { name: 'test', count: 5, suffix: null }
665
+ * ```
666
+ */
667
+ function filterUndefined(obj) {
668
+ const result = {};
669
+ for (const [key, value] of Object.entries(obj)) {
670
+ if (value !== undefined) {
671
+ result[key] = value;
672
+ }
673
+ }
674
+ return result;
675
+ }
676
+ /**
677
+ * Helper function for OData responses that ALWAYS return 200 with array indication
678
+ * Empty array = success, Non-empty array = error
679
+ * Used for task assignment APIs that don't use HTTP status codes for errors
680
+ */
681
+ function processODataArrayResponse(oDataResponse, successData) {
682
+ // Empty array = success
683
+ if (oDataResponse.value.length === 0) {
684
+ return {
685
+ success: true,
686
+ data: successData
687
+ };
688
+ }
689
+ // Non-empty array = error details
690
+ return {
691
+ success: false,
692
+ data: oDataResponse.value
693
+ };
694
+ }
695
+
696
+ /**
697
+ * Utility functions for platform detection
698
+ */
699
+ /**
700
+ * Checks if code is running in a browser environment
701
+ */
702
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
703
+
704
+ /**
705
+ * Base64 encoding/decoding
706
+ */
707
+ /**
708
+ * Encodes a string to base64
709
+ * @param str - The string to encode
710
+ * @returns Base64 encoded string
711
+ */
712
+ function encodeBase64(str) {
713
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
714
+ const encoder = new TextEncoder();
715
+ const data = encoder.encode(str);
716
+ // Convert Uint8Array to base64
717
+ if (isBrowser) {
718
+ // Browser environment
719
+ // Convert Uint8Array to binary string then to base64
720
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
721
+ return btoa(binaryString);
722
+ }
723
+ else {
724
+ // Node.js environment
725
+ return Buffer.from(data).toString('base64');
726
+ }
727
+ }
728
+ /**
729
+ * Decodes a base64 string
730
+ * @param base64 - The base64 string to decode
731
+ * @returns Decoded string
732
+ */
733
+ function decodeBase64(base64) {
734
+ let bytes;
735
+ if (isBrowser) {
736
+ // Browser environment
737
+ const binaryString = atob(base64);
738
+ bytes = new Uint8Array(binaryString.length);
739
+ for (let i = 0; i < binaryString.length; i++) {
740
+ bytes[i] = binaryString.charCodeAt(i);
741
+ }
742
+ }
743
+ else {
744
+ // Node.js environment
745
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
746
+ }
747
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
748
+ const decoder = new TextDecoder();
749
+ return decoder.decode(bytes);
750
+ }
751
+
752
+ /**
753
+ * PaginationManager handles the conversion between uniform cursor-based pagination
754
+ * and the specific pagination type for each service
755
+ */
756
+ class PaginationManager {
757
+ /**
758
+ * Create a pagination cursor for subsequent page requests
759
+ */
760
+ static createCursor({ pageInfo, type }) {
761
+ if (!pageInfo.hasMore) {
762
+ return undefined;
763
+ }
764
+ const cursorData = {
765
+ type,
766
+ pageSize: pageInfo.pageSize,
767
+ };
768
+ switch (type) {
769
+ case PaginationType.OFFSET:
770
+ if (pageInfo.currentPage) {
771
+ cursorData.pageNumber = pageInfo.currentPage + 1;
772
+ }
773
+ break;
774
+ case PaginationType.TOKEN:
775
+ if (pageInfo.continuationToken) {
776
+ cursorData.continuationToken = pageInfo.continuationToken;
777
+ }
778
+ else {
779
+ return undefined; // No continuation token, can't continue
780
+ }
781
+ break;
782
+ }
783
+ return {
784
+ value: encodeBase64(JSON.stringify(cursorData))
785
+ };
786
+ }
787
+ /**
788
+ * Create a paginated response with navigation cursors
789
+ */
790
+ static createPaginatedResponse({ pageInfo, type }, items) {
791
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
792
+ // Create previous page cursor if applicable
793
+ let previousCursor = undefined;
794
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
795
+ const prevCursorData = {
796
+ type,
797
+ pageNumber: pageInfo.currentPage - 1,
798
+ pageSize: pageInfo.pageSize,
799
+ };
800
+ previousCursor = {
801
+ value: encodeBase64(JSON.stringify(prevCursorData))
802
+ };
803
+ }
804
+ // Calculate total pages if we have totalCount and pageSize
805
+ let totalPages = undefined;
806
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
807
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
808
+ }
809
+ // Determine if this pagination type supports page jumping
810
+ const supportsPageJump = type === PaginationType.OFFSET;
811
+ // Create the result object with all fields, then filter out undefined values
812
+ const result = filterUndefined({
813
+ items,
814
+ totalCount: pageInfo.totalCount,
815
+ hasNextPage: pageInfo.hasMore,
816
+ nextCursor: nextCursor,
817
+ previousCursor: previousCursor,
818
+ currentPage: pageInfo.currentPage,
819
+ totalPages,
820
+ supportsPageJump
821
+ });
822
+ return result;
823
+ }
824
+ }
825
+
826
+ /**
827
+ * Creates headers object from key-value pairs
828
+ * @param headersObj - Object containing header key-value pairs
829
+ * @returns Headers object with all values converted to strings
830
+ *
831
+ * @example
832
+ * ```typescript
833
+ * // Single header
834
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
835
+ *
836
+ * // Multiple headers
837
+ * const headers = createHeaders({
838
+ * 'X-UIPATH-FolderKey': '1234567890',
839
+ * 'X-UIPATH-OrganizationUnitId': 123,
840
+ * 'Accept': 'application/json'
841
+ * });
842
+ *
843
+ * // Using constants
844
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
845
+ * const headers = createHeaders({
846
+ * [FOLDER_KEY]: 'abc-123',
847
+ * [FOLDER_ID]: 456
848
+ * });
849
+ *
850
+ * // Empty headers
851
+ * const headers = createHeaders();
852
+ * ```
853
+ */
854
+ function createHeaders(headersObj) {
855
+ const headers = {};
856
+ for (const [key, value] of Object.entries(headersObj)) {
857
+ if (value !== undefined && value !== null) {
858
+ headers[key] = value.toString();
859
+ }
860
+ }
861
+ return headers;
862
+ }
863
+
864
+ /**
865
+ * Common constants used across the SDK
866
+ */
867
+ /**
868
+ * Prefix used for OData query parameters
869
+ */
870
+ const ODATA_PREFIX = '$';
871
+ /**
872
+ * HTTP methods
873
+ */
874
+ const HTTP_METHODS = {
875
+ GET: 'GET',
876
+ POST: 'POST'};
877
+ /**
878
+ * OData pagination constants
879
+ */
880
+ const ODATA_PAGINATION = {
881
+ /** Default field name for items in a paginated OData response */
882
+ ITEMS_FIELD: 'value',
883
+ /** Default field name for total count in a paginated OData response */
884
+ TOTAL_COUNT_FIELD: '@odata.count'
885
+ };
886
+ /**
887
+ * OData OFFSET pagination parameter names (ODATA-style)
888
+ */
889
+ const ODATA_OFFSET_PARAMS = {
890
+ /** OData page size parameter name */
891
+ PAGE_SIZE_PARAM: '$top',
892
+ /** OData offset parameter name */
893
+ OFFSET_PARAM: '$skip',
894
+ /** OData count parameter name */
895
+ COUNT_PARAM: '$count'
896
+ };
897
+ /**
898
+ * Bucket TOKEN pagination parameter names
899
+ */
900
+ const BUCKET_TOKEN_PARAMS = {
901
+ /** Bucket page size parameter name */
902
+ PAGE_SIZE_PARAM: 'takeHint',
903
+ /** Bucket token parameter name */
904
+ TOKEN_PARAM: 'continuationToken'
905
+ };
906
+
907
+ /**
908
+ * Transforms data by mapping fields according to the provided field mapping
909
+ * @param data The source data to transform
910
+ * @param fieldMapping Object mapping source field names to target field names
911
+ * @returns Transformed data with mapped field names
912
+ *
913
+ * @example
914
+ * ```typescript
915
+ * // Single object transformation
916
+ * const data = { id: '123', userName: 'john' };
917
+ * const mapping = { id: 'userId', userName: 'name' };
918
+ * const result = transformData(data, mapping);
919
+ * // result = { userId: '123', name: 'john' }
920
+ *
921
+ * // Array transformation
922
+ * const dataArray = [
923
+ * { id: '123', userName: 'john' },
924
+ * { id: '456', userName: 'jane' }
925
+ * ];
926
+ * const result = transformData(dataArray, mapping);
927
+ * // result = [
928
+ * // { userId: '123', name: 'john' },
929
+ * // { userId: '456', name: 'jane' }
930
+ * // ]
931
+ * ```
932
+ */
933
+ function transformData(data, fieldMapping) {
934
+ // Handle array of objects
935
+ if (Array.isArray(data)) {
936
+ return data.map(item => transformData(item, fieldMapping));
937
+ }
938
+ // Handle single object
939
+ const result = { ...data };
940
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
941
+ if (sourceField in result) {
942
+ const value = result[sourceField];
943
+ delete result[sourceField];
944
+ result[targetField] = value;
945
+ }
946
+ }
947
+ return result;
948
+ }
949
+ /**
950
+ * Converts a string from PascalCase to camelCase
951
+ * @param str The PascalCase string to convert
952
+ * @returns The camelCase version of the string
953
+ *
954
+ * @example
955
+ * ```typescript
956
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
957
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
958
+ * ```
959
+ */
960
+ function pascalToCamelCase(str) {
961
+ if (!str)
962
+ return str;
963
+ return str.charAt(0).toLowerCase() + str.slice(1);
964
+ }
965
+ /**
966
+ * Converts a string from camelCase to PascalCase
967
+ * @param str The camelCase string to convert
968
+ * @returns The PascalCase version of the string
969
+ *
970
+ * @example
971
+ * ```typescript
972
+ * camelToPascalCase('helloWorld'); // 'HelloWorld'
973
+ * camelToPascalCase('taskAssignmentCriteria'); // 'TaskAssignmentCriteria'
974
+ * ```
975
+ */
976
+ function camelToPascalCase(str) {
977
+ if (!str)
978
+ return str;
979
+ return str.charAt(0).toUpperCase() + str.slice(1);
980
+ }
981
+ /**
982
+ * Generic function to transform object keys using a provided case conversion function
983
+ * @param data The object to transform
984
+ * @param convertCase The function to convert each key
985
+ * @returns A new object with transformed keys
986
+ */
987
+ function transformCaseKeys(data, convertCase) {
988
+ // Handle array of objects
989
+ if (Array.isArray(data)) {
990
+ return data.map(item => {
991
+ // If the array element is a primitive (string, number, etc.), return it as is
992
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
993
+ return item;
994
+ }
995
+ // Only recursively transform if it's actually an object
996
+ return transformCaseKeys(item, convertCase);
997
+ });
998
+ }
999
+ const result = {};
1000
+ for (const [key, value] of Object.entries(data)) {
1001
+ const transformedKey = convertCase(key);
1002
+ // Recursively transform nested objects and arrays
1003
+ if (value !== null && typeof value === 'object') {
1004
+ result[transformedKey] = transformCaseKeys(value, convertCase);
1005
+ }
1006
+ else {
1007
+ result[transformedKey] = value;
1008
+ }
1009
+ }
1010
+ return result;
1011
+ }
1012
+ /**
1013
+ * Transforms an object's keys from PascalCase to camelCase
1014
+ * @param data The object with PascalCase keys
1015
+ * @returns A new object with all keys converted to camelCase
1016
+ *
1017
+ * @example
1018
+ * ```typescript
1019
+ * // Simple object
1020
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
1021
+ * // Result: { id: "123", taskName: "Invoice" }
1022
+ *
1023
+ * // Nested object
1024
+ * pascalToCamelCaseKeys({
1025
+ * TaskId: "456",
1026
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
1027
+ * });
1028
+ * // Result: {
1029
+ * // taskId: "456",
1030
+ * // taskDetails: { assignedUser: "John", priority: "High" }
1031
+ * // }
1032
+ *
1033
+ * // Array of objects
1034
+ * pascalToCamelCaseKeys([
1035
+ * { Id: "1", IsComplete: false },
1036
+ * { Id: "2", IsComplete: true }
1037
+ * ]);
1038
+ * // Result: [
1039
+ * // { id: "1", isComplete: false },
1040
+ * // { id: "2", isComplete: true }
1041
+ * // ]
1042
+ * ```
1043
+ */
1044
+ function pascalToCamelCaseKeys(data) {
1045
+ return transformCaseKeys(data, pascalToCamelCase);
1046
+ }
1047
+ /**
1048
+ * Transforms an object's keys from camelCase to PascalCase
1049
+ * @param data The object with camelCase keys
1050
+ * @returns A new object with all keys converted to PascalCase
1051
+ *
1052
+ * @example
1053
+ * ```typescript
1054
+ * // Simple object
1055
+ * camelToPascalCaseKeys({ userId: "789", isActive: true });
1056
+ * // Result: { UserId: "789", IsActive: true }
1057
+ *
1058
+ * // Nested object
1059
+ * camelToPascalCaseKeys({
1060
+ * taskId: "ABC123",
1061
+ * submissionData: { customerName: "XYZ Corp" }
1062
+ * });
1063
+ * // Result: {
1064
+ * // TaskId: "ABC123",
1065
+ * // SubmissionData: { CustomerName: "XYZ Corp" }
1066
+ * // }
1067
+ *
1068
+ * // Array of objects
1069
+ * camelToPascalCaseKeys([
1070
+ * { userId: "u1", roleType: "admin" },
1071
+ * { userId: "u2", roleType: "user" }
1072
+ * ]);
1073
+ * // Result: [
1074
+ * // { UserId: "u1", RoleType: "admin" },
1075
+ * // { UserId: "u2", RoleType: "user" }
1076
+ * // ]
1077
+ * ```
1078
+ */
1079
+ function camelToPascalCaseKeys(data) {
1080
+ return transformCaseKeys(data, camelToPascalCase);
1081
+ }
1082
+ /**
1083
+ * Maps a field value in an object using a provided mapping object.
1084
+ * Returns a new object with the mapped field value.
1085
+ *
1086
+ * @param obj The object to map
1087
+ * @param field The field name to map
1088
+ * @param valueMap The mapping object (from input value to output value)
1089
+ * @returns A new object with the mapped field value
1090
+ *
1091
+ * @example
1092
+ * const statusMap = { 0: 'Unassigned', 1: 'Pending', 2: 'Completed' };
1093
+ * const task = { status: 1, id: 123 };
1094
+ * const mapped = mapFieldValue(task, 'status', statusMap);
1095
+ * // mapped = { status: 'Pending', id: 123 }
1096
+ */
1097
+ function _mapFieldValue(obj, field, valueMap) {
1098
+ const lookupKey = String(obj[field]);
1099
+ return {
1100
+ ...obj,
1101
+ [field]: lookupKey in valueMap
1102
+ ? valueMap[lookupKey]
1103
+ : obj[field],
1104
+ };
1105
+ }
1106
+ /**
1107
+ * General API response transformer with optional field value mapping.
1108
+ *
1109
+ * @param data - The API response data to transform
1110
+ * @param options - Optional mapping options:
1111
+ * - field: The field name to map (optional)
1112
+ * - valueMap: The mapping object for the field (optional)
1113
+ * - transform: A function to further transform the data (optional)
1114
+ * @returns The transformed data, with field value mapped if specified
1115
+ *
1116
+ * @example
1117
+ * // Just transform
1118
+ * const result = applyDataTransforms(data);
1119
+ *
1120
+ * // Map a field value, then transform
1121
+ * const result = applyDataTransforms(data, { field: 'status', valueMap: StatusMap });
1122
+ *
1123
+ * // Map a field value, then apply a custom transform
1124
+ * const result = applyDataTransforms(data, { field: 'status', valueMap: StatusMap, transform: customTransform });
1125
+ */
1126
+ function applyDataTransforms(data, options) {
1127
+ let result = data;
1128
+ if (options?.field && options?.valueMap) {
1129
+ result = _mapFieldValue(result, options.field, options.valueMap);
1130
+ }
1131
+ if (options?.transform) {
1132
+ result = options.transform(result);
1133
+ }
1134
+ return result;
1135
+ }
1136
+ /**
1137
+ * Adds a prefix to specified keys in an object, returning a new object.
1138
+ * Only the provided keys are prefixed; all others are left unchanged.
1139
+ *
1140
+ * @param obj The source object
1141
+ * @param prefix The prefix to add (e.g., '$')
1142
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1143
+ * @returns A new object with specified keys prefixed
1144
+ *
1145
+ * @example
1146
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1147
+ */
1148
+ function addPrefixToKeys(obj, prefix, keys) {
1149
+ const result = {};
1150
+ for (const [key, value] of Object.entries(obj)) {
1151
+ if (keys.includes(key)) {
1152
+ result[`${prefix}${key}`] = value;
1153
+ }
1154
+ else {
1155
+ result[key] = value;
1156
+ }
1157
+ }
1158
+ return result;
1159
+ }
1160
+
1161
+ /**
1162
+ * Constants used throughout the pagination system
1163
+ */
1164
+ /** Maximum number of items that can be requested in a single page */
1165
+ const MAX_PAGE_SIZE = 1000;
1166
+ /** Default page size when jumpToPage is used without specifying pageSize */
1167
+ const DEFAULT_PAGE_SIZE = 50;
1168
+ /** Default field name for items in a paginated response */
1169
+ const DEFAULT_ITEMS_FIELD = 'value';
1170
+ /** Default field name for total count in a paginated response */
1171
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1172
+ /**
1173
+ * Limits the page size to the maximum allowed value
1174
+ * @param pageSize - Requested page size
1175
+ * @returns Limited page size value
1176
+ */
1177
+ function getLimitedPageSize(pageSize) {
1178
+ if (pageSize === undefined || pageSize === null) {
1179
+ return DEFAULT_PAGE_SIZE;
1180
+ }
1181
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1182
+ }
1183
+
1184
+ /**
1185
+ * Helper functions for pagination that can be used across services
1186
+ */
1187
+ class PaginationHelpers {
1188
+ /**
1189
+ * Checks if any pagination parameters are provided
1190
+ *
1191
+ * @param options - The options object to check
1192
+ * @returns True if any pagination parameter is defined, false otherwise
1193
+ */
1194
+ static hasPaginationParameters(options = {}) {
1195
+ const { cursor, pageSize, jumpToPage } = options;
1196
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1197
+ }
1198
+ /**
1199
+ * Parse a pagination cursor string into cursor data
1200
+ */
1201
+ static parseCursor(cursorString) {
1202
+ try {
1203
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1204
+ return cursorData;
1205
+ }
1206
+ catch {
1207
+ throw new Error('Invalid pagination cursor');
1208
+ }
1209
+ }
1210
+ /**
1211
+ * Validates cursor format and structure
1212
+ *
1213
+ * @param paginationOptions - The pagination options containing the cursor
1214
+ * @param paginationType - Optional pagination type to validate against
1215
+ */
1216
+ static validateCursor(paginationOptions, paginationType) {
1217
+ if (paginationOptions.cursor !== undefined) {
1218
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1219
+ throw new Error('cursor must contain a valid cursor string');
1220
+ }
1221
+ try {
1222
+ // Try to parse the cursor to validate it
1223
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1224
+ // If type is provided, validate cursor contains expected type information
1225
+ if (paginationType) {
1226
+ if (!cursorData.type) {
1227
+ throw new Error('Invalid cursor: missing pagination type');
1228
+ }
1229
+ // Check pagination type compatibility
1230
+ if (cursorData.type !== paginationType) {
1231
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1232
+ }
1233
+ }
1234
+ }
1235
+ catch (error) {
1236
+ if (error instanceof Error) {
1237
+ // If it's already our error with specific message, pass it through
1238
+ if (error.message.startsWith('Invalid cursor') ||
1239
+ error.message.startsWith('Pagination type mismatch')) {
1240
+ throw error;
1241
+ }
1242
+ }
1243
+ throw new Error('Invalid pagination cursor format');
1244
+ }
1245
+ }
1246
+ }
1247
+ /**
1248
+ * Comprehensive validation for pagination options
1249
+ *
1250
+ * @param options - The pagination options to validate
1251
+ * @param paginationType - The pagination type these options will be used with
1252
+ * @returns Processed pagination parameters ready for use
1253
+ */
1254
+ static validatePaginationOptions(options, paginationType) {
1255
+ // Validate pageSize
1256
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1257
+ throw new Error('pageSize must be a positive number');
1258
+ }
1259
+ // Validate jumpToPage
1260
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1261
+ throw new Error('jumpToPage must be a positive number');
1262
+ }
1263
+ // Validate cursor
1264
+ PaginationHelpers.validateCursor(options, paginationType);
1265
+ // Validate service compatibility
1266
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1267
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1268
+ }
1269
+ // Get processed parameters
1270
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1271
+ }
1272
+ /**
1273
+ * Convert a unified pagination options to service-specific parameters
1274
+ */
1275
+ static getRequestParameters(options, paginationType) {
1276
+ // Handle jumpToPage
1277
+ if (options.jumpToPage !== undefined) {
1278
+ const jumpToPageOptions = {
1279
+ pageSize: options.pageSize,
1280
+ pageNumber: options.jumpToPage
1281
+ };
1282
+ return filterUndefined(jumpToPageOptions);
1283
+ }
1284
+ // If no cursor is provided, it's a first page request
1285
+ if (!options.cursor) {
1286
+ const firstPageOptions = {
1287
+ pageSize: options.pageSize,
1288
+ // Only set pageNumber for OFFSET pagination
1289
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1290
+ };
1291
+ return filterUndefined(firstPageOptions);
1292
+ }
1293
+ // Parse the cursor
1294
+ try {
1295
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1296
+ const cursorBasedOptions = {
1297
+ pageSize: cursorData.pageSize || options.pageSize,
1298
+ pageNumber: cursorData.pageNumber,
1299
+ continuationToken: cursorData.continuationToken,
1300
+ type: cursorData.type,
1301
+ };
1302
+ return filterUndefined(cursorBasedOptions);
1303
+ }
1304
+ catch {
1305
+ throw new Error('Invalid pagination cursor');
1306
+ }
1307
+ }
1308
+ /**
1309
+ * Helper method for paginated resource retrieval
1310
+ *
1311
+ * @param params - Parameters for pagination
1312
+ * @returns Promise resolving to a paginated result
1313
+ */
1314
+ static async getAllPaginated(params) {
1315
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1316
+ const endpoint = getEndpoint(folderId);
1317
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1318
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1319
+ headers,
1320
+ params: additionalParams,
1321
+ pagination: {
1322
+ paginationType: options.paginationType || PaginationType.OFFSET,
1323
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1324
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1325
+ continuationTokenField: options.continuationTokenField,
1326
+ paginationParams: options.paginationParams
1327
+ }
1328
+ });
1329
+ // Parse items - automatically handle JSON string responses
1330
+ const rawItems = paginatedResponse.items;
1331
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1332
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1333
+ return {
1334
+ ...paginatedResponse,
1335
+ items: transformedItems
1336
+ };
1337
+ }
1338
+ /**
1339
+ * Helper method for non-paginated resource retrieval
1340
+ *
1341
+ * @param params - Parameters for non-paginated resource retrieval
1342
+ * @returns Promise resolving to an object with data and totalCount
1343
+ */
1344
+ static async getAllNonPaginated(params) {
1345
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1346
+ // Set default field names
1347
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1348
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1349
+ // Determine endpoint and headers based on folderId
1350
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1351
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1352
+ // Make the API call based on method
1353
+ let response;
1354
+ if (method === HTTP_METHODS.POST) {
1355
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1356
+ }
1357
+ else {
1358
+ response = await serviceAccess.get(endpoint, {
1359
+ params: additionalParams,
1360
+ headers
1361
+ });
1362
+ }
1363
+ // Extract and transform items from response
1364
+ const rawItems = response.data?.[itemsField];
1365
+ const totalCount = response.data?.[totalCountField];
1366
+ // Parse items - automatically handle JSON string responses
1367
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1368
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1369
+ return {
1370
+ items,
1371
+ totalCount
1372
+ };
1373
+ }
1374
+ /**
1375
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1376
+ *
1377
+ * @param config - Configuration for the getAll operation
1378
+ * @param options - Request options including pagination parameters
1379
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1380
+ */
1381
+ static async getAll(config, options) {
1382
+ const optionsWithDefaults = options || {};
1383
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1384
+ // Determine if pagination is requested
1385
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1386
+ // Process parameters (custom processing if provided, otherwise default)
1387
+ let processedOptions = restOptions;
1388
+ if (config.processParametersFn) {
1389
+ processedOptions = config.processParametersFn(restOptions, folderId);
1390
+ }
1391
+ // Apply ODATA prefix to keys (excluding specified keys)
1392
+ const excludeKeys = config.excludeFromPrefix || [];
1393
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1394
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1395
+ // Default pagination options
1396
+ const paginationOptions = {
1397
+ paginationType: PaginationType.OFFSET,
1398
+ itemsField: DEFAULT_ITEMS_FIELD,
1399
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1400
+ ...config.pagination
1401
+ };
1402
+ // Paginated flow
1403
+ if (isPaginationRequested) {
1404
+ return PaginationHelpers.getAllPaginated({
1405
+ serviceAccess: config.serviceAccess,
1406
+ getEndpoint: config.getEndpoint,
1407
+ folderId,
1408
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1409
+ additionalParams: prefixedOptions,
1410
+ transformFn: config.transformFn,
1411
+ method: config.method,
1412
+ options: {
1413
+ ...paginationOptions,
1414
+ paginationParams: config.pagination?.paginationParams
1415
+ }
1416
+ }); // Type assertion needed due to conditional return
1417
+ }
1418
+ // Non-paginated flow
1419
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1420
+ return PaginationHelpers.getAllNonPaginated({
1421
+ serviceAccess: config.serviceAccess,
1422
+ getAllEndpoint: config.getEndpoint(),
1423
+ getByFolderEndpoint: byFolderEndpoint,
1424
+ folderId,
1425
+ additionalParams: prefixedOptions,
1426
+ transformFn: config.transformFn,
1427
+ method: config.method,
1428
+ options: {
1429
+ itemsField: paginationOptions.itemsField,
1430
+ totalCountField: paginationOptions.totalCountField
1431
+ }
1432
+ });
1433
+ }
1434
+ }
1435
+
1436
+ /**
1437
+ * SDK Internals Registry - Internal registry for SDK instances
1438
+ *
1439
+ * This class is NOT exported in the public API.
1440
+ * It provides a secure way to share SDK internals between
1441
+ * the UiPath class and service classes without exposing them publicly.
1442
+ *
1443
+ * @internal
1444
+ */
1445
+ // Global symbol key to ensure WeakMap is shared across module instances
1446
+ // This prevents issues when core and service modules are bundled separately
1447
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1448
+ // Get or create the global WeakMap store
1449
+ const getGlobalStore = () => {
1450
+ const globalObj = globalThis;
1451
+ if (!globalObj[REGISTRY_KEY]) {
1452
+ globalObj[REGISTRY_KEY] = new WeakMap();
1453
+ }
1454
+ return globalObj[REGISTRY_KEY];
1455
+ };
1456
+ /**
1457
+ * Internal registry for SDK private components.
1458
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1459
+ * garbage collected when the SDK instance is no longer referenced.
1460
+ *
1461
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1462
+ * across separately bundled modules (core, entities, tasks, etc.).
1463
+ *
1464
+ * @internal - Not exported in public API
1465
+ */
1466
+ class SDKInternalsRegistry {
1467
+ // Use global store to ensure sharing across module bundles
1468
+ static get store() {
1469
+ return getGlobalStore();
1470
+ }
1471
+ /**
1472
+ * Register SDK instance internals
1473
+ * Called by UiPath constructor
1474
+ */
1475
+ static set(instance, internals) {
1476
+ this.store.set(instance, internals);
1477
+ }
1478
+ /**
1479
+ * Retrieve SDK instance internals
1480
+ * Called by BaseService constructor
1481
+ */
1482
+ static get(instance) {
1483
+ const internals = this.store.get(instance);
1484
+ if (!internals) {
1485
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1486
+ }
1487
+ return internals;
1488
+ }
1489
+ }
1490
+
1491
+ var _BaseService_apiClient;
1492
+ /**
1493
+ * Base class for all UiPath SDK services.
1494
+ *
1495
+ * Provides common functionality for authentication, configuration, and API communication.
1496
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1497
+ *
1498
+ * This class implements the dependency injection pattern where services receive a configured
1499
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1500
+ * including authentication token management.
1501
+ *
1502
+ * @remarks
1503
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1504
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1505
+ *
1506
+ */
1507
+ class BaseService {
1508
+ /**
1509
+ * Creates a base service instance with dependency injection.
1510
+ *
1511
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1512
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1513
+ * and token management internally.
1514
+ *
1515
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1516
+ * Services receive this via dependency injection in the modular pattern.
1517
+ *
1518
+ * @example
1519
+ * ```typescript
1520
+ * // Services automatically call this via super()
1521
+ * export class EntityService extends BaseService {
1522
+ * constructor(instance: IUiPath) {
1523
+ * super(instance); // Initializes the internal ApiClient
1524
+ * }
1525
+ * }
1526
+ *
1527
+ * // Usage in modular pattern
1528
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1529
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1530
+ *
1531
+ * const sdk = new UiPath(config);
1532
+ * await sdk.initialize();
1533
+ * const entities = new Entities(sdk);
1534
+ * ```
1535
+ */
1536
+ constructor(instance) {
1537
+ // Private field - not visible via Object.keys() or any reflection
1538
+ _BaseService_apiClient.set(this, void 0);
1539
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1540
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1541
+ }
1542
+ /**
1543
+ * Gets a valid authentication token, refreshing if necessary.
1544
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1545
+ *
1546
+ * @returns Promise resolving to a valid access token string
1547
+ * @throws AuthenticationError if no token is available or refresh fails
1548
+ */
1549
+ async getValidAuthToken() {
1550
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1551
+ }
1552
+ /**
1553
+ * Creates a service accessor for pagination helpers
1554
+ * This allows pagination helpers to access protected methods without making them public
1555
+ */
1556
+ createPaginationServiceAccess() {
1557
+ return {
1558
+ get: (path, options) => this.get(path, options || {}),
1559
+ post: (path, body, options) => this.post(path, body, options || {}),
1560
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1561
+ };
1562
+ }
1563
+ async request(method, path, options = {}) {
1564
+ switch (method.toUpperCase()) {
1565
+ case 'GET':
1566
+ return this.get(path, options);
1567
+ case 'POST':
1568
+ return this.post(path, options.body, options);
1569
+ case 'PUT':
1570
+ return this.put(path, options.body, options);
1571
+ case 'PATCH':
1572
+ return this.patch(path, options.body, options);
1573
+ case 'DELETE':
1574
+ return this.delete(path, options);
1575
+ default:
1576
+ throw new Error(`Unsupported HTTP method: ${method}`);
1577
+ }
1578
+ }
1579
+ async requestWithSpec(spec) {
1580
+ if (!spec.method || !spec.url) {
1581
+ throw new Error('Request spec must include method and url');
1582
+ }
1583
+ return this.request(spec.method, spec.url, spec);
1584
+ }
1585
+ async get(path, options = {}) {
1586
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1587
+ return { data: response };
1588
+ }
1589
+ async post(path, data, options = {}) {
1590
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1591
+ return { data: response };
1592
+ }
1593
+ async put(path, data, options = {}) {
1594
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1595
+ return { data: response };
1596
+ }
1597
+ async patch(path, data, options = {}) {
1598
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1599
+ return { data: response };
1600
+ }
1601
+ async delete(path, options = {}) {
1602
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1603
+ return { data: response };
1604
+ }
1605
+ /**
1606
+ * Execute a request with cursor-based pagination
1607
+ */
1608
+ async requestWithPagination(method, path, paginationOptions, options) {
1609
+ const paginationType = options.pagination.paginationType;
1610
+ // Validate and prepare pagination parameters
1611
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1612
+ // Prepare request parameters based on pagination type
1613
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1614
+ // For POST requests, merge pagination params into body; for GET, use query params
1615
+ if (method.toUpperCase() === 'POST') {
1616
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1617
+ options.body = {
1618
+ ...existingBody,
1619
+ ...options.params,
1620
+ ...requestParams
1621
+ };
1622
+ }
1623
+ else {
1624
+ // Merge pagination parameters with existing parameters
1625
+ options.params = {
1626
+ ...options.params,
1627
+ ...requestParams
1628
+ };
1629
+ }
1630
+ // Make the request
1631
+ const response = await this.request(method, path, options);
1632
+ // Extract data from the response and create page result
1633
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1634
+ itemsField: options.pagination.itemsField,
1635
+ totalCountField: options.pagination.totalCountField,
1636
+ continuationTokenField: options.pagination.continuationTokenField
1637
+ });
1638
+ }
1639
+ /**
1640
+ * Validates and prepares pagination parameters from options
1641
+ */
1642
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1643
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1644
+ }
1645
+ /**
1646
+ * Prepares request parameters for pagination based on pagination type
1647
+ */
1648
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1649
+ const requestParams = {};
1650
+ let limitedPageSize;
1651
+ const paginationParams = paginationConfig?.paginationParams;
1652
+ switch (paginationType) {
1653
+ case PaginationType.OFFSET:
1654
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1655
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1656
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1657
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1658
+ requestParams[pageSizeParam] = limitedPageSize;
1659
+ if (params.pageNumber && params.pageNumber > 1) {
1660
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1661
+ }
1662
+ // Include total count for ODATA APIs
1663
+ {
1664
+ requestParams[countParam] = true;
1665
+ }
1666
+ break;
1667
+ case PaginationType.TOKEN:
1668
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1669
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1670
+ if (params.pageSize) {
1671
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1672
+ }
1673
+ if (params.continuationToken) {
1674
+ requestParams[tokenParam] = params.continuationToken;
1675
+ }
1676
+ break;
1677
+ }
1678
+ return requestParams;
1679
+ }
1680
+ /**
1681
+ * Creates a paginated response from API response
1682
+ */
1683
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1684
+ // Extract fields from response
1685
+ const itemsField = fields.itemsField ||
1686
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1687
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1688
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1689
+ // Extract items and metadata
1690
+ const items = response.data[itemsField] || [];
1691
+ const totalCount = response.data[totalCountField];
1692
+ const continuationToken = response.data[continuationTokenField];
1693
+ // Determine if there are more pages
1694
+ const hasMore = this.determineHasMorePages(paginationType, {
1695
+ totalCount,
1696
+ pageSize: params.pageSize,
1697
+ currentPage: params.pageNumber || 1,
1698
+ itemsCount: items.length,
1699
+ continuationToken
1700
+ });
1701
+ // Create and return the page result
1702
+ return PaginationManager.createPaginatedResponse({
1703
+ pageInfo: {
1704
+ hasMore,
1705
+ totalCount,
1706
+ currentPage: params.pageNumber,
1707
+ pageSize: params.pageSize,
1708
+ continuationToken
1709
+ },
1710
+ type: paginationType,
1711
+ }, items);
1712
+ }
1713
+ /**
1714
+ * Determines if there are more pages based on pagination type and metadata
1715
+ */
1716
+ determineHasMorePages(paginationType, info) {
1717
+ switch (paginationType) {
1718
+ case PaginationType.OFFSET:
1719
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1720
+ // If totalCount is available, use it for precise calculation
1721
+ if (info.totalCount !== undefined) {
1722
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1723
+ }
1724
+ // Fallback when totalCount is not available
1725
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1726
+ return info.itemsCount === effectivePageSize;
1727
+ case PaginationType.TOKEN:
1728
+ return !!info.continuationToken;
1729
+ default:
1730
+ return false;
1731
+ }
1732
+ }
1733
+ }
1734
+ _BaseService_apiClient = new WeakMap();
1735
+
1736
+ var TaskType;
1737
+ (function (TaskType) {
1738
+ TaskType["Form"] = "FormTask";
1739
+ TaskType["External"] = "ExternalTask";
1740
+ TaskType["App"] = "AppTask";
1741
+ })(TaskType || (TaskType = {}));
1742
+ var TaskPriority;
1743
+ (function (TaskPriority) {
1744
+ TaskPriority["Low"] = "Low";
1745
+ TaskPriority["Medium"] = "Medium";
1746
+ TaskPriority["High"] = "High";
1747
+ TaskPriority["Critical"] = "Critical";
1748
+ })(TaskPriority || (TaskPriority = {}));
1749
+ var TaskStatus;
1750
+ (function (TaskStatus) {
1751
+ TaskStatus["Unassigned"] = "Unassigned";
1752
+ TaskStatus["Pending"] = "Pending";
1753
+ TaskStatus["Completed"] = "Completed";
1754
+ })(TaskStatus || (TaskStatus = {}));
1755
+ var TaskSlaCriteria;
1756
+ (function (TaskSlaCriteria) {
1757
+ TaskSlaCriteria["TaskCreated"] = "TaskCreated";
1758
+ TaskSlaCriteria["TaskAssigned"] = "TaskAssigned";
1759
+ TaskSlaCriteria["TaskCompleted"] = "TaskCompleted";
1760
+ })(TaskSlaCriteria || (TaskSlaCriteria = {}));
1761
+ var TaskSlaStatus;
1762
+ (function (TaskSlaStatus) {
1763
+ TaskSlaStatus["OverdueLater"] = "OverdueLater";
1764
+ TaskSlaStatus["OverdueSoon"] = "OverdueSoon";
1765
+ TaskSlaStatus["Overdue"] = "Overdue";
1766
+ TaskSlaStatus["CompletedInTime"] = "CompletedInTime";
1767
+ })(TaskSlaStatus || (TaskSlaStatus = {}));
1768
+ var TaskSourceName;
1769
+ (function (TaskSourceName) {
1770
+ TaskSourceName["Agent"] = "Agent";
1771
+ TaskSourceName["Workflow"] = "Workflow";
1772
+ TaskSourceName["Maestro"] = "Maestro";
1773
+ TaskSourceName["Default"] = "Default";
1774
+ })(TaskSourceName || (TaskSourceName = {}));
1775
+ /**
1776
+ * Task activity types
1777
+ */
1778
+ var TaskActivityType;
1779
+ (function (TaskActivityType) {
1780
+ TaskActivityType["Created"] = "Created";
1781
+ TaskActivityType["Assigned"] = "Assigned";
1782
+ TaskActivityType["Reassigned"] = "Reassigned";
1783
+ TaskActivityType["Unassigned"] = "Unassigned";
1784
+ TaskActivityType["Saved"] = "Saved";
1785
+ TaskActivityType["Forwarded"] = "Forwarded";
1786
+ TaskActivityType["Completed"] = "Completed";
1787
+ TaskActivityType["Commented"] = "Commented";
1788
+ TaskActivityType["Deleted"] = "Deleted";
1789
+ TaskActivityType["BulkSaved"] = "BulkSaved";
1790
+ TaskActivityType["BulkCompleted"] = "BulkCompleted";
1791
+ TaskActivityType["FirstOpened"] = "FirstOpened";
1792
+ })(TaskActivityType || (TaskActivityType = {}));
1793
+
1794
+ /**
1795
+ * Creates methods for a task
1796
+ *
1797
+ * @param taskData - The task data (response from API)
1798
+ * @param service - The task service instance
1799
+ * @returns Object containing task methods
1800
+ */
1801
+ function createTaskMethods(taskData, service) {
1802
+ return {
1803
+ async assign(options) {
1804
+ if (!taskData.id)
1805
+ throw new Error('Task ID is undefined');
1806
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
1807
+ ? { taskId: taskData.id, userId: options.userId }
1808
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
1809
+ return service.assign(assignmentOptions);
1810
+ },
1811
+ async reassign(options) {
1812
+ if (!taskData.id)
1813
+ throw new Error('Task ID is undefined');
1814
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
1815
+ ? { taskId: taskData.id, userId: options.userId }
1816
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
1817
+ return service.reassign(assignmentOptions);
1818
+ },
1819
+ async unassign() {
1820
+ if (!taskData.id)
1821
+ throw new Error('Task ID is undefined');
1822
+ return service.unassign(taskData.id);
1823
+ },
1824
+ async complete(options) {
1825
+ if (!taskData.id)
1826
+ throw new Error('Task ID is undefined');
1827
+ const folderId = taskData.folderId;
1828
+ if (!folderId)
1829
+ throw new Error('Folder ID is required');
1830
+ return service.complete({
1831
+ type: options.type,
1832
+ taskId: taskData.id,
1833
+ data: options.data,
1834
+ action: options.action
1835
+ }, folderId);
1836
+ }
1837
+ };
1838
+ }
1839
+ /**
1840
+ * Creates an actionable task by combining API task data with operational methods.
1841
+ *
1842
+ * @param taskData - The task data from API
1843
+ * @param service - The task service instance
1844
+ * @returns A task object with added methods
1845
+ */
1846
+ function createTaskWithMethods(taskData, service) {
1847
+ const methods = createTaskMethods(taskData, service);
1848
+ return Object.assign({}, taskData, methods);
1849
+ }
1850
+
1851
+ /**
1852
+ * Maps numeric TaskStatus values (from API) to TaskStatus enum values.
1853
+ * Extend this file with additional field mappings as needed.
1854
+ */
1855
+ const TaskStatusMap = {
1856
+ 0: TaskStatus.Unassigned,
1857
+ 1: TaskStatus.Pending,
1858
+ 2: TaskStatus.Completed,
1859
+ };
1860
+ // Field mapping for time-related fields to ensure consistent naming
1861
+ const TaskMap = {
1862
+ completionTime: 'completedTime',
1863
+ deletionTime: 'deletedTime',
1864
+ lastModificationTime: 'lastModifiedTime',
1865
+ creationTime: 'createdTime',
1866
+ organizationUnitId: 'folderId'
1867
+ };
1868
+ /**
1869
+ * Default expand parameters
1870
+ */
1871
+ const DEFAULT_TASK_EXPAND = 'AssignedToUser,CreatorUser,LastModifierUser';
1872
+
1873
+ /**
1874
+ * Base path constants for different services
1875
+ */
1876
+ const ORCHESTRATOR_BASE = 'orchestrator_';
1877
+
1878
+ /**
1879
+ * Orchestrator Service Endpoints
1880
+ */
1881
+ /**
1882
+ * Task Service (Action Center) Endpoints
1883
+ */
1884
+ const TASK_ENDPOINTS = {
1885
+ CREATE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CreateTask`,
1886
+ GET_TASK_USERS: (folderId) => `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTaskUsers(organizationUnitId=${folderId})`,
1887
+ GET_TASKS_ACROSS_FOLDERS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFolders`,
1888
+ GET_TASKS_ACROSS_FOLDERS_ADMIN: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFoldersForAdmin`,
1889
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Tasks(${id})`,
1890
+ ASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.AssignTasks`,
1891
+ REASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.ReassignTasks`,
1892
+ UNASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.UnassignTasks`,
1893
+ COMPLETE_FORM_TASK: `${ORCHESTRATOR_BASE}/forms/TaskForms/CompleteTask`,
1894
+ COMPLETE_APP_TASK: `${ORCHESTRATOR_BASE}/tasks/AppTasks/CompleteAppTask`,
1895
+ COMPLETE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CompleteTask`,
1896
+ GET_TASK_FORM_BY_ID: `${ORCHESTRATOR_BASE}/forms/TaskForms/GetTaskFormById`,
1897
+ };
1898
+
1899
+ /**
1900
+ * SDK Telemetry constants
1901
+ */
1902
+ // Connection string placeholder that will be replaced during build
1903
+ 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";
1904
+ // SDK Version placeholder
1905
+ const SDK_VERSION = "1.1.0";
1906
+ const VERSION = "Version";
1907
+ const SERVICE = "Service";
1908
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1909
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1910
+ const CLOUD_URL = "CloudUrl";
1911
+ const CLOUD_CLIENT_ID = "CloudClientId";
1912
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1913
+ const APP_NAME = "ApplicationName";
1914
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1915
+ // Service and logger names
1916
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1917
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1918
+ // Event names
1919
+ const SDK_RUN_EVENT = "Sdk.Run";
1920
+ // Default value for unknown/empty attributes
1921
+ const UNKNOWN = "";
1922
+
1923
+ /**
1924
+ * Log exporter that sends ALL logs as Application Insights custom events
1925
+ */
1926
+ class ApplicationInsightsEventExporter {
1927
+ constructor(connectionString) {
1928
+ this.connectionString = connectionString;
1929
+ }
1930
+ export(logs, resultCallback) {
1931
+ try {
1932
+ logs.forEach(logRecord => {
1933
+ this.sendAsCustomEvent(logRecord);
1934
+ });
1935
+ resultCallback({ code: 0 });
1936
+ }
1937
+ catch (error) {
1938
+ console.debug('Failed to export logs to Application Insights:', error);
1939
+ resultCallback({ code: 2, error });
1940
+ }
1941
+ }
1942
+ shutdown() {
1943
+ return Promise.resolve();
1944
+ }
1945
+ sendAsCustomEvent(logRecord) {
1946
+ // Get event name from body or attributes
1947
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1948
+ const payload = {
1949
+ name: 'Microsoft.ApplicationInsights.Event',
1950
+ time: new Date().toISOString(),
1951
+ iKey: this.extractInstrumentationKey(),
1952
+ data: {
1953
+ baseType: 'EventData',
1954
+ baseData: {
1955
+ ver: 2,
1956
+ name: eventName,
1957
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1958
+ }
1959
+ },
1960
+ tags: {
1961
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1962
+ 'ai.cloud.roleInstance': SDK_VERSION
1963
+ }
1964
+ };
1965
+ this.sendToApplicationInsights(payload);
1966
+ }
1967
+ extractInstrumentationKey() {
1968
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1969
+ return match ? match[1] : '';
1970
+ }
1971
+ convertAttributesToProperties(attributes) {
1972
+ const properties = {};
1973
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1974
+ properties[key] = String(value);
1975
+ });
1976
+ return properties;
1977
+ }
1978
+ async sendToApplicationInsights(payload) {
1979
+ try {
1980
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1981
+ if (!ingestionEndpoint) {
1982
+ console.debug('No ingestion endpoint found in connection string');
1983
+ return;
1984
+ }
1985
+ const url = `${ingestionEndpoint}/v2/track`;
1986
+ const response = await fetch(url, {
1987
+ method: 'POST',
1988
+ headers: {
1989
+ 'Content-Type': 'application/json',
1990
+ },
1991
+ body: JSON.stringify(payload)
1992
+ });
1993
+ if (!response.ok) {
1994
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1995
+ }
1996
+ }
1997
+ catch (error) {
1998
+ console.debug('Error sending event telemetry to Application Insights:', error);
1999
+ }
2000
+ }
2001
+ extractIngestionEndpoint() {
2002
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
2003
+ return match ? match[1] : '';
2004
+ }
2005
+ }
2006
+ /**
2007
+ * Singleton telemetry client
2008
+ */
2009
+ class TelemetryClient {
2010
+ constructor() {
2011
+ this.isInitialized = false;
2012
+ }
2013
+ static getInstance() {
2014
+ if (!TelemetryClient.instance) {
2015
+ TelemetryClient.instance = new TelemetryClient();
2016
+ }
2017
+ return TelemetryClient.instance;
2018
+ }
2019
+ /**
2020
+ * Initialize telemetry
2021
+ */
2022
+ initialize(config) {
2023
+ if (this.isInitialized) {
2024
+ return;
2025
+ }
2026
+ this.isInitialized = true;
2027
+ if (config) {
2028
+ this.telemetryContext = config;
2029
+ }
2030
+ try {
2031
+ const connectionString = this.getConnectionString();
2032
+ if (!connectionString) {
2033
+ return;
2034
+ }
2035
+ this.setupTelemetryProvider(connectionString);
2036
+ }
2037
+ catch (error) {
2038
+ // Silent failure - telemetry errors shouldn't break functionality
2039
+ console.debug('Failed to initialize OpenTelemetry:', error);
2040
+ }
2041
+ }
2042
+ getConnectionString() {
2043
+ const connectionString = CONNECTION_STRING;
2044
+ return connectionString;
2045
+ }
2046
+ setupTelemetryProvider(connectionString) {
2047
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
2048
+ const processor = new BatchLogRecordProcessor(exporter);
2049
+ this.logProvider = new LoggerProvider({
2050
+ processors: [processor]
2051
+ });
2052
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
2053
+ }
2054
+ /**
2055
+ * Track a telemetry event
2056
+ */
2057
+ track(eventName, name, extraAttributes = {}) {
2058
+ try {
2059
+ // Skip if logger not initialized
2060
+ if (!this.logger) {
2061
+ return;
2062
+ }
2063
+ const finalDisplayName = name || eventName;
2064
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
2065
+ // Emit as log
2066
+ this.logger.emit({
2067
+ body: finalDisplayName,
2068
+ attributes: attributes,
2069
+ timestamp: Date.now(),
2070
+ });
2071
+ }
2072
+ catch (error) {
2073
+ // Silent failure
2074
+ console.debug('Failed to track telemetry event:', error);
2075
+ }
2076
+ }
2077
+ /**
2078
+ * Get enriched attributes for telemetry events
2079
+ */
2080
+ getEnrichedAttributes(extraAttributes, eventName) {
2081
+ const attributes = {
2082
+ [APP_NAME]: SDK_SERVICE_NAME,
2083
+ [VERSION]: SDK_VERSION,
2084
+ [SERVICE]: eventName,
2085
+ [CLOUD_URL]: this.createCloudUrl(),
2086
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
2087
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
2088
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
2089
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
2090
+ ...extraAttributes,
2091
+ };
2092
+ return attributes;
2093
+ }
2094
+ /**
2095
+ * Create cloud URL from base URL, organization ID, and tenant ID
2096
+ */
2097
+ createCloudUrl() {
2098
+ const baseUrl = this.telemetryContext?.baseUrl;
2099
+ const orgId = this.telemetryContext?.orgName;
2100
+ const tenantId = this.telemetryContext?.tenantName;
2101
+ if (!baseUrl || !orgId || !tenantId) {
2102
+ return UNKNOWN;
2103
+ }
2104
+ return `${baseUrl}/${orgId}/${tenantId}`;
2105
+ }
2106
+ }
2107
+ // Export singleton instance
2108
+ const telemetryClient = TelemetryClient.getInstance();
2109
+
2110
+ /**
2111
+ * SDK Track decorator and function for telemetry
2112
+ */
2113
+ /**
2114
+ * Common tracking logic shared between method and function decorators
2115
+ */
2116
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
2117
+ return function (...args) {
2118
+ // Determine if we should track this call
2119
+ let shouldTrack = true;
2120
+ if (opts.condition !== undefined) {
2121
+ if (typeof opts.condition === 'function') {
2122
+ shouldTrack = opts.condition.apply(this, args);
2123
+ }
2124
+ else {
2125
+ shouldTrack = opts.condition;
2126
+ }
2127
+ }
2128
+ // Track the event if enabled
2129
+ if (shouldTrack) {
2130
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
2131
+ const serviceMethod = typeof nameOrOptions === 'string'
2132
+ ? nameOrOptions
2133
+ : fallbackName;
2134
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
2135
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
2136
+ }
2137
+ // Execute the original function
2138
+ return originalFunction.apply(this, args);
2139
+ };
2140
+ }
2141
+ /**
2142
+ * Track decorator that can be used to automatically track function calls
2143
+ *
2144
+ * Usage:
2145
+ * @track("Service.Method")
2146
+ * function myFunction() { ... }
2147
+ *
2148
+ * @track("Queue.GetAll")
2149
+ * async getAll() { ... }
2150
+ *
2151
+ * @track("Tasks.Create")
2152
+ * async create() { ... }
2153
+ *
2154
+ * @track("Assets.Update", { condition: false })
2155
+ * function myFunction() { ... }
2156
+ *
2157
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
2158
+ * function myFunction() { ... }
2159
+ */
2160
+ function track(nameOrOptions, options) {
2161
+ return function decorator(_target, propertyKey, descriptor) {
2162
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
2163
+ if (descriptor && typeof descriptor.value === 'function') {
2164
+ // Method decorator
2165
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
2166
+ return descriptor;
2167
+ }
2168
+ // Function decorator
2169
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2170
+ };
2171
+ }
2172
+
2173
+ /**
2174
+ * Service for interacting with UiPath Tasks API
2175
+ */
2176
+ class TaskService extends BaseService {
2177
+ constructor() {
2178
+ super(...arguments);
2179
+ /**
2180
+ * Process parameters for task queries with folder filtering
2181
+ * @param options - The REST API options to process
2182
+ * @param folderId - Optional folder ID to filter by
2183
+ * @returns Processed options with folder filtering applied if needed
2184
+ * @private
2185
+ */
2186
+ this.processTaskParameters = (options, folderId) => {
2187
+ // Add default expand parameters
2188
+ const processedOptions = this.addDefaultExpand(options);
2189
+ if (folderId) {
2190
+ // Create or add to existing filter for folder-specific queries
2191
+ if (processedOptions.filter) {
2192
+ processedOptions.filter = `${processedOptions.filter} and organizationUnitId eq ${folderId}`;
2193
+ }
2194
+ else {
2195
+ processedOptions.filter = `organizationUnitId eq ${folderId}`;
2196
+ }
2197
+ }
2198
+ return processedOptions;
2199
+ };
2200
+ }
2201
+ /**
2202
+ * Creates a new task
2203
+ * @param task - The task to be created
2204
+ * @param folderId - Required folder ID
2205
+ * @returns Promise resolving to the created task
2206
+ *
2207
+ * @example
2208
+ * ```typescript
2209
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2210
+ *
2211
+ * const tasks = new Tasks(sdk);
2212
+ * const task = await tasks.create({
2213
+ * title: "My Task",
2214
+ * priority: TaskPriority.Medium,
2215
+ * data: { key: "value" }
2216
+ * }, 123); // folderId is required
2217
+ * ```
2218
+ */
2219
+ async create(task, folderId) {
2220
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2221
+ const externalTask = {
2222
+ ...task,
2223
+ type: TaskType.External //currently only external task is supported
2224
+ };
2225
+ const response = await this.post(TASK_ENDPOINTS.CREATE_GENERIC_TASK, externalTask, { headers });
2226
+ // Transform time fields for consistency
2227
+ const normalizedData = transformData(response.data, TaskMap);
2228
+ const transformedData = applyDataTransforms(normalizedData, { field: 'status', valueMap: TaskStatusMap });
2229
+ return createTaskWithMethods(transformedData, this);
2230
+ }
2231
+ /**
2232
+ * Gets users in the given folder who have Tasks.View and Tasks.Edit permissions
2233
+ *
2234
+ * The method returns either:
2235
+ * - An array of users (when no pagination parameters are provided)
2236
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
2237
+ *
2238
+ * @param folderId - The folder ID to get users from
2239
+ * @param options - Optional query and pagination parameters
2240
+ * @returns Promise resolving to an array of users or paginated result
2241
+ *
2242
+ * @example
2243
+ * ```typescript
2244
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2245
+ *
2246
+ * const tasks = new Tasks(sdk);
2247
+ *
2248
+ * // Standard array return
2249
+ * const users = await tasks.getUsers(123);
2250
+ *
2251
+ * // Get users with filtering
2252
+ * const users = await tasks.getUsers(123, {
2253
+ * filter: "name eq 'abc'"
2254
+ * });
2255
+ *
2256
+ * // First page with pagination
2257
+ * const page1 = await tasks.getUsers(123, { pageSize: 10 });
2258
+ *
2259
+ * // Navigate using cursor
2260
+ * if (page1.hasNextPage) {
2261
+ * const page2 = await tasks.getUsers(123, { cursor: page1.nextCursor });
2262
+ * }
2263
+ *
2264
+ * // Jump to specific page
2265
+ * const page5 = await tasks.getUsers(123, {
2266
+ * jumpToPage: 5,
2267
+ * pageSize: 10
2268
+ * });
2269
+ * ```
2270
+ */
2271
+ async getUsers(folderId, options) {
2272
+ // Transformation function for users
2273
+ const transformUserResponse = (user) => pascalToCamelCaseKeys(user);
2274
+ // Add folderId to options so the centralized helper can handle it properly
2275
+ const optionsWithFolder = { ...options, folderId };
2276
+ return PaginationHelpers.getAll({
2277
+ serviceAccess: this.createPaginationServiceAccess(),
2278
+ getEndpoint: (folderId) => TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use folderId from centralized helper
2279
+ getByFolderEndpoint: TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use the passed folderId
2280
+ transformFn: transformUserResponse,
2281
+ pagination: {
2282
+ paginationType: PaginationType.OFFSET,
2283
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2284
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2285
+ paginationParams: {
2286
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2287
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
2288
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
2289
+ }
2290
+ }
2291
+ }, optionsWithFolder);
2292
+ }
2293
+ /**
2294
+ * Gets tasks across folders with optional filtering and folder scoping
2295
+ *
2296
+ * The method returns either:
2297
+ * - An array of tasks (when no pagination parameters are provided)
2298
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
2299
+ *
2300
+ * @param options - Query options including optional folderId, asTaskAdmin flag and pagination options
2301
+ * @returns Promise resolving to an array of tasks or paginated result
2302
+ *
2303
+ * @example
2304
+ * ```typescript
2305
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2306
+ *
2307
+ * const tasks = new Tasks(sdk);
2308
+ *
2309
+ * // Standard array return
2310
+ * const allTasks = await tasks.getAll();
2311
+ *
2312
+ * // Get tasks within a specific folder
2313
+ * const folderTasks = await tasks.getAll({
2314
+ * folderId: 123
2315
+ * });
2316
+ *
2317
+ * // Get tasks with admin permissions
2318
+ * const adminTasks = await tasks.getAll({
2319
+ * asTaskAdmin: true
2320
+ * });
2321
+ *
2322
+ * // First page with pagination
2323
+ * const page1 = await tasks.getAll({ pageSize: 10 });
2324
+ *
2325
+ * // Navigate using cursor
2326
+ * if (page1.hasNextPage) {
2327
+ * const page2 = await tasks.getAll({ cursor: page1.nextCursor });
2328
+ * }
2329
+ *
2330
+ * // Jump to specific page
2331
+ * const page5 = await tasks.getAll({
2332
+ * jumpToPage: 5,
2333
+ * pageSize: 10
2334
+ * });
2335
+ * ```
2336
+ */
2337
+ async getAll(options) {
2338
+ // Determine which endpoint to use based on asTaskAdmin flag
2339
+ const endpoint = options?.asTaskAdmin
2340
+ ? TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS_ADMIN
2341
+ : TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS;
2342
+ // Transformation function for tasks
2343
+ const transformTaskResponse = (task) => {
2344
+ const transformedTask = transformData(pascalToCamelCaseKeys(task), TaskMap);
2345
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
2346
+ };
2347
+ return PaginationHelpers.getAll({
2348
+ serviceAccess: this.createPaginationServiceAccess(),
2349
+ getEndpoint: () => endpoint,
2350
+ transformFn: transformTaskResponse,
2351
+ processParametersFn: this.processTaskParameters,
2352
+ excludeFromPrefix: ['event'], // Exclude 'event' key from ODATA prefix transformation
2353
+ pagination: {
2354
+ paginationType: PaginationType.OFFSET,
2355
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2356
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2357
+ paginationParams: {
2358
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM, // OData OFFSET parameter
2359
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM, // OData OFFSET parameter
2360
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM // OData OFFSET parameter
2361
+ }
2362
+ }
2363
+ }, options);
2364
+ }
2365
+ /**
2366
+ * Gets a task by ID
2367
+ * IMPORTANT: For form tasks, folderId must be provided.
2368
+ *
2369
+ * @param id - The ID of the task to retrieve
2370
+ * @param options - Optional query parameters
2371
+ * @param folderId - Optional folder ID (REQUIRED for form tasks)
2372
+ * @returns Promise resolving to the task (form tasks will return form-specific data)
2373
+ *
2374
+ * @example
2375
+ * ```typescript
2376
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2377
+ *
2378
+ * const tasks = new Tasks(sdk);
2379
+ *
2380
+ * // Get task by ID
2381
+ * const task = await tasks.getById(123);
2382
+ *
2383
+ * // If the task is a form task, it will automatically return form-specific data
2384
+ * ```
2385
+ */
2386
+ async getById(id, options = {}, folderId) {
2387
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2388
+ // Add default expand parameters
2389
+ const modifiedOptions = this.addDefaultExpand(options);
2390
+ // prefix all keys in options
2391
+ const keysToPrefix = Object.keys(modifiedOptions);
2392
+ const apiOptions = addPrefixToKeys(modifiedOptions, ODATA_PREFIX, keysToPrefix);
2393
+ const response = await this.get(TASK_ENDPOINTS.GET_BY_ID(id), {
2394
+ params: apiOptions,
2395
+ headers
2396
+ });
2397
+ // Transform response from PascalCase to camelCase and normalize time fields
2398
+ const transformedTask = transformData(pascalToCamelCaseKeys(response.data), TaskMap);
2399
+ // Check if this is a form task and get form-specific data if it is
2400
+ if (transformedTask.type === TaskType.Form) {
2401
+ const formOptions = { expandOnFormLayout: true };
2402
+ return this.getFormTaskById(id, folderId || transformedTask.folderId, formOptions);
2403
+ }
2404
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
2405
+ }
2406
+ /**
2407
+ * Assigns tasks to users
2408
+ *
2409
+ * @param taskAssignments - Single task assignment or array of task assignments
2410
+ * @returns Promise resolving to array of task assignment results
2411
+ *
2412
+ * @example
2413
+ * ```typescript
2414
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2415
+ *
2416
+ * const tasks = new Tasks(sdk);
2417
+ *
2418
+ * // Assign a single task to a user by ID
2419
+ * const result = await tasks.assign({
2420
+ * taskId: 123,
2421
+ * userId: 456
2422
+ * });
2423
+ *
2424
+ * // Assign a single task to a user by email
2425
+ * const result = await tasks.assign({
2426
+ * taskId: 123,
2427
+ * userNameOrEmail: "user@example.com"
2428
+ * });
2429
+ *
2430
+ * // Assign multiple tasks
2431
+ * const result = await tasks.assign([
2432
+ * {
2433
+ * taskId: 123,
2434
+ * userId: 456
2435
+ * },
2436
+ * {
2437
+ * taskId: 789,
2438
+ * userNameOrEmail: "user@example.com"
2439
+ * }
2440
+ * ]);
2441
+ * ```
2442
+ */
2443
+ async assign(taskAssignments) {
2444
+ // Normalize input to array
2445
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
2446
+ const options = {
2447
+ taskAssignments: assignmentArray
2448
+ };
2449
+ // Convert options to PascalCase for API
2450
+ const pascalOptions = camelToPascalCaseKeys(options);
2451
+ const response = await this.post(TASK_ENDPOINTS.ASSIGN_TASKS, pascalOptions);
2452
+ // Transform response from PascalCase to camelCase
2453
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2454
+ // Process OData array response - empty array = success, non-empty = error
2455
+ return processODataArrayResponse(transformedResponse, assignmentArray);
2456
+ }
2457
+ /**
2458
+ * Reassigns tasks to new users
2459
+ *
2460
+ * @param taskAssignments - Single task assignment or array of task assignments
2461
+ * @returns Promise resolving to array of task assignment results
2462
+ *
2463
+ * @example
2464
+ * ```typescript
2465
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2466
+ *
2467
+ * const tasks = new Tasks(sdk);
2468
+ *
2469
+ * // Reassign a single task to a user by ID
2470
+ * const result = await tasks.reassign({
2471
+ * taskId: 123,
2472
+ * userId: 456
2473
+ * });
2474
+ *
2475
+ * // Reassign a single task to a user by email
2476
+ * const result = await tasks.reassign({
2477
+ * taskId: 123,
2478
+ * userNameOrEmail: "user@example.com"
2479
+ * });
2480
+ *
2481
+ * // Reassign multiple tasks
2482
+ * const result = await tasks.reassign([
2483
+ * {
2484
+ * taskId: 123,
2485
+ * userId: 456
2486
+ * },
2487
+ * {
2488
+ * taskId: 789,
2489
+ * userNameOrEmail: "user@example.com"
2490
+ * }
2491
+ * ]);
2492
+ * ```
2493
+ */
2494
+ async reassign(taskAssignments) {
2495
+ // Normalize input to array
2496
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
2497
+ const options = {
2498
+ taskAssignments: assignmentArray
2499
+ };
2500
+ // Convert options to PascalCase for API
2501
+ const pascalOptions = camelToPascalCaseKeys(options);
2502
+ const response = await this.post(TASK_ENDPOINTS.REASSIGN_TASKS, pascalOptions);
2503
+ // Transform response from PascalCase to camelCase
2504
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2505
+ // Process OData array response - empty array = success, non-empty = error
2506
+ return processODataArrayResponse(transformedResponse, assignmentArray);
2507
+ }
2508
+ /**
2509
+ * Unassigns tasks (removes current assignees)
2510
+ *
2511
+ * @param taskIds - Single task ID or array of task IDs to unassign
2512
+ * @returns Promise resolving to array of task assignment results
2513
+ *
2514
+ * @example
2515
+ * ```typescript
2516
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2517
+ *
2518
+ * const tasks = new Tasks(sdk);
2519
+ *
2520
+ * // Unassign a single task
2521
+ * const result = await tasks.unassign(123);
2522
+ *
2523
+ * // Unassign multiple tasks
2524
+ * const result = await tasks.unassign([123, 456, 789]);
2525
+ * ```
2526
+ */
2527
+ async unassign(taskIds) {
2528
+ // Normalize input to array
2529
+ const taskIdArray = Array.isArray(taskIds) ? taskIds : [taskIds];
2530
+ const options = {
2531
+ taskIds: taskIdArray
2532
+ };
2533
+ const response = await this.post(TASK_ENDPOINTS.UNASSIGN_TASKS, options);
2534
+ // Transform response from PascalCase to camelCase
2535
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2536
+ // Process OData array response - empty array = success, non-empty = error
2537
+ // Return the task IDs that were unassigned
2538
+ return processODataArrayResponse(transformedResponse, taskIdArray.map(id => ({ taskId: id })));
2539
+ }
2540
+ /**
2541
+ * Completes a task with the specified type and data
2542
+ *
2543
+ * @param options - The completion options including task type, taskId, data, and action
2544
+ * @param folderId - Required folder ID
2545
+ * @returns Promise resolving to completion result
2546
+ *
2547
+ * @example
2548
+ * ```typescript
2549
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2550
+ *
2551
+ * const tasks = new Tasks(sdk);
2552
+ *
2553
+ * // Complete an app task
2554
+ * await tasks.complete({
2555
+ * type: TaskType.App,
2556
+ * taskId: 456,
2557
+ * data: {},
2558
+ * action: "submit"
2559
+ * }, 123); // folderId is required
2560
+ *
2561
+ * // Complete an external task
2562
+ * await tasks.complete({
2563
+ * type: TaskType.External,
2564
+ * taskId: 789
2565
+ * }, 123); // folderId is required
2566
+ * ```
2567
+ */
2568
+ async complete(options, folderId) {
2569
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2570
+ let endpoint;
2571
+ switch (options.type) {
2572
+ case TaskType.Form:
2573
+ endpoint = TASK_ENDPOINTS.COMPLETE_FORM_TASK;
2574
+ break;
2575
+ case TaskType.App:
2576
+ endpoint = TASK_ENDPOINTS.COMPLETE_APP_TASK;
2577
+ break;
2578
+ default:
2579
+ endpoint = TASK_ENDPOINTS.COMPLETE_GENERIC_TASK;
2580
+ break;
2581
+ }
2582
+ // CompleteAppTask returns 204 no content
2583
+ await this.post(endpoint, options, { headers });
2584
+ // Return success with the request context data
2585
+ return {
2586
+ success: true,
2587
+ data: options
2588
+ };
2589
+ }
2590
+ /**
2591
+ * Gets a form task by ID (private method)
2592
+ *
2593
+ * @param id - The ID of the form task to retrieve
2594
+ * @param folderId - Required folder ID
2595
+ * @param options - Optional query parameters
2596
+ * @returns Promise resolving to the form task
2597
+ */
2598
+ async getFormTaskById(id, folderId, options = {}) {
2599
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2600
+ const response = await this.get(TASK_ENDPOINTS.GET_TASK_FORM_BY_ID, {
2601
+ params: {
2602
+ taskId: id,
2603
+ ...options
2604
+ },
2605
+ headers
2606
+ });
2607
+ const transformedFormTask = transformData(response.data, TaskMap);
2608
+ return createTaskWithMethods(applyDataTransforms(transformedFormTask, { field: 'status', valueMap: TaskStatusMap }), this);
2609
+ }
2610
+ /**
2611
+ * Adds default expand parameters to options
2612
+ * @param options - The options object to add default expand to
2613
+ * @returns Options with default expand parameters added
2614
+ * @private
2615
+ */
2616
+ addDefaultExpand(options) {
2617
+ const processedOptions = { ...options };
2618
+ processedOptions.expand = processedOptions.expand
2619
+ ? `${DEFAULT_TASK_EXPAND},${processedOptions.expand}`
2620
+ : DEFAULT_TASK_EXPAND;
2621
+ return processedOptions;
2622
+ }
2623
+ }
2624
+ __decorate([
2625
+ track('Tasks.Create')
2626
+ ], TaskService.prototype, "create", null);
2627
+ __decorate([
2628
+ track('Tasks.GetUsers')
2629
+ ], TaskService.prototype, "getUsers", null);
2630
+ __decorate([
2631
+ track('Tasks.GetAll')
2632
+ ], TaskService.prototype, "getAll", null);
2633
+ __decorate([
2634
+ track('Tasks.GetById')
2635
+ ], TaskService.prototype, "getById", null);
2636
+ __decorate([
2637
+ track('Tasks.Assign')
2638
+ ], TaskService.prototype, "assign", null);
2639
+ __decorate([
2640
+ track('Tasks.Reassign')
2641
+ ], TaskService.prototype, "reassign", null);
2642
+ __decorate([
2643
+ track('Tasks.Unassign')
2644
+ ], TaskService.prototype, "unassign", null);
2645
+ __decorate([
2646
+ track('Tasks.Complete')
2647
+ ], TaskService.prototype, "complete", null);
2648
+
2649
+ export { TaskActivityType, TaskPriority, TaskService, TaskSlaCriteria, TaskSlaStatus, TaskSourceName, TaskStatus, TaskType, TaskService as Tasks, createTaskWithMethods };