@uipath/uipath-typescript 1.2.1 → 1.3.0

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