@uipath/uipath-typescript 1.3.10 → 1.4.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/agent-memory/index.cjs +1765 -0
- package/dist/agent-memory/index.d.ts +588 -0
- package/dist/agent-memory/index.mjs +1763 -0
- package/dist/agents/index.cjs +1726 -0
- package/dist/agents/index.d.ts +502 -0
- package/dist/agents/index.mjs +1724 -0
- package/dist/assets/index.cjs +155 -30
- package/dist/assets/index.d.ts +84 -5
- package/dist/assets/index.mjs +155 -30
- package/dist/attachments/index.cjs +37 -6
- package/dist/attachments/index.d.ts +1 -0
- package/dist/attachments/index.mjs +37 -6
- package/dist/buckets/index.cjs +37 -6
- package/dist/buckets/index.d.ts +1 -0
- package/dist/buckets/index.mjs +37 -6
- package/dist/cases/index.cjs +192 -10
- package/dist/cases/index.d.ts +208 -7
- package/dist/cases/index.mjs +192 -11
- package/dist/conversational-agent/index.cjs +124 -57
- package/dist/conversational-agent/index.d.ts +190 -122
- package/dist/conversational-agent/index.mjs +124 -57
- package/dist/core/index.cjs +413 -105
- package/dist/core/index.d.ts +15 -0
- package/dist/core/index.mjs +413 -105
- package/dist/entities/index.cjs +135 -70
- package/dist/entities/index.d.ts +146 -45
- package/dist/entities/index.mjs +135 -70
- package/dist/feedback/index.cjs +37 -6
- package/dist/feedback/index.d.ts +1 -0
- package/dist/feedback/index.mjs +37 -6
- package/dist/governance/index.cjs +1782 -0
- package/dist/governance/index.d.ts +598 -0
- package/dist/governance/index.mjs +1780 -0
- package/dist/index.cjs +1050 -291
- package/dist/index.d.ts +1313 -134
- package/dist/index.mjs +1050 -292
- package/dist/index.umd.js +4546 -3770
- package/dist/jobs/index.cjs +37 -6
- package/dist/jobs/index.d.ts +1 -0
- package/dist/jobs/index.mjs +37 -6
- package/dist/maestro-processes/index.cjs +224 -18
- package/dist/maestro-processes/index.d.ts +221 -9
- package/dist/maestro-processes/index.mjs +224 -18
- package/dist/processes/index.cjs +37 -6
- package/dist/processes/index.d.ts +1 -0
- package/dist/processes/index.mjs +37 -6
- package/dist/queues/index.cjs +37 -6
- package/dist/queues/index.d.ts +1 -0
- package/dist/queues/index.mjs +37 -6
- package/dist/tasks/index.cjs +37 -6
- package/dist/tasks/index.d.ts +1 -0
- package/dist/tasks/index.mjs +37 -6
- package/dist/traces/index.cjs +1933 -0
- package/dist/traces/index.d.ts +566 -0
- package/dist/traces/index.mjs +1931 -0
- package/package.json +42 -2
|
@@ -0,0 +1,1931 @@
|
|
|
1
|
+
import { getOrCreateClient, createTrack, createTrackEvent } from '@uipath/core-telemetry';
|
|
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
|
+
const TRACEPARENT = 'traceparent';
|
|
508
|
+
const UIPATH_TRACEPARENT_ID = 'x-uipath-traceparent-id';
|
|
509
|
+
/**
|
|
510
|
+
* Content type constants for HTTP requests/responses
|
|
511
|
+
*/
|
|
512
|
+
const CONTENT_TYPES = {
|
|
513
|
+
JSON: 'application/json',
|
|
514
|
+
XML: 'application/xml',
|
|
515
|
+
OCTET_STREAM: 'application/octet-stream'
|
|
516
|
+
};
|
|
517
|
+
/**
|
|
518
|
+
* Response type constants for HTTP requests
|
|
519
|
+
*/
|
|
520
|
+
const RESPONSE_TYPES = {
|
|
521
|
+
JSON: 'json',
|
|
522
|
+
TEXT: 'text',
|
|
523
|
+
BLOB: 'blob',
|
|
524
|
+
ARRAYBUFFER: 'arraybuffer'
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
class ApiClient {
|
|
528
|
+
constructor(config, executionContext, tokenManager, clientConfig = {}) {
|
|
529
|
+
this.config = config;
|
|
530
|
+
this.executionContext = executionContext;
|
|
531
|
+
this.clientConfig = clientConfig;
|
|
532
|
+
this.tokenManager = tokenManager;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Gets a valid authentication token, refreshing if necessary.
|
|
536
|
+
* Used internally for API requests and exposed for services that need manual auth headers.
|
|
537
|
+
*
|
|
538
|
+
* @returns The valid token
|
|
539
|
+
* @throws AuthenticationError if no token available or refresh fails
|
|
540
|
+
*/
|
|
541
|
+
async getValidToken() {
|
|
542
|
+
return this.tokenManager.getValidToken();
|
|
543
|
+
}
|
|
544
|
+
async getDefaultHeaders() {
|
|
545
|
+
const token = await this.getValidToken();
|
|
546
|
+
return {
|
|
547
|
+
'Authorization': `Bearer ${token}`,
|
|
548
|
+
'Content-Type': CONTENT_TYPES.JSON,
|
|
549
|
+
...this.clientConfig.headers
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
async request(method, path, options = {}) {
|
|
553
|
+
// Ensure path starts with a forward slash
|
|
554
|
+
const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
|
|
555
|
+
// Construct URL with org and tenant names
|
|
556
|
+
const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
|
|
557
|
+
const isFormData = options.body instanceof FormData;
|
|
558
|
+
const defaultHeaders = await this.getDefaultHeaders();
|
|
559
|
+
if (isFormData) {
|
|
560
|
+
delete defaultHeaders['Content-Type'];
|
|
561
|
+
}
|
|
562
|
+
const traceId = crypto.randomUUID().replace(/-/g, '');
|
|
563
|
+
const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
|
|
564
|
+
const traceparentValue = `00-${traceId}-${spanId}-01`;
|
|
565
|
+
const headers = {
|
|
566
|
+
...defaultHeaders,
|
|
567
|
+
[TRACEPARENT]: traceparentValue,
|
|
568
|
+
[UIPATH_TRACEPARENT_ID]: traceparentValue,
|
|
569
|
+
...options.headers
|
|
570
|
+
};
|
|
571
|
+
// Convert params to URLSearchParams
|
|
572
|
+
const searchParams = new URLSearchParams();
|
|
573
|
+
if (options.params) {
|
|
574
|
+
Object.entries(options.params).forEach(([key, value]) => {
|
|
575
|
+
searchParams.append(key, value.toString());
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
|
|
579
|
+
let body = undefined;
|
|
580
|
+
if (options.body) {
|
|
581
|
+
body = isFormData ? options.body : JSON.stringify(options.body);
|
|
582
|
+
}
|
|
583
|
+
try {
|
|
584
|
+
const response = await fetch(fullUrl, {
|
|
585
|
+
method,
|
|
586
|
+
headers,
|
|
587
|
+
body,
|
|
588
|
+
signal: options.signal
|
|
589
|
+
});
|
|
590
|
+
if (!response.ok) {
|
|
591
|
+
const errorInfo = await errorResponseParser.parse(response);
|
|
592
|
+
throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
|
|
593
|
+
}
|
|
594
|
+
if (response.status === 204) {
|
|
595
|
+
return undefined;
|
|
596
|
+
}
|
|
597
|
+
// Handle blob response type for binary data (e.g., file downloads)
|
|
598
|
+
if (options.responseType === RESPONSE_TYPES.BLOB) {
|
|
599
|
+
const blob = await response.blob();
|
|
600
|
+
return blob;
|
|
601
|
+
}
|
|
602
|
+
// Check if we're expecting XML
|
|
603
|
+
const acceptHeader = headers['Accept'] || headers['accept'];
|
|
604
|
+
if (acceptHeader === CONTENT_TYPES.XML) {
|
|
605
|
+
const text = await response.text();
|
|
606
|
+
return text;
|
|
607
|
+
}
|
|
608
|
+
const text = await response.text();
|
|
609
|
+
if (!text) {
|
|
610
|
+
return undefined;
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
return JSON.parse(text);
|
|
614
|
+
}
|
|
615
|
+
catch (error) {
|
|
616
|
+
if (error instanceof SyntaxError) {
|
|
617
|
+
throw new ServerError({
|
|
618
|
+
message: `Server returned non-JSON response (${response.status} ${response.url}): ${error.message}`,
|
|
619
|
+
statusCode: response.status,
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
throw error;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
catch (error) {
|
|
626
|
+
// If it's already one of our errors, re-throw it
|
|
627
|
+
if (error.type && error.type.includes('Error')) {
|
|
628
|
+
throw error;
|
|
629
|
+
}
|
|
630
|
+
// Otherwise, it's a genuine network/fetch failure
|
|
631
|
+
throw ErrorFactory.createNetworkError(error);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
async get(path, options = {}) {
|
|
635
|
+
return this.request('GET', path, options);
|
|
636
|
+
}
|
|
637
|
+
async post(path, data, options = {}) {
|
|
638
|
+
return this.request('POST', path, { ...options, body: data });
|
|
639
|
+
}
|
|
640
|
+
async put(path, data, options = {}) {
|
|
641
|
+
return this.request('PUT', path, { ...options, body: data });
|
|
642
|
+
}
|
|
643
|
+
async patch(path, data, options = {}) {
|
|
644
|
+
return this.request('PATCH', path, { ...options, body: data });
|
|
645
|
+
}
|
|
646
|
+
async delete(path, options = {}) {
|
|
647
|
+
return this.request('DELETE', path, options);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Pagination types supported by the SDK
|
|
653
|
+
*/
|
|
654
|
+
var PaginationType;
|
|
655
|
+
(function (PaginationType) {
|
|
656
|
+
PaginationType["OFFSET"] = "offset";
|
|
657
|
+
PaginationType["TOKEN"] = "token";
|
|
658
|
+
})(PaginationType || (PaginationType = {}));
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Collection of utility functions for working with objects
|
|
662
|
+
*/
|
|
663
|
+
/**
|
|
664
|
+
* Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
|
|
665
|
+
* and dot-separated nested paths (e.g., 'pagination.totalCount').
|
|
666
|
+
* Direct key match takes priority over nested traversal.
|
|
667
|
+
*/
|
|
668
|
+
function resolveNestedField(data, fieldPath) {
|
|
669
|
+
if (!data) {
|
|
670
|
+
return undefined;
|
|
671
|
+
}
|
|
672
|
+
if (fieldPath in data) {
|
|
673
|
+
return data[fieldPath];
|
|
674
|
+
}
|
|
675
|
+
if (!fieldPath.includes('.')) {
|
|
676
|
+
return undefined;
|
|
677
|
+
}
|
|
678
|
+
let value = data;
|
|
679
|
+
for (const part of fieldPath.split('.')) {
|
|
680
|
+
value = value?.[part];
|
|
681
|
+
}
|
|
682
|
+
return value;
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Filters out undefined values from an object
|
|
686
|
+
* @param obj The source object
|
|
687
|
+
* @returns A new object without undefined values
|
|
688
|
+
*
|
|
689
|
+
* @example
|
|
690
|
+
* ```typescript
|
|
691
|
+
* // Object with undefined values
|
|
692
|
+
* const options = {
|
|
693
|
+
* name: 'test',
|
|
694
|
+
* count: 5,
|
|
695
|
+
* prefix: undefined,
|
|
696
|
+
* suffix: null
|
|
697
|
+
* };
|
|
698
|
+
* const result = filterUndefined(options);
|
|
699
|
+
* // result = { name: 'test', count: 5, suffix: null }
|
|
700
|
+
* ```
|
|
701
|
+
*/
|
|
702
|
+
function filterUndefined(obj) {
|
|
703
|
+
const result = {};
|
|
704
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
705
|
+
if (value !== undefined) {
|
|
706
|
+
result[key] = value;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return result;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* Utility functions for platform detection
|
|
714
|
+
*/
|
|
715
|
+
/**
|
|
716
|
+
* Checks if code is running in a browser environment
|
|
717
|
+
*/
|
|
718
|
+
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
719
|
+
isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
|
|
720
|
+
const _params = isBrowser ? new URLSearchParams(window.location.search) : null;
|
|
721
|
+
/**
|
|
722
|
+
* True when the coded app has been loaded inside a host frame that explicitly
|
|
723
|
+
* opted into token delegation by adding `?host=embed` to the iframe src URL.
|
|
724
|
+
*/
|
|
725
|
+
const isHostEmbedded = isBrowser && window.self !== window.top && _params?.get('host') === 'embed';
|
|
726
|
+
/**
|
|
727
|
+
* The validated parent origin, read from the `?basedomain=` query param set
|
|
728
|
+
* by the embedding host in the iframe src URL.
|
|
729
|
+
* Mirrors the same mechanism used by ActionCenterTokenManager.
|
|
730
|
+
* Non-null only when `?host=embed` is present and `?basedomain=` is a valid URL.
|
|
731
|
+
*/
|
|
732
|
+
(() => {
|
|
733
|
+
if (!isHostEmbedded)
|
|
734
|
+
return null;
|
|
735
|
+
const basedomain = _params?.get('basedomain');
|
|
736
|
+
if (!basedomain)
|
|
737
|
+
return null;
|
|
738
|
+
try {
|
|
739
|
+
return new URL(basedomain).origin;
|
|
740
|
+
}
|
|
741
|
+
catch {
|
|
742
|
+
console.warn('embeddingOrigin: basedomain query param is not a valid URL', basedomain);
|
|
743
|
+
return null;
|
|
744
|
+
}
|
|
745
|
+
})();
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* Base64 encoding/decoding
|
|
749
|
+
*/
|
|
750
|
+
/**
|
|
751
|
+
* Encodes a string to base64
|
|
752
|
+
* @param str - The string to encode
|
|
753
|
+
* @returns Base64 encoded string
|
|
754
|
+
*/
|
|
755
|
+
function encodeBase64(str) {
|
|
756
|
+
// TextEncoder for UTF-8 encoding (works in both browser and Node.js)
|
|
757
|
+
const encoder = new TextEncoder();
|
|
758
|
+
const data = encoder.encode(str);
|
|
759
|
+
// Convert Uint8Array to base64
|
|
760
|
+
if (isBrowser) {
|
|
761
|
+
// Browser environment
|
|
762
|
+
// Convert Uint8Array to binary string then to base64
|
|
763
|
+
const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
|
|
764
|
+
return btoa(binaryString);
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
// Node.js environment
|
|
768
|
+
return Buffer.from(data).toString('base64');
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Decodes a base64 string
|
|
773
|
+
* @param base64 - The base64 string to decode
|
|
774
|
+
* @returns Decoded string
|
|
775
|
+
*/
|
|
776
|
+
function decodeBase64(base64) {
|
|
777
|
+
let bytes;
|
|
778
|
+
if (isBrowser) {
|
|
779
|
+
// Browser environment
|
|
780
|
+
const binaryString = atob(base64);
|
|
781
|
+
bytes = new Uint8Array(binaryString.length);
|
|
782
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
783
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
else {
|
|
787
|
+
// Node.js environment
|
|
788
|
+
bytes = new Uint8Array(Buffer.from(base64, 'base64'));
|
|
789
|
+
}
|
|
790
|
+
// TextDecoder for UTF-8 decoding (works in both browser and Node.js)
|
|
791
|
+
const decoder = new TextDecoder();
|
|
792
|
+
return decoder.decode(bytes);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* PaginationManager handles the conversion between uniform cursor-based pagination
|
|
797
|
+
* and the specific pagination type for each service
|
|
798
|
+
*/
|
|
799
|
+
class PaginationManager {
|
|
800
|
+
/**
|
|
801
|
+
* Create a pagination cursor for subsequent page requests
|
|
802
|
+
*/
|
|
803
|
+
static createCursor({ pageInfo, type }) {
|
|
804
|
+
if (!pageInfo.hasMore) {
|
|
805
|
+
return undefined;
|
|
806
|
+
}
|
|
807
|
+
const cursorData = {
|
|
808
|
+
type,
|
|
809
|
+
pageSize: pageInfo.pageSize,
|
|
810
|
+
};
|
|
811
|
+
switch (type) {
|
|
812
|
+
case PaginationType.OFFSET:
|
|
813
|
+
if (pageInfo.currentPage) {
|
|
814
|
+
cursorData.pageNumber = pageInfo.currentPage + 1;
|
|
815
|
+
}
|
|
816
|
+
break;
|
|
817
|
+
case PaginationType.TOKEN:
|
|
818
|
+
if (pageInfo.continuationToken) {
|
|
819
|
+
cursorData.continuationToken = pageInfo.continuationToken;
|
|
820
|
+
}
|
|
821
|
+
else {
|
|
822
|
+
return undefined; // No continuation token, can't continue
|
|
823
|
+
}
|
|
824
|
+
break;
|
|
825
|
+
}
|
|
826
|
+
return {
|
|
827
|
+
value: encodeBase64(JSON.stringify(cursorData))
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Create a paginated response with navigation cursors
|
|
832
|
+
*/
|
|
833
|
+
static createPaginatedResponse({ pageInfo, type }, items) {
|
|
834
|
+
const nextCursor = PaginationManager.createCursor({ pageInfo, type });
|
|
835
|
+
// Create previous page cursor if applicable
|
|
836
|
+
let previousCursor = undefined;
|
|
837
|
+
if (pageInfo.currentPage && pageInfo.currentPage > 1) {
|
|
838
|
+
const prevCursorData = {
|
|
839
|
+
type,
|
|
840
|
+
pageNumber: pageInfo.currentPage - 1,
|
|
841
|
+
pageSize: pageInfo.pageSize,
|
|
842
|
+
};
|
|
843
|
+
previousCursor = {
|
|
844
|
+
value: encodeBase64(JSON.stringify(prevCursorData))
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
// Calculate total pages if we have totalCount and pageSize
|
|
848
|
+
let totalPages = undefined;
|
|
849
|
+
if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
|
|
850
|
+
totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
|
|
851
|
+
}
|
|
852
|
+
// Determine if this pagination type supports page jumping
|
|
853
|
+
const supportsPageJump = type === PaginationType.OFFSET;
|
|
854
|
+
// Create the result object with all fields, then filter out undefined values
|
|
855
|
+
const result = filterUndefined({
|
|
856
|
+
items,
|
|
857
|
+
totalCount: pageInfo.totalCount,
|
|
858
|
+
hasNextPage: pageInfo.hasMore,
|
|
859
|
+
nextCursor: nextCursor,
|
|
860
|
+
previousCursor: previousCursor,
|
|
861
|
+
currentPage: pageInfo.currentPage,
|
|
862
|
+
totalPages,
|
|
863
|
+
supportsPageJump
|
|
864
|
+
});
|
|
865
|
+
return result;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* Creates headers object from key-value pairs
|
|
871
|
+
* @param headersObj - Object containing header key-value pairs
|
|
872
|
+
* @returns Headers object with all values converted to strings
|
|
873
|
+
*
|
|
874
|
+
* @example
|
|
875
|
+
* ```typescript
|
|
876
|
+
* // Single header
|
|
877
|
+
* const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
|
|
878
|
+
*
|
|
879
|
+
* // Multiple headers
|
|
880
|
+
* const headers = createHeaders({
|
|
881
|
+
* 'X-UIPATH-FolderKey': '1234567890',
|
|
882
|
+
* 'X-UIPATH-OrganizationUnitId': 123,
|
|
883
|
+
* 'Accept': 'application/json'
|
|
884
|
+
* });
|
|
885
|
+
*
|
|
886
|
+
* // Using constants
|
|
887
|
+
* import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
|
|
888
|
+
* const headers = createHeaders({
|
|
889
|
+
* [FOLDER_KEY]: 'abc-123',
|
|
890
|
+
* [FOLDER_ID]: 456
|
|
891
|
+
* });
|
|
892
|
+
*
|
|
893
|
+
* // Empty headers
|
|
894
|
+
* const headers = createHeaders();
|
|
895
|
+
* ```
|
|
896
|
+
*/
|
|
897
|
+
function createHeaders(headersObj) {
|
|
898
|
+
const headers = {};
|
|
899
|
+
for (const [key, value] of Object.entries(headersObj)) {
|
|
900
|
+
if (value !== undefined && value !== null) {
|
|
901
|
+
headers[key] = value.toString();
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
return headers;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* Common constants used across the SDK
|
|
909
|
+
*/
|
|
910
|
+
/**
|
|
911
|
+
* Prefix used for OData query parameters
|
|
912
|
+
*/
|
|
913
|
+
const ODATA_PREFIX = '$';
|
|
914
|
+
/**
|
|
915
|
+
* HTTP methods
|
|
916
|
+
*/
|
|
917
|
+
const HTTP_METHODS = {
|
|
918
|
+
GET: 'GET',
|
|
919
|
+
POST: 'POST'};
|
|
920
|
+
/**
|
|
921
|
+
* OData OFFSET pagination parameter names (ODATA-style)
|
|
922
|
+
*/
|
|
923
|
+
const ODATA_OFFSET_PARAMS = {
|
|
924
|
+
/** OData page size parameter name */
|
|
925
|
+
PAGE_SIZE_PARAM: '$top',
|
|
926
|
+
/** OData offset parameter name */
|
|
927
|
+
OFFSET_PARAM: '$skip',
|
|
928
|
+
/** OData count parameter name */
|
|
929
|
+
COUNT_PARAM: '$count'
|
|
930
|
+
};
|
|
931
|
+
/**
|
|
932
|
+
* Bucket TOKEN pagination parameter names
|
|
933
|
+
*/
|
|
934
|
+
const BUCKET_TOKEN_PARAMS = {
|
|
935
|
+
/** Bucket page size parameter name */
|
|
936
|
+
PAGE_SIZE_PARAM: 'takeHint',
|
|
937
|
+
/** Bucket token parameter name */
|
|
938
|
+
TOKEN_PARAM: 'continuationToken'
|
|
939
|
+
};
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
|
|
943
|
+
* Returns the original value if parsing fails.
|
|
944
|
+
*/
|
|
945
|
+
/**
|
|
946
|
+
* Converts a string from PascalCase to camelCase
|
|
947
|
+
* @param str The PascalCase string to convert
|
|
948
|
+
* @returns The camelCase version of the string
|
|
949
|
+
*
|
|
950
|
+
* @example
|
|
951
|
+
* ```typescript
|
|
952
|
+
* pascalToCamelCase('HelloWorld'); // 'helloWorld'
|
|
953
|
+
* pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
|
|
954
|
+
* ```
|
|
955
|
+
*/
|
|
956
|
+
function pascalToCamelCase(str) {
|
|
957
|
+
if (!str)
|
|
958
|
+
return str;
|
|
959
|
+
return str.charAt(0).toLowerCase() + str.slice(1);
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Generic function to transform object keys using a provided case conversion function
|
|
963
|
+
* @param data The object to transform
|
|
964
|
+
* @param convertCase The function to convert each key
|
|
965
|
+
* @returns A new object with transformed keys
|
|
966
|
+
*/
|
|
967
|
+
function transformCaseKeys(data, convertCase) {
|
|
968
|
+
// Handle array of objects
|
|
969
|
+
if (Array.isArray(data)) {
|
|
970
|
+
return data.map(item => {
|
|
971
|
+
// If the array element is a primitive (string, number, etc.), return it as is
|
|
972
|
+
if (item === null || typeof item !== 'object' || typeof item === 'string') {
|
|
973
|
+
return item;
|
|
974
|
+
}
|
|
975
|
+
// Only recursively transform if it's actually an object
|
|
976
|
+
return transformCaseKeys(item, convertCase);
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
const result = {};
|
|
980
|
+
for (const [key, value] of Object.entries(data)) {
|
|
981
|
+
const transformedKey = convertCase(key);
|
|
982
|
+
// Recursively transform nested objects and arrays
|
|
983
|
+
if (value !== null && typeof value === 'object') {
|
|
984
|
+
result[transformedKey] = transformCaseKeys(value, convertCase);
|
|
985
|
+
}
|
|
986
|
+
else {
|
|
987
|
+
result[transformedKey] = value;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
return result;
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Transforms an object's keys from PascalCase to camelCase
|
|
994
|
+
* @param data The object with PascalCase keys
|
|
995
|
+
* @returns A new object with all keys converted to camelCase
|
|
996
|
+
*
|
|
997
|
+
* @example
|
|
998
|
+
* ```typescript
|
|
999
|
+
* // Simple object
|
|
1000
|
+
* pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
|
|
1001
|
+
* // Result: { id: "123", taskName: "Invoice" }
|
|
1002
|
+
*
|
|
1003
|
+
* // Nested object
|
|
1004
|
+
* pascalToCamelCaseKeys({
|
|
1005
|
+
* TaskId: "456",
|
|
1006
|
+
* TaskDetails: { AssignedUser: "John", Priority: "High" }
|
|
1007
|
+
* });
|
|
1008
|
+
* // Result: {
|
|
1009
|
+
* // taskId: "456",
|
|
1010
|
+
* // taskDetails: { assignedUser: "John", priority: "High" }
|
|
1011
|
+
* // }
|
|
1012
|
+
*
|
|
1013
|
+
* // Array of objects
|
|
1014
|
+
* pascalToCamelCaseKeys([
|
|
1015
|
+
* { Id: "1", IsComplete: false },
|
|
1016
|
+
* { Id: "2", IsComplete: true }
|
|
1017
|
+
* ]);
|
|
1018
|
+
* // Result: [
|
|
1019
|
+
* // { id: "1", isComplete: false },
|
|
1020
|
+
* // { id: "2", isComplete: true }
|
|
1021
|
+
* // ]
|
|
1022
|
+
* ```
|
|
1023
|
+
*/
|
|
1024
|
+
function pascalToCamelCaseKeys(data) {
|
|
1025
|
+
return transformCaseKeys(data, pascalToCamelCase);
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Adds a prefix to specified keys in an object, returning a new object.
|
|
1029
|
+
* Only the provided keys are prefixed; all others are left unchanged.
|
|
1030
|
+
*
|
|
1031
|
+
* @param obj The source object
|
|
1032
|
+
* @param prefix The prefix to add (e.g., '$')
|
|
1033
|
+
* @param keys The keys to prefix (e.g., ['expand', 'filter'])
|
|
1034
|
+
* @returns A new object with specified keys prefixed
|
|
1035
|
+
*
|
|
1036
|
+
* @example
|
|
1037
|
+
* addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
|
|
1038
|
+
*/
|
|
1039
|
+
function addPrefixToKeys(obj, prefix, keys) {
|
|
1040
|
+
const result = {};
|
|
1041
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
1042
|
+
if (keys.includes(key)) {
|
|
1043
|
+
result[`${prefix}${key}`] = value;
|
|
1044
|
+
}
|
|
1045
|
+
else {
|
|
1046
|
+
result[key] = value;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return result;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* Constants used throughout the pagination system
|
|
1054
|
+
*/
|
|
1055
|
+
/** Maximum number of items that can be requested in a single page */
|
|
1056
|
+
const MAX_PAGE_SIZE = 1000;
|
|
1057
|
+
/** Default page size when jumpToPage is used without specifying pageSize */
|
|
1058
|
+
const DEFAULT_PAGE_SIZE = 50;
|
|
1059
|
+
/** Default field name for items in a paginated response */
|
|
1060
|
+
const DEFAULT_ITEMS_FIELD = 'value';
|
|
1061
|
+
/** Default field name for total count in a paginated response */
|
|
1062
|
+
const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
|
|
1063
|
+
/**
|
|
1064
|
+
* Limits the page size to the maximum allowed value
|
|
1065
|
+
* @param pageSize - Requested page size
|
|
1066
|
+
* @returns Limited page size value
|
|
1067
|
+
*/
|
|
1068
|
+
function getLimitedPageSize(pageSize) {
|
|
1069
|
+
if (pageSize === undefined || pageSize === null) {
|
|
1070
|
+
return DEFAULT_PAGE_SIZE;
|
|
1071
|
+
}
|
|
1072
|
+
return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/**
|
|
1076
|
+
* Helper functions for pagination that can be used across services
|
|
1077
|
+
*/
|
|
1078
|
+
class PaginationHelpers {
|
|
1079
|
+
/**
|
|
1080
|
+
* Checks if any pagination parameters are provided
|
|
1081
|
+
*
|
|
1082
|
+
* @param options - The options object to check
|
|
1083
|
+
* @returns True if any pagination parameter is defined, false otherwise
|
|
1084
|
+
*/
|
|
1085
|
+
static hasPaginationParameters(options = {}) {
|
|
1086
|
+
const { cursor, pageSize, jumpToPage } = options;
|
|
1087
|
+
return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Parse a pagination cursor string into cursor data
|
|
1091
|
+
*/
|
|
1092
|
+
static parseCursor(cursorString) {
|
|
1093
|
+
try {
|
|
1094
|
+
const cursorData = JSON.parse(decodeBase64(cursorString));
|
|
1095
|
+
return cursorData;
|
|
1096
|
+
}
|
|
1097
|
+
catch {
|
|
1098
|
+
throw new Error('Invalid pagination cursor');
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Validates cursor format and structure
|
|
1103
|
+
*
|
|
1104
|
+
* @param paginationOptions - The pagination options containing the cursor
|
|
1105
|
+
* @param paginationType - Optional pagination type to validate against
|
|
1106
|
+
*/
|
|
1107
|
+
static validateCursor(paginationOptions, paginationType) {
|
|
1108
|
+
if (paginationOptions.cursor !== undefined) {
|
|
1109
|
+
if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
|
|
1110
|
+
throw new Error('cursor must contain a valid cursor string');
|
|
1111
|
+
}
|
|
1112
|
+
try {
|
|
1113
|
+
// Try to parse the cursor to validate it
|
|
1114
|
+
const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
|
|
1115
|
+
// If type is provided, validate cursor contains expected type information
|
|
1116
|
+
if (paginationType) {
|
|
1117
|
+
if (!cursorData.type) {
|
|
1118
|
+
throw new Error('Invalid cursor: missing pagination type');
|
|
1119
|
+
}
|
|
1120
|
+
// Check pagination type compatibility
|
|
1121
|
+
if (cursorData.type !== paginationType) {
|
|
1122
|
+
throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
catch (error) {
|
|
1127
|
+
if (error instanceof Error) {
|
|
1128
|
+
// If it's already our error with specific message, pass it through
|
|
1129
|
+
if (error.message.startsWith('Invalid cursor') ||
|
|
1130
|
+
error.message.startsWith('Pagination type mismatch')) {
|
|
1131
|
+
throw error;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
throw new Error('Invalid pagination cursor format');
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Comprehensive validation for pagination options
|
|
1140
|
+
*
|
|
1141
|
+
* @param options - The pagination options to validate
|
|
1142
|
+
* @param paginationType - The pagination type these options will be used with
|
|
1143
|
+
* @returns Processed pagination parameters ready for use
|
|
1144
|
+
*/
|
|
1145
|
+
static validatePaginationOptions(options, paginationType) {
|
|
1146
|
+
// Validate pageSize
|
|
1147
|
+
if (options.pageSize !== undefined && options.pageSize <= 0) {
|
|
1148
|
+
throw new Error('pageSize must be a positive number');
|
|
1149
|
+
}
|
|
1150
|
+
// Validate jumpToPage
|
|
1151
|
+
if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
|
|
1152
|
+
throw new Error('jumpToPage must be a positive number');
|
|
1153
|
+
}
|
|
1154
|
+
// Validate cursor
|
|
1155
|
+
PaginationHelpers.validateCursor(options, paginationType);
|
|
1156
|
+
// Validate service compatibility
|
|
1157
|
+
if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
|
|
1158
|
+
throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
|
|
1159
|
+
}
|
|
1160
|
+
// Get processed parameters
|
|
1161
|
+
return PaginationHelpers.getRequestParameters(options, paginationType);
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Convert a unified pagination options to service-specific parameters
|
|
1165
|
+
*/
|
|
1166
|
+
static getRequestParameters(options, paginationType) {
|
|
1167
|
+
// Handle jumpToPage
|
|
1168
|
+
if (options.jumpToPage !== undefined) {
|
|
1169
|
+
const jumpToPageOptions = {
|
|
1170
|
+
pageSize: options.pageSize,
|
|
1171
|
+
pageNumber: options.jumpToPage
|
|
1172
|
+
};
|
|
1173
|
+
return filterUndefined(jumpToPageOptions);
|
|
1174
|
+
}
|
|
1175
|
+
// If no cursor is provided, it's a first page request
|
|
1176
|
+
if (!options.cursor) {
|
|
1177
|
+
const firstPageOptions = {
|
|
1178
|
+
pageSize: options.pageSize,
|
|
1179
|
+
// Only set pageNumber for OFFSET pagination
|
|
1180
|
+
pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
|
|
1181
|
+
};
|
|
1182
|
+
return filterUndefined(firstPageOptions);
|
|
1183
|
+
}
|
|
1184
|
+
// Parse the cursor
|
|
1185
|
+
try {
|
|
1186
|
+
const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
|
|
1187
|
+
const cursorBasedOptions = {
|
|
1188
|
+
pageSize: cursorData.pageSize || options.pageSize,
|
|
1189
|
+
pageNumber: cursorData.pageNumber,
|
|
1190
|
+
continuationToken: cursorData.continuationToken,
|
|
1191
|
+
type: cursorData.type,
|
|
1192
|
+
};
|
|
1193
|
+
return filterUndefined(cursorBasedOptions);
|
|
1194
|
+
}
|
|
1195
|
+
catch {
|
|
1196
|
+
throw new Error('Invalid pagination cursor');
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* Helper method for paginated resource retrieval
|
|
1201
|
+
*
|
|
1202
|
+
* @param params - Parameters for pagination
|
|
1203
|
+
* @returns Promise resolving to a paginated result
|
|
1204
|
+
*/
|
|
1205
|
+
static async getAllPaginated(params) {
|
|
1206
|
+
const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
|
|
1207
|
+
const endpoint = getEndpoint(folderId);
|
|
1208
|
+
const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
|
|
1209
|
+
const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
|
|
1210
|
+
headers,
|
|
1211
|
+
params: additionalParams,
|
|
1212
|
+
pagination: {
|
|
1213
|
+
paginationType: options.paginationType || PaginationType.OFFSET,
|
|
1214
|
+
itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
|
|
1215
|
+
totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
|
|
1216
|
+
continuationTokenField: options.continuationTokenField,
|
|
1217
|
+
paginationParams: options.paginationParams
|
|
1218
|
+
}
|
|
1219
|
+
});
|
|
1220
|
+
// Parse items - automatically handle JSON string responses
|
|
1221
|
+
const rawItems = paginatedResponse.items;
|
|
1222
|
+
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1223
|
+
const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1224
|
+
return {
|
|
1225
|
+
...paginatedResponse,
|
|
1226
|
+
items: transformedItems
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Helper method for non-paginated resource retrieval
|
|
1231
|
+
*
|
|
1232
|
+
* @param params - Parameters for non-paginated resource retrieval
|
|
1233
|
+
* @returns Promise resolving to an object with data and totalCount
|
|
1234
|
+
*/
|
|
1235
|
+
static async getAllNonPaginated(params) {
|
|
1236
|
+
const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
|
|
1237
|
+
// Set default field names
|
|
1238
|
+
const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
|
|
1239
|
+
const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
|
|
1240
|
+
// Determine endpoint and headers based on folderId
|
|
1241
|
+
const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
|
|
1242
|
+
const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
|
|
1243
|
+
// Make the API call based on method
|
|
1244
|
+
let response;
|
|
1245
|
+
if (method === HTTP_METHODS.POST) {
|
|
1246
|
+
response = await serviceAccess.post(endpoint, additionalParams, { headers });
|
|
1247
|
+
}
|
|
1248
|
+
else {
|
|
1249
|
+
response = await serviceAccess.get(endpoint, {
|
|
1250
|
+
params: additionalParams,
|
|
1251
|
+
headers
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
// Extract and transform items from response
|
|
1255
|
+
// Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
|
|
1256
|
+
// itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
|
|
1257
|
+
const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
|
|
1258
|
+
const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
|
|
1259
|
+
const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
|
|
1260
|
+
// Parse items - automatically handle JSON string responses
|
|
1261
|
+
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1262
|
+
const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1263
|
+
return {
|
|
1264
|
+
items,
|
|
1265
|
+
totalCount
|
|
1266
|
+
};
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Centralized getAll implementation that handles both paginated and non-paginated requests
|
|
1270
|
+
*
|
|
1271
|
+
* @param config - Configuration for the getAll operation
|
|
1272
|
+
* @param options - Request options including pagination parameters
|
|
1273
|
+
* @returns Promise resolving to either paginated or non-paginated response based on options
|
|
1274
|
+
*/
|
|
1275
|
+
static async getAll(config, options) {
|
|
1276
|
+
const optionsWithDefaults = options || {};
|
|
1277
|
+
const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
|
|
1278
|
+
// Determine if pagination is requested
|
|
1279
|
+
const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
|
|
1280
|
+
// Process parameters (custom processing if provided, otherwise default)
|
|
1281
|
+
let processedOptions = restOptions;
|
|
1282
|
+
if (config.processParametersFn) {
|
|
1283
|
+
processedOptions = config.processParametersFn(restOptions, folderId);
|
|
1284
|
+
}
|
|
1285
|
+
// Apply ODATA prefix to keys (excluding specified keys)
|
|
1286
|
+
const excludeKeys = config.excludeFromPrefix || [];
|
|
1287
|
+
const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
|
|
1288
|
+
const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
|
|
1289
|
+
// Default pagination options
|
|
1290
|
+
const paginationOptions = {
|
|
1291
|
+
paginationType: PaginationType.OFFSET,
|
|
1292
|
+
itemsField: DEFAULT_ITEMS_FIELD,
|
|
1293
|
+
totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
|
|
1294
|
+
...config.pagination
|
|
1295
|
+
};
|
|
1296
|
+
// Paginated flow
|
|
1297
|
+
if (isPaginationRequested) {
|
|
1298
|
+
return PaginationHelpers.getAllPaginated({
|
|
1299
|
+
serviceAccess: config.serviceAccess,
|
|
1300
|
+
getEndpoint: config.getEndpoint,
|
|
1301
|
+
folderId,
|
|
1302
|
+
headers: config.headers,
|
|
1303
|
+
paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
|
|
1304
|
+
additionalParams: prefixedOptions,
|
|
1305
|
+
transformFn: config.transformFn,
|
|
1306
|
+
method: config.method,
|
|
1307
|
+
options: {
|
|
1308
|
+
...paginationOptions,
|
|
1309
|
+
paginationParams: config.pagination?.paginationParams
|
|
1310
|
+
}
|
|
1311
|
+
}); // Type assertion needed due to conditional return
|
|
1312
|
+
}
|
|
1313
|
+
// Non-paginated flow
|
|
1314
|
+
const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
|
|
1315
|
+
return PaginationHelpers.getAllNonPaginated({
|
|
1316
|
+
serviceAccess: config.serviceAccess,
|
|
1317
|
+
getAllEndpoint: config.getEndpoint(),
|
|
1318
|
+
getByFolderEndpoint: byFolderEndpoint,
|
|
1319
|
+
folderId,
|
|
1320
|
+
headers: config.headers,
|
|
1321
|
+
additionalParams: prefixedOptions,
|
|
1322
|
+
transformFn: config.transformFn,
|
|
1323
|
+
method: config.method,
|
|
1324
|
+
options: {
|
|
1325
|
+
itemsField: paginationOptions.itemsField,
|
|
1326
|
+
totalCountField: paginationOptions.totalCountField
|
|
1327
|
+
}
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/**
|
|
1333
|
+
* SDK Internals Registry - Internal registry for SDK instances
|
|
1334
|
+
*
|
|
1335
|
+
* This class is NOT exported in the public API.
|
|
1336
|
+
* It provides a secure way to share SDK internals between
|
|
1337
|
+
* the UiPath class and service classes without exposing them publicly.
|
|
1338
|
+
*
|
|
1339
|
+
* @internal
|
|
1340
|
+
*/
|
|
1341
|
+
// Global symbol key to ensure WeakMap is shared across module instances
|
|
1342
|
+
// This prevents issues when core and service modules are bundled separately
|
|
1343
|
+
const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
|
|
1344
|
+
// Get or create the global WeakMap store
|
|
1345
|
+
const getGlobalStore = () => {
|
|
1346
|
+
const globalObj = globalThis;
|
|
1347
|
+
if (!globalObj[REGISTRY_KEY]) {
|
|
1348
|
+
globalObj[REGISTRY_KEY] = new WeakMap();
|
|
1349
|
+
}
|
|
1350
|
+
return globalObj[REGISTRY_KEY];
|
|
1351
|
+
};
|
|
1352
|
+
/**
|
|
1353
|
+
* Internal registry for SDK private components.
|
|
1354
|
+
* Uses WeakMap to prevent memory leaks - entries are automatically
|
|
1355
|
+
* garbage collected when the SDK instance is no longer referenced.
|
|
1356
|
+
*
|
|
1357
|
+
* Uses a global singleton pattern to ensure the same WeakMap is shared
|
|
1358
|
+
* across separately bundled modules (core, entities, tasks, etc.).
|
|
1359
|
+
*
|
|
1360
|
+
* @internal - Not exported in public API
|
|
1361
|
+
*/
|
|
1362
|
+
class SDKInternalsRegistry {
|
|
1363
|
+
// Use global store to ensure sharing across module bundles
|
|
1364
|
+
static get store() {
|
|
1365
|
+
return getGlobalStore();
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Register SDK instance internals
|
|
1369
|
+
* Called by UiPath constructor
|
|
1370
|
+
*/
|
|
1371
|
+
static set(instance, internals) {
|
|
1372
|
+
this.store.set(instance, internals);
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* Retrieve SDK instance internals
|
|
1376
|
+
* Called by BaseService constructor
|
|
1377
|
+
*/
|
|
1378
|
+
static get(instance) {
|
|
1379
|
+
const internals = this.store.get(instance);
|
|
1380
|
+
if (!internals) {
|
|
1381
|
+
throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
|
|
1382
|
+
}
|
|
1383
|
+
return internals;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
var _BaseService_apiClient;
|
|
1388
|
+
/**
|
|
1389
|
+
* Base class for all UiPath SDK services.
|
|
1390
|
+
*
|
|
1391
|
+
* Provides common functionality for authentication, configuration, and API communication.
|
|
1392
|
+
* All service classes extend this base to inherit dependency injection and HTTP client access.
|
|
1393
|
+
*
|
|
1394
|
+
* This class implements the dependency injection pattern where services receive a configured
|
|
1395
|
+
* UiPath instance. The ApiClient is created internally and handles all HTTP operations
|
|
1396
|
+
* including authentication token management.
|
|
1397
|
+
*
|
|
1398
|
+
* @remarks
|
|
1399
|
+
* Service classes should extend this base and call `super(uiPath)` in their constructor.
|
|
1400
|
+
* Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
|
|
1401
|
+
*
|
|
1402
|
+
*/
|
|
1403
|
+
class BaseService {
|
|
1404
|
+
/**
|
|
1405
|
+
* Creates a base service instance with dependency injection.
|
|
1406
|
+
*
|
|
1407
|
+
* Extracts configuration, execution context, and token manager from the UiPath instance
|
|
1408
|
+
* to initialize an authenticated API client. The ApiClient handles all HTTP operations
|
|
1409
|
+
* and token management internally.
|
|
1410
|
+
*
|
|
1411
|
+
* @param instance - UiPath SDK instance providing authentication and configuration.
|
|
1412
|
+
* Services receive this via dependency injection in the modular pattern.
|
|
1413
|
+
* @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
|
|
1414
|
+
* CAS external-app auth)
|
|
1415
|
+
*
|
|
1416
|
+
* @example
|
|
1417
|
+
* ```typescript
|
|
1418
|
+
* // Services automatically call this via super()
|
|
1419
|
+
* export class EntityService extends BaseService {
|
|
1420
|
+
* constructor(instance: IUiPath) {
|
|
1421
|
+
* super(instance); // Initializes the internal ApiClient
|
|
1422
|
+
* }
|
|
1423
|
+
* }
|
|
1424
|
+
*
|
|
1425
|
+
* // Usage in modular pattern
|
|
1426
|
+
* import { UiPath } from '@uipath/uipath-typescript/core';
|
|
1427
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
1428
|
+
*
|
|
1429
|
+
* const sdk = new UiPath(config);
|
|
1430
|
+
* await sdk.initialize();
|
|
1431
|
+
* const entities = new Entities(sdk);
|
|
1432
|
+
* ```
|
|
1433
|
+
*/
|
|
1434
|
+
constructor(instance, headers) {
|
|
1435
|
+
// Private field - not visible via Object.keys() or any reflection
|
|
1436
|
+
_BaseService_apiClient.set(this, void 0);
|
|
1437
|
+
const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
|
|
1438
|
+
__classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
|
|
1439
|
+
this.config = { folderKey };
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* Gets a valid authentication token, refreshing if necessary.
|
|
1443
|
+
* Use this when you need to manually add Authorization headers (e.g., direct uploads).
|
|
1444
|
+
*
|
|
1445
|
+
* @returns Promise resolving to a valid access token string
|
|
1446
|
+
* @throws AuthenticationError if no token is available or refresh fails
|
|
1447
|
+
*/
|
|
1448
|
+
async getValidAuthToken() {
|
|
1449
|
+
return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Creates a service accessor for pagination helpers
|
|
1453
|
+
* This allows pagination helpers to access protected methods without making them public
|
|
1454
|
+
*/
|
|
1455
|
+
createPaginationServiceAccess() {
|
|
1456
|
+
return {
|
|
1457
|
+
get: (path, options) => this.get(path, options || {}),
|
|
1458
|
+
post: (path, body, options) => this.post(path, body, options || {}),
|
|
1459
|
+
requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
async request(method, path, options = {}) {
|
|
1463
|
+
switch (method.toUpperCase()) {
|
|
1464
|
+
case 'GET':
|
|
1465
|
+
return this.get(path, options);
|
|
1466
|
+
case 'POST':
|
|
1467
|
+
return this.post(path, options.body, options);
|
|
1468
|
+
case 'PUT':
|
|
1469
|
+
return this.put(path, options.body, options);
|
|
1470
|
+
case 'PATCH':
|
|
1471
|
+
return this.patch(path, options.body, options);
|
|
1472
|
+
case 'DELETE':
|
|
1473
|
+
return this.delete(path, options);
|
|
1474
|
+
default:
|
|
1475
|
+
throw new Error(`Unsupported HTTP method: ${method}`);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
async requestWithSpec(spec) {
|
|
1479
|
+
if (!spec.method || !spec.url) {
|
|
1480
|
+
throw new Error('Request spec must include method and url');
|
|
1481
|
+
}
|
|
1482
|
+
return this.request(spec.method, spec.url, spec);
|
|
1483
|
+
}
|
|
1484
|
+
async get(path, options = {}) {
|
|
1485
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
|
|
1486
|
+
return { data: response };
|
|
1487
|
+
}
|
|
1488
|
+
async post(path, data, options = {}) {
|
|
1489
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
|
|
1490
|
+
return { data: response };
|
|
1491
|
+
}
|
|
1492
|
+
async put(path, data, options = {}) {
|
|
1493
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
|
|
1494
|
+
return { data: response };
|
|
1495
|
+
}
|
|
1496
|
+
async patch(path, data, options = {}) {
|
|
1497
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
|
|
1498
|
+
return { data: response };
|
|
1499
|
+
}
|
|
1500
|
+
async delete(path, options = {}) {
|
|
1501
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
|
|
1502
|
+
return { data: response };
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Execute a request with cursor-based pagination
|
|
1506
|
+
*/
|
|
1507
|
+
async requestWithPagination(method, path, paginationOptions, options) {
|
|
1508
|
+
const paginationType = options.pagination.paginationType;
|
|
1509
|
+
// Validate and prepare pagination parameters
|
|
1510
|
+
const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
|
|
1511
|
+
// Prepare request parameters based on pagination type
|
|
1512
|
+
const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
|
|
1513
|
+
// For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
|
|
1514
|
+
if (method.toUpperCase() === 'POST') {
|
|
1515
|
+
const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
|
|
1516
|
+
options.body = {
|
|
1517
|
+
...existingBody,
|
|
1518
|
+
...options.params,
|
|
1519
|
+
...requestParams
|
|
1520
|
+
};
|
|
1521
|
+
options.params = undefined;
|
|
1522
|
+
}
|
|
1523
|
+
else {
|
|
1524
|
+
// Merge pagination parameters with existing parameters
|
|
1525
|
+
options.params = {
|
|
1526
|
+
...options.params,
|
|
1527
|
+
...requestParams
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
// Make the request
|
|
1531
|
+
const response = await this.request(method, path, options);
|
|
1532
|
+
// Extract data from the response and create page result
|
|
1533
|
+
return this.createPaginatedResponseFromResponse(response, params, paginationType, {
|
|
1534
|
+
itemsField: options.pagination.itemsField,
|
|
1535
|
+
totalCountField: options.pagination.totalCountField,
|
|
1536
|
+
continuationTokenField: options.pagination.continuationTokenField
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Validates and prepares pagination parameters from options
|
|
1541
|
+
*/
|
|
1542
|
+
validateAndPreparePaginationParams(paginationType, paginationOptions) {
|
|
1543
|
+
return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* Prepares request parameters for pagination based on pagination type
|
|
1547
|
+
*/
|
|
1548
|
+
preparePaginationRequestParams(paginationType, params, paginationConfig) {
|
|
1549
|
+
const requestParams = {};
|
|
1550
|
+
let limitedPageSize;
|
|
1551
|
+
const paginationParams = paginationConfig?.paginationParams;
|
|
1552
|
+
switch (paginationType) {
|
|
1553
|
+
case PaginationType.OFFSET:
|
|
1554
|
+
limitedPageSize = getLimitedPageSize(params.pageSize);
|
|
1555
|
+
const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
|
|
1556
|
+
const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
|
|
1557
|
+
const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
|
|
1558
|
+
// When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
|
|
1559
|
+
// When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
|
|
1560
|
+
const convertToSkip = paginationParams?.convertToSkip ?? true;
|
|
1561
|
+
// When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
|
|
1562
|
+
const zeroBased = paginationParams?.zeroBased ?? false;
|
|
1563
|
+
requestParams[pageSizeParam] = limitedPageSize;
|
|
1564
|
+
if (convertToSkip) {
|
|
1565
|
+
if (params.pageNumber && params.pageNumber > 1) {
|
|
1566
|
+
requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
else {
|
|
1570
|
+
const sdkPageNumber = params.pageNumber || 1;
|
|
1571
|
+
requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
|
|
1572
|
+
}
|
|
1573
|
+
{
|
|
1574
|
+
requestParams[countParam] = true;
|
|
1575
|
+
}
|
|
1576
|
+
break;
|
|
1577
|
+
case PaginationType.TOKEN:
|
|
1578
|
+
const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
|
|
1579
|
+
const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
|
|
1580
|
+
if (params.pageSize) {
|
|
1581
|
+
requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
|
|
1582
|
+
}
|
|
1583
|
+
if (params.continuationToken) {
|
|
1584
|
+
requestParams[tokenParam] = params.continuationToken;
|
|
1585
|
+
}
|
|
1586
|
+
break;
|
|
1587
|
+
}
|
|
1588
|
+
return requestParams;
|
|
1589
|
+
}
|
|
1590
|
+
/**
|
|
1591
|
+
* Creates a paginated response from API response
|
|
1592
|
+
*/
|
|
1593
|
+
createPaginatedResponseFromResponse(response, params, paginationType, fields) {
|
|
1594
|
+
// Extract fields from response
|
|
1595
|
+
const itemsField = fields.itemsField ||
|
|
1596
|
+
(paginationType === PaginationType.TOKEN ? 'items' : 'value');
|
|
1597
|
+
const totalCountField = fields.totalCountField || 'totalRecordCount';
|
|
1598
|
+
const continuationTokenField = fields.continuationTokenField || 'continuationToken';
|
|
1599
|
+
// Extract items and metadata
|
|
1600
|
+
// Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
|
|
1601
|
+
// itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
|
|
1602
|
+
const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
|
|
1603
|
+
const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
|
|
1604
|
+
const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
|
|
1605
|
+
const continuationToken = response.data[continuationTokenField];
|
|
1606
|
+
// Determine if there are more pages
|
|
1607
|
+
const hasMore = this.determineHasMorePages(paginationType, {
|
|
1608
|
+
totalCount,
|
|
1609
|
+
pageSize: params.pageSize,
|
|
1610
|
+
currentPage: params.pageNumber || 1,
|
|
1611
|
+
itemsCount: items.length,
|
|
1612
|
+
continuationToken
|
|
1613
|
+
});
|
|
1614
|
+
// Create and return the page result
|
|
1615
|
+
return PaginationManager.createPaginatedResponse({
|
|
1616
|
+
pageInfo: {
|
|
1617
|
+
hasMore,
|
|
1618
|
+
totalCount,
|
|
1619
|
+
currentPage: params.pageNumber,
|
|
1620
|
+
pageSize: params.pageSize,
|
|
1621
|
+
continuationToken
|
|
1622
|
+
},
|
|
1623
|
+
type: paginationType,
|
|
1624
|
+
}, items);
|
|
1625
|
+
}
|
|
1626
|
+
/**
|
|
1627
|
+
* Determines if there are more pages based on pagination type and metadata
|
|
1628
|
+
*/
|
|
1629
|
+
determineHasMorePages(paginationType, info) {
|
|
1630
|
+
switch (paginationType) {
|
|
1631
|
+
case PaginationType.OFFSET:
|
|
1632
|
+
const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
1633
|
+
// If totalCount is available, use it for precise calculation
|
|
1634
|
+
if (info.totalCount !== undefined) {
|
|
1635
|
+
return (info.currentPage * effectivePageSize) < info.totalCount;
|
|
1636
|
+
}
|
|
1637
|
+
// Fallback when totalCount is not available
|
|
1638
|
+
// NOTE: This code path should rarely be executed as the APIs typically return totalCount
|
|
1639
|
+
return info.itemsCount === effectivePageSize;
|
|
1640
|
+
case PaginationType.TOKEN:
|
|
1641
|
+
return !!info.continuationToken;
|
|
1642
|
+
default:
|
|
1643
|
+
return false;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
_BaseService_apiClient = new WeakMap();
|
|
1648
|
+
|
|
1649
|
+
/** Status of a span: whether it completed successfully, with an error, or was not set. */
|
|
1650
|
+
var SpanStatus;
|
|
1651
|
+
(function (SpanStatus) {
|
|
1652
|
+
SpanStatus["Unset"] = "Unset";
|
|
1653
|
+
SpanStatus["Ok"] = "Ok";
|
|
1654
|
+
SpanStatus["Error"] = "Error";
|
|
1655
|
+
/** Span is still in progress. */
|
|
1656
|
+
SpanStatus["Running"] = "Running";
|
|
1657
|
+
/** Span data is hidden from the caller due to tenant/folder permission rules. */
|
|
1658
|
+
SpanStatus["Restricted"] = "Restricted";
|
|
1659
|
+
/** Span was cancelled before completion. */
|
|
1660
|
+
SpanStatus["Cancelled"] = "Cancelled";
|
|
1661
|
+
})(SpanStatus || (SpanStatus = {}));
|
|
1662
|
+
/** Platform source that produced the span. */
|
|
1663
|
+
var SpanSource;
|
|
1664
|
+
(function (SpanSource) {
|
|
1665
|
+
SpanSource["Testing"] = "Testing";
|
|
1666
|
+
SpanSource["Agents"] = "Agents";
|
|
1667
|
+
SpanSource["ProcessOrchestration"] = "ProcessOrchestration";
|
|
1668
|
+
SpanSource["ApiWorkflows"] = "ApiWorkflows";
|
|
1669
|
+
SpanSource["Robots"] = "Robots";
|
|
1670
|
+
SpanSource["ConversationalAgentsService"] = "ConversationalAgentsService";
|
|
1671
|
+
SpanSource["IntegrationServiceTrigger"] = "IntegrationServiceTrigger";
|
|
1672
|
+
SpanSource["Playground"] = "Playground";
|
|
1673
|
+
SpanSource["Governance"] = "Governance";
|
|
1674
|
+
/** Intelligent Experience Platform — unstructured and complex document processing source. */
|
|
1675
|
+
SpanSource["IXPUnstructuredAndComplexDocuments"] = "IXPUnstructuredAndComplexDocuments";
|
|
1676
|
+
/** Agents authored in code (as opposed to visual/no-code designers). */
|
|
1677
|
+
SpanSource["CodedAgents"] = "CodedAgents";
|
|
1678
|
+
/** Intelligent Experience Platform — communications mining source. */
|
|
1679
|
+
SpanSource["IXPCommunicationsMining"] = "IXPCommunicationsMining";
|
|
1680
|
+
/** UiPath Context Grounding — span produced by the Enterprise Context Service for RAG/knowledge-base operations. */
|
|
1681
|
+
SpanSource["EnterpriseContextService"] = "EnterpriseContextService";
|
|
1682
|
+
/** Model Context Protocol — span produced by an MCP server integration. */
|
|
1683
|
+
SpanSource["MCP"] = "MCP";
|
|
1684
|
+
/** Agent-to-Agent — span produced by an A2A protocol call between agents. */
|
|
1685
|
+
SpanSource["A2A"] = "A2A";
|
|
1686
|
+
/** Serverless — span produced by a serverless function execution. */
|
|
1687
|
+
SpanSource["Serverless"] = "Serverless";
|
|
1688
|
+
})(SpanSource || (SpanSource = {}));
|
|
1689
|
+
/** Minimum severity level of events captured in the span. */
|
|
1690
|
+
var SpanVerbosityLevel;
|
|
1691
|
+
(function (SpanVerbosityLevel) {
|
|
1692
|
+
SpanVerbosityLevel["Verbose"] = "Verbose";
|
|
1693
|
+
SpanVerbosityLevel["Trace"] = "Trace";
|
|
1694
|
+
SpanVerbosityLevel["Information"] = "Information";
|
|
1695
|
+
SpanVerbosityLevel["Warning"] = "Warning";
|
|
1696
|
+
SpanVerbosityLevel["Error"] = "Error";
|
|
1697
|
+
SpanVerbosityLevel["Critical"] = "Critical";
|
|
1698
|
+
SpanVerbosityLevel["Off"] = "Off";
|
|
1699
|
+
})(SpanVerbosityLevel || (SpanVerbosityLevel = {}));
|
|
1700
|
+
/** Whether the span was produced during a debug or production runtime. */
|
|
1701
|
+
var SpanExecutionType;
|
|
1702
|
+
(function (SpanExecutionType) {
|
|
1703
|
+
SpanExecutionType["Debug"] = "Debug";
|
|
1704
|
+
SpanExecutionType["Runtime"] = "Runtime";
|
|
1705
|
+
})(SpanExecutionType || (SpanExecutionType = {}));
|
|
1706
|
+
/** Whether the caller has permission to read this span's data. */
|
|
1707
|
+
var SpanPermissionStatus;
|
|
1708
|
+
(function (SpanPermissionStatus) {
|
|
1709
|
+
SpanPermissionStatus["Allow"] = "Allow";
|
|
1710
|
+
/** Some span fields are redacted due to permission constraints (e.g. attributes visible but payload hidden). */
|
|
1711
|
+
SpanPermissionStatus["PartialBlock"] = "PartialBlock";
|
|
1712
|
+
SpanPermissionStatus["Block"] = "Block";
|
|
1713
|
+
})(SpanPermissionStatus || (SpanPermissionStatus = {}));
|
|
1714
|
+
/** Storage provider that created or manages the attachment. */
|
|
1715
|
+
var SpanAttachmentProvider;
|
|
1716
|
+
(function (SpanAttachmentProvider) {
|
|
1717
|
+
SpanAttachmentProvider["Orchestrator"] = "Orchestrator";
|
|
1718
|
+
/** Span attachment stored by the observability platform. */
|
|
1719
|
+
SpanAttachmentProvider["LLMOps"] = "LLMOps";
|
|
1720
|
+
})(SpanAttachmentProvider || (SpanAttachmentProvider = {}));
|
|
1721
|
+
/** Whether the attachment is an input, output, or neither. */
|
|
1722
|
+
var SpanAttachmentDirection;
|
|
1723
|
+
(function (SpanAttachmentDirection) {
|
|
1724
|
+
SpanAttachmentDirection["None"] = "None";
|
|
1725
|
+
SpanAttachmentDirection["In"] = "In";
|
|
1726
|
+
SpanAttachmentDirection["Out"] = "Out";
|
|
1727
|
+
})(SpanAttachmentDirection || (SpanAttachmentDirection = {}));
|
|
1728
|
+
|
|
1729
|
+
/** Maps integer Status values from the otel API to {@link SpanStatus} enum values. */
|
|
1730
|
+
const SpanStatusMap = {
|
|
1731
|
+
0: SpanStatus.Unset,
|
|
1732
|
+
1: SpanStatus.Ok,
|
|
1733
|
+
2: SpanStatus.Error,
|
|
1734
|
+
3: SpanStatus.Running,
|
|
1735
|
+
4: SpanStatus.Restricted,
|
|
1736
|
+
5: SpanStatus.Cancelled,
|
|
1737
|
+
};
|
|
1738
|
+
/** Maps integer Source values from the otel API to {@link SpanSource} enum values. */
|
|
1739
|
+
const SpanSourceMap = {
|
|
1740
|
+
0: SpanSource.Testing,
|
|
1741
|
+
1: SpanSource.Agents,
|
|
1742
|
+
2: SpanSource.ProcessOrchestration,
|
|
1743
|
+
3: SpanSource.ApiWorkflows,
|
|
1744
|
+
4: SpanSource.Robots,
|
|
1745
|
+
5: SpanSource.ConversationalAgentsService,
|
|
1746
|
+
6: SpanSource.IntegrationServiceTrigger,
|
|
1747
|
+
7: SpanSource.Playground,
|
|
1748
|
+
8: SpanSource.Governance,
|
|
1749
|
+
9: SpanSource.IXPUnstructuredAndComplexDocuments,
|
|
1750
|
+
10: SpanSource.CodedAgents,
|
|
1751
|
+
11: SpanSource.IXPCommunicationsMining,
|
|
1752
|
+
12: SpanSource.EnterpriseContextService,
|
|
1753
|
+
13: SpanSource.MCP,
|
|
1754
|
+
14: SpanSource.A2A,
|
|
1755
|
+
15: SpanSource.Serverless,
|
|
1756
|
+
};
|
|
1757
|
+
/** Maps integer VerbosityLevel values from the otel API to {@link SpanVerbosityLevel} enum values. */
|
|
1758
|
+
const SpanVerbosityLevelMap = {
|
|
1759
|
+
0: SpanVerbosityLevel.Verbose,
|
|
1760
|
+
1: SpanVerbosityLevel.Trace,
|
|
1761
|
+
2: SpanVerbosityLevel.Information,
|
|
1762
|
+
3: SpanVerbosityLevel.Warning,
|
|
1763
|
+
4: SpanVerbosityLevel.Error,
|
|
1764
|
+
5: SpanVerbosityLevel.Critical,
|
|
1765
|
+
6: SpanVerbosityLevel.Off,
|
|
1766
|
+
};
|
|
1767
|
+
/** Maps integer ExecutionType values from the otel API to {@link SpanExecutionType} enum values. */
|
|
1768
|
+
const SpanExecutionTypeMap = {
|
|
1769
|
+
0: SpanExecutionType.Debug,
|
|
1770
|
+
1: SpanExecutionType.Runtime,
|
|
1771
|
+
};
|
|
1772
|
+
/** Maps integer PermissionStatus values from the otel API to {@link SpanPermissionStatus} enum values. */
|
|
1773
|
+
const SpanPermissionStatusMap = {
|
|
1774
|
+
0: SpanPermissionStatus.Allow,
|
|
1775
|
+
1: SpanPermissionStatus.PartialBlock,
|
|
1776
|
+
2: SpanPermissionStatus.Block,
|
|
1777
|
+
};
|
|
1778
|
+
/** Maps integer Provider values from the otel API to {@link SpanAttachmentProvider} enum values. */
|
|
1779
|
+
const SpanAttachmentProviderMap = {
|
|
1780
|
+
0: SpanAttachmentProvider.Orchestrator,
|
|
1781
|
+
1: SpanAttachmentProvider.LLMOps,
|
|
1782
|
+
};
|
|
1783
|
+
/** Maps integer Direction values from the otel API to {@link SpanAttachmentDirection} enum values. */
|
|
1784
|
+
const SpanAttachmentDirectionMap = {
|
|
1785
|
+
0: SpanAttachmentDirection.None,
|
|
1786
|
+
1: SpanAttachmentDirection.In,
|
|
1787
|
+
2: SpanAttachmentDirection.Out,
|
|
1788
|
+
};
|
|
1789
|
+
|
|
1790
|
+
/**
|
|
1791
|
+
* Base path constants for different services
|
|
1792
|
+
*/
|
|
1793
|
+
const LLMOPS_BASE = 'llmopstenant_';
|
|
1794
|
+
|
|
1795
|
+
/**
|
|
1796
|
+
* Traces Service Endpoints
|
|
1797
|
+
*/
|
|
1798
|
+
const TRACES_ENDPOINTS = {
|
|
1799
|
+
/** GET spans for a trace (OTEL format). Query params: traceId, pageSize, agentId, isHistorical */
|
|
1800
|
+
GET_BY_TRACE_ID: `${LLMOPS_BASE}/api/Traces/v2/spans/otel`,
|
|
1801
|
+
/** POST specific spans by ID. traceId in query via params, spanIds array in body */
|
|
1802
|
+
POST_BY_IDS: `${LLMOPS_BASE}/api/Traces/v2/spans/otel/byIds`,
|
|
1803
|
+
};
|
|
1804
|
+
|
|
1805
|
+
/**
|
|
1806
|
+
* SDK Telemetry constants.
|
|
1807
|
+
*
|
|
1808
|
+
* Only the SDK's identity (version, service name, role name, …) lives
|
|
1809
|
+
* here. The Application Insights connection string is injected into
|
|
1810
|
+
* `@uipath/core-telemetry` itself at publish time, and the generic attribute
|
|
1811
|
+
* keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
|
|
1812
|
+
* `@uipath/core-telemetry` and consumed there — they are not part of the
|
|
1813
|
+
* SDK's public API.
|
|
1814
|
+
*/
|
|
1815
|
+
/** SDK version placeholder — patched by the SDK publish workflow. */
|
|
1816
|
+
const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
|
|
1817
|
+
|
|
1818
|
+
/**
|
|
1819
|
+
* UiPath TypeScript SDK Telemetry
|
|
1820
|
+
*
|
|
1821
|
+
* Constructs the SDK's own `TelemetryClient` and binds the SDK-local
|
|
1822
|
+
* `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
|
|
1823
|
+
* does this independently, so events carry their own consumer's identity
|
|
1824
|
+
* and tenant context.
|
|
1825
|
+
*/
|
|
1826
|
+
// Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
|
|
1827
|
+
// same `TelemetryClient` instance at runtime. A single `initialize(...)`
|
|
1828
|
+
// from the `UiPath` constructor therefore wires up `@track` decorators
|
|
1829
|
+
// across every subpath bundle (`assets`, `feedback`, `tasks`, …).
|
|
1830
|
+
const sdkClient = getOrCreateClient(CLOUD_ROLE_NAME);
|
|
1831
|
+
const track = createTrack(sdkClient);
|
|
1832
|
+
createTrackEvent(sdkClient);
|
|
1833
|
+
|
|
1834
|
+
class TracesService extends BaseService {
|
|
1835
|
+
transformOtelSpan(raw) {
|
|
1836
|
+
const { Attributes, ExpiryTimeUtc, Attachments, ...rest } = raw;
|
|
1837
|
+
const base = pascalToCamelCaseKeys(rest);
|
|
1838
|
+
return {
|
|
1839
|
+
...base,
|
|
1840
|
+
attributes: Attributes,
|
|
1841
|
+
expiredTime: ExpiryTimeUtc,
|
|
1842
|
+
status: SpanStatusMap[raw.Status] ?? SpanStatus.Unset,
|
|
1843
|
+
source: raw.Source == null ? null : (SpanSourceMap[raw.Source] ?? null),
|
|
1844
|
+
verbosityLevel: raw.VerbosityLevel == null ? null : (SpanVerbosityLevelMap[raw.VerbosityLevel] ?? null),
|
|
1845
|
+
executionType: raw.ExecutionType == null ? null : (SpanExecutionTypeMap[raw.ExecutionType] ?? null),
|
|
1846
|
+
permissionStatus: raw.PermissionStatus == null ? null : (SpanPermissionStatusMap[raw.PermissionStatus] ?? null),
|
|
1847
|
+
attachments: Attachments ? Attachments.map(a => ({
|
|
1848
|
+
provider: SpanAttachmentProviderMap[a.Provider] ?? SpanAttachmentProvider.Orchestrator,
|
|
1849
|
+
id: a.Id,
|
|
1850
|
+
fileName: a.FileName,
|
|
1851
|
+
mimeType: a.MimeType,
|
|
1852
|
+
direction: SpanAttachmentDirectionMap[a.Direction] ?? SpanAttachmentDirection.None,
|
|
1853
|
+
})) : null,
|
|
1854
|
+
};
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* Gets all spans for a specific trace ID.
|
|
1858
|
+
*
|
|
1859
|
+
* Returns up to `pageSize` spans (default 1000) in a single fetch.
|
|
1860
|
+
* Accepts both GUID format and OTEL 32-char hex format — the API normalizes both.
|
|
1861
|
+
*
|
|
1862
|
+
* @param traceId - Trace identifier
|
|
1863
|
+
* @param options - Optional filters {@link TracesGetByIdOptions}
|
|
1864
|
+
* @returns Promise resolving to an array of {@link SpanGetResponse}, each containing span identity, timing, status, source platform, attributes, verbosity, execution type, lineage context, and any file attachments.
|
|
1865
|
+
* @example
|
|
1866
|
+
* ```typescript
|
|
1867
|
+
* import { Traces } from '@uipath/uipath-typescript/traces';
|
|
1868
|
+
*
|
|
1869
|
+
* const traces = new Traces(sdk);
|
|
1870
|
+
* const spans = await traces.getById('<traceId>');
|
|
1871
|
+
* console.log(spans.length, spans[0].spanType, spans[0].status);
|
|
1872
|
+
* ```
|
|
1873
|
+
* @example
|
|
1874
|
+
* ```typescript
|
|
1875
|
+
* // Filter to a specific agent's spans
|
|
1876
|
+
* const agentSpans = await traces.getById('<traceId>', {
|
|
1877
|
+
* agentId: '<agentId>',
|
|
1878
|
+
* pageSize: 500,
|
|
1879
|
+
* });
|
|
1880
|
+
* ```
|
|
1881
|
+
*/
|
|
1882
|
+
async getById(traceId, options) {
|
|
1883
|
+
if (!traceId)
|
|
1884
|
+
throw new ValidationError({ message: 'traceId is required for getById' });
|
|
1885
|
+
const { pageSize = 1000, agentId, includeExpiredSpans } = options ?? {};
|
|
1886
|
+
const params = { traceId, pageSize };
|
|
1887
|
+
if (agentId !== undefined)
|
|
1888
|
+
params.agentId = agentId;
|
|
1889
|
+
if (includeExpiredSpans !== undefined)
|
|
1890
|
+
params.isHistorical = includeExpiredSpans;
|
|
1891
|
+
const response = await this.get(TRACES_ENDPOINTS.GET_BY_TRACE_ID, { params });
|
|
1892
|
+
const spans = response.data?.Spans ?? [];
|
|
1893
|
+
return spans.map(span => this.transformOtelSpan(span));
|
|
1894
|
+
}
|
|
1895
|
+
/**
|
|
1896
|
+
* Gets specific spans by trace ID and span IDs.
|
|
1897
|
+
*
|
|
1898
|
+
* Accepts OTEL 16-char hex or GUID format for span IDs.
|
|
1899
|
+
*
|
|
1900
|
+
* @param traceId - Trace identifier
|
|
1901
|
+
* @param spanIds - List of span IDs to retrieve
|
|
1902
|
+
* @returns Promise resolving to an array of matching {@link SpanGetResponse}
|
|
1903
|
+
* @example
|
|
1904
|
+
* ```typescript
|
|
1905
|
+
* import { Traces } from '@uipath/uipath-typescript/traces';
|
|
1906
|
+
*
|
|
1907
|
+
* const traces = new Traces(sdk);
|
|
1908
|
+
*
|
|
1909
|
+
* // First retrieve all spans to find the IDs you want
|
|
1910
|
+
* const allSpans = await traces.getById('<traceId>');
|
|
1911
|
+
* const spanIds = allSpans.slice(0, 3).map(s => s.id);
|
|
1912
|
+
*
|
|
1913
|
+
* const subset = await traces.getSpansByIds('<traceId>', spanIds);
|
|
1914
|
+
* ```
|
|
1915
|
+
*/
|
|
1916
|
+
async getSpansByIds(traceId, spanIds) {
|
|
1917
|
+
if (!traceId)
|
|
1918
|
+
throw new ValidationError({ message: 'traceId is required for getSpansByIds' });
|
|
1919
|
+
const response = await this.post(TRACES_ENDPOINTS.POST_BY_IDS, spanIds, { params: { traceId } });
|
|
1920
|
+
const spans = response.data ?? [];
|
|
1921
|
+
return spans.map(span => this.transformOtelSpan(span));
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
__decorate([
|
|
1925
|
+
track('Traces.GetById')
|
|
1926
|
+
], TracesService.prototype, "getById", null);
|
|
1927
|
+
__decorate([
|
|
1928
|
+
track('Traces.GetSpansByIds')
|
|
1929
|
+
], TracesService.prototype, "getSpansByIds", null);
|
|
1930
|
+
|
|
1931
|
+
export { SpanAttachmentDirection, SpanAttachmentProvider, SpanExecutionType, SpanPermissionStatus, SpanSource, SpanStatus, SpanVerbosityLevel, TracesService as Traces };
|