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