@uipath/uipath-typescript 1.3.8 → 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.
- package/dist/assets/index.cjs +25 -270
- package/dist/assets/index.mjs +25 -270
- package/dist/attachments/index.cjs +23 -267
- package/dist/attachments/index.mjs +23 -267
- package/dist/buckets/index.cjs +54 -270
- package/dist/buckets/index.d.ts +50 -1
- package/dist/buckets/index.mjs +54 -270
- package/dist/cases/index.cjs +408 -337
- package/dist/cases/index.d.ts +534 -2
- package/dist/cases/index.mjs +409 -338
- package/dist/conversational-agent/index.cjs +71 -281
- package/dist/conversational-agent/index.d.ts +62 -12
- package/dist/conversational-agent/index.mjs +71 -282
- package/dist/core/index.cjs +39 -289
- package/dist/core/index.d.ts +9 -98
- package/dist/core/index.mjs +40 -275
- package/dist/document-understanding/index.cjs +18 -1
- package/dist/document-understanding/index.d.ts +636 -610
- package/dist/document-understanding/index.mjs +18 -1
- package/dist/entities/index.cjs +25 -270
- package/dist/entities/index.mjs +25 -270
- package/dist/feedback/index.cjs +23 -268
- package/dist/feedback/index.mjs +23 -268
- package/dist/index.cjs +600 -293
- package/dist/index.d.ts +1603 -722
- package/dist/index.mjs +600 -279
- package/dist/index.umd.js +789 -158
- package/dist/jobs/index.cjs +25 -270
- package/dist/jobs/index.mjs +25 -270
- package/dist/maestro-processes/index.cjs +1751 -1720
- package/dist/maestro-processes/index.d.ts +430 -2
- package/dist/maestro-processes/index.mjs +1752 -1721
- package/dist/processes/index.cjs +25 -270
- package/dist/processes/index.mjs +25 -270
- package/dist/queues/index.cjs +25 -270
- package/dist/queues/index.mjs +25 -270
- package/dist/tasks/index.cjs +25 -270
- package/dist/tasks/index.mjs +25 -270
- package/package.json +8 -10
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getOrCreateClient, createTrack, createTrackEvent } from '@uipath/core-telemetry';
|
|
2
2
|
|
|
3
3
|
/******************************************************************************
|
|
4
4
|
Copyright (c) Microsoft Corporation.
|
|
@@ -43,466 +43,405 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
|
|
|
43
43
|
};
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
|
-
*
|
|
46
|
+
* Base path constants for different services
|
|
47
47
|
*/
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
error !== null &&
|
|
51
|
-
'message' in error &&
|
|
52
|
-
'errorCode' in error &&
|
|
53
|
-
typeof error.message === 'string' &&
|
|
54
|
-
typeof error.errorCode === 'number';
|
|
55
|
-
}
|
|
56
|
-
function isEntityError(error) {
|
|
57
|
-
return typeof error === 'object' &&
|
|
58
|
-
error !== null &&
|
|
59
|
-
'error' in error &&
|
|
60
|
-
typeof error.error === 'string';
|
|
61
|
-
}
|
|
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';
|
|
71
|
-
}
|
|
48
|
+
const PIMS_BASE = 'pims_';
|
|
49
|
+
const INSIGHTS_RTM_BASE = 'insightsrtm_';
|
|
72
50
|
|
|
73
51
|
/**
|
|
74
|
-
*
|
|
52
|
+
* Maestro Service Endpoints
|
|
75
53
|
*/
|
|
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
54
|
/**
|
|
90
|
-
*
|
|
55
|
+
* Maestro Process Service Endpoints
|
|
91
56
|
*/
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
+
},
|
|
100
85
|
};
|
|
86
|
+
|
|
101
87
|
/**
|
|
102
|
-
*
|
|
88
|
+
* Maestro Process Models
|
|
89
|
+
* Model classes for Maestro processes
|
|
103
90
|
*/
|
|
104
|
-
const HttpHeaders = {
|
|
105
|
-
X_REQUEST_ID: 'x-request-id'
|
|
106
|
-
};
|
|
107
91
|
/**
|
|
108
|
-
*
|
|
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
|
|
109
97
|
*/
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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',
|
|
127
|
-
};
|
|
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
|
+
};
|
|
108
|
+
}
|
|
128
109
|
/**
|
|
129
|
-
*
|
|
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
|
|
130
115
|
*/
|
|
131
|
-
|
|
132
|
-
|
|
116
|
+
function createProcessWithMethods(processData, service) {
|
|
117
|
+
const methods = createProcessMethods(processData, service);
|
|
118
|
+
return Object.assign({}, processData, methods);
|
|
119
|
+
}
|
|
133
120
|
|
|
134
121
|
/**
|
|
135
|
-
*
|
|
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
|
|
136
130
|
*/
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
traceId: error.traceId,
|
|
149
|
-
originalResponse: error
|
|
150
|
-
},
|
|
151
|
-
requestId: error.traceId
|
|
152
|
-
};
|
|
153
|
-
}
|
|
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
|
+
};
|
|
154
142
|
}
|
|
155
143
|
/**
|
|
156
|
-
*
|
|
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
|
|
157
154
|
*/
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
traceId: error.traceId,
|
|
170
|
-
originalResponse: error
|
|
171
|
-
},
|
|
172
|
-
requestId: error.traceId
|
|
173
|
-
};
|
|
174
|
-
}
|
|
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 ?? [];
|
|
175
166
|
}
|
|
167
|
+
|
|
176
168
|
/**
|
|
177
|
-
*
|
|
169
|
+
* Common constants used across the SDK
|
|
178
170
|
*/
|
|
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}`;
|
|
192
|
-
}
|
|
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
|
-
}
|
|
207
|
-
}
|
|
208
171
|
/**
|
|
209
|
-
*
|
|
172
|
+
* Prefix used for OData query parameters
|
|
210
173
|
*/
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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
|
-
}
|
|
174
|
+
const ODATA_PREFIX = '$';
|
|
175
|
+
const UNKNOWN = 'Unknown';
|
|
176
|
+
const NO_INSTANCE = 'no-instance';
|
|
227
177
|
/**
|
|
228
|
-
*
|
|
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
|
|
178
|
+
* HTTP methods
|
|
243
179
|
*/
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
new OrchestratorErrorParser(),
|
|
248
|
-
new EntityErrorParser(),
|
|
249
|
-
new PimsErrorParser(),
|
|
250
|
-
new GenericErrorParser() // Must be last
|
|
251
|
-
];
|
|
252
|
-
}
|
|
253
|
-
/**
|
|
254
|
-
* Parses error response body into standardized format
|
|
255
|
-
* @param response - The HTTP response object
|
|
256
|
-
* @returns Standardized error information
|
|
257
|
-
*/
|
|
258
|
-
async parse(response) {
|
|
259
|
-
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);
|
|
265
|
-
}
|
|
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
|
-
};
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
// Export singleton instance
|
|
282
|
-
const errorResponseParser = new ErrorResponseParser();
|
|
283
|
-
|
|
180
|
+
const HTTP_METHODS = {
|
|
181
|
+
GET: 'GET',
|
|
182
|
+
POST: 'POST'};
|
|
284
183
|
/**
|
|
285
|
-
*
|
|
286
|
-
* Extends Error for standard error handling compatibility
|
|
184
|
+
* Process Instance pagination constants for token-based pagination
|
|
287
185
|
*/
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Returns a clean JSON representation of the error
|
|
303
|
-
*/
|
|
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
|
-
};
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* Returns detailed debug information including stack trace
|
|
315
|
-
*/
|
|
316
|
-
getDebugInfo() {
|
|
317
|
-
return {
|
|
318
|
-
...this.toJSON(),
|
|
319
|
-
stack: this.stack
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
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'
|
|
191
|
+
};
|
|
324
192
|
/**
|
|
325
|
-
*
|
|
326
|
-
* Common scenarios:
|
|
327
|
-
* - Invalid credentials
|
|
328
|
-
* - Expired token
|
|
329
|
-
* - Missing authentication
|
|
193
|
+
* OData OFFSET pagination parameter names (ODATA-style)
|
|
330
194
|
*/
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
|
|
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'
|
|
202
|
+
};
|
|
341
203
|
/**
|
|
342
|
-
*
|
|
343
|
-
* Common scenarios:
|
|
344
|
-
* - Insufficient permissions
|
|
345
|
-
* - Access denied to resource
|
|
346
|
-
* - Invalid scope
|
|
204
|
+
* Bucket TOKEN pagination parameter names
|
|
347
205
|
*/
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
|
|
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'
|
|
211
|
+
};
|
|
358
212
|
/**
|
|
359
|
-
*
|
|
360
|
-
* Common scenarios:
|
|
361
|
-
* - Invalid input parameters
|
|
362
|
-
* - Missing required fields
|
|
363
|
-
* - Invalid data format
|
|
213
|
+
* Process Instance TOKEN pagination parameter names
|
|
364
214
|
*/
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
});
|
|
372
|
-
}
|
|
373
|
-
}
|
|
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
|
+
};
|
|
374
221
|
|
|
375
222
|
/**
|
|
376
|
-
*
|
|
377
|
-
*
|
|
378
|
-
* - Resource doesn't exist
|
|
379
|
-
* - Invalid ID provided
|
|
380
|
-
* - Resource deleted
|
|
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.
|
|
381
225
|
*/
|
|
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
226
|
/**
|
|
393
|
-
*
|
|
394
|
-
*
|
|
395
|
-
*
|
|
396
|
-
*
|
|
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
|
+
* ```
|
|
397
251
|
*/
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
|
|
403
|
-
requestId: params.requestId
|
|
404
|
-
});
|
|
252
|
+
function transformData(data, fieldMapping) {
|
|
253
|
+
// Handle array of objects
|
|
254
|
+
if (Array.isArray(data)) {
|
|
255
|
+
return data.map(item => transformData(item, fieldMapping));
|
|
405
256
|
}
|
|
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
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return result;
|
|
406
267
|
}
|
|
407
|
-
|
|
408
268
|
/**
|
|
409
|
-
*
|
|
410
|
-
*
|
|
411
|
-
*
|
|
412
|
-
*
|
|
413
|
-
*
|
|
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 }
|
|
414
279
|
*/
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
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;
|
|
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;
|
|
288
|
+
}
|
|
430
289
|
}
|
|
290
|
+
return result;
|
|
431
291
|
}
|
|
432
292
|
|
|
433
293
|
/**
|
|
434
|
-
*
|
|
435
|
-
* Common scenarios:
|
|
436
|
-
* - Connection timeout
|
|
437
|
-
* - DNS resolution failure
|
|
438
|
-
* - Network unreachable
|
|
439
|
-
* - Request aborted
|
|
294
|
+
* Maps fields for Incident entities
|
|
440
295
|
*/
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
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
|
-
|
|
296
|
+
const ProcessIncidentMap = {
|
|
297
|
+
errorTimeUtc: 'errorTime'
|
|
298
|
+
};
|
|
451
299
|
/**
|
|
452
|
-
*
|
|
453
|
-
* Follows the Factory pattern for clean error instantiation
|
|
300
|
+
* Maps fields for Incident Summary entities
|
|
454
301
|
*/
|
|
455
|
-
|
|
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 {
|
|
456
310
|
/**
|
|
457
|
-
*
|
|
311
|
+
* Parse BPMN XML and extract element id → {name,type} used for incidents
|
|
458
312
|
*/
|
|
459
|
-
static
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
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 });
|
|
313
|
+
static parseBpmnElementsForIncidents(bpmnXml) {
|
|
314
|
+
const elementInfo = {};
|
|
315
|
+
try {
|
|
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;
|
|
477
325
|
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
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
|
+
}
|
|
484
337
|
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
console.warn('Failed to parse BPMN XML for incidents:', error);
|
|
340
|
+
}
|
|
341
|
+
return elementInfo;
|
|
485
342
|
}
|
|
486
343
|
/**
|
|
487
|
-
*
|
|
344
|
+
* Format BPMN element type to human-readable activity type for incidents
|
|
488
345
|
*/
|
|
489
|
-
static
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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));
|
|
501
364
|
}
|
|
502
|
-
|
|
365
|
+
else {
|
|
366
|
+
// Multiple instances optimization (in case of process incidents)
|
|
367
|
+
return this.enrichMultipleInstanceIncidents(incidents, folderKey, service);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* When incidents span multiple instances, fetch BPMN per instance and annotate
|
|
372
|
+
*/
|
|
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();
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Retrieve BPMN XML for an instance and derive element id → {name,type}
|
|
388
|
+
*/
|
|
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);
|
|
408
|
+
return {
|
|
409
|
+
...transformed,
|
|
410
|
+
incidentElementActivityType: element?.type || UNKNOWN,
|
|
411
|
+
incidentElementActivityName: element?.name || UNKNOWN
|
|
412
|
+
};
|
|
503
413
|
}
|
|
504
414
|
}
|
|
505
415
|
|
|
416
|
+
/**
|
|
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';
|
|
428
|
+
|
|
429
|
+
/**
|
|
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);
|
|
444
|
+
|
|
506
445
|
const FOLDER_KEY = 'X-UIPATH-FolderKey';
|
|
507
446
|
const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
|
|
508
447
|
const TRACEPARENT = 'traceparent';
|
|
@@ -525,1524 +464,1399 @@ const RESPONSE_TYPES = {
|
|
|
525
464
|
ARRAYBUFFER: 'arraybuffer'
|
|
526
465
|
};
|
|
527
466
|
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
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
|
-
*
|
|
506
|
+
* Type guards for error response types
|
|
643
507
|
*/
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
655
|
-
* and dot-separated nested paths (e.g., 'pagination.totalCount').
|
|
656
|
-
* Direct key match takes priority over nested traversal.
|
|
550
|
+
* Error type constants for consistent error identification
|
|
657
551
|
*/
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
}
|
|
668
|
-
let value = data;
|
|
669
|
-
for (const part of fieldPath.split('.')) {
|
|
670
|
-
value = value?.[part];
|
|
671
|
-
}
|
|
672
|
-
return value;
|
|
673
|
-
}
|
|
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
|
+
};
|
|
674
561
|
/**
|
|
675
|
-
*
|
|
676
|
-
* @param obj The source object
|
|
677
|
-
* @returns A new object without undefined values
|
|
678
|
-
*
|
|
679
|
-
* @example
|
|
680
|
-
* ```typescript
|
|
681
|
-
* // Object with undefined values
|
|
682
|
-
* const options = {
|
|
683
|
-
* name: 'test',
|
|
684
|
-
* count: 5,
|
|
685
|
-
* prefix: undefined,
|
|
686
|
-
* suffix: null
|
|
687
|
-
* };
|
|
688
|
-
* const result = filterUndefined(options);
|
|
689
|
-
* // result = { name: 'test', count: 5, suffix: null }
|
|
690
|
-
* ```
|
|
562
|
+
* HTTP header constants for error handling
|
|
691
563
|
*/
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
if (value !== undefined) {
|
|
696
|
-
result[key] = value;
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
return result;
|
|
700
|
-
}
|
|
701
|
-
|
|
564
|
+
const HttpHeaders = {
|
|
565
|
+
X_REQUEST_ID: 'x-request-id'
|
|
566
|
+
};
|
|
702
567
|
/**
|
|
703
|
-
*
|
|
568
|
+
* Standard error message constants
|
|
704
569
|
*/
|
|
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
|
+
};
|
|
705
588
|
/**
|
|
706
|
-
*
|
|
589
|
+
* Error name constants for network error identification
|
|
707
590
|
*/
|
|
708
|
-
const
|
|
709
|
-
|
|
591
|
+
const ErrorNames = {
|
|
592
|
+
ABORT_ERROR: 'AbortError'};
|
|
710
593
|
|
|
711
594
|
/**
|
|
712
|
-
*
|
|
713
|
-
*/
|
|
714
|
-
/**
|
|
715
|
-
* Encodes a string to base64
|
|
716
|
-
* @param str - The string to encode
|
|
717
|
-
* @returns Base64 encoded string
|
|
595
|
+
* Parser for Orchestrator/Task error format
|
|
718
596
|
*/
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
const data = encoder.encode(str);
|
|
723
|
-
// Convert Uint8Array to base64
|
|
724
|
-
if (isBrowser) {
|
|
725
|
-
// Browser environment
|
|
726
|
-
// Convert Uint8Array to binary string then to base64
|
|
727
|
-
const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
|
|
728
|
-
return btoa(binaryString);
|
|
597
|
+
class OrchestratorErrorParser {
|
|
598
|
+
canParse(errorBody) {
|
|
599
|
+
return isOrchestratorError(errorBody);
|
|
729
600
|
}
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
return
|
|
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
|
+
};
|
|
733
613
|
}
|
|
734
614
|
}
|
|
735
615
|
/**
|
|
736
|
-
*
|
|
737
|
-
* @param base64 - The base64 string to decode
|
|
738
|
-
* @returns Decoded string
|
|
616
|
+
* Parser for Entity (Data Fabric) error format
|
|
739
617
|
*/
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
// Browser environment
|
|
744
|
-
const binaryString = atob(base64);
|
|
745
|
-
bytes = new Uint8Array(binaryString.length);
|
|
746
|
-
for (let i = 0; i < binaryString.length; i++) {
|
|
747
|
-
bytes[i] = binaryString.charCodeAt(i);
|
|
748
|
-
}
|
|
618
|
+
class EntityErrorParser {
|
|
619
|
+
canParse(errorBody) {
|
|
620
|
+
return isEntityError(errorBody);
|
|
749
621
|
}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
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
|
+
};
|
|
753
634
|
}
|
|
754
|
-
// TextDecoder for UTF-8 decoding (works in both browser and Node.js)
|
|
755
|
-
const decoder = new TextDecoder();
|
|
756
|
-
return decoder.decode(bytes);
|
|
757
635
|
}
|
|
758
|
-
|
|
759
636
|
/**
|
|
760
|
-
*
|
|
761
|
-
* and the specific pagination type for each service
|
|
637
|
+
* Parser for PIMS error format
|
|
762
638
|
*/
|
|
763
|
-
class
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
case PaginationType.OFFSET:
|
|
777
|
-
if (pageInfo.currentPage) {
|
|
778
|
-
cursorData.pageNumber = pageInfo.currentPage + 1;
|
|
779
|
-
}
|
|
780
|
-
break;
|
|
781
|
-
case PaginationType.TOKEN:
|
|
782
|
-
if (pageInfo.continuationToken) {
|
|
783
|
-
cursorData.continuationToken = pageInfo.continuationToken;
|
|
784
|
-
}
|
|
785
|
-
else {
|
|
786
|
-
return undefined; // No continuation token, can't continue
|
|
787
|
-
}
|
|
788
|
-
break;
|
|
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}`;
|
|
789
652
|
}
|
|
790
653
|
return {
|
|
791
|
-
|
|
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
|
|
665
|
+
};
|
|
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';
|
|
678
|
+
return {
|
|
679
|
+
message,
|
|
680
|
+
code: response?.status?.toString(),
|
|
681
|
+
details: {
|
|
682
|
+
originalResponse: errorBody
|
|
683
|
+
},
|
|
792
684
|
};
|
|
793
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
|
+
}
|
|
794
713
|
/**
|
|
795
|
-
*
|
|
714
|
+
* Parses error response body into standardized format
|
|
715
|
+
* @param response - The HTTP response object
|
|
716
|
+
* @returns Standardized error information
|
|
796
717
|
*/
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
pageNumber: pageInfo.currentPage - 1,
|
|
805
|
-
pageSize: pageInfo.pageSize,
|
|
806
|
-
};
|
|
807
|
-
previousCursor = {
|
|
808
|
-
value: encodeBase64(JSON.stringify(prevCursorData))
|
|
809
|
-
};
|
|
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);
|
|
810
725
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
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
|
+
};
|
|
815
738
|
}
|
|
816
|
-
// Determine if this pagination type supports page jumping
|
|
817
|
-
const supportsPageJump = type === PaginationType.OFFSET;
|
|
818
|
-
// Create the result object with all fields, then filter out undefined values
|
|
819
|
-
const result = filterUndefined({
|
|
820
|
-
items,
|
|
821
|
-
totalCount: pageInfo.totalCount,
|
|
822
|
-
hasNextPage: pageInfo.hasMore,
|
|
823
|
-
nextCursor: nextCursor,
|
|
824
|
-
previousCursor: previousCursor,
|
|
825
|
-
currentPage: pageInfo.currentPage,
|
|
826
|
-
totalPages,
|
|
827
|
-
supportsPageJump
|
|
828
|
-
});
|
|
829
|
-
return result;
|
|
830
739
|
}
|
|
831
740
|
}
|
|
741
|
+
// Export singleton instance
|
|
742
|
+
const errorResponseParser = new ErrorResponseParser();
|
|
832
743
|
|
|
833
744
|
/**
|
|
834
|
-
*
|
|
835
|
-
*
|
|
836
|
-
* @returns Headers object with all values converted to strings
|
|
837
|
-
*
|
|
838
|
-
* @example
|
|
839
|
-
* ```typescript
|
|
840
|
-
* // Single header
|
|
841
|
-
* const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
|
|
842
|
-
*
|
|
843
|
-
* // Multiple headers
|
|
844
|
-
* const headers = createHeaders({
|
|
845
|
-
* 'X-UIPATH-FolderKey': '1234567890',
|
|
846
|
-
* 'X-UIPATH-OrganizationUnitId': 123,
|
|
847
|
-
* 'Accept': 'application/json'
|
|
848
|
-
* });
|
|
849
|
-
*
|
|
850
|
-
* // Using constants
|
|
851
|
-
* import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
|
|
852
|
-
* const headers = createHeaders({
|
|
853
|
-
* [FOLDER_KEY]: 'abc-123',
|
|
854
|
-
* [FOLDER_ID]: 456
|
|
855
|
-
* });
|
|
856
|
-
*
|
|
857
|
-
* // Empty headers
|
|
858
|
-
* const headers = createHeaders();
|
|
859
|
-
* ```
|
|
745
|
+
* Base error class for all UiPath SDK errors
|
|
746
|
+
* Extends Error for standard error handling compatibility
|
|
860
747
|
*/
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
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);
|
|
866
759
|
}
|
|
867
760
|
}
|
|
868
|
-
|
|
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
|
+
}
|
|
869
782
|
}
|
|
870
783
|
|
|
871
784
|
/**
|
|
872
|
-
*
|
|
785
|
+
* Error thrown when authentication fails (401 errors)
|
|
786
|
+
* Common scenarios:
|
|
787
|
+
* - Invalid credentials
|
|
788
|
+
* - Expired token
|
|
789
|
+
* - Missing authentication
|
|
873
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
|
+
|
|
874
801
|
/**
|
|
875
|
-
*
|
|
802
|
+
* Error thrown when authorization fails (403 errors)
|
|
803
|
+
* Common scenarios:
|
|
804
|
+
* - Insufficient permissions
|
|
805
|
+
* - Access denied to resource
|
|
806
|
+
* - Invalid scope
|
|
876
807
|
*/
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
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
|
+
|
|
880
818
|
/**
|
|
881
|
-
*
|
|
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
|
|
882
824
|
*/
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
/** Field name for continuation token in process instance response */
|
|
893
|
-
CONTINUATION_TOKEN_FIELD: 'nextPage'
|
|
894
|
-
};
|
|
895
|
-
/**
|
|
896
|
-
* OData OFFSET pagination parameter names (ODATA-style)
|
|
897
|
-
*/
|
|
898
|
-
const ODATA_OFFSET_PARAMS = {
|
|
899
|
-
/** OData page size parameter name */
|
|
900
|
-
PAGE_SIZE_PARAM: '$top',
|
|
901
|
-
/** OData offset parameter name */
|
|
902
|
-
OFFSET_PARAM: '$skip',
|
|
903
|
-
/** OData count parameter name */
|
|
904
|
-
COUNT_PARAM: '$count'
|
|
905
|
-
};
|
|
906
|
-
/**
|
|
907
|
-
* Bucket TOKEN pagination parameter names
|
|
908
|
-
*/
|
|
909
|
-
const BUCKET_TOKEN_PARAMS = {
|
|
910
|
-
/** Bucket page size parameter name */
|
|
911
|
-
PAGE_SIZE_PARAM: 'takeHint',
|
|
912
|
-
/** Bucket token parameter name */
|
|
913
|
-
TOKEN_PARAM: 'continuationToken'
|
|
914
|
-
};
|
|
915
|
-
/**
|
|
916
|
-
* Process Instance TOKEN pagination parameter names
|
|
917
|
-
*/
|
|
918
|
-
const PROCESS_INSTANCE_TOKEN_PARAMS = {
|
|
919
|
-
/** Process instance page size parameter name */
|
|
920
|
-
PAGE_SIZE_PARAM: 'pageSize',
|
|
921
|
-
/** Process instance token parameter name */
|
|
922
|
-
TOKEN_PARAM: 'nextPage'
|
|
923
|
-
};
|
|
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
|
+
}
|
|
924
834
|
|
|
925
835
|
/**
|
|
926
|
-
*
|
|
927
|
-
*
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
*
|
|
931
|
-
* @param data The source data to transform
|
|
932
|
-
* @param fieldMapping Object mapping source field names to target field names
|
|
933
|
-
* @returns Transformed data with mapped field names
|
|
934
|
-
*
|
|
935
|
-
* @example
|
|
936
|
-
* ```typescript
|
|
937
|
-
* // Single object transformation
|
|
938
|
-
* const data = { id: '123', userName: 'john' };
|
|
939
|
-
* const mapping = { id: 'userId', userName: 'name' };
|
|
940
|
-
* const result = transformData(data, mapping);
|
|
941
|
-
* // result = { userId: '123', name: 'john' }
|
|
942
|
-
*
|
|
943
|
-
* // Array transformation
|
|
944
|
-
* const dataArray = [
|
|
945
|
-
* { id: '123', userName: 'john' },
|
|
946
|
-
* { id: '456', userName: 'jane' }
|
|
947
|
-
* ];
|
|
948
|
-
* const result = transformData(dataArray, mapping);
|
|
949
|
-
* // result = [
|
|
950
|
-
* // { userId: '123', name: 'john' },
|
|
951
|
-
* // { userId: '456', name: 'jane' }
|
|
952
|
-
* // ]
|
|
953
|
-
* ```
|
|
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
|
|
954
841
|
*/
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
|
|
963
|
-
if (sourceField in result) {
|
|
964
|
-
const value = result[sourceField];
|
|
965
|
-
delete result[sourceField];
|
|
966
|
-
result[targetField] = value;
|
|
967
|
-
}
|
|
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
|
+
});
|
|
968
849
|
}
|
|
969
|
-
return result;
|
|
970
850
|
}
|
|
851
|
+
|
|
971
852
|
/**
|
|
972
|
-
*
|
|
973
|
-
*
|
|
974
|
-
*
|
|
975
|
-
*
|
|
976
|
-
* @param prefix The prefix to add (e.g., '$')
|
|
977
|
-
* @param keys The keys to prefix (e.g., ['expand', 'filter'])
|
|
978
|
-
* @returns A new object with specified keys prefixed
|
|
979
|
-
*
|
|
980
|
-
* @example
|
|
981
|
-
* addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
|
|
853
|
+
* Error thrown when rate limit is exceeded (429 errors)
|
|
854
|
+
* Common scenarios:
|
|
855
|
+
* - Too many requests in a time window
|
|
856
|
+
* - API throttling
|
|
982
857
|
*/
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
result[key] = value;
|
|
991
|
-
}
|
|
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
|
+
});
|
|
992
865
|
}
|
|
993
|
-
return result;
|
|
994
866
|
}
|
|
995
867
|
|
|
996
868
|
/**
|
|
997
|
-
*
|
|
869
|
+
* Error thrown when server encounters an error (5xx errors)
|
|
870
|
+
* Common scenarios:
|
|
871
|
+
* - Internal server error
|
|
872
|
+
* - Service unavailable
|
|
873
|
+
* - Gateway timeout
|
|
998
874
|
*/
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
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;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
1007
893
|
/**
|
|
1008
|
-
*
|
|
1009
|
-
*
|
|
1010
|
-
*
|
|
894
|
+
* Error thrown when network/connection issues occur
|
|
895
|
+
* Common scenarios:
|
|
896
|
+
* - Connection timeout
|
|
897
|
+
* - DNS resolution failure
|
|
898
|
+
* - Network unreachable
|
|
899
|
+
* - Request aborted
|
|
1011
900
|
*/
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
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
|
+
});
|
|
1015
908
|
}
|
|
1016
|
-
return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
|
|
1017
909
|
}
|
|
1018
910
|
|
|
1019
911
|
/**
|
|
1020
|
-
*
|
|
912
|
+
* Factory for creating typed errors based on HTTP status codes
|
|
913
|
+
* Follows the Factory pattern for clean error instantiation
|
|
1021
914
|
*/
|
|
1022
|
-
class
|
|
915
|
+
class ErrorFactory {
|
|
1023
916
|
/**
|
|
1024
|
-
*
|
|
1025
|
-
*
|
|
1026
|
-
* @param options - The options object to check
|
|
1027
|
-
* @returns True if any pagination parameter is defined, false otherwise
|
|
917
|
+
* Creates appropriate error instance based on HTTP status code
|
|
1028
918
|
*/
|
|
1029
|
-
static
|
|
1030
|
-
const {
|
|
1031
|
-
|
|
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
|
+
});
|
|
944
|
+
}
|
|
1032
945
|
}
|
|
1033
946
|
/**
|
|
1034
|
-
*
|
|
947
|
+
* Creates a NetworkError from a fetch/network error
|
|
1035
948
|
*/
|
|
1036
|
-
static
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
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;
|
|
954
|
+
}
|
|
955
|
+
else if (error.message.includes('timeout')) {
|
|
956
|
+
message = ErrorMessages.REQUEST_TIMEOUT;
|
|
957
|
+
}
|
|
958
|
+
else {
|
|
959
|
+
message = error.message;
|
|
960
|
+
}
|
|
1043
961
|
}
|
|
962
|
+
return new NetworkError({ message });
|
|
963
|
+
}
|
|
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;
|
|
1044
972
|
}
|
|
1045
973
|
/**
|
|
1046
|
-
*
|
|
974
|
+
* Gets a valid authentication token, refreshing if necessary.
|
|
975
|
+
* Used internally for API requests and exposed for services that need manual auth headers.
|
|
1047
976
|
*
|
|
1048
|
-
* @
|
|
1049
|
-
* @
|
|
977
|
+
* @returns The valid token
|
|
978
|
+
* @throws AuthenticationError if no token available or refresh fails
|
|
1050
979
|
*/
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
|
|
1054
|
-
throw new Error('cursor must contain a valid cursor string');
|
|
1055
|
-
}
|
|
1056
|
-
try {
|
|
1057
|
-
// Try to parse the cursor to validate it
|
|
1058
|
-
const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
|
|
1059
|
-
// If type is provided, validate cursor contains expected type information
|
|
1060
|
-
if (paginationType) {
|
|
1061
|
-
if (!cursorData.type) {
|
|
1062
|
-
throw new Error('Invalid cursor: missing pagination type');
|
|
1063
|
-
}
|
|
1064
|
-
// Check pagination type compatibility
|
|
1065
|
-
if (cursorData.type !== paginationType) {
|
|
1066
|
-
throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
catch (error) {
|
|
1071
|
-
if (error instanceof Error) {
|
|
1072
|
-
// If it's already our error with specific message, pass it through
|
|
1073
|
-
if (error.message.startsWith('Invalid cursor') ||
|
|
1074
|
-
error.message.startsWith('Pagination type mismatch')) {
|
|
1075
|
-
throw error;
|
|
1076
|
-
}
|
|
1077
|
-
}
|
|
1078
|
-
throw new Error('Invalid pagination cursor format');
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
980
|
+
async getValidToken() {
|
|
981
|
+
return this.tokenManager.getValidToken();
|
|
1081
982
|
}
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
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'];
|
|
1093
1000
|
}
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
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
|
+
});
|
|
1097
1016
|
}
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
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);
|
|
1103
1021
|
}
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
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);
|
|
1118
1052
|
}
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
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);
|
|
1127
1060
|
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
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;
|
|
1138
1135
|
}
|
|
1139
|
-
|
|
1140
|
-
|
|
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);
|
|
1141
1186
|
}
|
|
1142
1187
|
}
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
* @param params - Parameters for pagination
|
|
1147
|
-
* @returns Promise resolving to a paginated result
|
|
1148
|
-
*/
|
|
1149
|
-
static async getAllPaginated(params) {
|
|
1150
|
-
const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
|
|
1151
|
-
const endpoint = getEndpoint(folderId);
|
|
1152
|
-
const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
|
|
1153
|
-
const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
|
|
1154
|
-
headers,
|
|
1155
|
-
params: additionalParams,
|
|
1156
|
-
pagination: {
|
|
1157
|
-
paginationType: options.paginationType || PaginationType.OFFSET,
|
|
1158
|
-
itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
|
|
1159
|
-
totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
|
|
1160
|
-
continuationTokenField: options.continuationTokenField,
|
|
1161
|
-
paginationParams: options.paginationParams
|
|
1162
|
-
}
|
|
1163
|
-
});
|
|
1164
|
-
// Parse items - automatically handle JSON string responses
|
|
1165
|
-
const rawItems = paginatedResponse.items;
|
|
1166
|
-
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1167
|
-
const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1168
|
-
return {
|
|
1169
|
-
...paginatedResponse,
|
|
1170
|
-
items: transformedItems
|
|
1171
|
-
};
|
|
1188
|
+
else {
|
|
1189
|
+
// Node.js environment
|
|
1190
|
+
bytes = new Uint8Array(Buffer.from(base64, 'base64'));
|
|
1172
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 {
|
|
1173
1202
|
/**
|
|
1174
|
-
*
|
|
1175
|
-
*
|
|
1176
|
-
* @param params - Parameters for non-paginated resource retrieval
|
|
1177
|
-
* @returns Promise resolving to an object with data and totalCount
|
|
1203
|
+
* Create a pagination cursor for subsequent page requests
|
|
1178
1204
|
*/
|
|
1179
|
-
static
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
|
|
1183
|
-
const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
|
|
1184
|
-
// Determine endpoint and headers based on folderId
|
|
1185
|
-
const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
|
|
1186
|
-
const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
|
|
1187
|
-
// Make the API call based on method
|
|
1188
|
-
let response;
|
|
1189
|
-
if (method === HTTP_METHODS.POST) {
|
|
1190
|
-
response = await serviceAccess.post(endpoint, additionalParams, { headers });
|
|
1205
|
+
static createCursor({ pageInfo, type }) {
|
|
1206
|
+
if (!pageInfo.hasMore) {
|
|
1207
|
+
return undefined;
|
|
1191
1208
|
}
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
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;
|
|
1197
1227
|
}
|
|
1198
|
-
// Extract and transform items from response
|
|
1199
|
-
// Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
|
|
1200
|
-
const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
|
|
1201
|
-
const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
|
|
1202
|
-
const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
|
|
1203
|
-
// Parse items - automatically handle JSON string responses
|
|
1204
|
-
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1205
|
-
const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1206
1228
|
return {
|
|
1207
|
-
|
|
1208
|
-
totalCount
|
|
1229
|
+
value: encodeBase64(JSON.stringify(cursorData))
|
|
1209
1230
|
};
|
|
1210
1231
|
}
|
|
1211
1232
|
/**
|
|
1212
|
-
*
|
|
1213
|
-
*
|
|
1214
|
-
* @param config - Configuration for the getAll operation
|
|
1215
|
-
* @param options - Request options including pagination parameters
|
|
1216
|
-
* @returns Promise resolving to either paginated or non-paginated response based on options
|
|
1233
|
+
* Create a paginated response with navigation cursors
|
|
1217
1234
|
*/
|
|
1218
|
-
static
|
|
1219
|
-
const
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
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
|
+
};
|
|
1227
1248
|
}
|
|
1228
|
-
//
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
// Default pagination options
|
|
1233
|
-
const paginationOptions = {
|
|
1234
|
-
paginationType: PaginationType.OFFSET,
|
|
1235
|
-
itemsField: DEFAULT_ITEMS_FIELD,
|
|
1236
|
-
totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
|
|
1237
|
-
...config.pagination
|
|
1238
|
-
};
|
|
1239
|
-
// Paginated flow
|
|
1240
|
-
if (isPaginationRequested) {
|
|
1241
|
-
return PaginationHelpers.getAllPaginated({
|
|
1242
|
-
serviceAccess: config.serviceAccess,
|
|
1243
|
-
getEndpoint: config.getEndpoint,
|
|
1244
|
-
folderId,
|
|
1245
|
-
paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
|
|
1246
|
-
additionalParams: prefixedOptions,
|
|
1247
|
-
transformFn: config.transformFn,
|
|
1248
|
-
method: config.method,
|
|
1249
|
-
options: {
|
|
1250
|
-
...paginationOptions,
|
|
1251
|
-
paginationParams: config.pagination?.paginationParams
|
|
1252
|
-
}
|
|
1253
|
-
}); // 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);
|
|
1254
1253
|
}
|
|
1255
|
-
//
|
|
1256
|
-
const
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
totalCountField: paginationOptions.totalCountField
|
|
1268
|
-
}
|
|
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
|
|
1269
1266
|
});
|
|
1267
|
+
return result;
|
|
1270
1268
|
}
|
|
1271
1269
|
}
|
|
1272
1270
|
|
|
1273
1271
|
/**
|
|
1274
|
-
*
|
|
1275
|
-
*
|
|
1276
|
-
* This class is NOT exported in the public API.
|
|
1277
|
-
* It provides a secure way to share SDK internals between
|
|
1278
|
-
* the UiPath class and service classes without exposing them publicly.
|
|
1279
|
-
*
|
|
1280
|
-
* @internal
|
|
1281
|
-
*/
|
|
1282
|
-
// Global symbol key to ensure WeakMap is shared across module instances
|
|
1283
|
-
// This prevents issues when core and service modules are bundled separately
|
|
1284
|
-
const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
|
|
1285
|
-
// Get or create the global WeakMap store
|
|
1286
|
-
const getGlobalStore = () => {
|
|
1287
|
-
const globalObj = globalThis;
|
|
1288
|
-
if (!globalObj[REGISTRY_KEY]) {
|
|
1289
|
-
globalObj[REGISTRY_KEY] = new WeakMap();
|
|
1290
|
-
}
|
|
1291
|
-
return globalObj[REGISTRY_KEY];
|
|
1292
|
-
};
|
|
1293
|
-
/**
|
|
1294
|
-
* Internal registry for SDK private components.
|
|
1295
|
-
* Uses WeakMap to prevent memory leaks - entries are automatically
|
|
1296
|
-
* garbage collected when the SDK instance is no longer referenced.
|
|
1297
|
-
*
|
|
1298
|
-
* Uses a global singleton pattern to ensure the same WeakMap is shared
|
|
1299
|
-
* across separately bundled modules (core, entities, tasks, etc.).
|
|
1300
|
-
*
|
|
1301
|
-
* @internal - Not exported in public API
|
|
1272
|
+
* Constants used throughout the pagination system
|
|
1302
1273
|
*/
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
static get(instance) {
|
|
1320
|
-
const internals = this.store.get(instance);
|
|
1321
|
-
if (!internals) {
|
|
1322
|
-
throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
|
|
1323
|
-
}
|
|
1324
|
-
return internals;
|
|
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;
|
|
1325
1290
|
}
|
|
1291
|
+
return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
|
|
1326
1292
|
}
|
|
1327
1293
|
|
|
1328
|
-
var _BaseService_apiClient;
|
|
1329
1294
|
/**
|
|
1330
|
-
*
|
|
1331
|
-
*
|
|
1332
|
-
* Provides common functionality for authentication, configuration, and API communication.
|
|
1333
|
-
* All service classes extend this base to inherit dependency injection and HTTP client access.
|
|
1334
|
-
*
|
|
1335
|
-
* This class implements the dependency injection pattern where services receive a configured
|
|
1336
|
-
* UiPath instance. The ApiClient is created internally and handles all HTTP operations
|
|
1337
|
-
* including authentication token management.
|
|
1338
|
-
*
|
|
1339
|
-
* @remarks
|
|
1340
|
-
* Service classes should extend this base and call `super(uiPath)` in their constructor.
|
|
1341
|
-
* Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
|
|
1342
|
-
*
|
|
1295
|
+
* Helper functions for pagination that can be used across services
|
|
1343
1296
|
*/
|
|
1344
|
-
class
|
|
1297
|
+
class PaginationHelpers {
|
|
1345
1298
|
/**
|
|
1346
|
-
*
|
|
1347
|
-
*
|
|
1348
|
-
* Extracts configuration, execution context, and token manager from the UiPath instance
|
|
1349
|
-
* to initialize an authenticated API client. The ApiClient handles all HTTP operations
|
|
1350
|
-
* and token management internally.
|
|
1351
|
-
*
|
|
1352
|
-
* @param instance - UiPath SDK instance providing authentication and configuration.
|
|
1353
|
-
* Services receive this via dependency injection in the modular pattern.
|
|
1354
|
-
* @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
|
|
1355
|
-
* CAS external-app auth)
|
|
1356
|
-
*
|
|
1357
|
-
* @example
|
|
1358
|
-
* ```typescript
|
|
1359
|
-
* // Services automatically call this via super()
|
|
1360
|
-
* export class EntityService extends BaseService {
|
|
1361
|
-
* constructor(instance: IUiPath) {
|
|
1362
|
-
* super(instance); // Initializes the internal ApiClient
|
|
1363
|
-
* }
|
|
1364
|
-
* }
|
|
1365
|
-
*
|
|
1366
|
-
* // Usage in modular pattern
|
|
1367
|
-
* import { UiPath } from '@uipath/uipath-typescript/core';
|
|
1368
|
-
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
1299
|
+
* Checks if any pagination parameters are provided
|
|
1369
1300
|
*
|
|
1370
|
-
*
|
|
1371
|
-
*
|
|
1372
|
-
* const entities = new Entities(sdk);
|
|
1373
|
-
* ```
|
|
1301
|
+
* @param options - The options object to check
|
|
1302
|
+
* @returns True if any pagination parameter is defined, false otherwise
|
|
1374
1303
|
*/
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
|
|
1379
|
-
__classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
|
|
1380
|
-
this.config = { folderKey };
|
|
1304
|
+
static hasPaginationParameters(options = {}) {
|
|
1305
|
+
const { cursor, pageSize, jumpToPage } = options;
|
|
1306
|
+
return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
|
|
1381
1307
|
}
|
|
1382
1308
|
/**
|
|
1383
|
-
*
|
|
1384
|
-
* Use this when you need to manually add Authorization headers (e.g., direct uploads).
|
|
1385
|
-
*
|
|
1386
|
-
* @returns Promise resolving to a valid access token string
|
|
1387
|
-
* @throws AuthenticationError if no token is available or refresh fails
|
|
1309
|
+
* Parse a pagination cursor string into cursor data
|
|
1388
1310
|
*/
|
|
1389
|
-
|
|
1390
|
-
|
|
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');
|
|
1318
|
+
}
|
|
1391
1319
|
}
|
|
1392
1320
|
/**
|
|
1393
|
-
*
|
|
1394
|
-
*
|
|
1321
|
+
* Validates cursor format and structure
|
|
1322
|
+
*
|
|
1323
|
+
* @param paginationOptions - The pagination options containing the cursor
|
|
1324
|
+
* @param paginationType - Optional pagination type to validate against
|
|
1395
1325
|
*/
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
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
|
+
}
|
|
1417
1355
|
}
|
|
1418
1356
|
}
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1357
|
+
/**
|
|
1358
|
+
* Comprehensive validation for pagination options
|
|
1359
|
+
*
|
|
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
|
|
1363
|
+
*/
|
|
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');
|
|
1422
1368
|
}
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
return { data: response };
|
|
1436
|
-
}
|
|
1437
|
-
async patch(path, data, options = {}) {
|
|
1438
|
-
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
|
|
1439
|
-
return { data: response };
|
|
1440
|
-
}
|
|
1441
|
-
async delete(path, options = {}) {
|
|
1442
|
-
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
|
|
1443
|
-
return { data: response };
|
|
1369
|
+
// Validate jumpToPage
|
|
1370
|
+
if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
|
|
1371
|
+
throw new Error('jumpToPage must be a positive number');
|
|
1372
|
+
}
|
|
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);
|
|
1444
1381
|
}
|
|
1445
1382
|
/**
|
|
1446
|
-
*
|
|
1383
|
+
* Convert a unified pagination options to service-specific parameters
|
|
1447
1384
|
*/
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
// For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
|
|
1455
|
-
if (method.toUpperCase() === 'POST') {
|
|
1456
|
-
const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
|
|
1457
|
-
options.body = {
|
|
1458
|
-
...existingBody,
|
|
1459
|
-
...options.params,
|
|
1460
|
-
...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
|
|
1461
1391
|
};
|
|
1462
|
-
|
|
1392
|
+
return filterUndefined(jumpToPageOptions);
|
|
1463
1393
|
}
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
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
|
|
1469
1400
|
};
|
|
1401
|
+
return filterUndefined(firstPageOptions);
|
|
1470
1402
|
}
|
|
1471
|
-
//
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
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,
|
|
1411
|
+
};
|
|
1412
|
+
return filterUndefined(cursorBasedOptions);
|
|
1413
|
+
}
|
|
1414
|
+
catch {
|
|
1415
|
+
throw new Error('Invalid pagination cursor');
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* Helper method for paginated resource retrieval
|
|
1420
|
+
*
|
|
1421
|
+
* @param params - Parameters for pagination
|
|
1422
|
+
* @returns Promise resolving to a paginated result
|
|
1423
|
+
*/
|
|
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
|
+
}
|
|
1478
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
|
+
};
|
|
1479
1447
|
}
|
|
1480
1448
|
/**
|
|
1481
|
-
*
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
}
|
|
1486
|
-
/**
|
|
1487
|
-
* 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
|
|
1488
1453
|
*/
|
|
1489
|
-
|
|
1490
|
-
const
|
|
1491
|
-
|
|
1492
|
-
const
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
const convertToSkip = paginationParams?.convertToSkip ?? true;
|
|
1502
|
-
requestParams[pageSizeParam] = limitedPageSize;
|
|
1503
|
-
if (convertToSkip) {
|
|
1504
|
-
if (params.pageNumber && params.pageNumber > 1) {
|
|
1505
|
-
requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
|
|
1506
|
-
}
|
|
1507
|
-
}
|
|
1508
|
-
else {
|
|
1509
|
-
requestParams[offsetParam] = params.pageNumber || 1;
|
|
1510
|
-
}
|
|
1511
|
-
{
|
|
1512
|
-
requestParams[countParam] = true;
|
|
1513
|
-
}
|
|
1514
|
-
break;
|
|
1515
|
-
case PaginationType.TOKEN:
|
|
1516
|
-
const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
|
|
1517
|
-
const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
|
|
1518
|
-
if (params.pageSize) {
|
|
1519
|
-
requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
|
|
1520
|
-
}
|
|
1521
|
-
if (params.continuationToken) {
|
|
1522
|
-
requestParams[tokenParam] = params.continuationToken;
|
|
1523
|
-
}
|
|
1524
|
-
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 });
|
|
1525
1466
|
}
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
// Extract
|
|
1533
|
-
const itemsField = fields.itemsField ||
|
|
1534
|
-
(paginationType === PaginationType.TOKEN ? 'items' : 'value');
|
|
1535
|
-
const totalCountField = fields.totalCountField || 'totalRecordCount';
|
|
1536
|
-
const continuationTokenField = fields.continuationTokenField || 'continuationToken';
|
|
1537
|
-
// 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
|
|
1538
1474
|
// Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
|
|
1539
|
-
const
|
|
1475
|
+
const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
|
|
1540
1476
|
const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
|
|
1541
1477
|
const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
const
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
continuationToken
|
|
1550
|
-
});
|
|
1551
|
-
// Create and return the page result
|
|
1552
|
-
return PaginationManager.createPaginatedResponse({
|
|
1553
|
-
pageInfo: {
|
|
1554
|
-
hasMore,
|
|
1555
|
-
totalCount,
|
|
1556
|
-
currentPage: params.pageNumber,
|
|
1557
|
-
pageSize: params.pageSize,
|
|
1558
|
-
continuationToken
|
|
1559
|
-
},
|
|
1560
|
-
type: paginationType,
|
|
1561
|
-
}, items);
|
|
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
|
+
};
|
|
1562
1485
|
}
|
|
1563
1486
|
/**
|
|
1564
|
-
*
|
|
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
|
|
1565
1492
|
*/
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
// NOTE: This code path should rarely be executed as the APIs typically return totalCount
|
|
1576
|
-
return info.itemsCount === effectivePageSize;
|
|
1577
|
-
case PaginationType.TOKEN:
|
|
1578
|
-
return !!info.continuationToken;
|
|
1579
|
-
default:
|
|
1580
|
-
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);
|
|
1581
1502
|
}
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
|
|
1609
|
-
},
|
|
1610
|
-
INCIDENTS: {
|
|
1611
|
-
GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
|
|
1612
|
-
GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
|
|
1613
|
-
GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
|
|
1614
|
-
}};
|
|
1615
|
-
|
|
1616
|
-
/**
|
|
1617
|
-
* Maestro Process Models
|
|
1618
|
-
* Model classes for Maestro processes
|
|
1619
|
-
*/
|
|
1620
|
-
/**
|
|
1621
|
-
* Creates methods for a process object
|
|
1622
|
-
*
|
|
1623
|
-
* @param processData - The process data (response from API)
|
|
1624
|
-
* @param service - The process service instance
|
|
1625
|
-
* @returns Object containing process methods
|
|
1626
|
-
*/
|
|
1627
|
-
function createProcessMethods(processData, service) {
|
|
1628
|
-
return {
|
|
1629
|
-
async getIncidents() {
|
|
1630
|
-
if (!processData.processKey)
|
|
1631
|
-
throw new Error('Process key is undefined');
|
|
1632
|
-
if (!processData.folderKey)
|
|
1633
|
-
throw new Error('Folder key is undefined');
|
|
1634
|
-
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
|
|
1635
1529
|
}
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
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
|
+
}
|
|
1648
1546
|
}
|
|
1649
1547
|
|
|
1650
1548
|
/**
|
|
1651
|
-
*
|
|
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
|
|
1652
1556
|
*/
|
|
1653
|
-
|
|
1654
|
-
|
|
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];
|
|
1655
1567
|
};
|
|
1656
1568
|
/**
|
|
1657
|
-
*
|
|
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
|
|
1658
1577
|
*/
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
/**
|
|
1664
|
-
* Helpers for fetching BPMN XML and extracting element details used to annotate responses
|
|
1665
|
-
*/
|
|
1666
|
-
class BpmnHelpers {
|
|
1667
|
-
/**
|
|
1668
|
-
* Parse BPMN XML and extract element id → {name,type} used for incidents
|
|
1669
|
-
*/
|
|
1670
|
-
static parseBpmnElementsForIncidents(bpmnXml) {
|
|
1671
|
-
const elementInfo = {};
|
|
1672
|
-
try {
|
|
1673
|
-
// Find <bpmn:...> start tags and capture the element type.
|
|
1674
|
-
// Then read 'id' and 'name' attributes from each tag.
|
|
1675
|
-
const bpmnOpenTagRegex = /<bpmn:([A-Za-z][\w.-]*)\b[^>]*>/g;
|
|
1676
|
-
for (const tagMatch of bpmnXml.matchAll(bpmnOpenTagRegex)) {
|
|
1677
|
-
const [fullTag, elementType] = tagMatch;
|
|
1678
|
-
// Extract attributes from the current tag text.
|
|
1679
|
-
const idMatch = /\bid\s*=\s*"([^"]*)"/.exec(fullTag);
|
|
1680
|
-
if (!idMatch) {
|
|
1681
|
-
continue;
|
|
1682
|
-
}
|
|
1683
|
-
const elementId = idMatch[1];
|
|
1684
|
-
const nameMatch = /\bname\s*=\s*"([^"]*)"/.exec(fullTag);
|
|
1685
|
-
const name = nameMatch ? nameMatch[1] : '';
|
|
1686
|
-
// Convert BPMN element type to human-readable format
|
|
1687
|
-
const activityType = this.formatActivityTypeForIncidents(elementType);
|
|
1688
|
-
const activityName = name || elementId;
|
|
1689
|
-
elementInfo[elementId] = {
|
|
1690
|
-
type: activityType,
|
|
1691
|
-
name: activityName
|
|
1692
|
-
};
|
|
1693
|
-
}
|
|
1694
|
-
}
|
|
1695
|
-
catch (error) {
|
|
1696
|
-
console.warn('Failed to parse BPMN XML for incidents:', error);
|
|
1697
|
-
}
|
|
1698
|
-
return elementInfo;
|
|
1578
|
+
class SDKInternalsRegistry {
|
|
1579
|
+
// Use global store to ensure sharing across module bundles
|
|
1580
|
+
static get store() {
|
|
1581
|
+
return getGlobalStore();
|
|
1699
1582
|
}
|
|
1700
1583
|
/**
|
|
1701
|
-
*
|
|
1584
|
+
* Register SDK instance internals
|
|
1585
|
+
* Called by UiPath constructor
|
|
1702
1586
|
*/
|
|
1703
|
-
static
|
|
1704
|
-
|
|
1705
|
-
// e.g., "serviceTask" -> "Service Task", "exclusiveGateway" -> "Exclusive Gateway"
|
|
1706
|
-
return elementType
|
|
1707
|
-
.replace(/([A-Z])/g, ' $1') // Add space before uppercase letters
|
|
1708
|
-
.replace(/^./, str => str.toUpperCase()) // Capitalize first letter
|
|
1709
|
-
.trim(); // Remove any leading/trailing spaces
|
|
1587
|
+
static set(instance, internals) {
|
|
1588
|
+
this.store.set(instance, internals);
|
|
1710
1589
|
}
|
|
1711
1590
|
/**
|
|
1712
|
-
*
|
|
1591
|
+
* Retrieve SDK instance internals
|
|
1592
|
+
* Called by BaseService constructor
|
|
1713
1593
|
*/
|
|
1714
|
-
static
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
// Single instance optimization (in case of process instance incidents)
|
|
1719
|
-
const elementInfo = await this.getBpmnElementInfo(uniqueInstanceIds[0], folderKey, service);
|
|
1720
|
-
return incidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
|
|
1721
|
-
}
|
|
1722
|
-
else {
|
|
1723
|
-
// Multiple instances optimization (in case of process incidents)
|
|
1724
|
-
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.');
|
|
1725
1598
|
}
|
|
1599
|
+
return internals;
|
|
1726
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 {
|
|
1727
1620
|
/**
|
|
1728
|
-
*
|
|
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
|
+
* ```
|
|
1729
1649
|
*/
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
const results = await Promise.all(Object.entries(groups).map(async (entry) => {
|
|
1737
|
-
const [instanceId, groupIncidents] = entry;
|
|
1738
|
-
const elementInfo = await this.getBpmnElementInfo(instanceId, folderKey, service);
|
|
1739
|
-
return groupIncidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
|
|
1740
|
-
}));
|
|
1741
|
-
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 };
|
|
1742
1656
|
}
|
|
1743
1657
|
/**
|
|
1744
|
-
*
|
|
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
|
|
1745
1663
|
*/
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
return {};
|
|
1749
|
-
}
|
|
1750
|
-
try {
|
|
1751
|
-
const bpmnXml = await service.getBpmn(instanceId, folderKey);
|
|
1752
|
-
return this.parseBpmnElementsForIncidents(bpmnXml);
|
|
1753
|
-
}
|
|
1754
|
-
catch (error) {
|
|
1755
|
-
console.warn(`Failed to get BPMN for instance ${instanceId}:`, error);
|
|
1756
|
-
return {};
|
|
1757
|
-
}
|
|
1664
|
+
async getValidAuthToken() {
|
|
1665
|
+
return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
|
|
1758
1666
|
}
|
|
1759
1667
|
/**
|
|
1760
|
-
*
|
|
1668
|
+
* Creates a service accessor for pagination helpers
|
|
1669
|
+
* This allows pagination helpers to access protected methods without making them public
|
|
1761
1670
|
*/
|
|
1762
|
-
|
|
1763
|
-
const element = elementInfo[incident.elementId];
|
|
1764
|
-
const transformed = transformData(incident, ProcessIncidentMap);
|
|
1671
|
+
createPaginationServiceAccess() {
|
|
1765
1672
|
return {
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
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)
|
|
1769
1676
|
};
|
|
1770
1677
|
}
|
|
1771
|
-
}
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
const CLOUD_CLIENT_ID = "CloudClientId";
|
|
1786
|
-
const CLOUD_REDIRECT_URI = "CloudRedirectUri";
|
|
1787
|
-
const APP_NAME = "ApplicationName";
|
|
1788
|
-
const CLOUD_ROLE_NAME = "uipath-ts-sdk";
|
|
1789
|
-
// Service and logger names
|
|
1790
|
-
const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
|
|
1791
|
-
const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
|
|
1792
|
-
// Event names
|
|
1793
|
-
const SDK_RUN_EVENT = "Sdk.Run";
|
|
1794
|
-
// Default value for unknown/empty attributes
|
|
1795
|
-
const UNKNOWN = "";
|
|
1796
|
-
|
|
1797
|
-
/**
|
|
1798
|
-
* Log exporter that sends ALL logs as Application Insights custom events
|
|
1799
|
-
*/
|
|
1800
|
-
class ApplicationInsightsEventExporter {
|
|
1801
|
-
constructor(connectionString) {
|
|
1802
|
-
this.connectionString = connectionString;
|
|
1803
|
-
}
|
|
1804
|
-
export(logs, resultCallback) {
|
|
1805
|
-
try {
|
|
1806
|
-
logs.forEach(logRecord => {
|
|
1807
|
-
this.sendAsCustomEvent(logRecord);
|
|
1808
|
-
});
|
|
1809
|
-
resultCallback({ code: 0 });
|
|
1810
|
-
}
|
|
1811
|
-
catch (error) {
|
|
1812
|
-
console.debug('Failed to export logs to Application Insights:', error);
|
|
1813
|
-
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}`);
|
|
1814
1692
|
}
|
|
1815
1693
|
}
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
const eventName = logRecord.body || SDK_RUN_EVENT;
|
|
1822
|
-
const payload = {
|
|
1823
|
-
name: 'Microsoft.ApplicationInsights.Event',
|
|
1824
|
-
time: new Date().toISOString(),
|
|
1825
|
-
iKey: this.extractInstrumentationKey(),
|
|
1826
|
-
data: {
|
|
1827
|
-
baseType: 'EventData',
|
|
1828
|
-
baseData: {
|
|
1829
|
-
ver: 2,
|
|
1830
|
-
name: eventName,
|
|
1831
|
-
properties: this.convertAttributesToProperties(logRecord.attributes || {})
|
|
1832
|
-
}
|
|
1833
|
-
},
|
|
1834
|
-
tags: {
|
|
1835
|
-
'ai.cloud.role': CLOUD_ROLE_NAME,
|
|
1836
|
-
'ai.cloud.roleInstance': SDK_VERSION
|
|
1837
|
-
}
|
|
1838
|
-
};
|
|
1839
|
-
this.sendToApplicationInsights(payload);
|
|
1840
|
-
}
|
|
1841
|
-
extractInstrumentationKey() {
|
|
1842
|
-
const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
|
|
1843
|
-
return match ? match[1] : '';
|
|
1694
|
+
async requestWithSpec(spec) {
|
|
1695
|
+
if (!spec.method || !spec.url) {
|
|
1696
|
+
throw new Error('Request spec must include method and url');
|
|
1697
|
+
}
|
|
1698
|
+
return this.request(spec.method, spec.url, spec);
|
|
1844
1699
|
}
|
|
1845
|
-
|
|
1846
|
-
const
|
|
1847
|
-
|
|
1848
|
-
properties[key] = String(value);
|
|
1849
|
-
});
|
|
1850
|
-
return properties;
|
|
1700
|
+
async get(path, options = {}) {
|
|
1701
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
|
|
1702
|
+
return { data: response };
|
|
1851
1703
|
}
|
|
1852
|
-
async
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
if (!ingestionEndpoint) {
|
|
1856
|
-
console.debug('No ingestion endpoint found in connection string');
|
|
1857
|
-
return;
|
|
1858
|
-
}
|
|
1859
|
-
const url = `${ingestionEndpoint}/v2/track`;
|
|
1860
|
-
const response = await fetch(url, {
|
|
1861
|
-
method: 'POST',
|
|
1862
|
-
headers: {
|
|
1863
|
-
'Content-Type': 'application/json',
|
|
1864
|
-
},
|
|
1865
|
-
body: JSON.stringify(payload)
|
|
1866
|
-
});
|
|
1867
|
-
if (!response.ok) {
|
|
1868
|
-
console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
|
|
1869
|
-
}
|
|
1870
|
-
}
|
|
1871
|
-
catch (error) {
|
|
1872
|
-
console.debug('Error sending event telemetry to Application Insights:', error);
|
|
1873
|
-
}
|
|
1704
|
+
async post(path, data, options = {}) {
|
|
1705
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
|
|
1706
|
+
return { data: response };
|
|
1874
1707
|
}
|
|
1875
|
-
|
|
1876
|
-
const
|
|
1877
|
-
return
|
|
1708
|
+
async put(path, data, options = {}) {
|
|
1709
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
|
|
1710
|
+
return { data: response };
|
|
1878
1711
|
}
|
|
1879
|
-
}
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
*/
|
|
1883
|
-
class TelemetryClient {
|
|
1884
|
-
constructor() {
|
|
1885
|
-
this.isInitialized = false;
|
|
1712
|
+
async patch(path, data, options = {}) {
|
|
1713
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
|
|
1714
|
+
return { data: response };
|
|
1886
1715
|
}
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
}
|
|
1891
|
-
return TelemetryClient.instance;
|
|
1716
|
+
async delete(path, options = {}) {
|
|
1717
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
|
|
1718
|
+
return { data: response };
|
|
1892
1719
|
}
|
|
1893
1720
|
/**
|
|
1894
|
-
*
|
|
1721
|
+
* Execute a request with cursor-based pagination
|
|
1895
1722
|
*/
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
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;
|
|
1910
1738
|
}
|
|
1911
|
-
|
|
1912
|
-
//
|
|
1913
|
-
|
|
1739
|
+
else {
|
|
1740
|
+
// Merge pagination parameters with existing parameters
|
|
1741
|
+
options.params = {
|
|
1742
|
+
...options.params,
|
|
1743
|
+
...requestParams
|
|
1744
|
+
};
|
|
1914
1745
|
}
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
return
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
const processor = new BatchLogRecordProcessor(exporter);
|
|
1923
|
-
this.logProvider = new LoggerProvider({
|
|
1924
|
-
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
|
|
1925
1753
|
});
|
|
1926
|
-
this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
|
|
1927
1754
|
}
|
|
1928
1755
|
/**
|
|
1929
|
-
*
|
|
1756
|
+
* Validates and prepares pagination parameters from options
|
|
1930
1757
|
*/
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
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;
|
|
1949
1800
|
}
|
|
1801
|
+
return requestParams;
|
|
1950
1802
|
}
|
|
1951
1803
|
/**
|
|
1952
|
-
*
|
|
1804
|
+
* Creates a paginated response from API response
|
|
1953
1805
|
*/
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
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);
|
|
1967
1837
|
}
|
|
1968
1838
|
/**
|
|
1969
|
-
*
|
|
1839
|
+
* Determines if there are more pages based on pagination type and metadata
|
|
1970
1840
|
*/
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
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;
|
|
1977
1856
|
}
|
|
1978
|
-
return `${baseUrl}/${orgId}/${tenantId}`;
|
|
1979
1857
|
}
|
|
1980
1858
|
}
|
|
1981
|
-
|
|
1982
|
-
const telemetryClient = TelemetryClient.getInstance();
|
|
1983
|
-
|
|
1984
|
-
/**
|
|
1985
|
-
* SDK Track decorator and function for telemetry
|
|
1986
|
-
*/
|
|
1987
|
-
/**
|
|
1988
|
-
* Common tracking logic shared between method and function decorators
|
|
1989
|
-
*/
|
|
1990
|
-
function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
|
|
1991
|
-
return function (...args) {
|
|
1992
|
-
// Determine if we should track this call
|
|
1993
|
-
let shouldTrack = true;
|
|
1994
|
-
if (opts.condition !== undefined) {
|
|
1995
|
-
if (typeof opts.condition === 'function') {
|
|
1996
|
-
shouldTrack = opts.condition.apply(this, args);
|
|
1997
|
-
}
|
|
1998
|
-
else {
|
|
1999
|
-
shouldTrack = opts.condition;
|
|
2000
|
-
}
|
|
2001
|
-
}
|
|
2002
|
-
// Track the event if enabled
|
|
2003
|
-
if (shouldTrack) {
|
|
2004
|
-
// Use the full name provided in the decorator (e.g., "Queue.GetAll")
|
|
2005
|
-
const serviceMethod = typeof nameOrOptions === 'string'
|
|
2006
|
-
? nameOrOptions
|
|
2007
|
-
: fallbackName;
|
|
2008
|
-
// Use 'Sdk.Run' as the name and serviceMethod as the service
|
|
2009
|
-
telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
|
|
2010
|
-
}
|
|
2011
|
-
// Execute the original function
|
|
2012
|
-
return originalFunction.apply(this, args);
|
|
2013
|
-
};
|
|
2014
|
-
}
|
|
2015
|
-
/**
|
|
2016
|
-
* Track decorator that can be used to automatically track function calls
|
|
2017
|
-
*
|
|
2018
|
-
* Usage:
|
|
2019
|
-
* @track("Service.Method")
|
|
2020
|
-
* function myFunction() { ... }
|
|
2021
|
-
*
|
|
2022
|
-
* @track("Queue.GetAll")
|
|
2023
|
-
* async getAll() { ... }
|
|
2024
|
-
*
|
|
2025
|
-
* @track("Tasks.Create")
|
|
2026
|
-
* async create() { ... }
|
|
2027
|
-
*
|
|
2028
|
-
* @track("Assets.Update", { condition: false })
|
|
2029
|
-
* function myFunction() { ... }
|
|
2030
|
-
*
|
|
2031
|
-
* @track("Processes.Start", { attributes: { customProp: "value" } })
|
|
2032
|
-
* function myFunction() { ... }
|
|
2033
|
-
*/
|
|
2034
|
-
function track(nameOrOptions, options) {
|
|
2035
|
-
return function decorator(_target, propertyKey, descriptor) {
|
|
2036
|
-
const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
|
|
2037
|
-
if (descriptor && typeof descriptor.value === 'function') {
|
|
2038
|
-
// Method decorator
|
|
2039
|
-
descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
|
|
2040
|
-
return descriptor;
|
|
2041
|
-
}
|
|
2042
|
-
// Function decorator
|
|
2043
|
-
return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
|
|
2044
|
-
};
|
|
2045
|
-
}
|
|
1859
|
+
_BaseService_apiClient = new WeakMap();
|
|
2046
1860
|
|
|
2047
1861
|
/**
|
|
2048
1862
|
* Creates methods for a process instance
|
|
@@ -2237,6 +2051,40 @@ var SLADurationUnit;
|
|
|
2237
2051
|
SLADurationUnit["MONTHS"] = "m";
|
|
2238
2052
|
})(SLADurationUnit || (SLADurationUnit = {}));
|
|
2239
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
|
+
|
|
2240
2088
|
/**
|
|
2241
2089
|
* Maps fields for Process Instance entities to ensure consistent naming
|
|
2242
2090
|
*/
|
|
@@ -2612,6 +2460,177 @@ class MaestroProcessesService extends BaseService {
|
|
|
2612
2460
|
// Fetch BPMN XML and add element name/type to each incident
|
|
2613
2461
|
return BpmnHelpers.enrichIncidentsWithBpmnData(rawResponse.data || [], folderKey, this.processInstancesService);
|
|
2614
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
|
+
}
|
|
2615
2634
|
}
|
|
2616
2635
|
__decorate([
|
|
2617
2636
|
track('MaestroProcesses.GetAll')
|
|
@@ -2619,6 +2638,18 @@ __decorate([
|
|
|
2619
2638
|
__decorate([
|
|
2620
2639
|
track('MaestroProcesses.GetIncidents')
|
|
2621
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);
|
|
2622
2653
|
|
|
2623
2654
|
/**
|
|
2624
2655
|
* Service class for Maestro Process Incidents
|
|
@@ -2656,4 +2687,4 @@ __decorate([
|
|
|
2656
2687
|
track('ProcessIncidents.getAll')
|
|
2657
2688
|
], ProcessIncidentsService.prototype, "getAll", null);
|
|
2658
2689
|
|
|
2659
|
-
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 };
|