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