@uipath/uipath-typescript 1.0.0-beta.17 → 1.0.0

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