@uipath/uipath-typescript 1.4.0 → 1.4.2

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 (51) hide show
  1. package/dist/agent-memory/index.cjs +16 -9
  2. package/dist/agent-memory/index.mjs +16 -9
  3. package/dist/agents/index.cjs +278 -9
  4. package/dist/agents/index.d.ts +465 -6
  5. package/dist/agents/index.mjs +279 -10
  6. package/dist/assets/index.cjs +16 -9
  7. package/dist/assets/index.mjs +16 -9
  8. package/dist/attachments/index.cjs +16 -9
  9. package/dist/attachments/index.mjs +16 -9
  10. package/dist/buckets/index.cjs +114 -124
  11. package/dist/buckets/index.d.ts +197 -84
  12. package/dist/buckets/index.mjs +114 -124
  13. package/dist/cases/index.cjs +79 -13
  14. package/dist/cases/index.d.ts +30 -3
  15. package/dist/cases/index.mjs +79 -13
  16. package/dist/conversational-agent/index.cjs +16 -9
  17. package/dist/conversational-agent/index.mjs +16 -9
  18. package/dist/core/index.cjs +35 -6
  19. package/dist/core/index.mjs +35 -6
  20. package/dist/document-understanding/index.cjs +84 -84
  21. package/dist/document-understanding/index.d.ts +2 -1
  22. package/dist/document-understanding/index.mjs +1 -1
  23. package/dist/entities/index.cjs +253 -69
  24. package/dist/entities/index.d.ts +343 -116
  25. package/dist/entities/index.mjs +253 -69
  26. package/dist/feedback/index.cjs +16 -9
  27. package/dist/feedback/index.mjs +16 -9
  28. package/dist/governance/index.cjs +16 -9
  29. package/dist/governance/index.mjs +16 -9
  30. package/dist/index.cjs +529 -193
  31. package/dist/index.d.ts +2141 -750
  32. package/dist/index.mjs +529 -194
  33. package/dist/index.umd.js +529 -193
  34. package/dist/jobs/index.cjs +16 -9
  35. package/dist/jobs/index.mjs +16 -9
  36. package/dist/maestro-processes/index.cjs +16 -9
  37. package/dist/maestro-processes/index.mjs +16 -9
  38. package/dist/orchestrator-du-module/index.cjs +1788 -0
  39. package/dist/orchestrator-du-module/index.d.ts +757 -0
  40. package/dist/orchestrator-du-module/index.mjs +1785 -0
  41. package/dist/processes/index.cjs +16 -9
  42. package/dist/processes/index.mjs +16 -9
  43. package/dist/queues/index.cjs +16 -9
  44. package/dist/queues/index.mjs +16 -9
  45. package/dist/tasks/index.cjs +79 -13
  46. package/dist/tasks/index.d.ts +109 -4
  47. package/dist/tasks/index.mjs +80 -14
  48. package/dist/traces/index.cjs +303 -9
  49. package/dist/traces/index.d.ts +482 -2
  50. package/dist/traces/index.mjs +302 -10
  51. package/package.json +11 -1
@@ -0,0 +1,1788 @@
1
+ 'use strict';
2
+
3
+ var coreTelemetry = require('@uipath/core-telemetry');
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
+ * SDK Telemetry constants.
49
+ *
50
+ * Only the SDK's identity (version, service name, role name, …) lives
51
+ * here. The Application Insights connection string is injected into
52
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
53
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
54
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
55
+ * SDK's public API.
56
+ */
57
+ /** SDK version placeholder — patched by the SDK publish workflow. */
58
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
59
+
60
+ /**
61
+ * UiPath TypeScript SDK Telemetry
62
+ *
63
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
64
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
65
+ * does this independently, so events carry their own consumer's identity
66
+ * and tenant context.
67
+ */
68
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
69
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
70
+ // from the `UiPath` constructor therefore wires up `@track` decorators
71
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
72
+ const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
73
+ const track = coreTelemetry.createTrack(sdkClient);
74
+ coreTelemetry.createTrackEvent(sdkClient);
75
+
76
+ /**
77
+ * Base path constants for different services
78
+ */
79
+ const ORCHESTRATOR_BASE = 'orchestrator_';
80
+
81
+ /**
82
+ * Orchestrator Service Endpoints
83
+ */
84
+ /**
85
+ * Orchestrator DU Module Endpoints (validation flows)
86
+ */
87
+ const ORCHESTRATOR_DU_MODULE_ENDPOINTS = {
88
+ SUBMIT_EXCEPTION_REPORT: `${ORCHESTRATOR_BASE}/doc-understanding/DocumentModule/SubmitExceptionReport`,
89
+ PROCESS_EXTRACTED_DATA: `${ORCHESTRATOR_BASE}/doc-understanding/DocumentModule/ProcessExtractedData`,
90
+ };
91
+
92
+ /**
93
+ * Base error class for all UiPath SDK errors
94
+ * Extends Error for standard error handling compatibility
95
+ */
96
+ class UiPathError extends Error {
97
+ constructor(type, params) {
98
+ super(params.message);
99
+ this.name = type;
100
+ this.type = type;
101
+ this.statusCode = params.statusCode;
102
+ this.requestId = params.requestId;
103
+ this.timestamp = new Date();
104
+ // Maintains proper stack trace for where our error was thrown
105
+ if (Error.captureStackTrace) {
106
+ Error.captureStackTrace(this, this.constructor);
107
+ }
108
+ }
109
+ /**
110
+ * Returns a clean JSON representation of the error
111
+ */
112
+ toJSON() {
113
+ return {
114
+ type: this.type,
115
+ message: this.message,
116
+ statusCode: this.statusCode,
117
+ requestId: this.requestId,
118
+ timestamp: this.timestamp
119
+ };
120
+ }
121
+ /**
122
+ * Returns detailed debug information including stack trace
123
+ */
124
+ getDebugInfo() {
125
+ return {
126
+ ...this.toJSON(),
127
+ stack: this.stack
128
+ };
129
+ }
130
+ }
131
+
132
+ /**
133
+ * HTTP status code constants for error handling
134
+ */
135
+ const HttpStatus = {
136
+ // Client errors (4xx)
137
+ BAD_REQUEST: 400,
138
+ UNAUTHORIZED: 401,
139
+ FORBIDDEN: 403,
140
+ NOT_FOUND: 404,
141
+ TOO_MANY_REQUESTS: 429,
142
+ // Server errors (5xx)
143
+ INTERNAL_SERVER_ERROR: 500,
144
+ BAD_GATEWAY: 502,
145
+ SERVICE_UNAVAILABLE: 503,
146
+ GATEWAY_TIMEOUT: 504
147
+ };
148
+ /**
149
+ * Error type constants for consistent error identification
150
+ */
151
+ const ErrorType = {
152
+ AUTHENTICATION: 'AuthenticationError',
153
+ AUTHORIZATION: 'AuthorizationError',
154
+ VALIDATION: 'ValidationError',
155
+ NOT_FOUND: 'NotFoundError',
156
+ RATE_LIMIT: 'RateLimitError',
157
+ SERVER: 'ServerError',
158
+ NETWORK: 'NetworkError'
159
+ };
160
+ /**
161
+ * HTTP header constants for error handling
162
+ */
163
+ const HttpHeaders = {
164
+ X_REQUEST_ID: 'x-request-id'
165
+ };
166
+ /**
167
+ * Standard error message constants
168
+ */
169
+ const ErrorMessages = {
170
+ // Authentication errors
171
+ AUTHENTICATION_FAILED: 'Authentication failed',
172
+ // Authorization errors
173
+ ACCESS_DENIED: 'Access denied',
174
+ // Validation errors
175
+ VALIDATION_FAILED: 'Validation failed',
176
+ // Not found errors
177
+ RESOURCE_NOT_FOUND: 'Resource not found',
178
+ // Rate limit errors
179
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
180
+ // Server errors
181
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
182
+ // Network errors
183
+ NETWORK_ERROR: 'Network error occurred',
184
+ REQUEST_TIMEOUT: 'Request timed out',
185
+ REQUEST_ABORTED: 'Request was aborted',
186
+ };
187
+ /**
188
+ * Error name constants for network error identification
189
+ */
190
+ const ErrorNames = {
191
+ ABORT_ERROR: 'AbortError'};
192
+
193
+ /**
194
+ * Error thrown when authentication fails (401 errors)
195
+ * Common scenarios:
196
+ * - Invalid credentials
197
+ * - Expired token
198
+ * - Missing authentication
199
+ */
200
+ class AuthenticationError extends UiPathError {
201
+ constructor(params = {}) {
202
+ super(ErrorType.AUTHENTICATION, {
203
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
204
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
205
+ requestId: params.requestId
206
+ });
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Error thrown when authorization fails (403 errors)
212
+ * Common scenarios:
213
+ * - Insufficient permissions
214
+ * - Access denied to resource
215
+ * - Invalid scope
216
+ */
217
+ class AuthorizationError extends UiPathError {
218
+ constructor(params = {}) {
219
+ super(ErrorType.AUTHORIZATION, {
220
+ message: params.message || ErrorMessages.ACCESS_DENIED,
221
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
222
+ requestId: params.requestId
223
+ });
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Error thrown when validation fails (400 errors or client-side validation)
229
+ * Common scenarios:
230
+ * - Invalid input parameters
231
+ * - Missing required fields
232
+ * - Invalid data format
233
+ */
234
+ class ValidationError extends UiPathError {
235
+ constructor(params = {}) {
236
+ super(ErrorType.VALIDATION, {
237
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
238
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
239
+ requestId: params.requestId
240
+ });
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Error thrown when a resource is not found (404 errors)
246
+ * Common scenarios:
247
+ * - Resource doesn't exist
248
+ * - Invalid ID provided
249
+ * - Resource deleted
250
+ */
251
+ class NotFoundError extends UiPathError {
252
+ constructor(params = {}) {
253
+ super(ErrorType.NOT_FOUND, {
254
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
255
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
256
+ requestId: params.requestId
257
+ });
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Error thrown when rate limit is exceeded (429 errors)
263
+ * Common scenarios:
264
+ * - Too many requests in a time window
265
+ * - API throttling
266
+ */
267
+ class RateLimitError extends UiPathError {
268
+ constructor(params = {}) {
269
+ super(ErrorType.RATE_LIMIT, {
270
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
271
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
272
+ requestId: params.requestId
273
+ });
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Error thrown when server encounters an error (5xx errors)
279
+ * Common scenarios:
280
+ * - Internal server error
281
+ * - Service unavailable
282
+ * - Gateway timeout
283
+ */
284
+ class ServerError extends UiPathError {
285
+ constructor(params = {}) {
286
+ super(ErrorType.SERVER, {
287
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
288
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
289
+ requestId: params.requestId
290
+ });
291
+ }
292
+ /**
293
+ * Checks if this is a temporary error that might succeed on retry
294
+ */
295
+ get isRetryable() {
296
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
297
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
298
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Error thrown when network/connection issues occur
304
+ * Common scenarios:
305
+ * - Connection timeout
306
+ * - DNS resolution failure
307
+ * - Network unreachable
308
+ * - Request aborted
309
+ */
310
+ class NetworkError extends UiPathError {
311
+ constructor(params = {}) {
312
+ super(ErrorType.NETWORK, {
313
+ message: params.message || ErrorMessages.NETWORK_ERROR,
314
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
315
+ requestId: params.requestId
316
+ });
317
+ }
318
+ }
319
+
320
+ const FOLDER_KEY = 'X-UIPATH-FolderKey';
321
+ const FOLDER_PATH_ENCODED = 'X-UIPATH-FolderPath-Encoded';
322
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
323
+ const TRACEPARENT = 'traceparent';
324
+ const UIPATH_TRACEPARENT_ID = 'x-uipath-traceparent-id';
325
+ /**
326
+ * Content type constants for HTTP requests/responses
327
+ */
328
+ const CONTENT_TYPES = {
329
+ JSON: 'application/json',
330
+ XML: 'application/xml',
331
+ OCTET_STREAM: 'application/octet-stream'
332
+ };
333
+ /**
334
+ * Response type constants for HTTP requests
335
+ */
336
+ const RESPONSE_TYPES = {
337
+ JSON: 'json',
338
+ TEXT: 'text',
339
+ BLOB: 'blob',
340
+ ARRAYBUFFER: 'arraybuffer'
341
+ };
342
+
343
+ /**
344
+ * Creates headers object from key-value pairs
345
+ * @param headersObj - Object containing header key-value pairs
346
+ * @returns Headers object with all values converted to strings
347
+ *
348
+ * @example
349
+ * ```typescript
350
+ * // Single header
351
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
352
+ *
353
+ * // Multiple headers
354
+ * const headers = createHeaders({
355
+ * 'X-UIPATH-FolderKey': '1234567890',
356
+ * 'X-UIPATH-OrganizationUnitId': 123,
357
+ * 'Accept': 'application/json'
358
+ * });
359
+ *
360
+ * // Using constants
361
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
362
+ * const headers = createHeaders({
363
+ * [FOLDER_KEY]: 'abc-123',
364
+ * [FOLDER_ID]: 456
365
+ * });
366
+ *
367
+ * // Empty headers
368
+ * const headers = createHeaders();
369
+ * ```
370
+ */
371
+ function createHeaders(headersObj) {
372
+ const headers = {};
373
+ for (const [key, value] of Object.entries(headersObj)) {
374
+ if (value !== undefined && value !== null) {
375
+ headers[key] = value.toString();
376
+ }
377
+ }
378
+ return headers;
379
+ }
380
+
381
+ /**
382
+ * Encodes a folder path for the `X-UIPATH-FolderPath-Encoded` header.
383
+ *
384
+ * Orchestrator decodes this header as **base64-encoded UTF-16 LE bytes**
385
+ * (see `HttpHeadersProviderExtensions.GetDecoded` + `OrganizationUnitProvider`
386
+ * in the Orchestrator repo, which call `Encoding.Unicode.GetString(...)`).
387
+ * URL-encoding is NOT what the server expects — it must be base64-of-UTF-16-LE
388
+ * bytes.
389
+ *
390
+ * @param folderPath - The folder path (e.g. 'Shared/Finance')
391
+ * @returns Base64 string suitable for the `X-UIPATH-FolderPath-Encoded` header
392
+ */
393
+ function encodeFolderPathHeader(folderPath) {
394
+ // Force little-endian regardless of host byte order. `Uint16Array` viewed
395
+ // as `Uint8Array` would use the host's native order — correct on LE hosts
396
+ // (x86/ARM-LE) but wrong on BE hosts. `DataView.setUint16(..., true)`
397
+ // pins LE.
398
+ const buf = new ArrayBuffer(folderPath.length * 2);
399
+ const view = new DataView(buf);
400
+ for (let i = 0; i < folderPath.length; i++) {
401
+ view.setUint16(i * 2, folderPath.charCodeAt(i), true);
402
+ }
403
+ const bytes = new Uint8Array(buf);
404
+ let binary = '';
405
+ for (let i = 0; i < bytes.byteLength; i++) {
406
+ binary += String.fromCharCode(bytes[i]);
407
+ }
408
+ // btoa is browser-native; Node 16+ also has it as a global
409
+ return btoa(binary);
410
+ }
411
+
412
+ /**
413
+ * Resolves folder context into the appropriate Orchestrator folder headers.
414
+ *
415
+ * Centralized so all folder-scoped methods (e.g. `assets.getByName`,
416
+ * `processes.getByName`, future Queues/Buckets/Jobs) share one implementation.
417
+ *
418
+ * Each input field maps directly to its header — no auto-detection or type
419
+ * coercion. When multiple fields are supplied, all corresponding headers
420
+ * are forwarded and the server resolves precedence.
421
+ *
422
+ * Routing:
423
+ * - `folderId` → `X-UIPATH-OrganizationUnitId`
424
+ * - `folderKey` → `X-UIPATH-FolderKey`
425
+ * - `folderPath` → `X-UIPATH-FolderPath-Encoded`
426
+ * - none set + `fallbackFolderKey` → fallback used as `X-UIPATH-FolderKey`
427
+ * - none set + no fallback → `ValidationError`
428
+ *
429
+ * @throws ValidationError when no folder context can be resolved.
430
+ */
431
+ function resolveFolderHeaders(input) {
432
+ const { folderId, folderKey, folderPath, resourceType, fallbackFolderKey } = input;
433
+ const trimmedKey = folderKey?.trim();
434
+ const trimmedPath = folderPath?.trim();
435
+ const headers = {};
436
+ if (folderId !== undefined) {
437
+ headers[FOLDER_ID] = folderId;
438
+ }
439
+ if (trimmedKey) {
440
+ headers[FOLDER_KEY] = trimmedKey;
441
+ }
442
+ if (trimmedPath) {
443
+ headers[FOLDER_PATH_ENCODED] = encodeFolderPathHeader(trimmedPath);
444
+ }
445
+ // No explicit folder context → meta-tag fallback or error.
446
+ if (Object.keys(headers).length === 0) {
447
+ if (!fallbackFolderKey) {
448
+ throw new ValidationError({
449
+ message: `${resourceType} requires folder context: pass \`folderId\`, \`folderKey\`, or \`folderPath\`, or initialize the SDK with a folder context.`,
450
+ });
451
+ }
452
+ headers[FOLDER_KEY] = fallbackFolderKey;
453
+ }
454
+ return createHeaders(headers);
455
+ }
456
+
457
+ /**
458
+ * Type guards for error response types
459
+ */
460
+ function isOrchestratorError(error) {
461
+ return typeof error === 'object' &&
462
+ error !== null &&
463
+ 'message' in error &&
464
+ 'errorCode' in error &&
465
+ typeof error.message === 'string' &&
466
+ typeof error.errorCode === 'number';
467
+ }
468
+ function isEntityError(error) {
469
+ return typeof error === 'object' &&
470
+ error !== null &&
471
+ 'error' in error &&
472
+ typeof error.error === 'string';
473
+ }
474
+ function isPimsError(error) {
475
+ return typeof error === 'object' &&
476
+ error !== null &&
477
+ 'type' in error &&
478
+ 'title' in error &&
479
+ 'status' in error &&
480
+ typeof error.type === 'string' &&
481
+ typeof error.title === 'string' &&
482
+ typeof error.status === 'number';
483
+ }
484
+
485
+ /**
486
+ * Parser for Orchestrator/Task error format
487
+ */
488
+ class OrchestratorErrorParser {
489
+ canParse(errorBody) {
490
+ return isOrchestratorError(errorBody);
491
+ }
492
+ parse(errorBody, response) {
493
+ const error = errorBody;
494
+ return {
495
+ message: error.message,
496
+ code: response?.status?.toString(),
497
+ details: {
498
+ errorCode: error.errorCode,
499
+ traceId: error.traceId,
500
+ originalResponse: error
501
+ },
502
+ requestId: error.traceId
503
+ };
504
+ }
505
+ }
506
+ /**
507
+ * Parser for Entity (Data Fabric) error format
508
+ */
509
+ class EntityErrorParser {
510
+ canParse(errorBody) {
511
+ return isEntityError(errorBody);
512
+ }
513
+ parse(errorBody, response) {
514
+ const error = errorBody;
515
+ return {
516
+ message: error.error,
517
+ code: response?.status?.toString(),
518
+ details: {
519
+ error: error.error,
520
+ traceId: error.traceId,
521
+ originalResponse: error
522
+ },
523
+ requestId: error.traceId
524
+ };
525
+ }
526
+ }
527
+ /**
528
+ * Parser for PIMS error format
529
+ */
530
+ class PimsErrorParser {
531
+ canParse(errorBody) {
532
+ return isPimsError(errorBody);
533
+ }
534
+ parse(errorBody, response) {
535
+ const error = errorBody;
536
+ let message = error.title;
537
+ // If there are validation errors, append them to the message for better visibility
538
+ if (error.errors && Object.keys(error.errors).length > 0) {
539
+ const errorMessages = Object.entries(error.errors)
540
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
541
+ .join('; ');
542
+ message += `. Validation errors: ${errorMessages}`;
543
+ }
544
+ return {
545
+ message,
546
+ code: response?.status?.toString(),
547
+ details: {
548
+ type: error.type,
549
+ title: error.title,
550
+ status: error.status,
551
+ errors: error.errors,
552
+ traceId: error.traceId,
553
+ originalResponse: error
554
+ },
555
+ requestId: error.traceId
556
+ };
557
+ }
558
+ }
559
+ /**
560
+ * Fallback parser for unrecognized formats
561
+ */
562
+ class GenericErrorParser {
563
+ canParse(_errorBody) {
564
+ return true; // Always can parse as last resort
565
+ }
566
+ parse(errorBody, response) {
567
+ // For unknown error formats, just pass through the raw error with fallback message
568
+ const message = response?.statusText || 'An error occurred';
569
+ return {
570
+ message,
571
+ code: response?.status?.toString(),
572
+ details: {
573
+ originalResponse: errorBody
574
+ },
575
+ };
576
+ }
577
+ }
578
+ /**
579
+ * Main error response parser using Chain of Responsibility pattern
580
+ *
581
+ * This parser standardizes error responses from different UiPath services into a
582
+ * consistent format, regardless of the original error structure.
583
+ *
584
+ * Supported formats:
585
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
586
+ * 2. Entity (Data Fabric): { error, traceId }
587
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
588
+ * 4. Generic: Fallback for any other format
589
+ *
590
+ * @example
591
+ * const parser = new ErrorResponseParser();
592
+ * const errorInfo = await parser.parse(response);
593
+ * // errorInfo will have consistent structure regardless of service
594
+ */
595
+ class ErrorResponseParser {
596
+ constructor() {
597
+ this.strategies = [
598
+ new OrchestratorErrorParser(),
599
+ new EntityErrorParser(),
600
+ new PimsErrorParser(),
601
+ new GenericErrorParser() // Must be last
602
+ ];
603
+ }
604
+ /**
605
+ * Parses error response body into standardized format
606
+ * @param response - The HTTP response object
607
+ * @returns Standardized error information
608
+ */
609
+ async parse(response) {
610
+ try {
611
+ const errorBody = await response.json();
612
+ // Find the first strategy that can parse this error format
613
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
614
+ // GenericErrorParser always returns true, so this will never be null
615
+ return strategy.parse(errorBody, response);
616
+ }
617
+ catch {
618
+ // Handle non-JSON responses
619
+ const responseText = await response.text().catch(() => '');
620
+ return {
621
+ message: response.statusText,
622
+ code: response.status.toString(),
623
+ details: {
624
+ parseError: 'Failed to parse error response as JSON',
625
+ responseText
626
+ },
627
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
628
+ };
629
+ }
630
+ }
631
+ }
632
+ // Export singleton instance
633
+ const errorResponseParser = new ErrorResponseParser();
634
+
635
+ /**
636
+ * Factory for creating typed errors based on HTTP status codes
637
+ * Follows the Factory pattern for clean error instantiation
638
+ */
639
+ class ErrorFactory {
640
+ /**
641
+ * Creates appropriate error instance based on HTTP status code
642
+ */
643
+ static createFromHttpStatus(statusCode, errorInfo) {
644
+ const { message, requestId } = errorInfo;
645
+ // Map status codes to error types
646
+ switch (statusCode) {
647
+ case HttpStatus.BAD_REQUEST:
648
+ return new ValidationError({ message, statusCode, requestId });
649
+ case HttpStatus.UNAUTHORIZED:
650
+ return new AuthenticationError({ message, statusCode, requestId });
651
+ case HttpStatus.FORBIDDEN:
652
+ return new AuthorizationError({ message, statusCode, requestId });
653
+ case HttpStatus.NOT_FOUND:
654
+ return new NotFoundError({ message, statusCode, requestId });
655
+ case HttpStatus.TOO_MANY_REQUESTS:
656
+ return new RateLimitError({ message, statusCode, requestId });
657
+ default:
658
+ // For 5xx errors or any other status code
659
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
660
+ return new ServerError({ message, statusCode, requestId });
661
+ }
662
+ // For unknown client errors, treat as validation error
663
+ return new ValidationError({
664
+ message: `${message} (HTTP ${statusCode})`,
665
+ statusCode,
666
+ requestId
667
+ });
668
+ }
669
+ }
670
+ /**
671
+ * Creates a NetworkError from a fetch/network error
672
+ */
673
+ static createNetworkError(error) {
674
+ let message = ErrorMessages.NETWORK_ERROR;
675
+ if (error instanceof Error) {
676
+ if (error.name === ErrorNames.ABORT_ERROR) {
677
+ message = ErrorMessages.REQUEST_ABORTED;
678
+ }
679
+ else if (error.message.includes('timeout')) {
680
+ message = ErrorMessages.REQUEST_TIMEOUT;
681
+ }
682
+ else {
683
+ message = error.message;
684
+ }
685
+ }
686
+ return new NetworkError({ message });
687
+ }
688
+ }
689
+
690
+ class ApiClient {
691
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
692
+ this.config = config;
693
+ this.executionContext = executionContext;
694
+ this.clientConfig = clientConfig;
695
+ this.tokenManager = tokenManager;
696
+ }
697
+ /**
698
+ * Gets a valid authentication token, refreshing if necessary.
699
+ * Used internally for API requests and exposed for services that need manual auth headers.
700
+ *
701
+ * @returns The valid token
702
+ * @throws AuthenticationError if no token available or refresh fails
703
+ */
704
+ async getValidToken() {
705
+ return this.tokenManager.getValidToken();
706
+ }
707
+ async getDefaultHeaders() {
708
+ const token = await this.getValidToken();
709
+ return {
710
+ 'Authorization': `Bearer ${token}`,
711
+ 'Content-Type': CONTENT_TYPES.JSON,
712
+ ...this.clientConfig.headers
713
+ };
714
+ }
715
+ async request(method, path, options = {}) {
716
+ // Ensure path starts with a forward slash
717
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
718
+ // Construct URL with org and tenant names
719
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
720
+ const isFormData = options.body instanceof FormData;
721
+ const defaultHeaders = await this.getDefaultHeaders();
722
+ if (isFormData) {
723
+ delete defaultHeaders['Content-Type'];
724
+ }
725
+ const traceId = crypto.randomUUID().replace(/-/g, '');
726
+ const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
727
+ const traceparentValue = `00-${traceId}-${spanId}-01`;
728
+ const headers = {
729
+ ...defaultHeaders,
730
+ [TRACEPARENT]: traceparentValue,
731
+ [UIPATH_TRACEPARENT_ID]: traceparentValue,
732
+ ...options.headers
733
+ };
734
+ // Convert params to URLSearchParams
735
+ const searchParams = new URLSearchParams();
736
+ if (options.params) {
737
+ Object.entries(options.params).forEach(([key, value]) => {
738
+ searchParams.append(key, value.toString());
739
+ });
740
+ }
741
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
742
+ let body = undefined;
743
+ if (options.body) {
744
+ body = isFormData ? options.body : JSON.stringify(options.body);
745
+ }
746
+ try {
747
+ const response = await fetch(fullUrl, {
748
+ method,
749
+ headers,
750
+ body,
751
+ signal: options.signal
752
+ });
753
+ if (!response.ok) {
754
+ const errorInfo = await errorResponseParser.parse(response);
755
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
756
+ }
757
+ if (response.status === 204) {
758
+ return undefined;
759
+ }
760
+ // Handle blob response type for binary data (e.g., file downloads)
761
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
762
+ const blob = await response.blob();
763
+ return blob;
764
+ }
765
+ // Check if we're expecting XML
766
+ const acceptHeader = headers['Accept'] || headers['accept'];
767
+ if (acceptHeader === CONTENT_TYPES.XML) {
768
+ const text = await response.text();
769
+ return text;
770
+ }
771
+ const text = await response.text();
772
+ if (!text) {
773
+ return undefined;
774
+ }
775
+ try {
776
+ return JSON.parse(text);
777
+ }
778
+ catch (error) {
779
+ if (error instanceof SyntaxError) {
780
+ throw new ServerError({
781
+ message: `Server returned non-JSON response (${response.status} ${response.url}): ${error.message}`,
782
+ statusCode: response.status,
783
+ });
784
+ }
785
+ throw error;
786
+ }
787
+ }
788
+ catch (error) {
789
+ // If it's already one of our errors, re-throw it
790
+ if (error.type && error.type.includes('Error')) {
791
+ throw error;
792
+ }
793
+ // Otherwise, it's a genuine network/fetch failure
794
+ throw ErrorFactory.createNetworkError(error);
795
+ }
796
+ }
797
+ async get(path, options = {}) {
798
+ return this.request('GET', path, options);
799
+ }
800
+ async post(path, data, options = {}) {
801
+ return this.request('POST', path, { ...options, body: data });
802
+ }
803
+ async put(path, data, options = {}) {
804
+ return this.request('PUT', path, { ...options, body: data });
805
+ }
806
+ async patch(path, data, options = {}) {
807
+ return this.request('PATCH', path, { ...options, body: data });
808
+ }
809
+ async delete(path, options = {}) {
810
+ return this.request('DELETE', path, options);
811
+ }
812
+ }
813
+
814
+ /**
815
+ * Pagination types supported by the SDK
816
+ */
817
+ var PaginationType;
818
+ (function (PaginationType) {
819
+ PaginationType["OFFSET"] = "offset";
820
+ PaginationType["TOKEN"] = "token";
821
+ })(PaginationType || (PaginationType = {}));
822
+
823
+ /**
824
+ * Collection of utility functions for working with objects
825
+ */
826
+ /**
827
+ * Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
828
+ * and dot-separated nested paths (e.g., 'pagination.totalCount').
829
+ * Direct key match takes priority over nested traversal.
830
+ */
831
+ function resolveNestedField(data, fieldPath) {
832
+ if (!data) {
833
+ return undefined;
834
+ }
835
+ if (fieldPath in data) {
836
+ return data[fieldPath];
837
+ }
838
+ if (!fieldPath.includes('.')) {
839
+ return undefined;
840
+ }
841
+ let value = data;
842
+ for (const part of fieldPath.split('.')) {
843
+ value = value?.[part];
844
+ }
845
+ return value;
846
+ }
847
+ /**
848
+ * Filters out undefined values from an object
849
+ * @param obj The source object
850
+ * @returns A new object without undefined values
851
+ *
852
+ * @example
853
+ * ```typescript
854
+ * // Object with undefined values
855
+ * const options = {
856
+ * name: 'test',
857
+ * count: 5,
858
+ * prefix: undefined,
859
+ * suffix: null
860
+ * };
861
+ * const result = filterUndefined(options);
862
+ * // result = { name: 'test', count: 5, suffix: null }
863
+ * ```
864
+ */
865
+ function filterUndefined(obj) {
866
+ const result = {};
867
+ for (const [key, value] of Object.entries(obj)) {
868
+ if (value !== undefined) {
869
+ result[key] = value;
870
+ }
871
+ }
872
+ return result;
873
+ }
874
+
875
+ /**
876
+ * Utility functions for platform detection
877
+ */
878
+ /**
879
+ * Checks if code is running in a browser environment
880
+ */
881
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
882
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
883
+ const _params = isBrowser ? new URLSearchParams(window.location.search) : null;
884
+ /**
885
+ * True when the coded app has been loaded inside a host frame that explicitly
886
+ * opted into token delegation by adding `?host=embed` to the iframe src URL.
887
+ */
888
+ const isHostEmbedded = isBrowser && window.self !== window.top && _params?.get('host') === 'embed';
889
+ /**
890
+ * The validated parent origin, read from the `?basedomain=` query param set
891
+ * by the embedding host in the iframe src URL.
892
+ * Mirrors the same mechanism used by ActionCenterTokenManager.
893
+ * Non-null only when `?host=embed` is present and `?basedomain=` is a valid URL.
894
+ */
895
+ (() => {
896
+ if (!isHostEmbedded)
897
+ return null;
898
+ const basedomain = _params?.get('basedomain');
899
+ if (!basedomain)
900
+ return null;
901
+ try {
902
+ return new URL(basedomain).origin;
903
+ }
904
+ catch {
905
+ console.warn('embeddingOrigin: basedomain query param is not a valid URL', basedomain);
906
+ return null;
907
+ }
908
+ })();
909
+
910
+ /**
911
+ * Base64 encoding/decoding
912
+ */
913
+ /**
914
+ * Encodes a string to base64
915
+ * @param str - The string to encode
916
+ * @returns Base64 encoded string
917
+ */
918
+ function encodeBase64(str) {
919
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
920
+ const encoder = new TextEncoder();
921
+ const data = encoder.encode(str);
922
+ // Convert Uint8Array to base64
923
+ if (isBrowser) {
924
+ // Browser environment
925
+ // Convert Uint8Array to binary string then to base64
926
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
927
+ return btoa(binaryString);
928
+ }
929
+ else {
930
+ // Node.js environment
931
+ return Buffer.from(data).toString('base64');
932
+ }
933
+ }
934
+ /**
935
+ * Decodes a base64 string
936
+ * @param base64 - The base64 string to decode
937
+ * @returns Decoded string
938
+ */
939
+ function decodeBase64(base64) {
940
+ let bytes;
941
+ if (isBrowser) {
942
+ // Browser environment
943
+ const binaryString = atob(base64);
944
+ bytes = new Uint8Array(binaryString.length);
945
+ for (let i = 0; i < binaryString.length; i++) {
946
+ bytes[i] = binaryString.charCodeAt(i);
947
+ }
948
+ }
949
+ else {
950
+ // Node.js environment
951
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
952
+ }
953
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
954
+ const decoder = new TextDecoder();
955
+ return decoder.decode(bytes);
956
+ }
957
+
958
+ /**
959
+ * PaginationManager handles the conversion between uniform cursor-based pagination
960
+ * and the specific pagination type for each service
961
+ */
962
+ class PaginationManager {
963
+ /**
964
+ * Create a pagination cursor for subsequent page requests
965
+ */
966
+ static createCursor({ pageInfo, type }) {
967
+ if (!pageInfo.hasMore) {
968
+ return undefined;
969
+ }
970
+ const cursorData = {
971
+ type,
972
+ pageSize: pageInfo.pageSize,
973
+ };
974
+ switch (type) {
975
+ case PaginationType.OFFSET:
976
+ if (pageInfo.currentPage) {
977
+ cursorData.pageNumber = pageInfo.currentPage + 1;
978
+ }
979
+ break;
980
+ case PaginationType.TOKEN:
981
+ if (pageInfo.continuationToken) {
982
+ cursorData.continuationToken = pageInfo.continuationToken;
983
+ }
984
+ else {
985
+ return undefined; // No continuation token, can't continue
986
+ }
987
+ break;
988
+ }
989
+ return {
990
+ value: encodeBase64(JSON.stringify(cursorData))
991
+ };
992
+ }
993
+ /**
994
+ * Create a paginated response with navigation cursors
995
+ */
996
+ static createPaginatedResponse({ pageInfo, type }, items) {
997
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
998
+ // Create previous page cursor if applicable
999
+ let previousCursor = undefined;
1000
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
1001
+ const prevCursorData = {
1002
+ type,
1003
+ pageNumber: pageInfo.currentPage - 1,
1004
+ pageSize: pageInfo.pageSize,
1005
+ };
1006
+ previousCursor = {
1007
+ value: encodeBase64(JSON.stringify(prevCursorData))
1008
+ };
1009
+ }
1010
+ // Calculate total pages if we have totalCount and pageSize
1011
+ let totalPages = undefined;
1012
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
1013
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
1014
+ }
1015
+ // Determine if this pagination type supports page jumping
1016
+ const supportsPageJump = type === PaginationType.OFFSET;
1017
+ // Create the result object with all fields, then filter out undefined values
1018
+ const result = filterUndefined({
1019
+ items,
1020
+ totalCount: pageInfo.totalCount,
1021
+ hasNextPage: pageInfo.hasMore,
1022
+ nextCursor: nextCursor,
1023
+ previousCursor: previousCursor,
1024
+ currentPage: pageInfo.currentPage,
1025
+ totalPages,
1026
+ supportsPageJump
1027
+ });
1028
+ return result;
1029
+ }
1030
+ }
1031
+
1032
+ /**
1033
+ * Common constants used across the SDK
1034
+ */
1035
+ /**
1036
+ * Prefix used for OData query parameters
1037
+ */
1038
+ const ODATA_PREFIX = '$';
1039
+ /**
1040
+ * HTTP methods
1041
+ */
1042
+ const HTTP_METHODS = {
1043
+ GET: 'GET',
1044
+ POST: 'POST'};
1045
+ /**
1046
+ * OData OFFSET pagination parameter names (ODATA-style)
1047
+ */
1048
+ const ODATA_OFFSET_PARAMS = {
1049
+ /** OData page size parameter name */
1050
+ PAGE_SIZE_PARAM: '$top',
1051
+ /** OData offset parameter name */
1052
+ OFFSET_PARAM: '$skip',
1053
+ /** OData count parameter name */
1054
+ COUNT_PARAM: '$count'
1055
+ };
1056
+ /**
1057
+ * Bucket TOKEN pagination parameter names
1058
+ */
1059
+ const BUCKET_TOKEN_PARAMS = {
1060
+ /** Bucket page size parameter name */
1061
+ PAGE_SIZE_PARAM: 'takeHint',
1062
+ /** Bucket token parameter name */
1063
+ TOKEN_PARAM: 'continuationToken'
1064
+ };
1065
+
1066
+ /**
1067
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
1068
+ * Returns the original value if parsing fails.
1069
+ */
1070
+ /**
1071
+ * Adds a prefix to specified keys in an object, returning a new object.
1072
+ * Only the provided keys are prefixed; all others are left unchanged.
1073
+ *
1074
+ * @param obj The source object
1075
+ * @param prefix The prefix to add (e.g., '$')
1076
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1077
+ * @returns A new object with specified keys prefixed
1078
+ *
1079
+ * @example
1080
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1081
+ */
1082
+ function addPrefixToKeys(obj, prefix, keys) {
1083
+ const result = {};
1084
+ for (const [key, value] of Object.entries(obj)) {
1085
+ if (keys.includes(key)) {
1086
+ result[`${prefix}${key}`] = value;
1087
+ }
1088
+ else {
1089
+ result[key] = value;
1090
+ }
1091
+ }
1092
+ return result;
1093
+ }
1094
+
1095
+ /**
1096
+ * Constants used throughout the pagination system
1097
+ */
1098
+ /** Maximum number of items that can be requested in a single page */
1099
+ const MAX_PAGE_SIZE = 1000;
1100
+ /** Default page size when jumpToPage is used without specifying pageSize */
1101
+ const DEFAULT_PAGE_SIZE = 50;
1102
+ /** Default field name for items in a paginated response */
1103
+ const DEFAULT_ITEMS_FIELD = 'value';
1104
+ /** Default field name for total count in a paginated response */
1105
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1106
+ /**
1107
+ * Limits the page size to the maximum allowed value
1108
+ * @param pageSize - Requested page size
1109
+ * @returns Limited page size value
1110
+ */
1111
+ function getLimitedPageSize(pageSize) {
1112
+ if (pageSize === undefined || pageSize === null) {
1113
+ return DEFAULT_PAGE_SIZE;
1114
+ }
1115
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1116
+ }
1117
+
1118
+ /**
1119
+ * Helper functions for pagination that can be used across services
1120
+ */
1121
+ class PaginationHelpers {
1122
+ /**
1123
+ * Checks if any pagination parameters are provided
1124
+ *
1125
+ * @param options - The options object to check
1126
+ * @returns True if any pagination parameter is defined, false otherwise
1127
+ */
1128
+ static hasPaginationParameters(options = {}) {
1129
+ const { cursor, pageSize, jumpToPage } = options;
1130
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1131
+ }
1132
+ /**
1133
+ * Parse a pagination cursor string into cursor data
1134
+ */
1135
+ static parseCursor(cursorString) {
1136
+ try {
1137
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1138
+ return cursorData;
1139
+ }
1140
+ catch {
1141
+ throw new Error('Invalid pagination cursor');
1142
+ }
1143
+ }
1144
+ /**
1145
+ * Validates cursor format and structure
1146
+ *
1147
+ * @param paginationOptions - The pagination options containing the cursor
1148
+ * @param paginationType - Optional pagination type to validate against
1149
+ */
1150
+ static validateCursor(paginationOptions, paginationType) {
1151
+ if (paginationOptions.cursor !== undefined) {
1152
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1153
+ throw new Error('cursor must contain a valid cursor string');
1154
+ }
1155
+ try {
1156
+ // Try to parse the cursor to validate it
1157
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1158
+ // If type is provided, validate cursor contains expected type information
1159
+ if (paginationType) {
1160
+ if (!cursorData.type) {
1161
+ throw new Error('Invalid cursor: missing pagination type');
1162
+ }
1163
+ // Check pagination type compatibility
1164
+ if (cursorData.type !== paginationType) {
1165
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1166
+ }
1167
+ }
1168
+ }
1169
+ catch (error) {
1170
+ if (error instanceof Error) {
1171
+ // If it's already our error with specific message, pass it through
1172
+ if (error.message.startsWith('Invalid cursor') ||
1173
+ error.message.startsWith('Pagination type mismatch')) {
1174
+ throw error;
1175
+ }
1176
+ }
1177
+ throw new Error('Invalid pagination cursor format');
1178
+ }
1179
+ }
1180
+ }
1181
+ /**
1182
+ * Comprehensive validation for pagination options
1183
+ *
1184
+ * @param options - The pagination options to validate
1185
+ * @param paginationType - The pagination type these options will be used with
1186
+ * @returns Processed pagination parameters ready for use
1187
+ */
1188
+ static validatePaginationOptions(options, paginationType) {
1189
+ // Validate pageSize
1190
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1191
+ throw new Error('pageSize must be a positive number');
1192
+ }
1193
+ // Validate jumpToPage
1194
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1195
+ throw new Error('jumpToPage must be a positive number');
1196
+ }
1197
+ // Validate cursor
1198
+ PaginationHelpers.validateCursor(options, paginationType);
1199
+ // Validate service compatibility
1200
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1201
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1202
+ }
1203
+ // Get processed parameters
1204
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1205
+ }
1206
+ /**
1207
+ * Convert a unified pagination options to service-specific parameters
1208
+ */
1209
+ static getRequestParameters(options, paginationType) {
1210
+ // Handle jumpToPage
1211
+ if (options.jumpToPage !== undefined) {
1212
+ const jumpToPageOptions = {
1213
+ pageSize: options.pageSize,
1214
+ pageNumber: options.jumpToPage
1215
+ };
1216
+ return filterUndefined(jumpToPageOptions);
1217
+ }
1218
+ // If no cursor is provided, it's a first page request
1219
+ if (!options.cursor) {
1220
+ const firstPageOptions = {
1221
+ pageSize: options.pageSize,
1222
+ // Only set pageNumber for OFFSET pagination
1223
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1224
+ };
1225
+ return filterUndefined(firstPageOptions);
1226
+ }
1227
+ // Parse the cursor
1228
+ try {
1229
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1230
+ const cursorBasedOptions = {
1231
+ pageSize: cursorData.pageSize || options.pageSize,
1232
+ pageNumber: cursorData.pageNumber,
1233
+ continuationToken: cursorData.continuationToken,
1234
+ type: cursorData.type,
1235
+ };
1236
+ return filterUndefined(cursorBasedOptions);
1237
+ }
1238
+ catch {
1239
+ throw new Error('Invalid pagination cursor');
1240
+ }
1241
+ }
1242
+ /**
1243
+ * Helper method for paginated resource retrieval
1244
+ *
1245
+ * @param params - Parameters for pagination
1246
+ * @returns Promise resolving to a paginated result
1247
+ */
1248
+ static async getAllPaginated(params) {
1249
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1250
+ const endpoint = getEndpoint(folderId);
1251
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1252
+ // On POST, the caller's options go in the body; queryParams stays in the URL.
1253
+ // On GET, everything is URL — queryParams merges with additionalParams.
1254
+ const isPost = method === HTTP_METHODS.POST;
1255
+ const requestSpec = isPost
1256
+ ? { body: additionalParams, params: queryParams }
1257
+ : { params: { ...additionalParams, ...queryParams } };
1258
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1259
+ headers,
1260
+ ...requestSpec,
1261
+ pagination: {
1262
+ paginationType: options.paginationType || PaginationType.OFFSET,
1263
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1264
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1265
+ continuationTokenField: options.continuationTokenField,
1266
+ paginationParams: options.paginationParams
1267
+ }
1268
+ });
1269
+ // Parse items - automatically handle JSON string responses
1270
+ const rawItems = paginatedResponse.items;
1271
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1272
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1273
+ return {
1274
+ ...paginatedResponse,
1275
+ items: transformedItems
1276
+ };
1277
+ }
1278
+ /**
1279
+ * Helper method for non-paginated resource retrieval
1280
+ *
1281
+ * @param params - Parameters for non-paginated resource retrieval
1282
+ * @returns Promise resolving to an object with data and totalCount
1283
+ */
1284
+ static async getAllNonPaginated(params) {
1285
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1286
+ // Set default field names
1287
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1288
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1289
+ // Determine endpoint and headers based on folderId
1290
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1291
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1292
+ // Make the API call based on method
1293
+ let response;
1294
+ if (method === HTTP_METHODS.POST) {
1295
+ response = await serviceAccess.post(endpoint, additionalParams, { headers, params: queryParams });
1296
+ }
1297
+ else {
1298
+ response = await serviceAccess.get(endpoint, {
1299
+ params: { ...additionalParams, ...queryParams },
1300
+ headers
1301
+ });
1302
+ }
1303
+ // Extract and transform items from response
1304
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1305
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1306
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
1307
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1308
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1309
+ // Parse items - automatically handle JSON string responses
1310
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1311
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1312
+ return {
1313
+ items,
1314
+ totalCount
1315
+ };
1316
+ }
1317
+ /**
1318
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1319
+ *
1320
+ * @param config - Configuration for the getAll operation
1321
+ * @param options - Request options including pagination parameters
1322
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1323
+ */
1324
+ static async getAll(config, options) {
1325
+ const optionsWithDefaults = options || {};
1326
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1327
+ // Determine if pagination is requested
1328
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1329
+ // Process parameters (custom processing if provided, otherwise default)
1330
+ let processedOptions = restOptions;
1331
+ if (config.processParametersFn) {
1332
+ processedOptions = config.processParametersFn(restOptions, folderId);
1333
+ }
1334
+ // Apply ODATA prefix to keys (excluding specified keys)
1335
+ const excludeKeys = config.excludeFromPrefix || [];
1336
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1337
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1338
+ // Default pagination options
1339
+ const paginationOptions = {
1340
+ paginationType: PaginationType.OFFSET,
1341
+ itemsField: DEFAULT_ITEMS_FIELD,
1342
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1343
+ ...config.pagination
1344
+ };
1345
+ // Paginated flow
1346
+ if (isPaginationRequested) {
1347
+ return PaginationHelpers.getAllPaginated({
1348
+ serviceAccess: config.serviceAccess,
1349
+ getEndpoint: config.getEndpoint,
1350
+ folderId,
1351
+ headers: config.headers,
1352
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
1353
+ additionalParams: prefixedOptions,
1354
+ queryParams: config.queryParams,
1355
+ transformFn: config.transformFn,
1356
+ method: config.method,
1357
+ options: {
1358
+ ...paginationOptions,
1359
+ paginationParams: config.pagination?.paginationParams
1360
+ }
1361
+ }); // Type assertion needed due to conditional return
1362
+ }
1363
+ // Non-paginated flow
1364
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1365
+ return PaginationHelpers.getAllNonPaginated({
1366
+ serviceAccess: config.serviceAccess,
1367
+ getAllEndpoint: config.getEndpoint(),
1368
+ getByFolderEndpoint: byFolderEndpoint,
1369
+ folderId,
1370
+ headers: config.headers,
1371
+ additionalParams: prefixedOptions,
1372
+ queryParams: config.queryParams,
1373
+ transformFn: config.transformFn,
1374
+ method: config.method,
1375
+ options: {
1376
+ itemsField: paginationOptions.itemsField,
1377
+ totalCountField: paginationOptions.totalCountField
1378
+ }
1379
+ });
1380
+ }
1381
+ }
1382
+
1383
+ /**
1384
+ * SDK Internals Registry - Internal registry for SDK instances
1385
+ *
1386
+ * This class is NOT exported in the public API.
1387
+ * It provides a secure way to share SDK internals between
1388
+ * the UiPath class and service classes without exposing them publicly.
1389
+ *
1390
+ * @internal
1391
+ */
1392
+ // Global symbol key to ensure WeakMap is shared across module instances
1393
+ // This prevents issues when core and service modules are bundled separately
1394
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1395
+ // Get or create the global WeakMap store
1396
+ const getGlobalStore = () => {
1397
+ const globalObj = globalThis;
1398
+ if (!globalObj[REGISTRY_KEY]) {
1399
+ globalObj[REGISTRY_KEY] = new WeakMap();
1400
+ }
1401
+ return globalObj[REGISTRY_KEY];
1402
+ };
1403
+ /**
1404
+ * Internal registry for SDK private components.
1405
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1406
+ * garbage collected when the SDK instance is no longer referenced.
1407
+ *
1408
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1409
+ * across separately bundled modules (core, entities, tasks, etc.).
1410
+ *
1411
+ * @internal - Not exported in public API
1412
+ */
1413
+ class SDKInternalsRegistry {
1414
+ // Use global store to ensure sharing across module bundles
1415
+ static get store() {
1416
+ return getGlobalStore();
1417
+ }
1418
+ /**
1419
+ * Register SDK instance internals
1420
+ * Called by UiPath constructor
1421
+ */
1422
+ static set(instance, internals) {
1423
+ this.store.set(instance, internals);
1424
+ }
1425
+ /**
1426
+ * Retrieve SDK instance internals
1427
+ * Called by BaseService constructor
1428
+ */
1429
+ static get(instance) {
1430
+ const internals = this.store.get(instance);
1431
+ if (!internals) {
1432
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1433
+ }
1434
+ return internals;
1435
+ }
1436
+ }
1437
+
1438
+ var _BaseService_apiClient;
1439
+ /**
1440
+ * Base class for all UiPath SDK services.
1441
+ *
1442
+ * Provides common functionality for authentication, configuration, and API communication.
1443
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1444
+ *
1445
+ * This class implements the dependency injection pattern where services receive a configured
1446
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1447
+ * including authentication token management.
1448
+ *
1449
+ * @remarks
1450
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1451
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1452
+ *
1453
+ */
1454
+ class BaseService {
1455
+ /**
1456
+ * Creates a base service instance with dependency injection.
1457
+ *
1458
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1459
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1460
+ * and token management internally.
1461
+ *
1462
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1463
+ * Services receive this via dependency injection in the modular pattern.
1464
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1465
+ * CAS external-app auth)
1466
+ *
1467
+ * @example
1468
+ * ```typescript
1469
+ * // Services automatically call this via super()
1470
+ * export class EntityService extends BaseService {
1471
+ * constructor(instance: IUiPath) {
1472
+ * super(instance); // Initializes the internal ApiClient
1473
+ * }
1474
+ * }
1475
+ *
1476
+ * // Usage in modular pattern
1477
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1478
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1479
+ *
1480
+ * const sdk = new UiPath(config);
1481
+ * await sdk.initialize();
1482
+ * const entities = new Entities(sdk);
1483
+ * ```
1484
+ */
1485
+ constructor(instance, headers) {
1486
+ // Private field - not visible via Object.keys() or any reflection
1487
+ _BaseService_apiClient.set(this, void 0);
1488
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1489
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1490
+ this.config = { folderKey };
1491
+ }
1492
+ /**
1493
+ * Gets a valid authentication token, refreshing if necessary.
1494
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1495
+ *
1496
+ * @returns Promise resolving to a valid access token string
1497
+ * @throws AuthenticationError if no token is available or refresh fails
1498
+ */
1499
+ async getValidAuthToken() {
1500
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1501
+ }
1502
+ /**
1503
+ * Creates a service accessor for pagination helpers
1504
+ * This allows pagination helpers to access protected methods without making them public
1505
+ */
1506
+ createPaginationServiceAccess() {
1507
+ return {
1508
+ get: (path, options) => this.get(path, options || {}),
1509
+ post: (path, body, options) => this.post(path, body, options || {}),
1510
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1511
+ };
1512
+ }
1513
+ async request(method, path, options = {}) {
1514
+ switch (method.toUpperCase()) {
1515
+ case 'GET':
1516
+ return this.get(path, options);
1517
+ case 'POST':
1518
+ return this.post(path, options.body, options);
1519
+ case 'PUT':
1520
+ return this.put(path, options.body, options);
1521
+ case 'PATCH':
1522
+ return this.patch(path, options.body, options);
1523
+ case 'DELETE':
1524
+ return this.delete(path, options);
1525
+ default:
1526
+ throw new Error(`Unsupported HTTP method: ${method}`);
1527
+ }
1528
+ }
1529
+ async requestWithSpec(spec) {
1530
+ if (!spec.method || !spec.url) {
1531
+ throw new Error('Request spec must include method and url');
1532
+ }
1533
+ return this.request(spec.method, spec.url, spec);
1534
+ }
1535
+ async get(path, options = {}) {
1536
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1537
+ return { data: response };
1538
+ }
1539
+ async post(path, data, options = {}) {
1540
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1541
+ return { data: response };
1542
+ }
1543
+ async put(path, data, options = {}) {
1544
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1545
+ return { data: response };
1546
+ }
1547
+ async patch(path, data, options = {}) {
1548
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1549
+ return { data: response };
1550
+ }
1551
+ async delete(path, options = {}) {
1552
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1553
+ return { data: response };
1554
+ }
1555
+ /**
1556
+ * Execute a request with cursor-based pagination
1557
+ */
1558
+ async requestWithPagination(method, path, paginationOptions, options) {
1559
+ const paginationType = options.pagination.paginationType;
1560
+ // Validate and prepare pagination parameters
1561
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1562
+ // Prepare request parameters based on pagination type
1563
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1564
+ // Route pagination state to wherever the API expects it (body for POST, URL for GET).
1565
+ // Caller-supplied options.body / options.params are respected as-is — the api-client
1566
+ // already handles params (URL) and body (request body) independently for every method.
1567
+ if (method.toUpperCase() === 'POST') {
1568
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1569
+ options.body = {
1570
+ ...existingBody,
1571
+ ...requestParams
1572
+ };
1573
+ }
1574
+ else {
1575
+ options.params = {
1576
+ ...options.params,
1577
+ ...requestParams
1578
+ };
1579
+ }
1580
+ // Make the request
1581
+ const response = await this.request(method, path, options);
1582
+ // Extract data from the response and create page result
1583
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1584
+ itemsField: options.pagination.itemsField,
1585
+ totalCountField: options.pagination.totalCountField,
1586
+ continuationTokenField: options.pagination.continuationTokenField
1587
+ });
1588
+ }
1589
+ /**
1590
+ * Validates and prepares pagination parameters from options
1591
+ */
1592
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1593
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1594
+ }
1595
+ /**
1596
+ * Prepares request parameters for pagination based on pagination type
1597
+ */
1598
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1599
+ const requestParams = {};
1600
+ let limitedPageSize;
1601
+ const paginationParams = paginationConfig?.paginationParams;
1602
+ switch (paginationType) {
1603
+ case PaginationType.OFFSET:
1604
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1605
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1606
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1607
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1608
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1609
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1610
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1611
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
1612
+ const zeroBased = paginationParams?.zeroBased ?? false;
1613
+ requestParams[pageSizeParam] = limitedPageSize;
1614
+ if (convertToSkip) {
1615
+ if (params.pageNumber && params.pageNumber > 1) {
1616
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1617
+ }
1618
+ }
1619
+ else {
1620
+ const sdkPageNumber = params.pageNumber || 1;
1621
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
1622
+ }
1623
+ {
1624
+ requestParams[countParam] = true;
1625
+ }
1626
+ break;
1627
+ case PaginationType.TOKEN:
1628
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1629
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1630
+ if (params.pageSize) {
1631
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1632
+ }
1633
+ if (params.continuationToken) {
1634
+ requestParams[tokenParam] = params.continuationToken;
1635
+ }
1636
+ break;
1637
+ }
1638
+ return requestParams;
1639
+ }
1640
+ /**
1641
+ * Creates a paginated response from API response
1642
+ */
1643
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1644
+ // Extract fields from response
1645
+ const itemsField = fields.itemsField ||
1646
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1647
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1648
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1649
+ // Extract items and metadata
1650
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1651
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1652
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
1653
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1654
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1655
+ const continuationToken = response.data[continuationTokenField];
1656
+ // Determine if there are more pages
1657
+ const hasMore = this.determineHasMorePages(paginationType, {
1658
+ totalCount,
1659
+ pageSize: params.pageSize,
1660
+ currentPage: params.pageNumber || 1,
1661
+ itemsCount: items.length,
1662
+ continuationToken
1663
+ });
1664
+ // Create and return the page result
1665
+ return PaginationManager.createPaginatedResponse({
1666
+ pageInfo: {
1667
+ hasMore,
1668
+ totalCount,
1669
+ currentPage: params.pageNumber,
1670
+ pageSize: params.pageSize,
1671
+ continuationToken
1672
+ },
1673
+ type: paginationType,
1674
+ }, items);
1675
+ }
1676
+ /**
1677
+ * Determines if there are more pages based on pagination type and metadata
1678
+ */
1679
+ determineHasMorePages(paginationType, info) {
1680
+ switch (paginationType) {
1681
+ case PaginationType.OFFSET:
1682
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1683
+ // If totalCount is available, use it for precise calculation
1684
+ if (info.totalCount !== undefined) {
1685
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1686
+ }
1687
+ // Fallback when totalCount is not available
1688
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1689
+ return info.itemsCount === effectivePageSize;
1690
+ case PaginationType.TOKEN:
1691
+ return !!info.continuationToken;
1692
+ default:
1693
+ return false;
1694
+ }
1695
+ }
1696
+ }
1697
+ _BaseService_apiClient = new WeakMap();
1698
+
1699
+ /**
1700
+ * Service for the Orchestrator Document Understanding module.
1701
+ */
1702
+ class OrchestratorDuModuleService extends BaseService {
1703
+ /**
1704
+ * Submits an exception report for a Document Understanding validation task.
1705
+ *
1706
+ * Records that the document under validation cannot be processed normally and captures
1707
+ * a reason. The server echoes the submitted payload and signals acceptance via
1708
+ * {@link SubmitExceptionReportResponse.IsSuccessful}.
1709
+ *
1710
+ * @param taskId - Identifier of the validation task the exception applies to.
1711
+ * @param documentId - Identifier of the document the exception applies to.
1712
+ * @param reason - Free-text reason the document is being reported as an exception.
1713
+ * @returns Promise resolving to a {@link SubmitExceptionReportResponse} containing the echoed payload and success status.
1714
+ *
1715
+ * @example
1716
+ * ```typescript
1717
+ * import { Tasks, TaskType } from '@uipath/uipath-typescript/tasks';
1718
+ *
1719
+ * const tasks = new Tasks(sdk);
1720
+ *
1721
+ * // Fetch the Document Validation task to get its documentId
1722
+ * const dvTask = await tasks.getById(<taskId>, { taskType: TaskType.DocumentValidation }, <folderId>);
1723
+ * const documentId = dvTask.data?.documentId as string;
1724
+ *
1725
+ * // Submit an exception report for the validation task
1726
+ * const result = await orchestratorDuModule.submitExceptionReport(<taskId>, documentId, '<reason>');
1727
+ *
1728
+ * if (result.IsSuccessful) {
1729
+ * console.log('Exception recorded for', result.SubmitResult?.DocumentId);
1730
+ * }
1731
+ * ```
1732
+ * @internal
1733
+ */
1734
+ async submitExceptionReport(taskId, documentId, reason, options) {
1735
+ const headers = resolveFolderHeaders({
1736
+ folderId: options.folderId,
1737
+ folderKey: options.folderKey,
1738
+ folderPath: options.folderPath,
1739
+ resourceType: 'orchestratorDuModule.submitExceptionReport',
1740
+ fallbackFolderKey: this.config.folderKey,
1741
+ });
1742
+ const response = await this.post(ORCHESTRATOR_DU_MODULE_ENDPOINTS.SUBMIT_EXCEPTION_REPORT, { DocumentId: documentId, Reason: reason }, { params: { taskId }, headers });
1743
+ return response.data;
1744
+ }
1745
+ /**
1746
+ * Processes automatically extracted data against validator-edited data and a taxonomy.
1747
+ *
1748
+ * Sends the automatic extraction result, the validated extraction result, and the
1749
+ * document taxonomy to the server, which merges and normalizes the inputs and returns
1750
+ * the resulting {@link ExtractionResult}.
1751
+ *
1752
+ * @param request - Automatic and validated extraction results plus the document taxonomy.
1753
+ * @returns Promise resolving to the merged {@link ExtractionResult}.
1754
+ *
1755
+ * @example
1756
+ * ```typescript
1757
+ * // Merge automatic and validator-edited extraction results against a taxonomy
1758
+ * const result = await orchestratorDuModule.processExtractedData({
1759
+ * AutomaticExtractedResults: <automaticExtractionResult>,
1760
+ * ValidatedExtractedResults: <validatedData>,
1761
+ * Taxonomy: <taxonomy>,
1762
+ * });
1763
+ *
1764
+ * console.log(result.DocumentId, result.ResultsDocument?.DocumentTypeName);
1765
+ * ```
1766
+ * @internal
1767
+ */
1768
+ async processExtractedData(request, options) {
1769
+ const headers = resolveFolderHeaders({
1770
+ folderId: options.folderId,
1771
+ folderKey: options.folderKey,
1772
+ folderPath: options.folderPath,
1773
+ resourceType: 'orchestratorDuModule.processExtractedData',
1774
+ fallbackFolderKey: this.config.folderKey,
1775
+ });
1776
+ const response = await this.post(ORCHESTRATOR_DU_MODULE_ENDPOINTS.PROCESS_EXTRACTED_DATA, request, { headers });
1777
+ return response.data;
1778
+ }
1779
+ }
1780
+ __decorate([
1781
+ track('OrchestratorDuModule.SubmitExceptionReport')
1782
+ ], OrchestratorDuModuleService.prototype, "submitExceptionReport", null);
1783
+ __decorate([
1784
+ track('OrchestratorDuModule.ProcessExtractedData')
1785
+ ], OrchestratorDuModuleService.prototype, "processExtractedData", null);
1786
+
1787
+ exports.OrchestratorDuModule = OrchestratorDuModuleService;
1788
+ exports.OrchestratorDuModuleService = OrchestratorDuModuleService;