@uipath/uipath-typescript 1.3.7 → 1.3.9

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 (47) hide show
  1. package/dist/assets/index.cjs +64 -274
  2. package/dist/assets/index.d.ts +1 -0
  3. package/dist/assets/index.mjs +64 -274
  4. package/dist/attachments/index.cjs +62 -271
  5. package/dist/attachments/index.d.ts +1 -0
  6. package/dist/attachments/index.mjs +62 -271
  7. package/dist/buckets/index.cjs +93 -274
  8. package/dist/buckets/index.d.ts +51 -1
  9. package/dist/buckets/index.mjs +93 -274
  10. package/dist/cases/index.cjs +580 -336
  11. package/dist/cases/index.d.ts +690 -3
  12. package/dist/cases/index.mjs +581 -337
  13. package/dist/conversational-agent/index.cjs +110 -285
  14. package/dist/conversational-agent/index.d.ts +63 -12
  15. package/dist/conversational-agent/index.mjs +110 -286
  16. package/dist/core/index.cjs +39 -289
  17. package/dist/core/index.d.ts +9 -98
  18. package/dist/core/index.mjs +40 -275
  19. package/dist/document-understanding/index.cjs +18 -1
  20. package/dist/document-understanding/index.d.ts +636 -610
  21. package/dist/document-understanding/index.mjs +18 -1
  22. package/dist/entities/index.cjs +64 -274
  23. package/dist/entities/index.d.ts +1 -0
  24. package/dist/entities/index.mjs +64 -274
  25. package/dist/feedback/index.cjs +313 -276
  26. package/dist/feedback/index.d.ts +418 -12
  27. package/dist/feedback/index.mjs +313 -276
  28. package/dist/index.cjs +777 -297
  29. package/dist/index.d.ts +2005 -721
  30. package/dist/index.mjs +777 -283
  31. package/dist/index.umd.js +966 -162
  32. package/dist/jobs/index.cjs +64 -274
  33. package/dist/jobs/index.d.ts +1 -0
  34. package/dist/jobs/index.mjs +64 -274
  35. package/dist/maestro-processes/index.cjs +1789 -1686
  36. package/dist/maestro-processes/index.d.ts +431 -2
  37. package/dist/maestro-processes/index.mjs +1790 -1687
  38. package/dist/processes/index.cjs +64 -274
  39. package/dist/processes/index.d.ts +1 -0
  40. package/dist/processes/index.mjs +64 -274
  41. package/dist/queues/index.cjs +64 -274
  42. package/dist/queues/index.d.ts +1 -0
  43. package/dist/queues/index.mjs +64 -274
  44. package/dist/tasks/index.cjs +64 -274
  45. package/dist/tasks/index.d.ts +1 -0
  46. package/dist/tasks/index.mjs +64 -274
  47. package/package.json +8 -10
@@ -1,4 +1,4 @@
1
- import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';
1
+ import { getOrCreateClient, createTrack, createTrackEvent } from '@uipath/core-telemetry';
2
2
 
3
3
  /******************************************************************************
4
4
  Copyright (c) Microsoft Corporation.
@@ -43,465 +43,404 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
43
43
  };
44
44
 
45
45
  /**
46
- * Type guards for error response types
46
+ * Base path constants for different services
47
47
  */
48
- function isOrchestratorError(error) {
49
- return typeof error === 'object' &&
50
- error !== null &&
51
- 'message' in error &&
52
- 'errorCode' in error &&
53
- typeof error.message === 'string' &&
54
- typeof error.errorCode === 'number';
48
+ const PIMS_BASE = 'pims_';
49
+ const INSIGHTS_RTM_BASE = 'insightsrtm_';
50
+
51
+ /**
52
+ * Maestro Service Endpoints
53
+ */
54
+ /**
55
+ * Maestro Process Service Endpoints
56
+ */
57
+ const MAESTRO_ENDPOINTS = {
58
+ PROCESSES: {
59
+ GET_ALL: `${PIMS_BASE}/api/v1/processes/summary`},
60
+ INSTANCES: {
61
+ GET_ALL: `${PIMS_BASE}/api/v1/instances`,
62
+ GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
63
+ GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
64
+ GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
65
+ GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
66
+ CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
67
+ PAUSE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/pause`,
68
+ RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
69
+ },
70
+ INCIDENTS: {
71
+ GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
72
+ GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
73
+ GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
74
+ },
75
+ INSIGHTS: {
76
+ /** Top processes ranked by run count */
77
+ TOP_PROCESSES_BY_RUN_COUNT: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcessesByRunCount`,
78
+ /** Top processes ranked by failure count */
79
+ TOP_PROCESSES_WITH_FAILURE: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcesseswithFailure`,
80
+ /** Instance status aggregated by date for time-series charts */
81
+ INSTANCE_STATUS_BY_DATE: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/InstanceStatusByDate`,
82
+ /** Top processes ranked by total duration */
83
+ TOP_PROCESSES_BY_DURATION: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcessesByDuration`,
84
+ },
85
+ };
86
+
87
+ /**
88
+ * Maestro Process Models
89
+ * Model classes for Maestro processes
90
+ */
91
+ /**
92
+ * Creates methods for a process object
93
+ *
94
+ * @param processData - The process data (response from API)
95
+ * @param service - The process service instance
96
+ * @returns Object containing process methods
97
+ */
98
+ function createProcessMethods(processData, service) {
99
+ return {
100
+ async getIncidents() {
101
+ if (!processData.processKey)
102
+ throw new Error('Process key is undefined');
103
+ if (!processData.folderKey)
104
+ throw new Error('Folder key is undefined');
105
+ return service.getIncidents(processData.processKey, processData.folderKey);
106
+ }
107
+ };
55
108
  }
56
- function isEntityError(error) {
57
- return typeof error === 'object' &&
58
- error !== null &&
59
- 'error' in error &&
60
- typeof error.error === 'string';
109
+ /**
110
+ * Creates an actionable process by combining API process data with operational methods.
111
+ *
112
+ * @param processData - The process data from API
113
+ * @param service - The process service instance
114
+ * @returns A process object with added methods
115
+ */
116
+ function createProcessWithMethods(processData, service) {
117
+ const methods = createProcessMethods(processData, service);
118
+ return Object.assign({}, processData, methods);
61
119
  }
62
- function isPimsError(error) {
63
- return typeof error === 'object' &&
64
- error !== null &&
65
- 'type' in error &&
66
- 'title' in error &&
67
- 'status' in error &&
68
- typeof error.type === 'string' &&
69
- typeof error.title === 'string' &&
70
- typeof error.status === 'number';
120
+
121
+ /**
122
+ * Builds the request body for Insights RTM "top" endpoints.
123
+ *
124
+ * @param startTime - Start of the time range to query
125
+ * @param endTime - End of the time range to query
126
+ * @param isCaseManagement - Whether to filter for case management processes
127
+ * @param options - Optional filters (packageId, processKey, version)
128
+ * @returns Request body for the Insights RTM endpoint
129
+ * @internal
130
+ */
131
+ function buildInsightsTopBody(startTime, endTime, isCaseManagement, options) {
132
+ return {
133
+ commonParams: {
134
+ startTime: startTime.getTime(),
135
+ endTime: endTime.getTime(),
136
+ isCaseManagement,
137
+ ...(options?.packageId ? { packageId: options.packageId } : {}),
138
+ ...(options?.processKey ? { processKey: options.processKey } : {}),
139
+ ...(options?.version ? { version: options.version } : {}),
140
+ }
141
+ };
142
+ }
143
+ /**
144
+ * Fetches instance status timeline from the Insights API.
145
+ * Shared implementation used by both MaestroProcessesService and CasesService.
146
+ *
147
+ * @param postFn - Bound post method from a BaseService subclass
148
+ * @param startTime - Start of the time range to query
149
+ * @param endTime - End of the time range to query
150
+ * @param isCaseManagement - Whether to filter for case management processes
151
+ * @param options - Optional settings for time bucketing granularity
152
+ * @returns Promise resolving to an array of instance status timeline entries
153
+ * @internal
154
+ */
155
+ async function fetchInstanceStatusTimeline(postFn, startTime, endTime, isCaseManagement, options) {
156
+ const response = await postFn(MAESTRO_ENDPOINTS.INSIGHTS.INSTANCE_STATUS_BY_DATE, {
157
+ commonParams: {
158
+ startTime: startTime.getTime(),
159
+ endTime: endTime.getTime(),
160
+ isCaseManagement,
161
+ },
162
+ timeSliceUnit: options?.groupBy,
163
+ timezoneOffset: new Date().getTimezoneOffset() * -1,
164
+ });
165
+ return response.data ?? [];
71
166
  }
72
167
 
73
168
  /**
74
- * HTTP status code constants for error handling
169
+ * Common constants used across the SDK
75
170
  */
76
- const HttpStatus = {
77
- // Client errors (4xx)
78
- BAD_REQUEST: 400,
79
- UNAUTHORIZED: 401,
80
- FORBIDDEN: 403,
81
- NOT_FOUND: 404,
82
- TOO_MANY_REQUESTS: 429,
83
- // Server errors (5xx)
84
- INTERNAL_SERVER_ERROR: 500,
85
- BAD_GATEWAY: 502,
86
- SERVICE_UNAVAILABLE: 503,
87
- GATEWAY_TIMEOUT: 504
88
- };
89
171
  /**
90
- * Error type constants for consistent error identification
172
+ * Prefix used for OData query parameters
91
173
  */
92
- const ErrorType = {
93
- AUTHENTICATION: 'AuthenticationError',
94
- AUTHORIZATION: 'AuthorizationError',
95
- VALIDATION: 'ValidationError',
96
- NOT_FOUND: 'NotFoundError',
97
- RATE_LIMIT: 'RateLimitError',
98
- SERVER: 'ServerError',
99
- NETWORK: 'NetworkError'
174
+ const ODATA_PREFIX = '$';
175
+ const UNKNOWN = 'Unknown';
176
+ const NO_INSTANCE = 'no-instance';
177
+ /**
178
+ * HTTP methods
179
+ */
180
+ const HTTP_METHODS = {
181
+ GET: 'GET',
182
+ POST: 'POST'};
183
+ /**
184
+ * Process Instance pagination constants for token-based pagination
185
+ */
186
+ const PROCESS_INSTANCE_PAGINATION = {
187
+ /** Field name for items in process instance response */
188
+ ITEMS_FIELD: 'instances',
189
+ /** Field name for continuation token in process instance response */
190
+ CONTINUATION_TOKEN_FIELD: 'nextPage'
100
191
  };
101
192
  /**
102
- * HTTP header constants for error handling
193
+ * OData OFFSET pagination parameter names (ODATA-style)
103
194
  */
104
- const HttpHeaders = {
105
- X_REQUEST_ID: 'x-request-id'
195
+ const ODATA_OFFSET_PARAMS = {
196
+ /** OData page size parameter name */
197
+ PAGE_SIZE_PARAM: '$top',
198
+ /** OData offset parameter name */
199
+ OFFSET_PARAM: '$skip',
200
+ /** OData count parameter name */
201
+ COUNT_PARAM: '$count'
106
202
  };
107
203
  /**
108
- * Standard error message constants
204
+ * Bucket TOKEN pagination parameter names
109
205
  */
110
- const ErrorMessages = {
111
- // Authentication errors
112
- AUTHENTICATION_FAILED: 'Authentication failed',
113
- // Authorization errors
114
- ACCESS_DENIED: 'Access denied',
115
- // Validation errors
116
- VALIDATION_FAILED: 'Validation failed',
117
- // Not found errors
118
- RESOURCE_NOT_FOUND: 'Resource not found',
119
- // Rate limit errors
120
- RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
121
- // Server errors
122
- INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
123
- // Network errors
124
- NETWORK_ERROR: 'Network error occurred',
125
- REQUEST_TIMEOUT: 'Request timed out',
126
- REQUEST_ABORTED: 'Request was aborted',
206
+ const BUCKET_TOKEN_PARAMS = {
207
+ /** Bucket page size parameter name */
208
+ PAGE_SIZE_PARAM: 'takeHint',
209
+ /** Bucket token parameter name */
210
+ TOKEN_PARAM: 'continuationToken'
127
211
  };
128
212
  /**
129
- * Error name constants for network error identification
213
+ * Process Instance TOKEN pagination parameter names
130
214
  */
131
- const ErrorNames = {
132
- ABORT_ERROR: 'AbortError'};
215
+ const PROCESS_INSTANCE_TOKEN_PARAMS = {
216
+ /** Process instance page size parameter name */
217
+ PAGE_SIZE_PARAM: 'pageSize',
218
+ /** Process instance token parameter name */
219
+ TOKEN_PARAM: 'nextPage'
220
+ };
133
221
 
134
222
  /**
135
- * Parser for Orchestrator/Task error format
223
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
224
+ * Returns the original value if parsing fails.
136
225
  */
137
- class OrchestratorErrorParser {
138
- canParse(errorBody) {
139
- return isOrchestratorError(errorBody);
140
- }
141
- parse(errorBody, response) {
142
- const error = errorBody;
143
- return {
144
- message: error.message,
145
- code: response?.status?.toString(),
146
- details: {
147
- errorCode: error.errorCode,
148
- traceId: error.traceId,
149
- originalResponse: error
150
- },
151
- requestId: error.traceId
152
- };
153
- }
154
- }
155
226
  /**
156
- * Parser for Entity (Data Fabric) error format
227
+ * Transforms data by mapping fields according to the provided field mapping
228
+ * @param data The source data to transform
229
+ * @param fieldMapping Object mapping source field names to target field names
230
+ * @returns Transformed data with mapped field names
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * // Single object transformation
235
+ * const data = { id: '123', userName: 'john' };
236
+ * const mapping = { id: 'userId', userName: 'name' };
237
+ * const result = transformData(data, mapping);
238
+ * // result = { userId: '123', name: 'john' }
239
+ *
240
+ * // Array transformation
241
+ * const dataArray = [
242
+ * { id: '123', userName: 'john' },
243
+ * { id: '456', userName: 'jane' }
244
+ * ];
245
+ * const result = transformData(dataArray, mapping);
246
+ * // result = [
247
+ * // { userId: '123', name: 'john' },
248
+ * // { userId: '456', name: 'jane' }
249
+ * // ]
250
+ * ```
157
251
  */
158
- class EntityErrorParser {
159
- canParse(errorBody) {
160
- return isEntityError(errorBody);
252
+ function transformData(data, fieldMapping) {
253
+ // Handle array of objects
254
+ if (Array.isArray(data)) {
255
+ return data.map(item => transformData(item, fieldMapping));
161
256
  }
162
- parse(errorBody, response) {
163
- const error = errorBody;
164
- return {
165
- message: error.error,
166
- code: response?.status?.toString(),
167
- details: {
168
- error: error.error,
169
- traceId: error.traceId,
170
- originalResponse: error
171
- },
172
- requestId: error.traceId
173
- };
257
+ // Handle single object
258
+ const result = { ...data };
259
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
260
+ if (sourceField in result) {
261
+ const value = result[sourceField];
262
+ delete result[sourceField];
263
+ result[targetField] = value;
264
+ }
174
265
  }
266
+ return result;
175
267
  }
176
268
  /**
177
- * Parser for PIMS error format
269
+ * Adds a prefix to specified keys in an object, returning a new object.
270
+ * Only the provided keys are prefixed; all others are left unchanged.
271
+ *
272
+ * @param obj The source object
273
+ * @param prefix The prefix to add (e.g., '$')
274
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
275
+ * @returns A new object with specified keys prefixed
276
+ *
277
+ * @example
278
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
178
279
  */
179
- class PimsErrorParser {
180
- canParse(errorBody) {
181
- return isPimsError(errorBody);
182
- }
183
- parse(errorBody, response) {
184
- const error = errorBody;
185
- let message = error.title;
186
- // If there are validation errors, append them to the message for better visibility
187
- if (error.errors && Object.keys(error.errors).length > 0) {
188
- const errorMessages = Object.entries(error.errors)
189
- .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
190
- .join('; ');
191
- message += `. Validation errors: ${errorMessages}`;
280
+ function addPrefixToKeys(obj, prefix, keys) {
281
+ const result = {};
282
+ for (const [key, value] of Object.entries(obj)) {
283
+ if (keys.includes(key)) {
284
+ result[`${prefix}${key}`] = value;
285
+ }
286
+ else {
287
+ result[key] = value;
192
288
  }
193
- return {
194
- message,
195
- code: response?.status?.toString(),
196
- details: {
197
- type: error.type,
198
- title: error.title,
199
- status: error.status,
200
- errors: error.errors,
201
- traceId: error.traceId,
202
- originalResponse: error
203
- },
204
- requestId: error.traceId
205
- };
206
289
  }
290
+ return result;
207
291
  }
292
+
208
293
  /**
209
- * Fallback parser for unrecognized formats
294
+ * Maps fields for Incident entities
210
295
  */
211
- class GenericErrorParser {
212
- canParse(_errorBody) {
213
- return true; // Always can parse as last resort
214
- }
215
- parse(errorBody, response) {
216
- // For unknown error formats, just pass through the raw error with fallback message
217
- const message = response?.statusText || 'An error occurred';
218
- return {
219
- message,
220
- code: response?.status?.toString(),
221
- details: {
222
- originalResponse: errorBody
223
- },
224
- };
225
- }
226
- }
296
+ const ProcessIncidentMap = {
297
+ errorTimeUtc: 'errorTime'
298
+ };
227
299
  /**
228
- * Main error response parser using Chain of Responsibility pattern
229
- *
230
- * This parser standardizes error responses from different UiPath services into a
231
- * consistent format, regardless of the original error structure.
232
- *
233
- * Supported formats:
234
- * 1. Orchestrator/Task: { message, errorCode, traceId }
235
- * 2. Entity (Data Fabric): { error, traceId }
236
- * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
237
- * 4. Generic: Fallback for any other format
238
- *
239
- * @example
240
- * const parser = new ErrorResponseParser();
241
- * const errorInfo = await parser.parse(response);
242
- * // errorInfo will have consistent structure regardless of service
300
+ * Maps fields for Incident Summary entities
243
301
  */
244
- class ErrorResponseParser {
245
- constructor() {
246
- this.strategies = [
247
- new OrchestratorErrorParser(),
248
- new EntityErrorParser(),
249
- new PimsErrorParser(),
250
- new GenericErrorParser() // Must be last
251
- ];
252
- }
302
+ const ProcessIncidentSummaryMap = {
303
+ firstTimeUtc: 'firstOccuranceTime'
304
+ };
305
+
306
+ /**
307
+ * Helpers for fetching BPMN XML and extracting element details used to annotate responses
308
+ */
309
+ class BpmnHelpers {
253
310
  /**
254
- * Parses error response body into standardized format
255
- * @param response - The HTTP response object
256
- * @returns Standardized error information
311
+ * Parse BPMN XML and extract element id → {name,type} used for incidents
257
312
  */
258
- async parse(response) {
313
+ static parseBpmnElementsForIncidents(bpmnXml) {
314
+ const elementInfo = {};
259
315
  try {
260
- const errorBody = await response.json();
261
- // Find the first strategy that can parse this error format
262
- const strategy = this.strategies.find(s => s.canParse(errorBody));
263
- // GenericErrorParser always returns true, so this will never be null
264
- return strategy.parse(errorBody, response);
316
+ // Find <bpmn:...> start tags and capture the element type.
317
+ // Then read 'id' and 'name' attributes from each tag.
318
+ const bpmnOpenTagRegex = /<bpmn:([A-Za-z][\w.-]*)\b[^>]*>/g;
319
+ for (const tagMatch of bpmnXml.matchAll(bpmnOpenTagRegex)) {
320
+ const [fullTag, elementType] = tagMatch;
321
+ // Extract attributes from the current tag text.
322
+ const idMatch = /\bid\s*=\s*"([^"]*)"/.exec(fullTag);
323
+ if (!idMatch) {
324
+ continue;
325
+ }
326
+ const elementId = idMatch[1];
327
+ const nameMatch = /\bname\s*=\s*"([^"]*)"/.exec(fullTag);
328
+ const name = nameMatch ? nameMatch[1] : '';
329
+ // Convert BPMN element type to human-readable format
330
+ const activityType = this.formatActivityTypeForIncidents(elementType);
331
+ const activityName = name || elementId;
332
+ elementInfo[elementId] = {
333
+ type: activityType,
334
+ name: activityName
335
+ };
336
+ }
265
337
  }
266
- catch {
267
- // Handle non-JSON responses
268
- const responseText = await response.text().catch(() => '');
269
- return {
270
- message: response.statusText,
271
- code: response.status.toString(),
272
- details: {
273
- parseError: 'Failed to parse error response as JSON',
274
- responseText
275
- },
276
- requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
277
- };
338
+ catch (error) {
339
+ console.warn('Failed to parse BPMN XML for incidents:', error);
278
340
  }
341
+ return elementInfo;
279
342
  }
280
- }
281
- // Export singleton instance
282
- const errorResponseParser = new ErrorResponseParser();
283
-
284
- /**
285
- * Base error class for all UiPath SDK errors
286
- * Extends Error for standard error handling compatibility
287
- */
288
- class UiPathError extends Error {
289
- constructor(type, params) {
290
- super(params.message);
291
- this.name = type;
292
- this.type = type;
293
- this.statusCode = params.statusCode;
294
- this.requestId = params.requestId;
295
- this.timestamp = new Date();
296
- // Maintains proper stack trace for where our error was thrown
297
- if (Error.captureStackTrace) {
298
- Error.captureStackTrace(this, this.constructor);
343
+ /**
344
+ * Format BPMN element type to human-readable activity type for incidents
345
+ */
346
+ static formatActivityTypeForIncidents(elementType) {
347
+ // Convert camelCase BPMN element types to human-readable format
348
+ // e.g., "serviceTask" -> "Service Task", "exclusiveGateway" -> "Exclusive Gateway"
349
+ return elementType
350
+ .replace(/([A-Z])/g, ' $1') // Add space before uppercase letters
351
+ .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
352
+ .trim(); // Remove any leading/trailing spaces
353
+ }
354
+ /**
355
+ * Fetch BPMN via getBpmn and add element name/type to each incident
356
+ */
357
+ static async enrichIncidentsWithBpmnData(incidents, folderKey, service) {
358
+ // Check if all incidents have the same instanceId
359
+ const uniqueInstanceIds = [...new Set(incidents.map(i => i.instanceId))];
360
+ if (uniqueInstanceIds.length === 1) {
361
+ // Single instance optimization (in case of process instance incidents)
362
+ const elementInfo = await this.getBpmnElementInfo(uniqueInstanceIds[0], folderKey, service);
363
+ return incidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
364
+ }
365
+ else {
366
+ // Multiple instances optimization (in case of process incidents)
367
+ return this.enrichMultipleInstanceIncidents(incidents, folderKey, service);
299
368
  }
300
369
  }
301
370
  /**
302
- * Returns a clean JSON representation of the error
371
+ * When incidents span multiple instances, fetch BPMN per instance and annotate
303
372
  */
304
- toJSON() {
305
- return {
306
- type: this.type,
307
- message: this.message,
308
- statusCode: this.statusCode,
309
- requestId: this.requestId,
310
- timestamp: this.timestamp
311
- };
373
+ static async enrichMultipleInstanceIncidents(incidents, folderKey, service) {
374
+ const groups = incidents.reduce((acc, incident) => {
375
+ const id = incident.instanceId || NO_INSTANCE;
376
+ (acc[id] = acc[id] || []).push(incident);
377
+ return acc;
378
+ }, {});
379
+ const results = await Promise.all(Object.entries(groups).map(async (entry) => {
380
+ const [instanceId, groupIncidents] = entry;
381
+ const elementInfo = await this.getBpmnElementInfo(instanceId, folderKey, service);
382
+ return groupIncidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
383
+ }));
384
+ return results.flat();
312
385
  }
313
386
  /**
314
- * Returns detailed debug information including stack trace
387
+ * Retrieve BPMN XML for an instance and derive element id → {name,type}
315
388
  */
316
- getDebugInfo() {
389
+ static async getBpmnElementInfo(instanceId, folderKey, service) {
390
+ if (!instanceId || instanceId === NO_INSTANCE) {
391
+ return {};
392
+ }
393
+ try {
394
+ const bpmnXml = await service.getBpmn(instanceId, folderKey);
395
+ return this.parseBpmnElementsForIncidents(bpmnXml);
396
+ }
397
+ catch (error) {
398
+ console.warn(`Failed to get BPMN for instance ${instanceId}:`, error);
399
+ return {};
400
+ }
401
+ }
402
+ /**
403
+ * Transform a raw incident by attaching element name/type from BPMN
404
+ */
405
+ static transformIncidentWithBpmn(incident, elementInfo) {
406
+ const element = elementInfo[incident.elementId];
407
+ const transformed = transformData(incident, ProcessIncidentMap);
317
408
  return {
318
- ...this.toJSON(),
319
- stack: this.stack
409
+ ...transformed,
410
+ incidentElementActivityType: element?.type || UNKNOWN,
411
+ incidentElementActivityName: element?.name || UNKNOWN
320
412
  };
321
413
  }
322
414
  }
323
415
 
324
416
  /**
325
- * Error thrown when authentication fails (401 errors)
326
- * Common scenarios:
327
- * - Invalid credentials
328
- * - Expired token
329
- * - Missing authentication
330
- */
331
- class AuthenticationError extends UiPathError {
332
- constructor(params = {}) {
333
- super(ErrorType.AUTHENTICATION, {
334
- message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
335
- statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
336
- requestId: params.requestId
337
- });
338
- }
339
- }
417
+ * SDK Telemetry constants.
418
+ *
419
+ * Only the SDK's identity (version, service name, role name, …) lives
420
+ * here. The Application Insights connection string is injected into
421
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
422
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
423
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
424
+ * SDK's public API.
425
+ */
426
+ /** SDK version placeholder — patched by the SDK publish workflow. */
427
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
340
428
 
341
429
  /**
342
- * Error thrown when authorization fails (403 errors)
343
- * Common scenarios:
344
- * - Insufficient permissions
345
- * - Access denied to resource
346
- * - Invalid scope
347
- */
348
- class AuthorizationError extends UiPathError {
349
- constructor(params = {}) {
350
- super(ErrorType.AUTHORIZATION, {
351
- message: params.message || ErrorMessages.ACCESS_DENIED,
352
- statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
353
- requestId: params.requestId
354
- });
355
- }
356
- }
357
-
358
- /**
359
- * Error thrown when validation fails (400 errors or client-side validation)
360
- * Common scenarios:
361
- * - Invalid input parameters
362
- * - Missing required fields
363
- * - Invalid data format
364
- */
365
- class ValidationError extends UiPathError {
366
- constructor(params = {}) {
367
- super(ErrorType.VALIDATION, {
368
- message: params.message || ErrorMessages.VALIDATION_FAILED,
369
- statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
370
- requestId: params.requestId
371
- });
372
- }
373
- }
374
-
375
- /**
376
- * Error thrown when a resource is not found (404 errors)
377
- * Common scenarios:
378
- * - Resource doesn't exist
379
- * - Invalid ID provided
380
- * - Resource deleted
381
- */
382
- class NotFoundError extends UiPathError {
383
- constructor(params = {}) {
384
- super(ErrorType.NOT_FOUND, {
385
- message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
386
- statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
387
- requestId: params.requestId
388
- });
389
- }
390
- }
391
-
392
- /**
393
- * Error thrown when rate limit is exceeded (429 errors)
394
- * Common scenarios:
395
- * - Too many requests in a time window
396
- * - API throttling
397
- */
398
- class RateLimitError extends UiPathError {
399
- constructor(params = {}) {
400
- super(ErrorType.RATE_LIMIT, {
401
- message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
402
- statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
403
- requestId: params.requestId
404
- });
405
- }
406
- }
407
-
408
- /**
409
- * Error thrown when server encounters an error (5xx errors)
410
- * Common scenarios:
411
- * - Internal server error
412
- * - Service unavailable
413
- * - Gateway timeout
414
- */
415
- class ServerError extends UiPathError {
416
- constructor(params = {}) {
417
- super(ErrorType.SERVER, {
418
- message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
419
- statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
420
- requestId: params.requestId
421
- });
422
- }
423
- /**
424
- * Checks if this is a temporary error that might succeed on retry
425
- */
426
- get isRetryable() {
427
- return this.statusCode === HttpStatus.BAD_GATEWAY ||
428
- this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
429
- this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
430
- }
431
- }
432
-
433
- /**
434
- * Error thrown when network/connection issues occur
435
- * Common scenarios:
436
- * - Connection timeout
437
- * - DNS resolution failure
438
- * - Network unreachable
439
- * - Request aborted
440
- */
441
- class NetworkError extends UiPathError {
442
- constructor(params = {}) {
443
- super(ErrorType.NETWORK, {
444
- message: params.message || ErrorMessages.NETWORK_ERROR,
445
- statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
446
- requestId: params.requestId
447
- });
448
- }
449
- }
450
-
451
- /**
452
- * Factory for creating typed errors based on HTTP status codes
453
- * Follows the Factory pattern for clean error instantiation
454
- */
455
- class ErrorFactory {
456
- /**
457
- * Creates appropriate error instance based on HTTP status code
458
- */
459
- static createFromHttpStatus(statusCode, errorInfo) {
460
- const { message, requestId } = errorInfo;
461
- // Map status codes to error types
462
- switch (statusCode) {
463
- case HttpStatus.BAD_REQUEST:
464
- return new ValidationError({ message, statusCode, requestId });
465
- case HttpStatus.UNAUTHORIZED:
466
- return new AuthenticationError({ message, statusCode, requestId });
467
- case HttpStatus.FORBIDDEN:
468
- return new AuthorizationError({ message, statusCode, requestId });
469
- case HttpStatus.NOT_FOUND:
470
- return new NotFoundError({ message, statusCode, requestId });
471
- case HttpStatus.TOO_MANY_REQUESTS:
472
- return new RateLimitError({ message, statusCode, requestId });
473
- default:
474
- // For 5xx errors or any other status code
475
- if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
476
- return new ServerError({ message, statusCode, requestId });
477
- }
478
- // For unknown client errors, treat as validation error
479
- return new ValidationError({
480
- message: `${message} (HTTP ${statusCode})`,
481
- statusCode,
482
- requestId
483
- });
484
- }
485
- }
486
- /**
487
- * Creates a NetworkError from a fetch/network error
488
- */
489
- static createNetworkError(error) {
490
- let message = ErrorMessages.NETWORK_ERROR;
491
- if (error instanceof Error) {
492
- if (error.name === ErrorNames.ABORT_ERROR) {
493
- message = ErrorMessages.REQUEST_ABORTED;
494
- }
495
- else if (error.message.includes('timeout')) {
496
- message = ErrorMessages.REQUEST_TIMEOUT;
497
- }
498
- else {
499
- message = error.message;
500
- }
501
- }
502
- return new NetworkError({ message });
503
- }
504
- }
430
+ * UiPath TypeScript SDK Telemetry
431
+ *
432
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
433
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
434
+ * does this independently, so events carry their own consumer's identity
435
+ * and tenant context.
436
+ */
437
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
438
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
439
+ // from the `UiPath` constructor therefore wires up `@track` decorators
440
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
441
+ const sdkClient = getOrCreateClient(CLOUD_ROLE_NAME);
442
+ const track = createTrack(sdkClient);
443
+ createTrackEvent(sdkClient);
505
444
 
506
445
  const FOLDER_KEY = 'X-UIPATH-FolderKey';
507
446
  const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
@@ -525,1489 +464,1399 @@ const RESPONSE_TYPES = {
525
464
  ARRAYBUFFER: 'arraybuffer'
526
465
  };
527
466
 
528
- class ApiClient {
529
- constructor(config, executionContext, tokenManager, clientConfig = {}) {
530
- this.config = config;
531
- this.executionContext = executionContext;
532
- this.clientConfig = clientConfig;
533
- this.tokenManager = tokenManager;
534
- }
535
- /**
536
- * Gets a valid authentication token, refreshing if necessary.
537
- * Used internally for API requests and exposed for services that need manual auth headers.
538
- *
539
- * @returns The valid token
540
- * @throws AuthenticationError if no token available or refresh fails
541
- */
542
- async getValidToken() {
543
- return this.tokenManager.getValidToken();
544
- }
545
- async getDefaultHeaders() {
546
- const token = await this.getValidToken();
547
- return {
548
- 'Authorization': `Bearer ${token}`,
549
- 'Content-Type': CONTENT_TYPES.JSON,
550
- ...this.clientConfig.headers
551
- };
552
- }
553
- async request(method, path, options = {}) {
554
- // Ensure path starts with a forward slash
555
- const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
556
- // Construct URL with org and tenant names
557
- const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
558
- const isFormData = options.body instanceof FormData;
559
- const defaultHeaders = await this.getDefaultHeaders();
560
- if (isFormData) {
561
- delete defaultHeaders['Content-Type'];
562
- }
563
- const traceId = crypto.randomUUID().replace(/-/g, '');
564
- const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
565
- const traceparentValue = `00-${traceId}-${spanId}-01`;
566
- const headers = {
567
- ...defaultHeaders,
568
- [TRACEPARENT]: traceparentValue,
569
- [UIPATH_TRACEPARENT_ID]: traceparentValue,
570
- ...options.headers
571
- };
572
- // Convert params to URLSearchParams
573
- const searchParams = new URLSearchParams();
574
- if (options.params) {
575
- Object.entries(options.params).forEach(([key, value]) => {
576
- searchParams.append(key, value.toString());
577
- });
578
- }
579
- const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
580
- let body = undefined;
581
- if (options.body) {
582
- body = isFormData ? options.body : JSON.stringify(options.body);
467
+ /**
468
+ * Creates headers object from key-value pairs
469
+ * @param headersObj - Object containing header key-value pairs
470
+ * @returns Headers object with all values converted to strings
471
+ *
472
+ * @example
473
+ * ```typescript
474
+ * // Single header
475
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
476
+ *
477
+ * // Multiple headers
478
+ * const headers = createHeaders({
479
+ * 'X-UIPATH-FolderKey': '1234567890',
480
+ * 'X-UIPATH-OrganizationUnitId': 123,
481
+ * 'Accept': 'application/json'
482
+ * });
483
+ *
484
+ * // Using constants
485
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
486
+ * const headers = createHeaders({
487
+ * [FOLDER_KEY]: 'abc-123',
488
+ * [FOLDER_ID]: 456
489
+ * });
490
+ *
491
+ * // Empty headers
492
+ * const headers = createHeaders();
493
+ * ```
494
+ */
495
+ function createHeaders(headersObj) {
496
+ const headers = {};
497
+ for (const [key, value] of Object.entries(headersObj)) {
498
+ if (value !== undefined && value !== null) {
499
+ headers[key] = value.toString();
583
500
  }
584
- try {
585
- const response = await fetch(fullUrl, {
586
- method,
587
- headers,
588
- body,
589
- signal: options.signal
590
- });
591
- if (!response.ok) {
592
- const errorInfo = await errorResponseParser.parse(response);
593
- throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
594
- }
595
- if (response.status === 204) {
596
- return undefined;
597
- }
598
- // Handle blob response type for binary data (e.g., file downloads)
599
- if (options.responseType === RESPONSE_TYPES.BLOB) {
600
- const blob = await response.blob();
601
- return blob;
602
- }
603
- // Check if we're expecting XML
604
- const acceptHeader = headers['Accept'] || headers['accept'];
605
- if (acceptHeader === CONTENT_TYPES.XML) {
606
- const text = await response.text();
607
- return text;
608
- }
609
- const text = await response.text();
610
- if (!text) {
611
- return undefined;
612
- }
613
- return JSON.parse(text);
614
- }
615
- catch (error) {
616
- // If it's already one of our errors, re-throw it
617
- if (error.type && error.type.includes('Error')) {
618
- throw error;
619
- }
620
- // Otherwise, it's likely a network error
621
- throw ErrorFactory.createNetworkError(error);
622
- }
623
- }
624
- async get(path, options = {}) {
625
- return this.request('GET', path, options);
626
- }
627
- async post(path, data, options = {}) {
628
- return this.request('POST', path, { ...options, body: data });
629
- }
630
- async put(path, data, options = {}) {
631
- return this.request('PUT', path, { ...options, body: data });
632
- }
633
- async patch(path, data, options = {}) {
634
- return this.request('PATCH', path, { ...options, body: data });
635
- }
636
- async delete(path, options = {}) {
637
- return this.request('DELETE', path, options);
638
501
  }
502
+ return headers;
639
503
  }
640
504
 
641
505
  /**
642
- * Pagination types supported by the SDK
506
+ * Type guards for error response types
643
507
  */
644
- var PaginationType;
645
- (function (PaginationType) {
646
- PaginationType["OFFSET"] = "offset";
647
- PaginationType["TOKEN"] = "token";
648
- })(PaginationType || (PaginationType = {}));
508
+ function isOrchestratorError(error) {
509
+ return typeof error === 'object' &&
510
+ error !== null &&
511
+ 'message' in error &&
512
+ 'errorCode' in error &&
513
+ typeof error.message === 'string' &&
514
+ typeof error.errorCode === 'number';
515
+ }
516
+ function isEntityError(error) {
517
+ return typeof error === 'object' &&
518
+ error !== null &&
519
+ 'error' in error &&
520
+ typeof error.error === 'string';
521
+ }
522
+ function isPimsError(error) {
523
+ return typeof error === 'object' &&
524
+ error !== null &&
525
+ 'type' in error &&
526
+ 'title' in error &&
527
+ 'status' in error &&
528
+ typeof error.type === 'string' &&
529
+ typeof error.title === 'string' &&
530
+ typeof error.status === 'number';
531
+ }
649
532
 
650
533
  /**
651
- * Collection of utility functions for working with objects
534
+ * HTTP status code constants for error handling
652
535
  */
536
+ const HttpStatus = {
537
+ // Client errors (4xx)
538
+ BAD_REQUEST: 400,
539
+ UNAUTHORIZED: 401,
540
+ FORBIDDEN: 403,
541
+ NOT_FOUND: 404,
542
+ TOO_MANY_REQUESTS: 429,
543
+ // Server errors (5xx)
544
+ INTERNAL_SERVER_ERROR: 500,
545
+ BAD_GATEWAY: 502,
546
+ SERVICE_UNAVAILABLE: 503,
547
+ GATEWAY_TIMEOUT: 504
548
+ };
653
549
  /**
654
- * Filters out undefined values from an object
655
- * @param obj The source object
656
- * @returns A new object without undefined values
657
- *
658
- * @example
659
- * ```typescript
660
- * // Object with undefined values
661
- * const options = {
662
- * name: 'test',
663
- * count: 5,
664
- * prefix: undefined,
665
- * suffix: null
666
- * };
667
- * const result = filterUndefined(options);
668
- * // result = { name: 'test', count: 5, suffix: null }
669
- * ```
550
+ * Error type constants for consistent error identification
670
551
  */
671
- function filterUndefined(obj) {
672
- const result = {};
673
- for (const [key, value] of Object.entries(obj)) {
674
- if (value !== undefined) {
675
- result[key] = value;
676
- }
677
- }
678
- return result;
679
- }
680
-
552
+ const ErrorType = {
553
+ AUTHENTICATION: 'AuthenticationError',
554
+ AUTHORIZATION: 'AuthorizationError',
555
+ VALIDATION: 'ValidationError',
556
+ NOT_FOUND: 'NotFoundError',
557
+ RATE_LIMIT: 'RateLimitError',
558
+ SERVER: 'ServerError',
559
+ NETWORK: 'NetworkError'
560
+ };
681
561
  /**
682
- * Utility functions for platform detection
562
+ * HTTP header constants for error handling
683
563
  */
564
+ const HttpHeaders = {
565
+ X_REQUEST_ID: 'x-request-id'
566
+ };
684
567
  /**
685
- * Checks if code is running in a browser environment
568
+ * Standard error message constants
686
569
  */
687
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
688
- isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
689
-
570
+ const ErrorMessages = {
571
+ // Authentication errors
572
+ AUTHENTICATION_FAILED: 'Authentication failed',
573
+ // Authorization errors
574
+ ACCESS_DENIED: 'Access denied',
575
+ // Validation errors
576
+ VALIDATION_FAILED: 'Validation failed',
577
+ // Not found errors
578
+ RESOURCE_NOT_FOUND: 'Resource not found',
579
+ // Rate limit errors
580
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
581
+ // Server errors
582
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
583
+ // Network errors
584
+ NETWORK_ERROR: 'Network error occurred',
585
+ REQUEST_TIMEOUT: 'Request timed out',
586
+ REQUEST_ABORTED: 'Request was aborted',
587
+ };
690
588
  /**
691
- * Base64 encoding/decoding
589
+ * Error name constants for network error identification
692
590
  */
591
+ const ErrorNames = {
592
+ ABORT_ERROR: 'AbortError'};
593
+
693
594
  /**
694
- * Encodes a string to base64
695
- * @param str - The string to encode
696
- * @returns Base64 encoded string
595
+ * Parser for Orchestrator/Task error format
697
596
  */
698
- function encodeBase64(str) {
699
- // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
700
- const encoder = new TextEncoder();
701
- const data = encoder.encode(str);
702
- // Convert Uint8Array to base64
703
- if (isBrowser) {
704
- // Browser environment
705
- // Convert Uint8Array to binary string then to base64
706
- const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
707
- return btoa(binaryString);
597
+ class OrchestratorErrorParser {
598
+ canParse(errorBody) {
599
+ return isOrchestratorError(errorBody);
708
600
  }
709
- else {
710
- // Node.js environment
711
- return Buffer.from(data).toString('base64');
601
+ parse(errorBody, response) {
602
+ const error = errorBody;
603
+ return {
604
+ message: error.message,
605
+ code: response?.status?.toString(),
606
+ details: {
607
+ errorCode: error.errorCode,
608
+ traceId: error.traceId,
609
+ originalResponse: error
610
+ },
611
+ requestId: error.traceId
612
+ };
712
613
  }
713
614
  }
714
615
  /**
715
- * Decodes a base64 string
716
- * @param base64 - The base64 string to decode
717
- * @returns Decoded string
616
+ * Parser for Entity (Data Fabric) error format
718
617
  */
719
- function decodeBase64(base64) {
720
- let bytes;
721
- if (isBrowser) {
722
- // Browser environment
723
- const binaryString = atob(base64);
724
- bytes = new Uint8Array(binaryString.length);
725
- for (let i = 0; i < binaryString.length; i++) {
726
- bytes[i] = binaryString.charCodeAt(i);
727
- }
618
+ class EntityErrorParser {
619
+ canParse(errorBody) {
620
+ return isEntityError(errorBody);
728
621
  }
729
- else {
730
- // Node.js environment
731
- bytes = new Uint8Array(Buffer.from(base64, 'base64'));
622
+ parse(errorBody, response) {
623
+ const error = errorBody;
624
+ return {
625
+ message: error.error,
626
+ code: response?.status?.toString(),
627
+ details: {
628
+ error: error.error,
629
+ traceId: error.traceId,
630
+ originalResponse: error
631
+ },
632
+ requestId: error.traceId
633
+ };
732
634
  }
733
- // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
734
- const decoder = new TextDecoder();
735
- return decoder.decode(bytes);
736
635
  }
737
-
738
636
  /**
739
- * PaginationManager handles the conversion between uniform cursor-based pagination
740
- * and the specific pagination type for each service
637
+ * Parser for PIMS error format
741
638
  */
742
- class PaginationManager {
743
- /**
744
- * Create a pagination cursor for subsequent page requests
745
- */
746
- static createCursor({ pageInfo, type }) {
747
- if (!pageInfo.hasMore) {
748
- return undefined;
639
+ class PimsErrorParser {
640
+ canParse(errorBody) {
641
+ return isPimsError(errorBody);
642
+ }
643
+ parse(errorBody, response) {
644
+ const error = errorBody;
645
+ let message = error.title;
646
+ // If there are validation errors, append them to the message for better visibility
647
+ if (error.errors && Object.keys(error.errors).length > 0) {
648
+ const errorMessages = Object.entries(error.errors)
649
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
650
+ .join('; ');
651
+ message += `. Validation errors: ${errorMessages}`;
749
652
  }
750
- const cursorData = {
751
- type,
752
- pageSize: pageInfo.pageSize,
653
+ return {
654
+ message,
655
+ code: response?.status?.toString(),
656
+ details: {
657
+ type: error.type,
658
+ title: error.title,
659
+ status: error.status,
660
+ errors: error.errors,
661
+ traceId: error.traceId,
662
+ originalResponse: error
663
+ },
664
+ requestId: error.traceId
753
665
  };
754
- switch (type) {
755
- case PaginationType.OFFSET:
756
- if (pageInfo.currentPage) {
757
- cursorData.pageNumber = pageInfo.currentPage + 1;
758
- }
759
- break;
760
- case PaginationType.TOKEN:
761
- if (pageInfo.continuationToken) {
762
- cursorData.continuationToken = pageInfo.continuationToken;
763
- }
764
- else {
765
- return undefined; // No continuation token, can't continue
766
- }
767
- break;
768
- }
666
+ }
667
+ }
668
+ /**
669
+ * Fallback parser for unrecognized formats
670
+ */
671
+ class GenericErrorParser {
672
+ canParse(_errorBody) {
673
+ return true; // Always can parse as last resort
674
+ }
675
+ parse(errorBody, response) {
676
+ // For unknown error formats, just pass through the raw error with fallback message
677
+ const message = response?.statusText || 'An error occurred';
769
678
  return {
770
- value: encodeBase64(JSON.stringify(cursorData))
679
+ message,
680
+ code: response?.status?.toString(),
681
+ details: {
682
+ originalResponse: errorBody
683
+ },
771
684
  };
772
685
  }
686
+ }
687
+ /**
688
+ * Main error response parser using Chain of Responsibility pattern
689
+ *
690
+ * This parser standardizes error responses from different UiPath services into a
691
+ * consistent format, regardless of the original error structure.
692
+ *
693
+ * Supported formats:
694
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
695
+ * 2. Entity (Data Fabric): { error, traceId }
696
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
697
+ * 4. Generic: Fallback for any other format
698
+ *
699
+ * @example
700
+ * const parser = new ErrorResponseParser();
701
+ * const errorInfo = await parser.parse(response);
702
+ * // errorInfo will have consistent structure regardless of service
703
+ */
704
+ class ErrorResponseParser {
705
+ constructor() {
706
+ this.strategies = [
707
+ new OrchestratorErrorParser(),
708
+ new EntityErrorParser(),
709
+ new PimsErrorParser(),
710
+ new GenericErrorParser() // Must be last
711
+ ];
712
+ }
773
713
  /**
774
- * Create a paginated response with navigation cursors
714
+ * Parses error response body into standardized format
715
+ * @param response - The HTTP response object
716
+ * @returns Standardized error information
775
717
  */
776
- static createPaginatedResponse({ pageInfo, type }, items) {
777
- const nextCursor = PaginationManager.createCursor({ pageInfo, type });
778
- // Create previous page cursor if applicable
779
- let previousCursor = undefined;
780
- if (pageInfo.currentPage && pageInfo.currentPage > 1) {
781
- const prevCursorData = {
782
- type,
783
- pageNumber: pageInfo.currentPage - 1,
784
- pageSize: pageInfo.pageSize,
785
- };
786
- previousCursor = {
787
- value: encodeBase64(JSON.stringify(prevCursorData))
788
- };
718
+ async parse(response) {
719
+ try {
720
+ const errorBody = await response.json();
721
+ // Find the first strategy that can parse this error format
722
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
723
+ // GenericErrorParser always returns true, so this will never be null
724
+ return strategy.parse(errorBody, response);
789
725
  }
790
- // Calculate total pages if we have totalCount and pageSize
791
- let totalPages = undefined;
792
- if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
793
- totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
726
+ catch {
727
+ // Handle non-JSON responses
728
+ const responseText = await response.text().catch(() => '');
729
+ return {
730
+ message: response.statusText,
731
+ code: response.status.toString(),
732
+ details: {
733
+ parseError: 'Failed to parse error response as JSON',
734
+ responseText
735
+ },
736
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
737
+ };
794
738
  }
795
- // Determine if this pagination type supports page jumping
796
- const supportsPageJump = type === PaginationType.OFFSET;
797
- // Create the result object with all fields, then filter out undefined values
798
- const result = filterUndefined({
799
- items,
800
- totalCount: pageInfo.totalCount,
801
- hasNextPage: pageInfo.hasMore,
802
- nextCursor: nextCursor,
803
- previousCursor: previousCursor,
804
- currentPage: pageInfo.currentPage,
805
- totalPages,
806
- supportsPageJump
807
- });
808
- return result;
809
739
  }
810
740
  }
741
+ // Export singleton instance
742
+ const errorResponseParser = new ErrorResponseParser();
811
743
 
812
744
  /**
813
- * Creates headers object from key-value pairs
814
- * @param headersObj - Object containing header key-value pairs
815
- * @returns Headers object with all values converted to strings
816
- *
817
- * @example
818
- * ```typescript
819
- * // Single header
820
- * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
821
- *
822
- * // Multiple headers
823
- * const headers = createHeaders({
824
- * 'X-UIPATH-FolderKey': '1234567890',
825
- * 'X-UIPATH-OrganizationUnitId': 123,
826
- * 'Accept': 'application/json'
827
- * });
828
- *
829
- * // Using constants
830
- * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
831
- * const headers = createHeaders({
832
- * [FOLDER_KEY]: 'abc-123',
833
- * [FOLDER_ID]: 456
834
- * });
835
- *
836
- * // Empty headers
837
- * const headers = createHeaders();
838
- * ```
745
+ * Base error class for all UiPath SDK errors
746
+ * Extends Error for standard error handling compatibility
839
747
  */
840
- function createHeaders(headersObj) {
841
- const headers = {};
842
- for (const [key, value] of Object.entries(headersObj)) {
843
- if (value !== undefined && value !== null) {
844
- headers[key] = value.toString();
748
+ class UiPathError extends Error {
749
+ constructor(type, params) {
750
+ super(params.message);
751
+ this.name = type;
752
+ this.type = type;
753
+ this.statusCode = params.statusCode;
754
+ this.requestId = params.requestId;
755
+ this.timestamp = new Date();
756
+ // Maintains proper stack trace for where our error was thrown
757
+ if (Error.captureStackTrace) {
758
+ Error.captureStackTrace(this, this.constructor);
845
759
  }
846
760
  }
847
- return headers;
761
+ /**
762
+ * Returns a clean JSON representation of the error
763
+ */
764
+ toJSON() {
765
+ return {
766
+ type: this.type,
767
+ message: this.message,
768
+ statusCode: this.statusCode,
769
+ requestId: this.requestId,
770
+ timestamp: this.timestamp
771
+ };
772
+ }
773
+ /**
774
+ * Returns detailed debug information including stack trace
775
+ */
776
+ getDebugInfo() {
777
+ return {
778
+ ...this.toJSON(),
779
+ stack: this.stack
780
+ };
781
+ }
848
782
  }
849
783
 
850
784
  /**
851
- * Common constants used across the SDK
785
+ * Error thrown when authentication fails (401 errors)
786
+ * Common scenarios:
787
+ * - Invalid credentials
788
+ * - Expired token
789
+ * - Missing authentication
852
790
  */
791
+ class AuthenticationError extends UiPathError {
792
+ constructor(params = {}) {
793
+ super(ErrorType.AUTHENTICATION, {
794
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
795
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
796
+ requestId: params.requestId
797
+ });
798
+ }
799
+ }
800
+
853
801
  /**
854
- * Prefix used for OData query parameters
802
+ * Error thrown when authorization fails (403 errors)
803
+ * Common scenarios:
804
+ * - Insufficient permissions
805
+ * - Access denied to resource
806
+ * - Invalid scope
855
807
  */
856
- const ODATA_PREFIX = '$';
857
- const UNKNOWN$1 = 'Unknown';
858
- const NO_INSTANCE = 'no-instance';
808
+ class AuthorizationError extends UiPathError {
809
+ constructor(params = {}) {
810
+ super(ErrorType.AUTHORIZATION, {
811
+ message: params.message || ErrorMessages.ACCESS_DENIED,
812
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
813
+ requestId: params.requestId
814
+ });
815
+ }
816
+ }
817
+
859
818
  /**
860
- * HTTP methods
819
+ * Error thrown when validation fails (400 errors or client-side validation)
820
+ * Common scenarios:
821
+ * - Invalid input parameters
822
+ * - Missing required fields
823
+ * - Invalid data format
861
824
  */
862
- const HTTP_METHODS = {
863
- GET: 'GET',
864
- POST: 'POST'};
825
+ class ValidationError extends UiPathError {
826
+ constructor(params = {}) {
827
+ super(ErrorType.VALIDATION, {
828
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
829
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
830
+ requestId: params.requestId
831
+ });
832
+ }
833
+ }
834
+
865
835
  /**
866
- * Process Instance pagination constants for token-based pagination
836
+ * Error thrown when a resource is not found (404 errors)
837
+ * Common scenarios:
838
+ * - Resource doesn't exist
839
+ * - Invalid ID provided
840
+ * - Resource deleted
867
841
  */
868
- const PROCESS_INSTANCE_PAGINATION = {
869
- /** Field name for items in process instance response */
870
- ITEMS_FIELD: 'instances',
871
- /** Field name for continuation token in process instance response */
872
- CONTINUATION_TOKEN_FIELD: 'nextPage'
873
- };
874
- /**
875
- * OData OFFSET pagination parameter names (ODATA-style)
876
- */
877
- const ODATA_OFFSET_PARAMS = {
878
- /** OData page size parameter name */
879
- PAGE_SIZE_PARAM: '$top',
880
- /** OData offset parameter name */
881
- OFFSET_PARAM: '$skip',
882
- /** OData count parameter name */
883
- COUNT_PARAM: '$count'
884
- };
885
- /**
886
- * Bucket TOKEN pagination parameter names
887
- */
888
- const BUCKET_TOKEN_PARAMS = {
889
- /** Bucket page size parameter name */
890
- PAGE_SIZE_PARAM: 'takeHint',
891
- /** Bucket token parameter name */
892
- TOKEN_PARAM: 'continuationToken'
893
- };
894
- /**
895
- * Process Instance TOKEN pagination parameter names
896
- */
897
- const PROCESS_INSTANCE_TOKEN_PARAMS = {
898
- /** Process instance page size parameter name */
899
- PAGE_SIZE_PARAM: 'pageSize',
900
- /** Process instance token parameter name */
901
- TOKEN_PARAM: 'nextPage'
902
- };
842
+ class NotFoundError extends UiPathError {
843
+ constructor(params = {}) {
844
+ super(ErrorType.NOT_FOUND, {
845
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
846
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
847
+ requestId: params.requestId
848
+ });
849
+ }
850
+ }
903
851
 
904
852
  /**
905
- * Transforms data by mapping fields according to the provided field mapping
906
- * @param data The source data to transform
907
- * @param fieldMapping Object mapping source field names to target field names
908
- * @returns Transformed data with mapped field names
909
- *
910
- * @example
911
- * ```typescript
912
- * // Single object transformation
913
- * const data = { id: '123', userName: 'john' };
914
- * const mapping = { id: 'userId', userName: 'name' };
915
- * const result = transformData(data, mapping);
916
- * // result = { userId: '123', name: 'john' }
917
- *
918
- * // Array transformation
919
- * const dataArray = [
920
- * { id: '123', userName: 'john' },
921
- * { id: '456', userName: 'jane' }
922
- * ];
923
- * const result = transformData(dataArray, mapping);
924
- * // result = [
925
- * // { userId: '123', name: 'john' },
926
- * // { userId: '456', name: 'jane' }
927
- * // ]
928
- * ```
853
+ * Error thrown when rate limit is exceeded (429 errors)
854
+ * Common scenarios:
855
+ * - Too many requests in a time window
856
+ * - API throttling
929
857
  */
930
- function transformData(data, fieldMapping) {
931
- // Handle array of objects
932
- if (Array.isArray(data)) {
933
- return data.map(item => transformData(item, fieldMapping));
934
- }
935
- // Handle single object
936
- const result = { ...data };
937
- for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
938
- if (sourceField in result) {
939
- const value = result[sourceField];
940
- delete result[sourceField];
941
- result[targetField] = value;
942
- }
858
+ class RateLimitError extends UiPathError {
859
+ constructor(params = {}) {
860
+ super(ErrorType.RATE_LIMIT, {
861
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
862
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
863
+ requestId: params.requestId
864
+ });
943
865
  }
944
- return result;
945
866
  }
867
+
946
868
  /**
947
- * Adds a prefix to specified keys in an object, returning a new object.
948
- * Only the provided keys are prefixed; all others are left unchanged.
949
- *
950
- * @param obj The source object
951
- * @param prefix The prefix to add (e.g., '$')
952
- * @param keys The keys to prefix (e.g., ['expand', 'filter'])
953
- * @returns A new object with specified keys prefixed
954
- *
955
- * @example
956
- * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
869
+ * Error thrown when server encounters an error (5xx errors)
870
+ * Common scenarios:
871
+ * - Internal server error
872
+ * - Service unavailable
873
+ * - Gateway timeout
957
874
  */
958
- function addPrefixToKeys(obj, prefix, keys) {
959
- const result = {};
960
- for (const [key, value] of Object.entries(obj)) {
961
- if (keys.includes(key)) {
962
- result[`${prefix}${key}`] = value;
963
- }
964
- else {
965
- result[key] = value;
966
- }
875
+ class ServerError extends UiPathError {
876
+ constructor(params = {}) {
877
+ super(ErrorType.SERVER, {
878
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
879
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
880
+ requestId: params.requestId
881
+ });
882
+ }
883
+ /**
884
+ * Checks if this is a temporary error that might succeed on retry
885
+ */
886
+ get isRetryable() {
887
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
888
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
889
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
967
890
  }
968
- return result;
969
891
  }
970
892
 
971
893
  /**
972
- * Constants used throughout the pagination system
973
- */
974
- /** Maximum number of items that can be requested in a single page */
975
- const MAX_PAGE_SIZE = 1000;
976
- /** Default page size when jumpToPage is used without specifying pageSize */
977
- const DEFAULT_PAGE_SIZE = 50;
978
- /** Default field name for items in a paginated response */
979
- const DEFAULT_ITEMS_FIELD = 'value';
980
- /** Default field name for total count in a paginated response */
981
- const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
982
- /**
983
- * Limits the page size to the maximum allowed value
984
- * @param pageSize - Requested page size
985
- * @returns Limited page size value
894
+ * Error thrown when network/connection issues occur
895
+ * Common scenarios:
896
+ * - Connection timeout
897
+ * - DNS resolution failure
898
+ * - Network unreachable
899
+ * - Request aborted
986
900
  */
987
- function getLimitedPageSize(pageSize) {
988
- if (pageSize === undefined || pageSize === null) {
989
- return DEFAULT_PAGE_SIZE;
901
+ class NetworkError extends UiPathError {
902
+ constructor(params = {}) {
903
+ super(ErrorType.NETWORK, {
904
+ message: params.message || ErrorMessages.NETWORK_ERROR,
905
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
906
+ requestId: params.requestId
907
+ });
990
908
  }
991
- return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
992
909
  }
993
910
 
994
911
  /**
995
- * Helper functions for pagination that can be used across services
912
+ * Factory for creating typed errors based on HTTP status codes
913
+ * Follows the Factory pattern for clean error instantiation
996
914
  */
997
- class PaginationHelpers {
998
- /**
999
- * Checks if any pagination parameters are provided
1000
- *
1001
- * @param options - The options object to check
1002
- * @returns True if any pagination parameter is defined, false otherwise
1003
- */
1004
- static hasPaginationParameters(options = {}) {
1005
- const { cursor, pageSize, jumpToPage } = options;
1006
- return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1007
- }
915
+ class ErrorFactory {
1008
916
  /**
1009
- * Parse a pagination cursor string into cursor data
917
+ * Creates appropriate error instance based on HTTP status code
1010
918
  */
1011
- static parseCursor(cursorString) {
1012
- try {
1013
- const cursorData = JSON.parse(decodeBase64(cursorString));
1014
- return cursorData;
1015
- }
1016
- catch {
1017
- throw new Error('Invalid pagination cursor');
919
+ static createFromHttpStatus(statusCode, errorInfo) {
920
+ const { message, requestId } = errorInfo;
921
+ // Map status codes to error types
922
+ switch (statusCode) {
923
+ case HttpStatus.BAD_REQUEST:
924
+ return new ValidationError({ message, statusCode, requestId });
925
+ case HttpStatus.UNAUTHORIZED:
926
+ return new AuthenticationError({ message, statusCode, requestId });
927
+ case HttpStatus.FORBIDDEN:
928
+ return new AuthorizationError({ message, statusCode, requestId });
929
+ case HttpStatus.NOT_FOUND:
930
+ return new NotFoundError({ message, statusCode, requestId });
931
+ case HttpStatus.TOO_MANY_REQUESTS:
932
+ return new RateLimitError({ message, statusCode, requestId });
933
+ default:
934
+ // For 5xx errors or any other status code
935
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
936
+ return new ServerError({ message, statusCode, requestId });
937
+ }
938
+ // For unknown client errors, treat as validation error
939
+ return new ValidationError({
940
+ message: `${message} (HTTP ${statusCode})`,
941
+ statusCode,
942
+ requestId
943
+ });
1018
944
  }
1019
945
  }
1020
946
  /**
1021
- * Validates cursor format and structure
1022
- *
1023
- * @param paginationOptions - The pagination options containing the cursor
1024
- * @param paginationType - Optional pagination type to validate against
947
+ * Creates a NetworkError from a fetch/network error
1025
948
  */
1026
- static validateCursor(paginationOptions, paginationType) {
1027
- if (paginationOptions.cursor !== undefined) {
1028
- if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1029
- throw new Error('cursor must contain a valid cursor string');
949
+ static createNetworkError(error) {
950
+ let message = ErrorMessages.NETWORK_ERROR;
951
+ if (error instanceof Error) {
952
+ if (error.name === ErrorNames.ABORT_ERROR) {
953
+ message = ErrorMessages.REQUEST_ABORTED;
1030
954
  }
1031
- try {
1032
- // Try to parse the cursor to validate it
1033
- const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1034
- // If type is provided, validate cursor contains expected type information
1035
- if (paginationType) {
1036
- if (!cursorData.type) {
1037
- throw new Error('Invalid cursor: missing pagination type');
1038
- }
1039
- // Check pagination type compatibility
1040
- if (cursorData.type !== paginationType) {
1041
- throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1042
- }
1043
- }
955
+ else if (error.message.includes('timeout')) {
956
+ message = ErrorMessages.REQUEST_TIMEOUT;
1044
957
  }
1045
- catch (error) {
1046
- if (error instanceof Error) {
1047
- // If it's already our error with specific message, pass it through
1048
- if (error.message.startsWith('Invalid cursor') ||
1049
- error.message.startsWith('Pagination type mismatch')) {
1050
- throw error;
1051
- }
1052
- }
1053
- throw new Error('Invalid pagination cursor format');
958
+ else {
959
+ message = error.message;
1054
960
  }
1055
961
  }
962
+ return new NetworkError({ message });
1056
963
  }
1057
- /**
1058
- * Comprehensive validation for pagination options
964
+ }
965
+
966
+ class ApiClient {
967
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
968
+ this.config = config;
969
+ this.executionContext = executionContext;
970
+ this.clientConfig = clientConfig;
971
+ this.tokenManager = tokenManager;
972
+ }
973
+ /**
974
+ * Gets a valid authentication token, refreshing if necessary.
975
+ * Used internally for API requests and exposed for services that need manual auth headers.
1059
976
  *
1060
- * @param options - The pagination options to validate
1061
- * @param paginationType - The pagination type these options will be used with
1062
- * @returns Processed pagination parameters ready for use
977
+ * @returns The valid token
978
+ * @throws AuthenticationError if no token available or refresh fails
1063
979
  */
1064
- static validatePaginationOptions(options, paginationType) {
1065
- // Validate pageSize
1066
- if (options.pageSize !== undefined && options.pageSize <= 0) {
1067
- throw new Error('pageSize must be a positive number');
980
+ async getValidToken() {
981
+ return this.tokenManager.getValidToken();
982
+ }
983
+ async getDefaultHeaders() {
984
+ const token = await this.getValidToken();
985
+ return {
986
+ 'Authorization': `Bearer ${token}`,
987
+ 'Content-Type': CONTENT_TYPES.JSON,
988
+ ...this.clientConfig.headers
989
+ };
990
+ }
991
+ async request(method, path, options = {}) {
992
+ // Ensure path starts with a forward slash
993
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
994
+ // Construct URL with org and tenant names
995
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
996
+ const isFormData = options.body instanceof FormData;
997
+ const defaultHeaders = await this.getDefaultHeaders();
998
+ if (isFormData) {
999
+ delete defaultHeaders['Content-Type'];
1068
1000
  }
1069
- // Validate jumpToPage
1070
- if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1071
- throw new Error('jumpToPage must be a positive number');
1001
+ const traceId = crypto.randomUUID().replace(/-/g, '');
1002
+ const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
1003
+ const traceparentValue = `00-${traceId}-${spanId}-01`;
1004
+ const headers = {
1005
+ ...defaultHeaders,
1006
+ [TRACEPARENT]: traceparentValue,
1007
+ [UIPATH_TRACEPARENT_ID]: traceparentValue,
1008
+ ...options.headers
1009
+ };
1010
+ // Convert params to URLSearchParams
1011
+ const searchParams = new URLSearchParams();
1012
+ if (options.params) {
1013
+ Object.entries(options.params).forEach(([key, value]) => {
1014
+ searchParams.append(key, value.toString());
1015
+ });
1072
1016
  }
1073
- // Validate cursor
1074
- PaginationHelpers.validateCursor(options, paginationType);
1075
- // Validate service compatibility
1076
- if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1077
- throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1017
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
1018
+ let body = undefined;
1019
+ if (options.body) {
1020
+ body = isFormData ? options.body : JSON.stringify(options.body);
1078
1021
  }
1079
- // Get processed parameters
1080
- return PaginationHelpers.getRequestParameters(options, paginationType);
1081
- }
1082
- /**
1083
- * Convert a unified pagination options to service-specific parameters
1084
- */
1085
- static getRequestParameters(options, paginationType) {
1086
- // Handle jumpToPage
1087
- if (options.jumpToPage !== undefined) {
1088
- const jumpToPageOptions = {
1089
- pageSize: options.pageSize,
1090
- pageNumber: options.jumpToPage
1091
- };
1092
- return filterUndefined(jumpToPageOptions);
1022
+ try {
1023
+ const response = await fetch(fullUrl, {
1024
+ method,
1025
+ headers,
1026
+ body,
1027
+ signal: options.signal
1028
+ });
1029
+ if (!response.ok) {
1030
+ const errorInfo = await errorResponseParser.parse(response);
1031
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
1032
+ }
1033
+ if (response.status === 204) {
1034
+ return undefined;
1035
+ }
1036
+ // Handle blob response type for binary data (e.g., file downloads)
1037
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
1038
+ const blob = await response.blob();
1039
+ return blob;
1040
+ }
1041
+ // Check if we're expecting XML
1042
+ const acceptHeader = headers['Accept'] || headers['accept'];
1043
+ if (acceptHeader === CONTENT_TYPES.XML) {
1044
+ const text = await response.text();
1045
+ return text;
1046
+ }
1047
+ const text = await response.text();
1048
+ if (!text) {
1049
+ return undefined;
1050
+ }
1051
+ return JSON.parse(text);
1093
1052
  }
1094
- // If no cursor is provided, it's a first page request
1095
- if (!options.cursor) {
1096
- const firstPageOptions = {
1097
- pageSize: options.pageSize,
1098
- // Only set pageNumber for OFFSET pagination
1099
- pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1100
- };
1101
- return filterUndefined(firstPageOptions);
1053
+ catch (error) {
1054
+ // If it's already one of our errors, re-throw it
1055
+ if (error.type && error.type.includes('Error')) {
1056
+ throw error;
1057
+ }
1058
+ // Otherwise, it's likely a network error
1059
+ throw ErrorFactory.createNetworkError(error);
1102
1060
  }
1103
- // Parse the cursor
1104
- try {
1105
- const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1106
- const cursorBasedOptions = {
1107
- pageSize: cursorData.pageSize || options.pageSize,
1108
- pageNumber: cursorData.pageNumber,
1109
- continuationToken: cursorData.continuationToken,
1110
- type: cursorData.type,
1111
- };
1112
- return filterUndefined(cursorBasedOptions);
1061
+ }
1062
+ async get(path, options = {}) {
1063
+ return this.request('GET', path, options);
1064
+ }
1065
+ async post(path, data, options = {}) {
1066
+ return this.request('POST', path, { ...options, body: data });
1067
+ }
1068
+ async put(path, data, options = {}) {
1069
+ return this.request('PUT', path, { ...options, body: data });
1070
+ }
1071
+ async patch(path, data, options = {}) {
1072
+ return this.request('PATCH', path, { ...options, body: data });
1073
+ }
1074
+ async delete(path, options = {}) {
1075
+ return this.request('DELETE', path, options);
1076
+ }
1077
+ }
1078
+
1079
+ /**
1080
+ * Pagination types supported by the SDK
1081
+ */
1082
+ var PaginationType;
1083
+ (function (PaginationType) {
1084
+ PaginationType["OFFSET"] = "offset";
1085
+ PaginationType["TOKEN"] = "token";
1086
+ })(PaginationType || (PaginationType = {}));
1087
+
1088
+ /**
1089
+ * Collection of utility functions for working with objects
1090
+ */
1091
+ /**
1092
+ * Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
1093
+ * and dot-separated nested paths (e.g., 'pagination.totalCount').
1094
+ * Direct key match takes priority over nested traversal.
1095
+ */
1096
+ function resolveNestedField(data, fieldPath) {
1097
+ if (!data) {
1098
+ return undefined;
1099
+ }
1100
+ if (fieldPath in data) {
1101
+ return data[fieldPath];
1102
+ }
1103
+ if (!fieldPath.includes('.')) {
1104
+ return undefined;
1105
+ }
1106
+ let value = data;
1107
+ for (const part of fieldPath.split('.')) {
1108
+ value = value?.[part];
1109
+ }
1110
+ return value;
1111
+ }
1112
+ /**
1113
+ * Filters out undefined values from an object
1114
+ * @param obj The source object
1115
+ * @returns A new object without undefined values
1116
+ *
1117
+ * @example
1118
+ * ```typescript
1119
+ * // Object with undefined values
1120
+ * const options = {
1121
+ * name: 'test',
1122
+ * count: 5,
1123
+ * prefix: undefined,
1124
+ * suffix: null
1125
+ * };
1126
+ * const result = filterUndefined(options);
1127
+ * // result = { name: 'test', count: 5, suffix: null }
1128
+ * ```
1129
+ */
1130
+ function filterUndefined(obj) {
1131
+ const result = {};
1132
+ for (const [key, value] of Object.entries(obj)) {
1133
+ if (value !== undefined) {
1134
+ result[key] = value;
1113
1135
  }
1114
- catch {
1115
- throw new Error('Invalid pagination cursor');
1136
+ }
1137
+ return result;
1138
+ }
1139
+
1140
+ /**
1141
+ * Utility functions for platform detection
1142
+ */
1143
+ /**
1144
+ * Checks if code is running in a browser environment
1145
+ */
1146
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
1147
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
1148
+
1149
+ /**
1150
+ * Base64 encoding/decoding
1151
+ */
1152
+ /**
1153
+ * Encodes a string to base64
1154
+ * @param str - The string to encode
1155
+ * @returns Base64 encoded string
1156
+ */
1157
+ function encodeBase64(str) {
1158
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
1159
+ const encoder = new TextEncoder();
1160
+ const data = encoder.encode(str);
1161
+ // Convert Uint8Array to base64
1162
+ if (isBrowser) {
1163
+ // Browser environment
1164
+ // Convert Uint8Array to binary string then to base64
1165
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
1166
+ return btoa(binaryString);
1167
+ }
1168
+ else {
1169
+ // Node.js environment
1170
+ return Buffer.from(data).toString('base64');
1171
+ }
1172
+ }
1173
+ /**
1174
+ * Decodes a base64 string
1175
+ * @param base64 - The base64 string to decode
1176
+ * @returns Decoded string
1177
+ */
1178
+ function decodeBase64(base64) {
1179
+ let bytes;
1180
+ if (isBrowser) {
1181
+ // Browser environment
1182
+ const binaryString = atob(base64);
1183
+ bytes = new Uint8Array(binaryString.length);
1184
+ for (let i = 0; i < binaryString.length; i++) {
1185
+ bytes[i] = binaryString.charCodeAt(i);
1116
1186
  }
1117
1187
  }
1118
- /**
1119
- * Helper method for paginated resource retrieval
1120
- *
1121
- * @param params - Parameters for pagination
1122
- * @returns Promise resolving to a paginated result
1123
- */
1124
- static async getAllPaginated(params) {
1125
- const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1126
- const endpoint = getEndpoint(folderId);
1127
- const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1128
- const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1129
- headers,
1130
- params: additionalParams,
1131
- pagination: {
1132
- paginationType: options.paginationType || PaginationType.OFFSET,
1133
- itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1134
- totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1135
- continuationTokenField: options.continuationTokenField,
1136
- paginationParams: options.paginationParams
1137
- }
1138
- });
1139
- // Parse items - automatically handle JSON string responses
1140
- const rawItems = paginatedResponse.items;
1141
- const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1142
- const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1143
- return {
1144
- ...paginatedResponse,
1145
- items: transformedItems
1146
- };
1188
+ else {
1189
+ // Node.js environment
1190
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
1147
1191
  }
1192
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
1193
+ const decoder = new TextDecoder();
1194
+ return decoder.decode(bytes);
1195
+ }
1196
+
1197
+ /**
1198
+ * PaginationManager handles the conversion between uniform cursor-based pagination
1199
+ * and the specific pagination type for each service
1200
+ */
1201
+ class PaginationManager {
1148
1202
  /**
1149
- * Helper method for non-paginated resource retrieval
1150
- *
1151
- * @param params - Parameters for non-paginated resource retrieval
1152
- * @returns Promise resolving to an object with data and totalCount
1203
+ * Create a pagination cursor for subsequent page requests
1153
1204
  */
1154
- static async getAllNonPaginated(params) {
1155
- const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1156
- // Set default field names
1157
- const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1158
- const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1159
- // Determine endpoint and headers based on folderId
1160
- const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1161
- const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1162
- // Make the API call based on method
1163
- let response;
1164
- if (method === HTTP_METHODS.POST) {
1165
- response = await serviceAccess.post(endpoint, additionalParams, { headers });
1205
+ static createCursor({ pageInfo, type }) {
1206
+ if (!pageInfo.hasMore) {
1207
+ return undefined;
1166
1208
  }
1167
- else {
1168
- response = await serviceAccess.get(endpoint, {
1169
- params: additionalParams,
1170
- headers
1171
- });
1209
+ const cursorData = {
1210
+ type,
1211
+ pageSize: pageInfo.pageSize,
1212
+ };
1213
+ switch (type) {
1214
+ case PaginationType.OFFSET:
1215
+ if (pageInfo.currentPage) {
1216
+ cursorData.pageNumber = pageInfo.currentPage + 1;
1217
+ }
1218
+ break;
1219
+ case PaginationType.TOKEN:
1220
+ if (pageInfo.continuationToken) {
1221
+ cursorData.continuationToken = pageInfo.continuationToken;
1222
+ }
1223
+ else {
1224
+ return undefined; // No continuation token, can't continue
1225
+ }
1226
+ break;
1172
1227
  }
1173
- // Extract and transform items from response
1174
- // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1175
- const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
1176
- const totalCount = Array.isArray(response.data) ? undefined : response.data?.[totalCountField];
1177
- // Parse items - automatically handle JSON string responses
1178
- const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1179
- const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1180
1228
  return {
1181
- items,
1182
- totalCount
1229
+ value: encodeBase64(JSON.stringify(cursorData))
1183
1230
  };
1184
1231
  }
1185
1232
  /**
1186
- * Centralized getAll implementation that handles both paginated and non-paginated requests
1187
- *
1188
- * @param config - Configuration for the getAll operation
1189
- * @param options - Request options including pagination parameters
1190
- * @returns Promise resolving to either paginated or non-paginated response based on options
1233
+ * Create a paginated response with navigation cursors
1191
1234
  */
1192
- static async getAll(config, options) {
1193
- const optionsWithDefaults = options || {};
1194
- const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1195
- // Determine if pagination is requested
1196
- const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1197
- // Process parameters (custom processing if provided, otherwise default)
1198
- let processedOptions = restOptions;
1199
- if (config.processParametersFn) {
1200
- processedOptions = config.processParametersFn(restOptions, folderId);
1235
+ static createPaginatedResponse({ pageInfo, type }, items) {
1236
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
1237
+ // Create previous page cursor if applicable
1238
+ let previousCursor = undefined;
1239
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
1240
+ const prevCursorData = {
1241
+ type,
1242
+ pageNumber: pageInfo.currentPage - 1,
1243
+ pageSize: pageInfo.pageSize,
1244
+ };
1245
+ previousCursor = {
1246
+ value: encodeBase64(JSON.stringify(prevCursorData))
1247
+ };
1201
1248
  }
1202
- // Apply ODATA prefix to keys (excluding specified keys)
1203
- const excludeKeys = config.excludeFromPrefix || [];
1204
- const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1205
- const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1206
- // Default pagination options
1207
- const paginationOptions = {
1208
- paginationType: PaginationType.OFFSET,
1209
- itemsField: DEFAULT_ITEMS_FIELD,
1210
- totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1211
- ...config.pagination
1212
- };
1213
- // Paginated flow
1214
- if (isPaginationRequested) {
1215
- return PaginationHelpers.getAllPaginated({
1216
- serviceAccess: config.serviceAccess,
1217
- getEndpoint: config.getEndpoint,
1218
- folderId,
1219
- paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1220
- additionalParams: prefixedOptions,
1221
- transformFn: config.transformFn,
1222
- method: config.method,
1223
- options: {
1224
- ...paginationOptions,
1225
- paginationParams: config.pagination?.paginationParams
1226
- }
1227
- }); // Type assertion needed due to conditional return
1249
+ // Calculate total pages if we have totalCount and pageSize
1250
+ let totalPages = undefined;
1251
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
1252
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
1228
1253
  }
1229
- // Non-paginated flow
1230
- const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1231
- return PaginationHelpers.getAllNonPaginated({
1232
- serviceAccess: config.serviceAccess,
1233
- getAllEndpoint: config.getEndpoint(),
1234
- getByFolderEndpoint: byFolderEndpoint,
1235
- folderId,
1236
- additionalParams: prefixedOptions,
1237
- transformFn: config.transformFn,
1238
- method: config.method,
1239
- options: {
1240
- itemsField: paginationOptions.itemsField,
1241
- totalCountField: paginationOptions.totalCountField
1242
- }
1254
+ // Determine if this pagination type supports page jumping
1255
+ const supportsPageJump = type === PaginationType.OFFSET;
1256
+ // Create the result object with all fields, then filter out undefined values
1257
+ const result = filterUndefined({
1258
+ items,
1259
+ totalCount: pageInfo.totalCount,
1260
+ hasNextPage: pageInfo.hasMore,
1261
+ nextCursor: nextCursor,
1262
+ previousCursor: previousCursor,
1263
+ currentPage: pageInfo.currentPage,
1264
+ totalPages,
1265
+ supportsPageJump
1243
1266
  });
1267
+ return result;
1244
1268
  }
1245
1269
  }
1246
1270
 
1247
1271
  /**
1248
- * SDK Internals Registry - Internal registry for SDK instances
1249
- *
1250
- * This class is NOT exported in the public API.
1251
- * It provides a secure way to share SDK internals between
1252
- * the UiPath class and service classes without exposing them publicly.
1253
- *
1254
- * @internal
1272
+ * Constants used throughout the pagination system
1255
1273
  */
1256
- // Global symbol key to ensure WeakMap is shared across module instances
1257
- // This prevents issues when core and service modules are bundled separately
1258
- const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1259
- // Get or create the global WeakMap store
1260
- const getGlobalStore = () => {
1261
- const globalObj = globalThis;
1262
- if (!globalObj[REGISTRY_KEY]) {
1263
- globalObj[REGISTRY_KEY] = new WeakMap();
1274
+ /** Maximum number of items that can be requested in a single page */
1275
+ const MAX_PAGE_SIZE = 1000;
1276
+ /** Default page size when jumpToPage is used without specifying pageSize */
1277
+ const DEFAULT_PAGE_SIZE = 50;
1278
+ /** Default field name for items in a paginated response */
1279
+ const DEFAULT_ITEMS_FIELD = 'value';
1280
+ /** Default field name for total count in a paginated response */
1281
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1282
+ /**
1283
+ * Limits the page size to the maximum allowed value
1284
+ * @param pageSize - Requested page size
1285
+ * @returns Limited page size value
1286
+ */
1287
+ function getLimitedPageSize(pageSize) {
1288
+ if (pageSize === undefined || pageSize === null) {
1289
+ return DEFAULT_PAGE_SIZE;
1264
1290
  }
1265
- return globalObj[REGISTRY_KEY];
1266
- };
1291
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1292
+ }
1293
+
1267
1294
  /**
1268
- * Internal registry for SDK private components.
1269
- * Uses WeakMap to prevent memory leaks - entries are automatically
1270
- * garbage collected when the SDK instance is no longer referenced.
1271
- *
1272
- * Uses a global singleton pattern to ensure the same WeakMap is shared
1273
- * across separately bundled modules (core, entities, tasks, etc.).
1274
- *
1275
- * @internal - Not exported in public API
1295
+ * Helper functions for pagination that can be used across services
1276
1296
  */
1277
- class SDKInternalsRegistry {
1278
- // Use global store to ensure sharing across module bundles
1279
- static get store() {
1280
- return getGlobalStore();
1281
- }
1297
+ class PaginationHelpers {
1282
1298
  /**
1283
- * Register SDK instance internals
1284
- * Called by UiPath constructor
1299
+ * Checks if any pagination parameters are provided
1300
+ *
1301
+ * @param options - The options object to check
1302
+ * @returns True if any pagination parameter is defined, false otherwise
1285
1303
  */
1286
- static set(instance, internals) {
1287
- this.store.set(instance, internals);
1304
+ static hasPaginationParameters(options = {}) {
1305
+ const { cursor, pageSize, jumpToPage } = options;
1306
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1288
1307
  }
1289
1308
  /**
1290
- * Retrieve SDK instance internals
1291
- * Called by BaseService constructor
1309
+ * Parse a pagination cursor string into cursor data
1292
1310
  */
1293
- static get(instance) {
1294
- const internals = this.store.get(instance);
1295
- if (!internals) {
1296
- throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1311
+ static parseCursor(cursorString) {
1312
+ try {
1313
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1314
+ return cursorData;
1315
+ }
1316
+ catch {
1317
+ throw new Error('Invalid pagination cursor');
1297
1318
  }
1298
- return internals;
1299
1319
  }
1300
- }
1301
-
1302
- var _BaseService_apiClient;
1303
- /**
1304
- * Base class for all UiPath SDK services.
1305
- *
1306
- * Provides common functionality for authentication, configuration, and API communication.
1307
- * All service classes extend this base to inherit dependency injection and HTTP client access.
1308
- *
1309
- * This class implements the dependency injection pattern where services receive a configured
1310
- * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1311
- * including authentication token management.
1312
- *
1313
- * @remarks
1314
- * Service classes should extend this base and call `super(uiPath)` in their constructor.
1315
- * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1316
- *
1317
- */
1318
- class BaseService {
1319
1320
  /**
1320
- * Creates a base service instance with dependency injection.
1321
- *
1322
- * Extracts configuration, execution context, and token manager from the UiPath instance
1323
- * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1324
- * and token management internally.
1325
- *
1326
- * @param instance - UiPath SDK instance providing authentication and configuration.
1327
- * Services receive this via dependency injection in the modular pattern.
1328
- * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1329
- * CAS external-app auth)
1330
- *
1331
- * @example
1332
- * ```typescript
1333
- * // Services automatically call this via super()
1334
- * export class EntityService extends BaseService {
1335
- * constructor(instance: IUiPath) {
1336
- * super(instance); // Initializes the internal ApiClient
1337
- * }
1338
- * }
1339
- *
1340
- * // Usage in modular pattern
1341
- * import { UiPath } from '@uipath/uipath-typescript/core';
1342
- * import { Entities } from '@uipath/uipath-typescript/entities';
1321
+ * Validates cursor format and structure
1343
1322
  *
1344
- * const sdk = new UiPath(config);
1345
- * await sdk.initialize();
1346
- * const entities = new Entities(sdk);
1347
- * ```
1323
+ * @param paginationOptions - The pagination options containing the cursor
1324
+ * @param paginationType - Optional pagination type to validate against
1348
1325
  */
1349
- constructor(instance, headers) {
1350
- // Private field - not visible via Object.keys() or any reflection
1351
- _BaseService_apiClient.set(this, void 0);
1352
- const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1353
- __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1354
- this.config = { folderKey };
1326
+ static validateCursor(paginationOptions, paginationType) {
1327
+ if (paginationOptions.cursor !== undefined) {
1328
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1329
+ throw new Error('cursor must contain a valid cursor string');
1330
+ }
1331
+ try {
1332
+ // Try to parse the cursor to validate it
1333
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1334
+ // If type is provided, validate cursor contains expected type information
1335
+ if (paginationType) {
1336
+ if (!cursorData.type) {
1337
+ throw new Error('Invalid cursor: missing pagination type');
1338
+ }
1339
+ // Check pagination type compatibility
1340
+ if (cursorData.type !== paginationType) {
1341
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1342
+ }
1343
+ }
1344
+ }
1345
+ catch (error) {
1346
+ if (error instanceof Error) {
1347
+ // If it's already our error with specific message, pass it through
1348
+ if (error.message.startsWith('Invalid cursor') ||
1349
+ error.message.startsWith('Pagination type mismatch')) {
1350
+ throw error;
1351
+ }
1352
+ }
1353
+ throw new Error('Invalid pagination cursor format');
1354
+ }
1355
+ }
1355
1356
  }
1356
1357
  /**
1357
- * Gets a valid authentication token, refreshing if necessary.
1358
- * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1358
+ * Comprehensive validation for pagination options
1359
1359
  *
1360
- * @returns Promise resolving to a valid access token string
1361
- * @throws AuthenticationError if no token is available or refresh fails
1362
- */
1363
- async getValidAuthToken() {
1364
- return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1365
- }
1366
- /**
1367
- * Creates a service accessor for pagination helpers
1368
- * This allows pagination helpers to access protected methods without making them public
1360
+ * @param options - The pagination options to validate
1361
+ * @param paginationType - The pagination type these options will be used with
1362
+ * @returns Processed pagination parameters ready for use
1369
1363
  */
1370
- createPaginationServiceAccess() {
1371
- return {
1372
- get: (path, options) => this.get(path, options || {}),
1373
- post: (path, body, options) => this.post(path, body, options || {}),
1374
- requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1375
- };
1376
- }
1377
- async request(method, path, options = {}) {
1378
- switch (method.toUpperCase()) {
1379
- case 'GET':
1380
- return this.get(path, options);
1381
- case 'POST':
1382
- return this.post(path, options.body, options);
1383
- case 'PUT':
1384
- return this.put(path, options.body, options);
1385
- case 'PATCH':
1386
- return this.patch(path, options.body, options);
1387
- case 'DELETE':
1388
- return this.delete(path, options);
1389
- default:
1390
- throw new Error(`Unsupported HTTP method: ${method}`);
1364
+ static validatePaginationOptions(options, paginationType) {
1365
+ // Validate pageSize
1366
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1367
+ throw new Error('pageSize must be a positive number');
1391
1368
  }
1392
- }
1393
- async requestWithSpec(spec) {
1394
- if (!spec.method || !spec.url) {
1395
- throw new Error('Request spec must include method and url');
1369
+ // Validate jumpToPage
1370
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1371
+ throw new Error('jumpToPage must be a positive number');
1396
1372
  }
1397
- return this.request(spec.method, spec.url, spec);
1398
- }
1399
- async get(path, options = {}) {
1400
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1401
- return { data: response };
1402
- }
1403
- async post(path, data, options = {}) {
1404
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1405
- return { data: response };
1406
- }
1407
- async put(path, data, options = {}) {
1408
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1409
- return { data: response };
1410
- }
1411
- async patch(path, data, options = {}) {
1412
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1413
- return { data: response };
1414
- }
1415
- async delete(path, options = {}) {
1416
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1417
- return { data: response };
1373
+ // Validate cursor
1374
+ PaginationHelpers.validateCursor(options, paginationType);
1375
+ // Validate service compatibility
1376
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1377
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1378
+ }
1379
+ // Get processed parameters
1380
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1418
1381
  }
1419
1382
  /**
1420
- * Execute a request with cursor-based pagination
1383
+ * Convert a unified pagination options to service-specific parameters
1421
1384
  */
1422
- async requestWithPagination(method, path, paginationOptions, options) {
1423
- const paginationType = options.pagination.paginationType;
1424
- // Validate and prepare pagination parameters
1425
- const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1426
- // Prepare request parameters based on pagination type
1427
- const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1428
- // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1429
- if (method.toUpperCase() === 'POST') {
1430
- const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1431
- options.body = {
1432
- ...existingBody,
1433
- ...options.params,
1434
- ...requestParams
1385
+ static getRequestParameters(options, paginationType) {
1386
+ // Handle jumpToPage
1387
+ if (options.jumpToPage !== undefined) {
1388
+ const jumpToPageOptions = {
1389
+ pageSize: options.pageSize,
1390
+ pageNumber: options.jumpToPage
1435
1391
  };
1436
- options.params = undefined;
1392
+ return filterUndefined(jumpToPageOptions);
1437
1393
  }
1438
- else {
1439
- // Merge pagination parameters with existing parameters
1440
- options.params = {
1441
- ...options.params,
1442
- ...requestParams
1394
+ // If no cursor is provided, it's a first page request
1395
+ if (!options.cursor) {
1396
+ const firstPageOptions = {
1397
+ pageSize: options.pageSize,
1398
+ // Only set pageNumber for OFFSET pagination
1399
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1400
+ };
1401
+ return filterUndefined(firstPageOptions);
1402
+ }
1403
+ // Parse the cursor
1404
+ try {
1405
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1406
+ const cursorBasedOptions = {
1407
+ pageSize: cursorData.pageSize || options.pageSize,
1408
+ pageNumber: cursorData.pageNumber,
1409
+ continuationToken: cursorData.continuationToken,
1410
+ type: cursorData.type,
1443
1411
  };
1412
+ return filterUndefined(cursorBasedOptions);
1413
+ }
1414
+ catch {
1415
+ throw new Error('Invalid pagination cursor');
1444
1416
  }
1445
- // Make the request
1446
- const response = await this.request(method, path, options);
1447
- // Extract data from the response and create page result
1448
- return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1449
- itemsField: options.pagination.itemsField,
1450
- totalCountField: options.pagination.totalCountField,
1451
- continuationTokenField: options.pagination.continuationTokenField
1452
- });
1453
1417
  }
1454
1418
  /**
1455
- * Validates and prepares pagination parameters from options
1419
+ * Helper method for paginated resource retrieval
1420
+ *
1421
+ * @param params - Parameters for pagination
1422
+ * @returns Promise resolving to a paginated result
1456
1423
  */
1457
- validateAndPreparePaginationParams(paginationType, paginationOptions) {
1458
- return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1424
+ static async getAllPaginated(params) {
1425
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1426
+ const endpoint = getEndpoint(folderId);
1427
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1428
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1429
+ headers,
1430
+ params: additionalParams,
1431
+ pagination: {
1432
+ paginationType: options.paginationType || PaginationType.OFFSET,
1433
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1434
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1435
+ continuationTokenField: options.continuationTokenField,
1436
+ paginationParams: options.paginationParams
1437
+ }
1438
+ });
1439
+ // Parse items - automatically handle JSON string responses
1440
+ const rawItems = paginatedResponse.items;
1441
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1442
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1443
+ return {
1444
+ ...paginatedResponse,
1445
+ items: transformedItems
1446
+ };
1459
1447
  }
1460
1448
  /**
1461
- * Prepares request parameters for pagination based on pagination type
1449
+ * Helper method for non-paginated resource retrieval
1450
+ *
1451
+ * @param params - Parameters for non-paginated resource retrieval
1452
+ * @returns Promise resolving to an object with data and totalCount
1462
1453
  */
1463
- preparePaginationRequestParams(paginationType, params, paginationConfig) {
1464
- const requestParams = {};
1465
- let limitedPageSize;
1466
- const paginationParams = paginationConfig?.paginationParams;
1467
- switch (paginationType) {
1468
- case PaginationType.OFFSET:
1469
- limitedPageSize = getLimitedPageSize(params.pageSize);
1470
- const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1471
- const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1472
- const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1473
- requestParams[pageSizeParam] = limitedPageSize;
1474
- if (params.pageNumber && params.pageNumber > 1) {
1475
- requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1476
- }
1477
- {
1478
- requestParams[countParam] = true;
1479
- }
1480
- break;
1481
- case PaginationType.TOKEN:
1482
- const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1483
- const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1484
- if (params.pageSize) {
1485
- requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1486
- }
1487
- if (params.continuationToken) {
1488
- requestParams[tokenParam] = params.continuationToken;
1489
- }
1490
- break;
1454
+ static async getAllNonPaginated(params) {
1455
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1456
+ // Set default field names
1457
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1458
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1459
+ // Determine endpoint and headers based on folderId
1460
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1461
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1462
+ // Make the API call based on method
1463
+ let response;
1464
+ if (method === HTTP_METHODS.POST) {
1465
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1491
1466
  }
1492
- return requestParams;
1493
- }
1494
- /**
1495
- * Creates a paginated response from API response
1496
- */
1497
- createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1498
- // Extract fields from response
1499
- const itemsField = fields.itemsField ||
1500
- (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1501
- const totalCountField = fields.totalCountField || 'totalRecordCount';
1502
- const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1503
- // Extract items and metadata
1467
+ else {
1468
+ response = await serviceAccess.get(endpoint, {
1469
+ params: additionalParams,
1470
+ headers
1471
+ });
1472
+ }
1473
+ // Extract and transform items from response
1504
1474
  // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1505
- const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
1506
- const totalCount = Array.isArray(response.data) ? undefined : response.data[totalCountField];
1507
- const continuationToken = response.data[continuationTokenField];
1508
- // Determine if there are more pages
1509
- const hasMore = this.determineHasMorePages(paginationType, {
1510
- totalCount,
1511
- pageSize: params.pageSize,
1512
- currentPage: params.pageNumber || 1,
1513
- itemsCount: items.length,
1514
- continuationToken
1515
- });
1516
- // Create and return the page result
1517
- return PaginationManager.createPaginatedResponse({
1518
- pageInfo: {
1519
- hasMore,
1520
- totalCount,
1521
- currentPage: params.pageNumber,
1522
- pageSize: params.pageSize,
1523
- continuationToken
1524
- },
1525
- type: paginationType,
1526
- }, items);
1475
+ const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
1476
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1477
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1478
+ // Parse items - automatically handle JSON string responses
1479
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1480
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1481
+ return {
1482
+ items,
1483
+ totalCount
1484
+ };
1527
1485
  }
1528
1486
  /**
1529
- * Determines if there are more pages based on pagination type and metadata
1487
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1488
+ *
1489
+ * @param config - Configuration for the getAll operation
1490
+ * @param options - Request options including pagination parameters
1491
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1530
1492
  */
1531
- determineHasMorePages(paginationType, info) {
1532
- switch (paginationType) {
1533
- case PaginationType.OFFSET:
1534
- const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1535
- // If totalCount is available, use it for precise calculation
1536
- if (info.totalCount !== undefined) {
1537
- return (info.currentPage * effectivePageSize) < info.totalCount;
1538
- }
1539
- // Fallback when totalCount is not available
1540
- // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1541
- return info.itemsCount === effectivePageSize;
1542
- case PaginationType.TOKEN:
1543
- return !!info.continuationToken;
1544
- default:
1545
- return false;
1493
+ static async getAll(config, options) {
1494
+ const optionsWithDefaults = options || {};
1495
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1496
+ // Determine if pagination is requested
1497
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1498
+ // Process parameters (custom processing if provided, otherwise default)
1499
+ let processedOptions = restOptions;
1500
+ if (config.processParametersFn) {
1501
+ processedOptions = config.processParametersFn(restOptions, folderId);
1546
1502
  }
1547
- }
1548
- }
1549
- _BaseService_apiClient = new WeakMap();
1550
-
1551
- /**
1552
- * Base path constants for different services
1553
- */
1554
- const PIMS_BASE = 'pims_';
1555
-
1556
- /**
1557
- * Maestro Service Endpoints
1558
- */
1559
- /**
1560
- * Maestro Process Service Endpoints
1561
- */
1562
- const MAESTRO_ENDPOINTS = {
1563
- PROCESSES: {
1564
- GET_ALL: `${PIMS_BASE}/api/v1/processes/summary`},
1565
- INSTANCES: {
1566
- GET_ALL: `${PIMS_BASE}/api/v1/instances`,
1567
- GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
1568
- GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
1569
- GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
1570
- GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
1571
- CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
1572
- PAUSE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/pause`,
1573
- RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
1574
- },
1575
- INCIDENTS: {
1576
- GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
1577
- GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
1578
- GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
1579
- }};
1580
-
1581
- /**
1582
- * Maestro Process Models
1583
- * Model classes for Maestro processes
1584
- */
1585
- /**
1586
- * Creates methods for a process object
1587
- *
1588
- * @param processData - The process data (response from API)
1589
- * @param service - The process service instance
1590
- * @returns Object containing process methods
1591
- */
1592
- function createProcessMethods(processData, service) {
1593
- return {
1594
- async getIncidents() {
1595
- if (!processData.processKey)
1596
- throw new Error('Process key is undefined');
1597
- if (!processData.folderKey)
1598
- throw new Error('Folder key is undefined');
1599
- return service.getIncidents(processData.processKey, processData.folderKey);
1503
+ // Apply ODATA prefix to keys (excluding specified keys)
1504
+ const excludeKeys = config.excludeFromPrefix || [];
1505
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1506
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1507
+ // Default pagination options
1508
+ const paginationOptions = {
1509
+ paginationType: PaginationType.OFFSET,
1510
+ itemsField: DEFAULT_ITEMS_FIELD,
1511
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1512
+ ...config.pagination
1513
+ };
1514
+ // Paginated flow
1515
+ if (isPaginationRequested) {
1516
+ return PaginationHelpers.getAllPaginated({
1517
+ serviceAccess: config.serviceAccess,
1518
+ getEndpoint: config.getEndpoint,
1519
+ folderId,
1520
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1521
+ additionalParams: prefixedOptions,
1522
+ transformFn: config.transformFn,
1523
+ method: config.method,
1524
+ options: {
1525
+ ...paginationOptions,
1526
+ paginationParams: config.pagination?.paginationParams
1527
+ }
1528
+ }); // Type assertion needed due to conditional return
1600
1529
  }
1601
- };
1602
- }
1603
- /**
1604
- * Creates an actionable process by combining API process data with operational methods.
1605
- *
1606
- * @param processData - The process data from API
1607
- * @param service - The process service instance
1608
- * @returns A process object with added methods
1609
- */
1610
- function createProcessWithMethods(processData, service) {
1611
- const methods = createProcessMethods(processData, service);
1612
- return Object.assign({}, processData, methods);
1530
+ // Non-paginated flow
1531
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1532
+ return PaginationHelpers.getAllNonPaginated({
1533
+ serviceAccess: config.serviceAccess,
1534
+ getAllEndpoint: config.getEndpoint(),
1535
+ getByFolderEndpoint: byFolderEndpoint,
1536
+ folderId,
1537
+ additionalParams: prefixedOptions,
1538
+ transformFn: config.transformFn,
1539
+ method: config.method,
1540
+ options: {
1541
+ itemsField: paginationOptions.itemsField,
1542
+ totalCountField: paginationOptions.totalCountField
1543
+ }
1544
+ });
1545
+ }
1613
1546
  }
1614
1547
 
1615
1548
  /**
1616
- * Maps fields for Incident entities
1549
+ * SDK Internals Registry - Internal registry for SDK instances
1550
+ *
1551
+ * This class is NOT exported in the public API.
1552
+ * It provides a secure way to share SDK internals between
1553
+ * the UiPath class and service classes without exposing them publicly.
1554
+ *
1555
+ * @internal
1617
1556
  */
1618
- const ProcessIncidentMap = {
1619
- errorTimeUtc: 'errorTime'
1557
+ // Global symbol key to ensure WeakMap is shared across module instances
1558
+ // This prevents issues when core and service modules are bundled separately
1559
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1560
+ // Get or create the global WeakMap store
1561
+ const getGlobalStore = () => {
1562
+ const globalObj = globalThis;
1563
+ if (!globalObj[REGISTRY_KEY]) {
1564
+ globalObj[REGISTRY_KEY] = new WeakMap();
1565
+ }
1566
+ return globalObj[REGISTRY_KEY];
1620
1567
  };
1621
1568
  /**
1622
- * Maps fields for Incident Summary entities
1569
+ * Internal registry for SDK private components.
1570
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1571
+ * garbage collected when the SDK instance is no longer referenced.
1572
+ *
1573
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1574
+ * across separately bundled modules (core, entities, tasks, etc.).
1575
+ *
1576
+ * @internal - Not exported in public API
1623
1577
  */
1624
- const ProcessIncidentSummaryMap = {
1625
- firstTimeUtc: 'firstOccuranceTime'
1626
- };
1627
-
1628
- /**
1629
- * Helpers for fetching BPMN XML and extracting element details used to annotate responses
1630
- */
1631
- class BpmnHelpers {
1632
- /**
1633
- * Parse BPMN XML and extract element id → {name,type} used for incidents
1634
- */
1635
- static parseBpmnElementsForIncidents(bpmnXml) {
1636
- const elementInfo = {};
1637
- try {
1638
- // Find <bpmn:...> start tags and capture the element type.
1639
- // Then read 'id' and 'name' attributes from each tag.
1640
- const bpmnOpenTagRegex = /<bpmn:([A-Za-z][\w.-]*)\b[^>]*>/g;
1641
- for (const tagMatch of bpmnXml.matchAll(bpmnOpenTagRegex)) {
1642
- const [fullTag, elementType] = tagMatch;
1643
- // Extract attributes from the current tag text.
1644
- const idMatch = /\bid\s*=\s*"([^"]*)"/.exec(fullTag);
1645
- if (!idMatch) {
1646
- continue;
1647
- }
1648
- const elementId = idMatch[1];
1649
- const nameMatch = /\bname\s*=\s*"([^"]*)"/.exec(fullTag);
1650
- const name = nameMatch ? nameMatch[1] : '';
1651
- // Convert BPMN element type to human-readable format
1652
- const activityType = this.formatActivityTypeForIncidents(elementType);
1653
- const activityName = name || elementId;
1654
- elementInfo[elementId] = {
1655
- type: activityType,
1656
- name: activityName
1657
- };
1658
- }
1659
- }
1660
- catch (error) {
1661
- console.warn('Failed to parse BPMN XML for incidents:', error);
1662
- }
1663
- return elementInfo;
1578
+ class SDKInternalsRegistry {
1579
+ // Use global store to ensure sharing across module bundles
1580
+ static get store() {
1581
+ return getGlobalStore();
1664
1582
  }
1665
1583
  /**
1666
- * Format BPMN element type to human-readable activity type for incidents
1584
+ * Register SDK instance internals
1585
+ * Called by UiPath constructor
1667
1586
  */
1668
- static formatActivityTypeForIncidents(elementType) {
1669
- // Convert camelCase BPMN element types to human-readable format
1670
- // e.g., "serviceTask" -> "Service Task", "exclusiveGateway" -> "Exclusive Gateway"
1671
- return elementType
1672
- .replace(/([A-Z])/g, ' $1') // Add space before uppercase letters
1673
- .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
1674
- .trim(); // Remove any leading/trailing spaces
1587
+ static set(instance, internals) {
1588
+ this.store.set(instance, internals);
1675
1589
  }
1676
1590
  /**
1677
- * Fetch BPMN via getBpmn and add element name/type to each incident
1591
+ * Retrieve SDK instance internals
1592
+ * Called by BaseService constructor
1678
1593
  */
1679
- static async enrichIncidentsWithBpmnData(incidents, folderKey, service) {
1680
- // Check if all incidents have the same instanceId
1681
- const uniqueInstanceIds = [...new Set(incidents.map(i => i.instanceId))];
1682
- if (uniqueInstanceIds.length === 1) {
1683
- // Single instance optimization (in case of process instance incidents)
1684
- const elementInfo = await this.getBpmnElementInfo(uniqueInstanceIds[0], folderKey, service);
1685
- return incidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
1686
- }
1687
- else {
1688
- // Multiple instances optimization (in case of process incidents)
1689
- return this.enrichMultipleInstanceIncidents(incidents, folderKey, service);
1594
+ static get(instance) {
1595
+ const internals = this.store.get(instance);
1596
+ if (!internals) {
1597
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1690
1598
  }
1599
+ return internals;
1691
1600
  }
1601
+ }
1602
+
1603
+ var _BaseService_apiClient;
1604
+ /**
1605
+ * Base class for all UiPath SDK services.
1606
+ *
1607
+ * Provides common functionality for authentication, configuration, and API communication.
1608
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1609
+ *
1610
+ * This class implements the dependency injection pattern where services receive a configured
1611
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1612
+ * including authentication token management.
1613
+ *
1614
+ * @remarks
1615
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1616
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1617
+ *
1618
+ */
1619
+ class BaseService {
1692
1620
  /**
1693
- * When incidents span multiple instances, fetch BPMN per instance and annotate
1621
+ * Creates a base service instance with dependency injection.
1622
+ *
1623
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1624
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1625
+ * and token management internally.
1626
+ *
1627
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1628
+ * Services receive this via dependency injection in the modular pattern.
1629
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1630
+ * CAS external-app auth)
1631
+ *
1632
+ * @example
1633
+ * ```typescript
1634
+ * // Services automatically call this via super()
1635
+ * export class EntityService extends BaseService {
1636
+ * constructor(instance: IUiPath) {
1637
+ * super(instance); // Initializes the internal ApiClient
1638
+ * }
1639
+ * }
1640
+ *
1641
+ * // Usage in modular pattern
1642
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1643
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1644
+ *
1645
+ * const sdk = new UiPath(config);
1646
+ * await sdk.initialize();
1647
+ * const entities = new Entities(sdk);
1648
+ * ```
1694
1649
  */
1695
- static async enrichMultipleInstanceIncidents(incidents, folderKey, service) {
1696
- const groups = incidents.reduce((acc, incident) => {
1697
- const id = incident.instanceId || NO_INSTANCE;
1698
- (acc[id] = acc[id] || []).push(incident);
1699
- return acc;
1700
- }, {});
1701
- const results = await Promise.all(Object.entries(groups).map(async (entry) => {
1702
- const [instanceId, groupIncidents] = entry;
1703
- const elementInfo = await this.getBpmnElementInfo(instanceId, folderKey, service);
1704
- return groupIncidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
1705
- }));
1706
- return results.flat();
1650
+ constructor(instance, headers) {
1651
+ // Private field - not visible via Object.keys() or any reflection
1652
+ _BaseService_apiClient.set(this, void 0);
1653
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1654
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1655
+ this.config = { folderKey };
1707
1656
  }
1708
1657
  /**
1709
- * Retrieve BPMN XML for an instance and derive element id → {name,type}
1658
+ * Gets a valid authentication token, refreshing if necessary.
1659
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1660
+ *
1661
+ * @returns Promise resolving to a valid access token string
1662
+ * @throws AuthenticationError if no token is available or refresh fails
1710
1663
  */
1711
- static async getBpmnElementInfo(instanceId, folderKey, service) {
1712
- if (!instanceId || instanceId === NO_INSTANCE) {
1713
- return {};
1714
- }
1715
- try {
1716
- const bpmnXml = await service.getBpmn(instanceId, folderKey);
1717
- return this.parseBpmnElementsForIncidents(bpmnXml);
1718
- }
1719
- catch (error) {
1720
- console.warn(`Failed to get BPMN for instance ${instanceId}:`, error);
1721
- return {};
1722
- }
1664
+ async getValidAuthToken() {
1665
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1723
1666
  }
1724
1667
  /**
1725
- * Transform a raw incident by attaching element name/type from BPMN
1668
+ * Creates a service accessor for pagination helpers
1669
+ * This allows pagination helpers to access protected methods without making them public
1726
1670
  */
1727
- static transformIncidentWithBpmn(incident, elementInfo) {
1728
- const element = elementInfo[incident.elementId];
1729
- const transformed = transformData(incident, ProcessIncidentMap);
1671
+ createPaginationServiceAccess() {
1730
1672
  return {
1731
- ...transformed,
1732
- incidentElementActivityType: element?.type || UNKNOWN$1,
1733
- incidentElementActivityName: element?.name || UNKNOWN$1
1673
+ get: (path, options) => this.get(path, options || {}),
1674
+ post: (path, body, options) => this.post(path, body, options || {}),
1675
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1734
1676
  };
1735
1677
  }
1736
- }
1737
-
1738
- /**
1739
- * SDK Telemetry constants
1740
- */
1741
- // Connection string placeholder that will be replaced during build
1742
- 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";
1743
- // SDK Version placeholder
1744
- const SDK_VERSION = "1.3.7";
1745
- const VERSION = "Version";
1746
- const SERVICE = "Service";
1747
- const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1748
- const CLOUD_TENANT_NAME = "CloudTenantName";
1749
- const CLOUD_URL = "CloudUrl";
1750
- const CLOUD_CLIENT_ID = "CloudClientId";
1751
- const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1752
- const APP_NAME = "ApplicationName";
1753
- const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1754
- // Service and logger names
1755
- const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1756
- const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1757
- // Event names
1758
- const SDK_RUN_EVENT = "Sdk.Run";
1759
- // Default value for unknown/empty attributes
1760
- const UNKNOWN = "";
1761
-
1762
- /**
1763
- * Log exporter that sends ALL logs as Application Insights custom events
1764
- */
1765
- class ApplicationInsightsEventExporter {
1766
- constructor(connectionString) {
1767
- this.connectionString = connectionString;
1768
- }
1769
- export(logs, resultCallback) {
1770
- try {
1771
- logs.forEach(logRecord => {
1772
- this.sendAsCustomEvent(logRecord);
1773
- });
1774
- resultCallback({ code: 0 });
1775
- }
1776
- catch (error) {
1777
- console.debug('Failed to export logs to Application Insights:', error);
1778
- resultCallback({ code: 2, error });
1678
+ async request(method, path, options = {}) {
1679
+ switch (method.toUpperCase()) {
1680
+ case 'GET':
1681
+ return this.get(path, options);
1682
+ case 'POST':
1683
+ return this.post(path, options.body, options);
1684
+ case 'PUT':
1685
+ return this.put(path, options.body, options);
1686
+ case 'PATCH':
1687
+ return this.patch(path, options.body, options);
1688
+ case 'DELETE':
1689
+ return this.delete(path, options);
1690
+ default:
1691
+ throw new Error(`Unsupported HTTP method: ${method}`);
1779
1692
  }
1780
1693
  }
1781
- shutdown() {
1782
- return Promise.resolve();
1783
- }
1784
- sendAsCustomEvent(logRecord) {
1785
- // Get event name from body or attributes
1786
- const eventName = logRecord.body || SDK_RUN_EVENT;
1787
- const payload = {
1788
- name: 'Microsoft.ApplicationInsights.Event',
1789
- time: new Date().toISOString(),
1790
- iKey: this.extractInstrumentationKey(),
1791
- data: {
1792
- baseType: 'EventData',
1793
- baseData: {
1794
- ver: 2,
1795
- name: eventName,
1796
- properties: this.convertAttributesToProperties(logRecord.attributes || {})
1797
- }
1798
- },
1799
- tags: {
1800
- 'ai.cloud.role': CLOUD_ROLE_NAME,
1801
- 'ai.cloud.roleInstance': SDK_VERSION
1802
- }
1803
- };
1804
- this.sendToApplicationInsights(payload);
1805
- }
1806
- extractInstrumentationKey() {
1807
- const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1808
- return match ? match[1] : '';
1809
- }
1810
- convertAttributesToProperties(attributes) {
1811
- const properties = {};
1812
- Object.entries(attributes || {}).forEach(([key, value]) => {
1813
- properties[key] = String(value);
1814
- });
1815
- return properties;
1816
- }
1817
- async sendToApplicationInsights(payload) {
1818
- try {
1819
- const ingestionEndpoint = this.extractIngestionEndpoint();
1820
- if (!ingestionEndpoint) {
1821
- console.debug('No ingestion endpoint found in connection string');
1822
- return;
1823
- }
1824
- const url = `${ingestionEndpoint}/v2/track`;
1825
- const response = await fetch(url, {
1826
- method: 'POST',
1827
- headers: {
1828
- 'Content-Type': 'application/json',
1829
- },
1830
- body: JSON.stringify(payload)
1831
- });
1832
- if (!response.ok) {
1833
- console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1834
- }
1835
- }
1836
- catch (error) {
1837
- console.debug('Error sending event telemetry to Application Insights:', error);
1694
+ async requestWithSpec(spec) {
1695
+ if (!spec.method || !spec.url) {
1696
+ throw new Error('Request spec must include method and url');
1838
1697
  }
1698
+ return this.request(spec.method, spec.url, spec);
1699
+ }
1700
+ async get(path, options = {}) {
1701
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1702
+ return { data: response };
1839
1703
  }
1840
- extractIngestionEndpoint() {
1841
- const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1842
- return match ? match[1] : '';
1704
+ async post(path, data, options = {}) {
1705
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1706
+ return { data: response };
1843
1707
  }
1844
- }
1845
- /**
1846
- * Singleton telemetry client
1847
- */
1848
- class TelemetryClient {
1849
- constructor() {
1850
- this.isInitialized = false;
1708
+ async put(path, data, options = {}) {
1709
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1710
+ return { data: response };
1851
1711
  }
1852
- static getInstance() {
1853
- if (!TelemetryClient.instance) {
1854
- TelemetryClient.instance = new TelemetryClient();
1855
- }
1856
- return TelemetryClient.instance;
1712
+ async patch(path, data, options = {}) {
1713
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1714
+ return { data: response };
1715
+ }
1716
+ async delete(path, options = {}) {
1717
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1718
+ return { data: response };
1857
1719
  }
1858
1720
  /**
1859
- * Initialize telemetry
1721
+ * Execute a request with cursor-based pagination
1860
1722
  */
1861
- initialize(config) {
1862
- if (this.isInitialized) {
1863
- return;
1864
- }
1865
- this.isInitialized = true;
1866
- if (config) {
1867
- this.telemetryContext = config;
1868
- }
1869
- try {
1870
- const connectionString = this.getConnectionString();
1871
- if (!connectionString) {
1872
- return;
1873
- }
1874
- this.setupTelemetryProvider(connectionString);
1723
+ async requestWithPagination(method, path, paginationOptions, options) {
1724
+ const paginationType = options.pagination.paginationType;
1725
+ // Validate and prepare pagination parameters
1726
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1727
+ // Prepare request parameters based on pagination type
1728
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1729
+ // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1730
+ if (method.toUpperCase() === 'POST') {
1731
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1732
+ options.body = {
1733
+ ...existingBody,
1734
+ ...options.params,
1735
+ ...requestParams
1736
+ };
1737
+ options.params = undefined;
1875
1738
  }
1876
- catch (error) {
1877
- // Silent failure - telemetry errors shouldn't break functionality
1878
- console.debug('Failed to initialize OpenTelemetry:', error);
1739
+ else {
1740
+ // Merge pagination parameters with existing parameters
1741
+ options.params = {
1742
+ ...options.params,
1743
+ ...requestParams
1744
+ };
1879
1745
  }
1880
- }
1881
- getConnectionString() {
1882
- const connectionString = CONNECTION_STRING;
1883
- return connectionString;
1884
- }
1885
- setupTelemetryProvider(connectionString) {
1886
- const exporter = new ApplicationInsightsEventExporter(connectionString);
1887
- const processor = new BatchLogRecordProcessor(exporter);
1888
- this.logProvider = new LoggerProvider({
1889
- processors: [processor]
1746
+ // Make the request
1747
+ const response = await this.request(method, path, options);
1748
+ // Extract data from the response and create page result
1749
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1750
+ itemsField: options.pagination.itemsField,
1751
+ totalCountField: options.pagination.totalCountField,
1752
+ continuationTokenField: options.pagination.continuationTokenField
1890
1753
  });
1891
- this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1892
1754
  }
1893
1755
  /**
1894
- * Track a telemetry event
1756
+ * Validates and prepares pagination parameters from options
1895
1757
  */
1896
- track(eventName, name, extraAttributes = {}) {
1897
- try {
1898
- // Skip if logger not initialized
1899
- if (!this.logger) {
1900
- return;
1901
- }
1902
- const finalDisplayName = name || eventName;
1903
- const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1904
- // Emit as log
1905
- this.logger.emit({
1906
- body: finalDisplayName,
1907
- attributes: attributes,
1908
- timestamp: Date.now(),
1909
- });
1910
- }
1911
- catch (error) {
1912
- // Silent failure
1913
- console.debug('Failed to track telemetry event:', error);
1758
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1759
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1760
+ }
1761
+ /**
1762
+ * Prepares request parameters for pagination based on pagination type
1763
+ */
1764
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1765
+ const requestParams = {};
1766
+ let limitedPageSize;
1767
+ const paginationParams = paginationConfig?.paginationParams;
1768
+ switch (paginationType) {
1769
+ case PaginationType.OFFSET:
1770
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1771
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1772
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1773
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1774
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1775
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1776
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1777
+ requestParams[pageSizeParam] = limitedPageSize;
1778
+ if (convertToSkip) {
1779
+ if (params.pageNumber && params.pageNumber > 1) {
1780
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1781
+ }
1782
+ }
1783
+ else {
1784
+ requestParams[offsetParam] = params.pageNumber || 1;
1785
+ }
1786
+ {
1787
+ requestParams[countParam] = true;
1788
+ }
1789
+ break;
1790
+ case PaginationType.TOKEN:
1791
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1792
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1793
+ if (params.pageSize) {
1794
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1795
+ }
1796
+ if (params.continuationToken) {
1797
+ requestParams[tokenParam] = params.continuationToken;
1798
+ }
1799
+ break;
1914
1800
  }
1801
+ return requestParams;
1915
1802
  }
1916
1803
  /**
1917
- * Get enriched attributes for telemetry events
1804
+ * Creates a paginated response from API response
1918
1805
  */
1919
- getEnrichedAttributes(extraAttributes, eventName) {
1920
- const attributes = {
1921
- [APP_NAME]: SDK_SERVICE_NAME,
1922
- [VERSION]: SDK_VERSION,
1923
- [SERVICE]: eventName,
1924
- [CLOUD_URL]: this.createCloudUrl(),
1925
- [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1926
- [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1927
- [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1928
- [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1929
- ...extraAttributes,
1930
- };
1931
- return attributes;
1806
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1807
+ // Extract fields from response
1808
+ const itemsField = fields.itemsField ||
1809
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1810
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1811
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1812
+ // Extract items and metadata
1813
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1814
+ const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
1815
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1816
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1817
+ const continuationToken = response.data[continuationTokenField];
1818
+ // Determine if there are more pages
1819
+ const hasMore = this.determineHasMorePages(paginationType, {
1820
+ totalCount,
1821
+ pageSize: params.pageSize,
1822
+ currentPage: params.pageNumber || 1,
1823
+ itemsCount: items.length,
1824
+ continuationToken
1825
+ });
1826
+ // Create and return the page result
1827
+ return PaginationManager.createPaginatedResponse({
1828
+ pageInfo: {
1829
+ hasMore,
1830
+ totalCount,
1831
+ currentPage: params.pageNumber,
1832
+ pageSize: params.pageSize,
1833
+ continuationToken
1834
+ },
1835
+ type: paginationType,
1836
+ }, items);
1932
1837
  }
1933
1838
  /**
1934
- * Create cloud URL from base URL, organization ID, and tenant ID
1839
+ * Determines if there are more pages based on pagination type and metadata
1935
1840
  */
1936
- createCloudUrl() {
1937
- const baseUrl = this.telemetryContext?.baseUrl;
1938
- const orgId = this.telemetryContext?.orgName;
1939
- const tenantId = this.telemetryContext?.tenantName;
1940
- if (!baseUrl || !orgId || !tenantId) {
1941
- return UNKNOWN;
1841
+ determineHasMorePages(paginationType, info) {
1842
+ switch (paginationType) {
1843
+ case PaginationType.OFFSET:
1844
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1845
+ // If totalCount is available, use it for precise calculation
1846
+ if (info.totalCount !== undefined) {
1847
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1848
+ }
1849
+ // Fallback when totalCount is not available
1850
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1851
+ return info.itemsCount === effectivePageSize;
1852
+ case PaginationType.TOKEN:
1853
+ return !!info.continuationToken;
1854
+ default:
1855
+ return false;
1942
1856
  }
1943
- return `${baseUrl}/${orgId}/${tenantId}`;
1944
1857
  }
1945
1858
  }
1946
- // Export singleton instance
1947
- const telemetryClient = TelemetryClient.getInstance();
1948
-
1949
- /**
1950
- * SDK Track decorator and function for telemetry
1951
- */
1952
- /**
1953
- * Common tracking logic shared between method and function decorators
1954
- */
1955
- function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1956
- return function (...args) {
1957
- // Determine if we should track this call
1958
- let shouldTrack = true;
1959
- if (opts.condition !== undefined) {
1960
- if (typeof opts.condition === 'function') {
1961
- shouldTrack = opts.condition.apply(this, args);
1962
- }
1963
- else {
1964
- shouldTrack = opts.condition;
1965
- }
1966
- }
1967
- // Track the event if enabled
1968
- if (shouldTrack) {
1969
- // Use the full name provided in the decorator (e.g., "Queue.GetAll")
1970
- const serviceMethod = typeof nameOrOptions === 'string'
1971
- ? nameOrOptions
1972
- : fallbackName;
1973
- // Use 'Sdk.Run' as the name and serviceMethod as the service
1974
- telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1975
- }
1976
- // Execute the original function
1977
- return originalFunction.apply(this, args);
1978
- };
1979
- }
1980
- /**
1981
- * Track decorator that can be used to automatically track function calls
1982
- *
1983
- * Usage:
1984
- * @track("Service.Method")
1985
- * function myFunction() { ... }
1986
- *
1987
- * @track("Queue.GetAll")
1988
- * async getAll() { ... }
1989
- *
1990
- * @track("Tasks.Create")
1991
- * async create() { ... }
1992
- *
1993
- * @track("Assets.Update", { condition: false })
1994
- * function myFunction() { ... }
1995
- *
1996
- * @track("Processes.Start", { attributes: { customProp: "value" } })
1997
- * function myFunction() { ... }
1998
- */
1999
- function track(nameOrOptions, options) {
2000
- return function decorator(_target, propertyKey, descriptor) {
2001
- const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
2002
- if (descriptor && typeof descriptor.value === 'function') {
2003
- // Method decorator
2004
- descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
2005
- return descriptor;
2006
- }
2007
- // Function decorator
2008
- return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2009
- };
2010
- }
1859
+ _BaseService_apiClient = new WeakMap();
2011
1860
 
2012
1861
  /**
2013
1862
  * Creates methods for a process instance
@@ -2119,6 +1968,41 @@ var DebugMode;
2119
1968
  * Case Instance Types
2120
1969
  * Types and interfaces for Maestro case instance management
2121
1970
  */
1971
+ /**
1972
+ * SLA status for a case instance
1973
+ */
1974
+ var SlaSummaryStatus;
1975
+ (function (SlaSummaryStatus) {
1976
+ /** Case is within SLA deadline */
1977
+ SlaSummaryStatus["ON_TRACK"] = "On Track";
1978
+ /** Case is approaching SLA deadline based on at-risk percentage threshold */
1979
+ SlaSummaryStatus["AT_RISK"] = "At Risk";
1980
+ /** Case has exceeded SLA deadline */
1981
+ SlaSummaryStatus["OVERDUE"] = "Overdue";
1982
+ /** Case instance has completed */
1983
+ SlaSummaryStatus["COMPLETED"] = "Completed";
1984
+ /** SLA status cannot be determined (no SLA deadline defined) */
1985
+ SlaSummaryStatus["UNKNOWN"] = "Unknown";
1986
+ })(SlaSummaryStatus || (SlaSummaryStatus = {}));
1987
+ /**
1988
+ * Instance status values for case instances and process instances
1989
+ */
1990
+ var InstanceStatus;
1991
+ (function (InstanceStatus) {
1992
+ /** Instance status not yet populated by the backend */
1993
+ InstanceStatus["UNKNOWN"] = "";
1994
+ InstanceStatus["CANCELLED"] = "Cancelled";
1995
+ InstanceStatus["CANCELING"] = "Canceling";
1996
+ InstanceStatus["COMPLETED"] = "Completed";
1997
+ InstanceStatus["FAULTED"] = "Faulted";
1998
+ InstanceStatus["PAUSED"] = "Paused";
1999
+ InstanceStatus["PAUSING"] = "Pausing";
2000
+ InstanceStatus["PENDING"] = "Pending";
2001
+ InstanceStatus["RESUMING"] = "Resuming";
2002
+ InstanceStatus["RETRYING"] = "Retrying";
2003
+ InstanceStatus["RUNNING"] = "Running";
2004
+ InstanceStatus["UPGRADING"] = "Upgrading";
2005
+ })(InstanceStatus || (InstanceStatus = {}));
2122
2006
  /**
2123
2007
  * Case stage task type
2124
2008
  */
@@ -2153,6 +2037,8 @@ var EscalationTriggerType;
2153
2037
  (function (EscalationTriggerType) {
2154
2038
  EscalationTriggerType["SLA_BREACHED"] = "sla-breached";
2155
2039
  EscalationTriggerType["AT_RISK"] = "at-risk";
2040
+ /** Default value when no escalation rule is defined */
2041
+ EscalationTriggerType["NONE"] = "None";
2156
2042
  })(EscalationTriggerType || (EscalationTriggerType = {}));
2157
2043
  /**
2158
2044
  * SLA duration unit
@@ -2165,6 +2051,40 @@ var SLADurationUnit;
2165
2051
  SLADurationUnit["MONTHS"] = "m";
2166
2052
  })(SLADurationUnit || (SLADurationUnit = {}));
2167
2053
 
2054
+ /**
2055
+ * Insights Types
2056
+ * Shared types for Maestro insights analytics endpoints
2057
+ */
2058
+ /**
2059
+ * Time bucketing granularity for insights time-series queries.
2060
+ *
2061
+ * Controls how data points are grouped on the time axis.
2062
+ */
2063
+ var TimeInterval;
2064
+ (function (TimeInterval) {
2065
+ /** Group data points by hour */
2066
+ TimeInterval["Hour"] = "HOUR";
2067
+ /** Group data points by day */
2068
+ TimeInterval["Day"] = "DAY";
2069
+ /** Group data points by week */
2070
+ TimeInterval["Week"] = "WEEK";
2071
+ })(TimeInterval || (TimeInterval = {}));
2072
+ /**
2073
+ * Final instance statuses returned by the instance status timeline endpoint.
2074
+ *
2075
+ * Only includes statuses where the instance has finished execution — Completed, Faulted, or Cancelled.
2076
+ * Active statuses like Running or Paused are not included.
2077
+ */
2078
+ var InstanceFinalStatus;
2079
+ (function (InstanceFinalStatus) {
2080
+ /** Instance completed successfully */
2081
+ InstanceFinalStatus["Completed"] = "Completed";
2082
+ /** Instance encountered an error */
2083
+ InstanceFinalStatus["Faulted"] = "Faulted";
2084
+ /** Instance was cancelled */
2085
+ InstanceFinalStatus["Cancelled"] = "Cancelled";
2086
+ })(InstanceFinalStatus || (InstanceFinalStatus = {}));
2087
+
2168
2088
  /**
2169
2089
  * Maps fields for Process Instance entities to ensure consistent naming
2170
2090
  */
@@ -2540,6 +2460,177 @@ class MaestroProcessesService extends BaseService {
2540
2460
  // Fetch BPMN XML and add element name/type to each incident
2541
2461
  return BpmnHelpers.enrichIncidentsWithBpmnData(rawResponse.data || [], folderKey, this.processInstancesService);
2542
2462
  }
2463
+ /**
2464
+ * Get the top 5 processes ranked by run count within a time range.
2465
+ *
2466
+ * Returns an array of up to 5 processes sorted by how many times they were executed,
2467
+ * useful for identifying the most active processes in a given period.
2468
+ *
2469
+ * @param startTime - Start of the time range to query
2470
+ * @param endTime - End of the time range to query
2471
+ * @param options - Optional filters (packageId, processKey, version)
2472
+ * @returns Promise resolving to an array of {@link ProcessGetTopRunCountResponse}
2473
+ * @example
2474
+ * ```typescript
2475
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
2476
+ *
2477
+ * const maestroProcesses = new MaestroProcesses(sdk);
2478
+ *
2479
+ * // Get top processes by run count for the last 7 days
2480
+ * const topProcesses = await maestroProcesses.getTopRunCount(
2481
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2482
+ * new Date()
2483
+ * );
2484
+ *
2485
+ * for (const process of topProcesses) {
2486
+ * console.log(`${process.packageId}: ${process.runCount} runs`);
2487
+ * }
2488
+ * ```
2489
+ *
2490
+ * @example
2491
+ * ```typescript
2492
+ * // Get top processes by run count for a specific package
2493
+ * const filtered = await maestroProcesses.getTopRunCount(
2494
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2495
+ * new Date(),
2496
+ * { packageId: '<packageId>' }
2497
+ * );
2498
+ * ```
2499
+ */
2500
+ async getTopRunCount(startTime, endTime, options) {
2501
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_RUN_COUNT, buildInsightsTopBody(startTime, endTime, false, options));
2502
+ return (data ?? []).map(process => ({ ...process, name: process.packageId }));
2503
+ }
2504
+ /**
2505
+ * Get all instances status counts aggregated by date for maestro processes.
2506
+ *
2507
+ * Returns time-grouped counts of instances grouped by status (Completed, Faulted, Cancelled),
2508
+ * useful for rendering time-series charts. Use `groupBy` to control the time bucket size
2509
+ * (hour, day, or week) — defaults to day if not provided.
2510
+ *
2511
+ * @param startTime - Start of the time range to query
2512
+ * @param endTime - End of the time range to query
2513
+ * @param options - Optional settings for time bucketing granularity
2514
+ * @returns Promise resolving to an array of {@link InstanceStatusTimelineResponse}
2515
+ *
2516
+ * @example
2517
+ * ```typescript
2518
+ * // Get daily instance status for the last 7 days
2519
+ * const now = new Date();
2520
+ * const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
2521
+ * const statuses = await maestroProcesses.getInstanceStatusTimeline(sevenDaysAgo, now);
2522
+ *
2523
+ * for (const entry of statuses) {
2524
+ * console.log(`${entry.startTime} — ${entry.status}: ${entry.count}`);
2525
+ * }
2526
+ * ```
2527
+ *
2528
+ * @example
2529
+ * ```typescript
2530
+ * import { TimeInterval } from '@uipath/uipath-typescript/maestro-processes';
2531
+ *
2532
+ * // Get hourly breakdown
2533
+ * const statuses = await maestroProcesses.getInstanceStatusTimeline(startTime, endTime, {
2534
+ * groupBy: TimeInterval.Hour,
2535
+ * });
2536
+ * ```
2537
+ *
2538
+ * @example
2539
+ * ```typescript
2540
+ * // Get all-time data (from Unix epoch to now)
2541
+ * const allTime = await maestroProcesses.getInstanceStatusTimeline(new Date(0), new Date());
2542
+ * ```
2543
+ */
2544
+ async getInstanceStatusTimeline(startTime, endTime, options) {
2545
+ return fetchInstanceStatusTimeline(this.post.bind(this), startTime, endTime, false, options);
2546
+ }
2547
+ /**
2548
+ * Get the top 10 processes ranked by failure count within a time range.
2549
+ *
2550
+ * Returns an array of up to 10 processes sorted by how many instances faulted,
2551
+ * useful for identifying the most error-prone processes in a given period.
2552
+ *
2553
+ * @param startTime - Start of the time range to query
2554
+ * @param endTime - End of the time range to query
2555
+ * @param options - Optional filters (packageId, processKey, version)
2556
+ * @returns Promise resolving to an array of {@link ProcessGetTopFaultedCountResponse}
2557
+ * @example
2558
+ * ```typescript
2559
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
2560
+ *
2561
+ * const maestroProcesses = new MaestroProcesses(sdk);
2562
+ *
2563
+ * // Get top processes by faulted count for the last 7 days
2564
+ * const topFailing = await maestroProcesses.getTopFaultedCount(
2565
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2566
+ * new Date()
2567
+ * );
2568
+ *
2569
+ * for (const process of topFailing) {
2570
+ * console.log(`${process.packageId}: ${process.faultedCount} failures`);
2571
+ * }
2572
+ * ```
2573
+ *
2574
+ * @example
2575
+ * ```typescript
2576
+ * // Get top processes by faulted count for a specific package
2577
+ * const filtered = await maestroProcesses.getTopFaultedCount(
2578
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2579
+ * new Date(),
2580
+ * { packageId: '<packageId>' }
2581
+ * );
2582
+ * ```
2583
+ */
2584
+ async getTopFaultedCount(startTime, endTime, options) {
2585
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_WITH_FAILURE, buildInsightsTopBody(startTime, endTime, false, options));
2586
+ return (data ?? []).map(item => ({
2587
+ packageId: item.packageId,
2588
+ processKey: item.processKey,
2589
+ faultedCount: item.runCount,
2590
+ name: item.packageId,
2591
+ }));
2592
+ }
2593
+ /**
2594
+ * Get the top 5 processes ranked by total duration within a time range.
2595
+ *
2596
+ * Returns an array of up to 5 processes sorted by their total execution time,
2597
+ * useful for identifying the longest-running processes in a given period.
2598
+ *
2599
+ * @param startTime - Start of the time range to query
2600
+ * @param endTime - End of the time range to query
2601
+ * @param options - Optional filters (packageId, processKey, version)
2602
+ * @returns Promise resolving to an array of {@link ProcessGetTopDurationResponse}
2603
+ * @example
2604
+ * ```typescript
2605
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
2606
+ *
2607
+ * const maestroProcesses = new MaestroProcesses(sdk);
2608
+ *
2609
+ * // Get top processes by duration for the last 7 days
2610
+ * const topProcesses = await maestroProcesses.getTopExecutionDuration(
2611
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2612
+ * new Date()
2613
+ * );
2614
+ *
2615
+ * for (const process of topProcesses) {
2616
+ * console.log(`${process.packageId}: ${process.duration}ms total`);
2617
+ * }
2618
+ * ```
2619
+ *
2620
+ * @example
2621
+ * ```typescript
2622
+ * // Get top processes by duration for a specific package
2623
+ * const filtered = await maestroProcesses.getTopExecutionDuration(
2624
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2625
+ * new Date(),
2626
+ * { packageId: '<packageId>' }
2627
+ * );
2628
+ * ```
2629
+ */
2630
+ async getTopExecutionDuration(startTime, endTime, options) {
2631
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_DURATION, buildInsightsTopBody(startTime, endTime, false, options));
2632
+ return (data ?? []).map(process => ({ ...process, name: process.packageId }));
2633
+ }
2543
2634
  }
2544
2635
  __decorate([
2545
2636
  track('MaestroProcesses.GetAll')
@@ -2547,6 +2638,18 @@ __decorate([
2547
2638
  __decorate([
2548
2639
  track('MaestroProcesses.GetIncidents')
2549
2640
  ], MaestroProcessesService.prototype, "getIncidents", null);
2641
+ __decorate([
2642
+ track('MaestroProcesses.GetTopRunCount')
2643
+ ], MaestroProcessesService.prototype, "getTopRunCount", null);
2644
+ __decorate([
2645
+ track('MaestroProcesses.GetInstanceStatusTimeline')
2646
+ ], MaestroProcessesService.prototype, "getInstanceStatusTimeline", null);
2647
+ __decorate([
2648
+ track('MaestroProcesses.GetTopFaultedCount')
2649
+ ], MaestroProcessesService.prototype, "getTopFaultedCount", null);
2650
+ __decorate([
2651
+ track('MaestroProcesses.GetTopExecutionDuration')
2652
+ ], MaestroProcessesService.prototype, "getTopExecutionDuration", null);
2550
2653
 
2551
2654
  /**
2552
2655
  * Service class for Maestro Process Incidents
@@ -2584,4 +2687,4 @@ __decorate([
2584
2687
  track('ProcessIncidents.getAll')
2585
2688
  ], ProcessIncidentsService.prototype, "getAll", null);
2586
2689
 
2587
- export { DebugMode, MaestroProcessesService as MaestroProcesses, MaestroProcessesService, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, ProcessIncidentsService as ProcessIncidents, ProcessIncidentsService, ProcessInstancesService as ProcessInstances, ProcessInstancesService, createProcessInstanceWithMethods, createProcessWithMethods };
2690
+ export { DebugMode, InstanceFinalStatus, MaestroProcessesService as MaestroProcesses, MaestroProcessesService, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, ProcessIncidentsService as ProcessIncidents, ProcessIncidentsService, ProcessInstancesService as ProcessInstances, ProcessInstancesService, TimeInterval, createProcessInstanceWithMethods, createProcessWithMethods };