@uipath/uipath-typescript 1.0.0-beta.18 → 1.0.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/README.md +98 -40
- package/dist/assets/index.cjs +2090 -0
- package/dist/assets/index.d.ts +513 -0
- package/dist/assets/index.mjs +2087 -0
- package/dist/buckets/index.cjs +2364 -0
- package/dist/buckets/index.d.ts +819 -0
- package/dist/buckets/index.mjs +2361 -0
- package/dist/cases/index.cjs +3493 -0
- package/dist/cases/index.d.ts +1397 -0
- package/dist/cases/index.mjs +3487 -0
- package/dist/core/index.cjs +5267 -0
- package/dist/core/index.d.ts +406 -0
- package/dist/core/index.mjs +5241 -0
- package/dist/entities/index.cjs +2749 -0
- package/dist/entities/index.d.ts +1513 -0
- package/dist/entities/index.mjs +2743 -0
- package/dist/index.cjs +3571 -3181
- package/dist/index.d.ts +964 -542
- package/dist/index.mjs +3571 -3181
- package/dist/index.umd.js +8561 -12013
- package/dist/maestro-processes/index.cjs +2609 -0
- package/dist/maestro-processes/index.d.ts +1127 -0
- package/dist/maestro-processes/index.mjs +2600 -0
- package/dist/processes/index.cjs +2233 -0
- package/dist/processes/index.d.ts +800 -0
- package/dist/processes/index.mjs +2230 -0
- package/dist/queues/index.cjs +2075 -0
- package/dist/queues/index.d.ts +504 -0
- package/dist/queues/index.mjs +2072 -0
- package/dist/tasks/index.cjs +2675 -0
- package/dist/tasks/index.d.ts +1122 -0
- package/dist/tasks/index.mjs +2671 -0
- package/package.json +100 -6
- package/dist/index.d.cts +0 -5463
- package/dist/index.d.mts +0 -5463
|
@@ -0,0 +1,2743 @@
|
|
|
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
|
+
* Base error class for all UiPath SDK errors
|
|
47
|
+
* Pure TypeScript class with clean interface
|
|
48
|
+
*/
|
|
49
|
+
class UiPathError {
|
|
50
|
+
constructor(type, params) {
|
|
51
|
+
this.type = type;
|
|
52
|
+
this.message = params.message;
|
|
53
|
+
this.statusCode = params.statusCode;
|
|
54
|
+
this.requestId = params.requestId;
|
|
55
|
+
this.timestamp = new Date();
|
|
56
|
+
// Capture stack trace for debugging
|
|
57
|
+
this.stack = (new Error()).stack;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Returns a clean JSON representation of the error
|
|
61
|
+
*/
|
|
62
|
+
toJSON() {
|
|
63
|
+
return {
|
|
64
|
+
type: this.type,
|
|
65
|
+
message: this.message,
|
|
66
|
+
statusCode: this.statusCode,
|
|
67
|
+
requestId: this.requestId,
|
|
68
|
+
timestamp: this.timestamp
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Returns detailed debug information including stack trace
|
|
73
|
+
*/
|
|
74
|
+
getDebugInfo() {
|
|
75
|
+
return {
|
|
76
|
+
...this.toJSON(),
|
|
77
|
+
stack: this.stack
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* HTTP status code constants for error handling
|
|
84
|
+
*/
|
|
85
|
+
const HttpStatus = {
|
|
86
|
+
// Client errors (4xx)
|
|
87
|
+
BAD_REQUEST: 400,
|
|
88
|
+
UNAUTHORIZED: 401,
|
|
89
|
+
FORBIDDEN: 403,
|
|
90
|
+
NOT_FOUND: 404,
|
|
91
|
+
TOO_MANY_REQUESTS: 429,
|
|
92
|
+
// Server errors (5xx)
|
|
93
|
+
INTERNAL_SERVER_ERROR: 500,
|
|
94
|
+
BAD_GATEWAY: 502,
|
|
95
|
+
SERVICE_UNAVAILABLE: 503,
|
|
96
|
+
GATEWAY_TIMEOUT: 504
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Error type constants for consistent error identification
|
|
100
|
+
*/
|
|
101
|
+
const ErrorType = {
|
|
102
|
+
AUTHENTICATION: 'AuthenticationError',
|
|
103
|
+
AUTHORIZATION: 'AuthorizationError',
|
|
104
|
+
VALIDATION: 'ValidationError',
|
|
105
|
+
NOT_FOUND: 'NotFoundError',
|
|
106
|
+
RATE_LIMIT: 'RateLimitError',
|
|
107
|
+
SERVER: 'ServerError',
|
|
108
|
+
NETWORK: 'NetworkError'
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* HTTP header constants for error handling
|
|
112
|
+
*/
|
|
113
|
+
const HttpHeaders = {
|
|
114
|
+
X_REQUEST_ID: 'x-request-id'
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Standard error message constants
|
|
118
|
+
*/
|
|
119
|
+
const ErrorMessages = {
|
|
120
|
+
// Authentication errors
|
|
121
|
+
AUTHENTICATION_FAILED: 'Authentication failed',
|
|
122
|
+
// Authorization errors
|
|
123
|
+
ACCESS_DENIED: 'Access denied',
|
|
124
|
+
// Validation errors
|
|
125
|
+
VALIDATION_FAILED: 'Validation failed',
|
|
126
|
+
// Not found errors
|
|
127
|
+
RESOURCE_NOT_FOUND: 'Resource not found',
|
|
128
|
+
// Rate limit errors
|
|
129
|
+
RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
|
|
130
|
+
// Server errors
|
|
131
|
+
INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
|
|
132
|
+
// Network errors
|
|
133
|
+
NETWORK_ERROR: 'Network error occurred',
|
|
134
|
+
REQUEST_TIMEOUT: 'Request timed out',
|
|
135
|
+
REQUEST_ABORTED: 'Request was aborted',
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Error name constants for network error identification
|
|
139
|
+
*/
|
|
140
|
+
const ErrorNames = {
|
|
141
|
+
ABORT_ERROR: 'AbortError'};
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Error thrown when authentication fails (401 errors)
|
|
145
|
+
* Common scenarios:
|
|
146
|
+
* - Invalid credentials
|
|
147
|
+
* - Expired token
|
|
148
|
+
* - Missing authentication
|
|
149
|
+
*/
|
|
150
|
+
class AuthenticationError extends UiPathError {
|
|
151
|
+
constructor(params = {}) {
|
|
152
|
+
super(ErrorType.AUTHENTICATION, {
|
|
153
|
+
message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
|
|
154
|
+
statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
|
|
155
|
+
requestId: params.requestId
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Error thrown when authorization fails (403 errors)
|
|
162
|
+
* Common scenarios:
|
|
163
|
+
* - Insufficient permissions
|
|
164
|
+
* - Access denied to resource
|
|
165
|
+
* - Invalid scope
|
|
166
|
+
*/
|
|
167
|
+
class AuthorizationError extends UiPathError {
|
|
168
|
+
constructor(params = {}) {
|
|
169
|
+
super(ErrorType.AUTHORIZATION, {
|
|
170
|
+
message: params.message || ErrorMessages.ACCESS_DENIED,
|
|
171
|
+
statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
|
|
172
|
+
requestId: params.requestId
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Error thrown when validation fails (400 errors or client-side validation)
|
|
179
|
+
* Common scenarios:
|
|
180
|
+
* - Invalid input parameters
|
|
181
|
+
* - Missing required fields
|
|
182
|
+
* - Invalid data format
|
|
183
|
+
*/
|
|
184
|
+
class ValidationError extends UiPathError {
|
|
185
|
+
constructor(params = {}) {
|
|
186
|
+
super(ErrorType.VALIDATION, {
|
|
187
|
+
message: params.message || ErrorMessages.VALIDATION_FAILED,
|
|
188
|
+
statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
|
|
189
|
+
requestId: params.requestId
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Error thrown when a resource is not found (404 errors)
|
|
196
|
+
* Common scenarios:
|
|
197
|
+
* - Resource doesn't exist
|
|
198
|
+
* - Invalid ID provided
|
|
199
|
+
* - Resource deleted
|
|
200
|
+
*/
|
|
201
|
+
class NotFoundError extends UiPathError {
|
|
202
|
+
constructor(params = {}) {
|
|
203
|
+
super(ErrorType.NOT_FOUND, {
|
|
204
|
+
message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
|
|
205
|
+
statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
|
|
206
|
+
requestId: params.requestId
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Error thrown when rate limit is exceeded (429 errors)
|
|
213
|
+
* Common scenarios:
|
|
214
|
+
* - Too many requests in a time window
|
|
215
|
+
* - API throttling
|
|
216
|
+
*/
|
|
217
|
+
class RateLimitError extends UiPathError {
|
|
218
|
+
constructor(params = {}) {
|
|
219
|
+
super(ErrorType.RATE_LIMIT, {
|
|
220
|
+
message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
|
|
221
|
+
statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
|
|
222
|
+
requestId: params.requestId
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Error thrown when server encounters an error (5xx errors)
|
|
229
|
+
* Common scenarios:
|
|
230
|
+
* - Internal server error
|
|
231
|
+
* - Service unavailable
|
|
232
|
+
* - Gateway timeout
|
|
233
|
+
*/
|
|
234
|
+
class ServerError extends UiPathError {
|
|
235
|
+
constructor(params = {}) {
|
|
236
|
+
super(ErrorType.SERVER, {
|
|
237
|
+
message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
|
|
238
|
+
statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
|
|
239
|
+
requestId: params.requestId
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Checks if this is a temporary error that might succeed on retry
|
|
244
|
+
*/
|
|
245
|
+
get isRetryable() {
|
|
246
|
+
return this.statusCode === HttpStatus.BAD_GATEWAY ||
|
|
247
|
+
this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
|
|
248
|
+
this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Error thrown when network/connection issues occur
|
|
254
|
+
* Common scenarios:
|
|
255
|
+
* - Connection timeout
|
|
256
|
+
* - DNS resolution failure
|
|
257
|
+
* - Network unreachable
|
|
258
|
+
* - Request aborted
|
|
259
|
+
*/
|
|
260
|
+
class NetworkError extends UiPathError {
|
|
261
|
+
constructor(params = {}) {
|
|
262
|
+
super(ErrorType.NETWORK, {
|
|
263
|
+
message: params.message || ErrorMessages.NETWORK_ERROR,
|
|
264
|
+
statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
|
|
265
|
+
requestId: params.requestId
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Type guards for error response types
|
|
272
|
+
*/
|
|
273
|
+
function isOrchestratorError(error) {
|
|
274
|
+
return typeof error === 'object' &&
|
|
275
|
+
error !== null &&
|
|
276
|
+
'message' in error &&
|
|
277
|
+
'errorCode' in error &&
|
|
278
|
+
typeof error.message === 'string' &&
|
|
279
|
+
typeof error.errorCode === 'number';
|
|
280
|
+
}
|
|
281
|
+
function isEntityError(error) {
|
|
282
|
+
return typeof error === 'object' &&
|
|
283
|
+
error !== null &&
|
|
284
|
+
'error' in error &&
|
|
285
|
+
typeof error.error === 'string';
|
|
286
|
+
}
|
|
287
|
+
function isPimsError(error) {
|
|
288
|
+
return typeof error === 'object' &&
|
|
289
|
+
error !== null &&
|
|
290
|
+
'type' in error &&
|
|
291
|
+
'title' in error &&
|
|
292
|
+
'status' in error &&
|
|
293
|
+
typeof error.type === 'string' &&
|
|
294
|
+
typeof error.title === 'string' &&
|
|
295
|
+
typeof error.status === 'number';
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Parser for Orchestrator/Task error format
|
|
300
|
+
*/
|
|
301
|
+
class OrchestratorErrorParser {
|
|
302
|
+
canParse(errorBody) {
|
|
303
|
+
return isOrchestratorError(errorBody);
|
|
304
|
+
}
|
|
305
|
+
parse(errorBody, response) {
|
|
306
|
+
const error = errorBody;
|
|
307
|
+
return {
|
|
308
|
+
message: error.message,
|
|
309
|
+
code: response?.status?.toString(),
|
|
310
|
+
details: {
|
|
311
|
+
errorCode: error.errorCode,
|
|
312
|
+
traceId: error.traceId,
|
|
313
|
+
originalResponse: error
|
|
314
|
+
},
|
|
315
|
+
requestId: error.traceId
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Parser for Entity (Data Fabric) error format
|
|
321
|
+
*/
|
|
322
|
+
class EntityErrorParser {
|
|
323
|
+
canParse(errorBody) {
|
|
324
|
+
return isEntityError(errorBody);
|
|
325
|
+
}
|
|
326
|
+
parse(errorBody, response) {
|
|
327
|
+
const error = errorBody;
|
|
328
|
+
return {
|
|
329
|
+
message: error.error,
|
|
330
|
+
code: response?.status?.toString(),
|
|
331
|
+
details: {
|
|
332
|
+
error: error.error,
|
|
333
|
+
traceId: error.traceId,
|
|
334
|
+
originalResponse: error
|
|
335
|
+
},
|
|
336
|
+
requestId: error.traceId
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Parser for PIMS error format
|
|
342
|
+
*/
|
|
343
|
+
class PimsErrorParser {
|
|
344
|
+
canParse(errorBody) {
|
|
345
|
+
return isPimsError(errorBody);
|
|
346
|
+
}
|
|
347
|
+
parse(errorBody, response) {
|
|
348
|
+
const error = errorBody;
|
|
349
|
+
let message = error.title;
|
|
350
|
+
// If there are validation errors, append them to the message for better visibility
|
|
351
|
+
if (error.errors && Object.keys(error.errors).length > 0) {
|
|
352
|
+
const errorMessages = Object.entries(error.errors)
|
|
353
|
+
.map(([field, messages]) => `${field}: ${messages.join(', ')}`)
|
|
354
|
+
.join('; ');
|
|
355
|
+
message += `. Validation errors: ${errorMessages}`;
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
message,
|
|
359
|
+
code: response?.status?.toString(),
|
|
360
|
+
details: {
|
|
361
|
+
type: error.type,
|
|
362
|
+
title: error.title,
|
|
363
|
+
status: error.status,
|
|
364
|
+
errors: error.errors,
|
|
365
|
+
traceId: error.traceId,
|
|
366
|
+
originalResponse: error
|
|
367
|
+
},
|
|
368
|
+
requestId: error.traceId
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Fallback parser for unrecognized formats
|
|
374
|
+
*/
|
|
375
|
+
class GenericErrorParser {
|
|
376
|
+
canParse(_errorBody) {
|
|
377
|
+
return true; // Always can parse as last resort
|
|
378
|
+
}
|
|
379
|
+
parse(errorBody, response) {
|
|
380
|
+
// For unknown error formats, just pass through the raw error with fallback message
|
|
381
|
+
const message = response?.statusText || 'An error occurred';
|
|
382
|
+
return {
|
|
383
|
+
message,
|
|
384
|
+
code: response?.status?.toString(),
|
|
385
|
+
details: {
|
|
386
|
+
originalResponse: errorBody
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Main error response parser using Chain of Responsibility pattern
|
|
393
|
+
*
|
|
394
|
+
* This parser standardizes error responses from different UiPath services into a
|
|
395
|
+
* consistent format, regardless of the original error structure.
|
|
396
|
+
*
|
|
397
|
+
* Supported formats:
|
|
398
|
+
* 1. Orchestrator/Task: { message, errorCode, traceId }
|
|
399
|
+
* 2. Entity (Data Fabric): { error, traceId }
|
|
400
|
+
* 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
|
|
401
|
+
* 4. Generic: Fallback for any other format
|
|
402
|
+
*
|
|
403
|
+
* @example
|
|
404
|
+
* const parser = new ErrorResponseParser();
|
|
405
|
+
* const errorInfo = await parser.parse(response);
|
|
406
|
+
* // errorInfo will have consistent structure regardless of service
|
|
407
|
+
*/
|
|
408
|
+
class ErrorResponseParser {
|
|
409
|
+
constructor() {
|
|
410
|
+
this.strategies = [
|
|
411
|
+
new OrchestratorErrorParser(),
|
|
412
|
+
new EntityErrorParser(),
|
|
413
|
+
new PimsErrorParser(),
|
|
414
|
+
new GenericErrorParser() // Must be last
|
|
415
|
+
];
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Parses error response body into standardized format
|
|
419
|
+
* @param response - The HTTP response object
|
|
420
|
+
* @returns Standardized error information
|
|
421
|
+
*/
|
|
422
|
+
async parse(response) {
|
|
423
|
+
try {
|
|
424
|
+
const errorBody = await response.json();
|
|
425
|
+
// Find the first strategy that can parse this error format
|
|
426
|
+
const strategy = this.strategies.find(s => s.canParse(errorBody));
|
|
427
|
+
// GenericErrorParser always returns true, so this will never be null
|
|
428
|
+
return strategy.parse(errorBody, response);
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
// Handle non-JSON responses
|
|
432
|
+
const responseText = await response.text().catch(() => '');
|
|
433
|
+
return {
|
|
434
|
+
message: response.statusText,
|
|
435
|
+
code: response.status.toString(),
|
|
436
|
+
details: {
|
|
437
|
+
parseError: 'Failed to parse error response as JSON',
|
|
438
|
+
responseText
|
|
439
|
+
},
|
|
440
|
+
requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
// Export singleton instance
|
|
446
|
+
const errorResponseParser = new ErrorResponseParser();
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Factory for creating typed errors based on HTTP status codes
|
|
450
|
+
* Follows the Factory pattern for clean error instantiation
|
|
451
|
+
*/
|
|
452
|
+
class ErrorFactory {
|
|
453
|
+
/**
|
|
454
|
+
* Creates appropriate error instance based on HTTP status code
|
|
455
|
+
*/
|
|
456
|
+
static createFromHttpStatus(statusCode, errorInfo) {
|
|
457
|
+
const { message, requestId } = errorInfo;
|
|
458
|
+
// Map status codes to error types
|
|
459
|
+
switch (statusCode) {
|
|
460
|
+
case HttpStatus.BAD_REQUEST:
|
|
461
|
+
return new ValidationError({ message, statusCode, requestId });
|
|
462
|
+
case HttpStatus.UNAUTHORIZED:
|
|
463
|
+
return new AuthenticationError({ message, statusCode, requestId });
|
|
464
|
+
case HttpStatus.FORBIDDEN:
|
|
465
|
+
return new AuthorizationError({ message, statusCode, requestId });
|
|
466
|
+
case HttpStatus.NOT_FOUND:
|
|
467
|
+
return new NotFoundError({ message, statusCode, requestId });
|
|
468
|
+
case HttpStatus.TOO_MANY_REQUESTS:
|
|
469
|
+
return new RateLimitError({ message, statusCode, requestId });
|
|
470
|
+
default:
|
|
471
|
+
// For 5xx errors or any other status code
|
|
472
|
+
if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
|
|
473
|
+
return new ServerError({ message, statusCode, requestId });
|
|
474
|
+
}
|
|
475
|
+
// For unknown client errors, treat as validation error
|
|
476
|
+
return new ValidationError({
|
|
477
|
+
message: `${message} (HTTP ${statusCode})`,
|
|
478
|
+
statusCode,
|
|
479
|
+
requestId
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Creates a NetworkError from a fetch/network error
|
|
485
|
+
*/
|
|
486
|
+
static createNetworkError(error) {
|
|
487
|
+
let message = ErrorMessages.NETWORK_ERROR;
|
|
488
|
+
if (error instanceof Error) {
|
|
489
|
+
if (error.name === ErrorNames.ABORT_ERROR) {
|
|
490
|
+
message = ErrorMessages.REQUEST_ABORTED;
|
|
491
|
+
}
|
|
492
|
+
else if (error.message.includes('timeout')) {
|
|
493
|
+
message = ErrorMessages.REQUEST_TIMEOUT;
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
message = error.message;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return new NetworkError({ message });
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
|
|
504
|
+
/**
|
|
505
|
+
* Content type constants for HTTP requests/responses
|
|
506
|
+
*/
|
|
507
|
+
const CONTENT_TYPES = {
|
|
508
|
+
JSON: 'application/json',
|
|
509
|
+
XML: 'application/xml',
|
|
510
|
+
OCTET_STREAM: 'application/octet-stream'
|
|
511
|
+
};
|
|
512
|
+
/**
|
|
513
|
+
* Response type constants for HTTP requests
|
|
514
|
+
*/
|
|
515
|
+
const RESPONSE_TYPES = {
|
|
516
|
+
JSON: 'json',
|
|
517
|
+
TEXT: 'text',
|
|
518
|
+
BLOB: 'blob',
|
|
519
|
+
ARRAYBUFFER: 'arraybuffer'
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
class ApiClient {
|
|
523
|
+
constructor(config, executionContext, tokenManager, clientConfig = {}) {
|
|
524
|
+
this.defaultHeaders = {};
|
|
525
|
+
this.config = config;
|
|
526
|
+
this.executionContext = executionContext;
|
|
527
|
+
this.clientConfig = clientConfig;
|
|
528
|
+
this.tokenManager = tokenManager;
|
|
529
|
+
}
|
|
530
|
+
setDefaultHeaders(headers) {
|
|
531
|
+
this.defaultHeaders = { ...this.defaultHeaders, ...headers };
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Gets a valid authentication token, refreshing if necessary.
|
|
535
|
+
* Used internally for API requests and exposed for services that need manual auth headers.
|
|
536
|
+
*
|
|
537
|
+
* @returns The valid token
|
|
538
|
+
* @throws AuthenticationError if no token available or refresh fails
|
|
539
|
+
*/
|
|
540
|
+
async getValidToken() {
|
|
541
|
+
// Try to get token info from context
|
|
542
|
+
const tokenInfo = this.executionContext.get('tokenInfo');
|
|
543
|
+
if (!tokenInfo) {
|
|
544
|
+
throw new AuthenticationError({ message: 'No authentication token available. Make sure to initialize the SDK first.' });
|
|
545
|
+
}
|
|
546
|
+
// For secret-based tokens, they never expire
|
|
547
|
+
if (tokenInfo.type === 'secret') {
|
|
548
|
+
return tokenInfo.token;
|
|
549
|
+
}
|
|
550
|
+
// If token is not expired, return it
|
|
551
|
+
if (!this.tokenManager.isTokenExpired(tokenInfo)) {
|
|
552
|
+
return tokenInfo.token;
|
|
553
|
+
}
|
|
554
|
+
try {
|
|
555
|
+
const newToken = await this.tokenManager.refreshAccessToken();
|
|
556
|
+
return newToken.access_token;
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
throw new AuthenticationError({
|
|
560
|
+
message: `Token refresh failed: ${error.message}. Please re-authenticate.`,
|
|
561
|
+
statusCode: HttpStatus.UNAUTHORIZED
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
async getDefaultHeaders() {
|
|
566
|
+
// Get headers from execution context first
|
|
567
|
+
const contextHeaders = this.executionContext.getHeaders();
|
|
568
|
+
// If Authorization header is already set in context, use that
|
|
569
|
+
if (contextHeaders['Authorization']) {
|
|
570
|
+
return {
|
|
571
|
+
...contextHeaders,
|
|
572
|
+
'Content-Type': CONTENT_TYPES.JSON,
|
|
573
|
+
...this.defaultHeaders,
|
|
574
|
+
...this.clientConfig.headers
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
const token = await this.getValidToken();
|
|
578
|
+
return {
|
|
579
|
+
...contextHeaders,
|
|
580
|
+
'Authorization': `Bearer ${token}`,
|
|
581
|
+
'Content-Type': CONTENT_TYPES.JSON,
|
|
582
|
+
...this.defaultHeaders,
|
|
583
|
+
...this.clientConfig.headers
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
async request(method, path, options = {}) {
|
|
587
|
+
// Ensure path starts with a forward slash
|
|
588
|
+
const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
|
|
589
|
+
// Construct URL with org and tenant names
|
|
590
|
+
const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
|
|
591
|
+
const headers = {
|
|
592
|
+
...await this.getDefaultHeaders(),
|
|
593
|
+
...options.headers
|
|
594
|
+
};
|
|
595
|
+
// Convert params to URLSearchParams
|
|
596
|
+
const searchParams = new URLSearchParams();
|
|
597
|
+
if (options.params) {
|
|
598
|
+
Object.entries(options.params).forEach(([key, value]) => {
|
|
599
|
+
searchParams.append(key, value.toString());
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
|
|
603
|
+
try {
|
|
604
|
+
const response = await fetch(fullUrl, {
|
|
605
|
+
method,
|
|
606
|
+
headers,
|
|
607
|
+
body: options.body ? JSON.stringify(options.body) : undefined,
|
|
608
|
+
signal: options.signal
|
|
609
|
+
});
|
|
610
|
+
if (!response.ok) {
|
|
611
|
+
const errorInfo = await errorResponseParser.parse(response);
|
|
612
|
+
throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
|
|
613
|
+
}
|
|
614
|
+
if (response.status === 204) {
|
|
615
|
+
return undefined;
|
|
616
|
+
}
|
|
617
|
+
// Handle blob response type for binary data (e.g., file downloads)
|
|
618
|
+
if (options.responseType === RESPONSE_TYPES.BLOB) {
|
|
619
|
+
const blob = await response.blob();
|
|
620
|
+
return blob;
|
|
621
|
+
}
|
|
622
|
+
// Check if we're expecting XML
|
|
623
|
+
const acceptHeader = headers['Accept'] || headers['accept'];
|
|
624
|
+
if (acceptHeader === CONTENT_TYPES.XML) {
|
|
625
|
+
const text = await response.text();
|
|
626
|
+
return text;
|
|
627
|
+
}
|
|
628
|
+
return response.json();
|
|
629
|
+
}
|
|
630
|
+
catch (error) {
|
|
631
|
+
// If it's already one of our errors, re-throw it
|
|
632
|
+
if (error.type && error.type.includes('Error')) {
|
|
633
|
+
throw error;
|
|
634
|
+
}
|
|
635
|
+
// Otherwise, it's likely a network error
|
|
636
|
+
throw ErrorFactory.createNetworkError(error);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
async get(path, options = {}) {
|
|
640
|
+
return this.request('GET', path, options);
|
|
641
|
+
}
|
|
642
|
+
async post(path, data, options = {}) {
|
|
643
|
+
return this.request('POST', path, { ...options, body: data });
|
|
644
|
+
}
|
|
645
|
+
async put(path, data, options = {}) {
|
|
646
|
+
return this.request('PUT', path, { ...options, body: data });
|
|
647
|
+
}
|
|
648
|
+
async patch(path, data, options = {}) {
|
|
649
|
+
return this.request('PATCH', path, { ...options, body: data });
|
|
650
|
+
}
|
|
651
|
+
async delete(path, options = {}) {
|
|
652
|
+
return this.request('DELETE', path, options);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* Pagination types supported by the SDK
|
|
658
|
+
*/
|
|
659
|
+
var PaginationType;
|
|
660
|
+
(function (PaginationType) {
|
|
661
|
+
PaginationType["OFFSET"] = "offset";
|
|
662
|
+
PaginationType["TOKEN"] = "token";
|
|
663
|
+
})(PaginationType || (PaginationType = {}));
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Collection of utility functions for working with objects
|
|
667
|
+
*/
|
|
668
|
+
/**
|
|
669
|
+
* Filters out undefined values from an object
|
|
670
|
+
* @param obj The source object
|
|
671
|
+
* @returns A new object without undefined values
|
|
672
|
+
*
|
|
673
|
+
* @example
|
|
674
|
+
* ```typescript
|
|
675
|
+
* // Object with undefined values
|
|
676
|
+
* const options = {
|
|
677
|
+
* name: 'test',
|
|
678
|
+
* count: 5,
|
|
679
|
+
* prefix: undefined,
|
|
680
|
+
* suffix: null
|
|
681
|
+
* };
|
|
682
|
+
* const result = filterUndefined(options);
|
|
683
|
+
* // result = { name: 'test', count: 5, suffix: null }
|
|
684
|
+
* ```
|
|
685
|
+
*/
|
|
686
|
+
function filterUndefined(obj) {
|
|
687
|
+
const result = {};
|
|
688
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
689
|
+
if (value !== undefined) {
|
|
690
|
+
result[key] = value;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
return result;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Utility functions for platform detection
|
|
698
|
+
*/
|
|
699
|
+
/**
|
|
700
|
+
* Checks if code is running in a browser environment
|
|
701
|
+
*/
|
|
702
|
+
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* Base64 encoding/decoding
|
|
706
|
+
*/
|
|
707
|
+
/**
|
|
708
|
+
* Encodes a string to base64
|
|
709
|
+
* @param str - The string to encode
|
|
710
|
+
* @returns Base64 encoded string
|
|
711
|
+
*/
|
|
712
|
+
function encodeBase64(str) {
|
|
713
|
+
// TextEncoder for UTF-8 encoding (works in both browser and Node.js)
|
|
714
|
+
const encoder = new TextEncoder();
|
|
715
|
+
const data = encoder.encode(str);
|
|
716
|
+
// Convert Uint8Array to base64
|
|
717
|
+
if (isBrowser) {
|
|
718
|
+
// Browser environment
|
|
719
|
+
// Convert Uint8Array to binary string then to base64
|
|
720
|
+
const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
|
|
721
|
+
return btoa(binaryString);
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
// Node.js environment
|
|
725
|
+
return Buffer.from(data).toString('base64');
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Decodes a base64 string
|
|
730
|
+
* @param base64 - The base64 string to decode
|
|
731
|
+
* @returns Decoded string
|
|
732
|
+
*/
|
|
733
|
+
function decodeBase64(base64) {
|
|
734
|
+
let bytes;
|
|
735
|
+
if (isBrowser) {
|
|
736
|
+
// Browser environment
|
|
737
|
+
const binaryString = atob(base64);
|
|
738
|
+
bytes = new Uint8Array(binaryString.length);
|
|
739
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
740
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
else {
|
|
744
|
+
// Node.js environment
|
|
745
|
+
bytes = new Uint8Array(Buffer.from(base64, 'base64'));
|
|
746
|
+
}
|
|
747
|
+
// TextDecoder for UTF-8 decoding (works in both browser and Node.js)
|
|
748
|
+
const decoder = new TextDecoder();
|
|
749
|
+
return decoder.decode(bytes);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* PaginationManager handles the conversion between uniform cursor-based pagination
|
|
754
|
+
* and the specific pagination type for each service
|
|
755
|
+
*/
|
|
756
|
+
class PaginationManager {
|
|
757
|
+
/**
|
|
758
|
+
* Create a pagination cursor for subsequent page requests
|
|
759
|
+
*/
|
|
760
|
+
static createCursor({ pageInfo, type }) {
|
|
761
|
+
if (!pageInfo.hasMore) {
|
|
762
|
+
return undefined;
|
|
763
|
+
}
|
|
764
|
+
const cursorData = {
|
|
765
|
+
type,
|
|
766
|
+
pageSize: pageInfo.pageSize,
|
|
767
|
+
};
|
|
768
|
+
switch (type) {
|
|
769
|
+
case PaginationType.OFFSET:
|
|
770
|
+
if (pageInfo.currentPage) {
|
|
771
|
+
cursorData.pageNumber = pageInfo.currentPage + 1;
|
|
772
|
+
}
|
|
773
|
+
break;
|
|
774
|
+
case PaginationType.TOKEN:
|
|
775
|
+
if (pageInfo.continuationToken) {
|
|
776
|
+
cursorData.continuationToken = pageInfo.continuationToken;
|
|
777
|
+
}
|
|
778
|
+
else {
|
|
779
|
+
return undefined; // No continuation token, can't continue
|
|
780
|
+
}
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
783
|
+
return {
|
|
784
|
+
value: encodeBase64(JSON.stringify(cursorData))
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Create a paginated response with navigation cursors
|
|
789
|
+
*/
|
|
790
|
+
static createPaginatedResponse({ pageInfo, type }, items) {
|
|
791
|
+
const nextCursor = PaginationManager.createCursor({ pageInfo, type });
|
|
792
|
+
// Create previous page cursor if applicable
|
|
793
|
+
let previousCursor = undefined;
|
|
794
|
+
if (pageInfo.currentPage && pageInfo.currentPage > 1) {
|
|
795
|
+
const prevCursorData = {
|
|
796
|
+
type,
|
|
797
|
+
pageNumber: pageInfo.currentPage - 1,
|
|
798
|
+
pageSize: pageInfo.pageSize,
|
|
799
|
+
};
|
|
800
|
+
previousCursor = {
|
|
801
|
+
value: encodeBase64(JSON.stringify(prevCursorData))
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
// Calculate total pages if we have totalCount and pageSize
|
|
805
|
+
let totalPages = undefined;
|
|
806
|
+
if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
|
|
807
|
+
totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
|
|
808
|
+
}
|
|
809
|
+
// Determine if this pagination type supports page jumping
|
|
810
|
+
const supportsPageJump = type === PaginationType.OFFSET;
|
|
811
|
+
// Create the result object with all fields, then filter out undefined values
|
|
812
|
+
const result = filterUndefined({
|
|
813
|
+
items,
|
|
814
|
+
totalCount: pageInfo.totalCount,
|
|
815
|
+
hasNextPage: pageInfo.hasMore,
|
|
816
|
+
nextCursor: nextCursor,
|
|
817
|
+
previousCursor: previousCursor,
|
|
818
|
+
currentPage: pageInfo.currentPage,
|
|
819
|
+
totalPages,
|
|
820
|
+
supportsPageJump
|
|
821
|
+
});
|
|
822
|
+
return result;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Creates headers object from key-value pairs
|
|
828
|
+
* @param headersObj - Object containing header key-value pairs
|
|
829
|
+
* @returns Headers object with all values converted to strings
|
|
830
|
+
*
|
|
831
|
+
* @example
|
|
832
|
+
* ```typescript
|
|
833
|
+
* // Single header
|
|
834
|
+
* const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
|
|
835
|
+
*
|
|
836
|
+
* // Multiple headers
|
|
837
|
+
* const headers = createHeaders({
|
|
838
|
+
* 'X-UIPATH-FolderKey': '1234567890',
|
|
839
|
+
* 'X-UIPATH-OrganizationUnitId': 123,
|
|
840
|
+
* 'Accept': 'application/json'
|
|
841
|
+
* });
|
|
842
|
+
*
|
|
843
|
+
* // Using constants
|
|
844
|
+
* import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
|
|
845
|
+
* const headers = createHeaders({
|
|
846
|
+
* [FOLDER_KEY]: 'abc-123',
|
|
847
|
+
* [FOLDER_ID]: 456
|
|
848
|
+
* });
|
|
849
|
+
*
|
|
850
|
+
* // Empty headers
|
|
851
|
+
* const headers = createHeaders();
|
|
852
|
+
* ```
|
|
853
|
+
*/
|
|
854
|
+
function createHeaders(headersObj) {
|
|
855
|
+
const headers = {};
|
|
856
|
+
for (const [key, value] of Object.entries(headersObj)) {
|
|
857
|
+
if (value !== undefined && value !== null) {
|
|
858
|
+
headers[key] = value.toString();
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
return headers;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
/**
|
|
865
|
+
* Common constants used across the SDK
|
|
866
|
+
*/
|
|
867
|
+
/**
|
|
868
|
+
* Prefix used for OData query parameters
|
|
869
|
+
*/
|
|
870
|
+
const ODATA_PREFIX = '$';
|
|
871
|
+
/**
|
|
872
|
+
* HTTP methods
|
|
873
|
+
*/
|
|
874
|
+
const HTTP_METHODS = {
|
|
875
|
+
GET: 'GET',
|
|
876
|
+
POST: 'POST'};
|
|
877
|
+
/**
|
|
878
|
+
* Entity pagination constants for Data Fabric entities
|
|
879
|
+
*/
|
|
880
|
+
const ENTITY_PAGINATION = {
|
|
881
|
+
/** Field name for items in entity response */
|
|
882
|
+
ITEMS_FIELD: 'value',
|
|
883
|
+
/** Field name for total count in entity response */
|
|
884
|
+
TOTAL_COUNT_FIELD: 'totalRecordCount'
|
|
885
|
+
};
|
|
886
|
+
/**
|
|
887
|
+
* Choice Set values endpoint pagination constants
|
|
888
|
+
* Note: The API returns items as a JSON string in 'jsonValue' field
|
|
889
|
+
*/
|
|
890
|
+
const CHOICESET_VALUES_PAGINATION = {
|
|
891
|
+
/** Field name for items in choice set values response (contains JSON string) */
|
|
892
|
+
ITEMS_FIELD: 'jsonValue',
|
|
893
|
+
/** Field name for total count in choice set values response */
|
|
894
|
+
TOTAL_COUNT_FIELD: 'totalRecordCount'
|
|
895
|
+
};
|
|
896
|
+
/**
|
|
897
|
+
* OData OFFSET pagination parameter names (ODATA-style)
|
|
898
|
+
*/
|
|
899
|
+
const ODATA_OFFSET_PARAMS = {
|
|
900
|
+
/** OData page size parameter name */
|
|
901
|
+
PAGE_SIZE_PARAM: '$top',
|
|
902
|
+
/** OData offset parameter name */
|
|
903
|
+
OFFSET_PARAM: '$skip',
|
|
904
|
+
/** OData count parameter name */
|
|
905
|
+
COUNT_PARAM: '$count'
|
|
906
|
+
};
|
|
907
|
+
/**
|
|
908
|
+
* Entity OFFSET pagination parameter names (limit/start style)
|
|
909
|
+
*/
|
|
910
|
+
const ENTITY_OFFSET_PARAMS = {
|
|
911
|
+
/** Entity page size parameter name */
|
|
912
|
+
PAGE_SIZE_PARAM: 'limit',
|
|
913
|
+
/** Entity offset parameter name */
|
|
914
|
+
OFFSET_PARAM: 'start',
|
|
915
|
+
/** Entity count parameter (not used) */
|
|
916
|
+
COUNT_PARAM: undefined
|
|
917
|
+
};
|
|
918
|
+
/**
|
|
919
|
+
* Bucket TOKEN pagination parameter names
|
|
920
|
+
*/
|
|
921
|
+
const BUCKET_TOKEN_PARAMS = {
|
|
922
|
+
/** Bucket page size parameter name */
|
|
923
|
+
PAGE_SIZE_PARAM: 'takeHint',
|
|
924
|
+
/** Bucket token parameter name */
|
|
925
|
+
TOKEN_PARAM: 'continuationToken'
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Transforms data by mapping fields according to the provided field mapping
|
|
930
|
+
* @param data The source data to transform
|
|
931
|
+
* @param fieldMapping Object mapping source field names to target field names
|
|
932
|
+
* @returns Transformed data with mapped field names
|
|
933
|
+
*
|
|
934
|
+
* @example
|
|
935
|
+
* ```typescript
|
|
936
|
+
* // Single object transformation
|
|
937
|
+
* const data = { id: '123', userName: 'john' };
|
|
938
|
+
* const mapping = { id: 'userId', userName: 'name' };
|
|
939
|
+
* const result = transformData(data, mapping);
|
|
940
|
+
* // result = { userId: '123', name: 'john' }
|
|
941
|
+
*
|
|
942
|
+
* // Array transformation
|
|
943
|
+
* const dataArray = [
|
|
944
|
+
* { id: '123', userName: 'john' },
|
|
945
|
+
* { id: '456', userName: 'jane' }
|
|
946
|
+
* ];
|
|
947
|
+
* const result = transformData(dataArray, mapping);
|
|
948
|
+
* // result = [
|
|
949
|
+
* // { userId: '123', name: 'john' },
|
|
950
|
+
* // { userId: '456', name: 'jane' }
|
|
951
|
+
* // ]
|
|
952
|
+
* ```
|
|
953
|
+
*/
|
|
954
|
+
function transformData(data, fieldMapping) {
|
|
955
|
+
// Handle array of objects
|
|
956
|
+
if (Array.isArray(data)) {
|
|
957
|
+
return data.map(item => transformData(item, fieldMapping));
|
|
958
|
+
}
|
|
959
|
+
// Handle single object
|
|
960
|
+
const result = { ...data };
|
|
961
|
+
for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
|
|
962
|
+
if (sourceField in result) {
|
|
963
|
+
const value = result[sourceField];
|
|
964
|
+
delete result[sourceField];
|
|
965
|
+
result[targetField] = value;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return result;
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Converts a string from PascalCase to camelCase
|
|
972
|
+
* @param str The PascalCase string to convert
|
|
973
|
+
* @returns The camelCase version of the string
|
|
974
|
+
*
|
|
975
|
+
* @example
|
|
976
|
+
* ```typescript
|
|
977
|
+
* pascalToCamelCase('HelloWorld'); // 'helloWorld'
|
|
978
|
+
* pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
|
|
979
|
+
* ```
|
|
980
|
+
*/
|
|
981
|
+
function pascalToCamelCase(str) {
|
|
982
|
+
if (!str)
|
|
983
|
+
return str;
|
|
984
|
+
return str.charAt(0).toLowerCase() + str.slice(1);
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Generic function to transform object keys using a provided case conversion function
|
|
988
|
+
* @param data The object to transform
|
|
989
|
+
* @param convertCase The function to convert each key
|
|
990
|
+
* @returns A new object with transformed keys
|
|
991
|
+
*/
|
|
992
|
+
function transformCaseKeys(data, convertCase) {
|
|
993
|
+
// Handle array of objects
|
|
994
|
+
if (Array.isArray(data)) {
|
|
995
|
+
return data.map(item => {
|
|
996
|
+
// If the array element is a primitive (string, number, etc.), return it as is
|
|
997
|
+
if (item === null || typeof item !== 'object' || typeof item === 'string') {
|
|
998
|
+
return item;
|
|
999
|
+
}
|
|
1000
|
+
// Only recursively transform if it's actually an object
|
|
1001
|
+
return transformCaseKeys(item, convertCase);
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
const result = {};
|
|
1005
|
+
for (const [key, value] of Object.entries(data)) {
|
|
1006
|
+
const transformedKey = convertCase(key);
|
|
1007
|
+
// Recursively transform nested objects and arrays
|
|
1008
|
+
if (value !== null && typeof value === 'object') {
|
|
1009
|
+
result[transformedKey] = transformCaseKeys(value, convertCase);
|
|
1010
|
+
}
|
|
1011
|
+
else {
|
|
1012
|
+
result[transformedKey] = value;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
return result;
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* Transforms an object's keys from PascalCase to camelCase
|
|
1019
|
+
* @param data The object with PascalCase keys
|
|
1020
|
+
* @returns A new object with all keys converted to camelCase
|
|
1021
|
+
*
|
|
1022
|
+
* @example
|
|
1023
|
+
* ```typescript
|
|
1024
|
+
* // Simple object
|
|
1025
|
+
* pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
|
|
1026
|
+
* // Result: { id: "123", taskName: "Invoice" }
|
|
1027
|
+
*
|
|
1028
|
+
* // Nested object
|
|
1029
|
+
* pascalToCamelCaseKeys({
|
|
1030
|
+
* TaskId: "456",
|
|
1031
|
+
* TaskDetails: { AssignedUser: "John", Priority: "High" }
|
|
1032
|
+
* });
|
|
1033
|
+
* // Result: {
|
|
1034
|
+
* // taskId: "456",
|
|
1035
|
+
* // taskDetails: { assignedUser: "John", priority: "High" }
|
|
1036
|
+
* // }
|
|
1037
|
+
*
|
|
1038
|
+
* // Array of objects
|
|
1039
|
+
* pascalToCamelCaseKeys([
|
|
1040
|
+
* { Id: "1", IsComplete: false },
|
|
1041
|
+
* { Id: "2", IsComplete: true }
|
|
1042
|
+
* ]);
|
|
1043
|
+
* // Result: [
|
|
1044
|
+
* // { id: "1", isComplete: false },
|
|
1045
|
+
* // { id: "2", isComplete: true }
|
|
1046
|
+
* // ]
|
|
1047
|
+
* ```
|
|
1048
|
+
*/
|
|
1049
|
+
function pascalToCamelCaseKeys(data) {
|
|
1050
|
+
return transformCaseKeys(data, pascalToCamelCase);
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Adds a prefix to specified keys in an object, returning a new object.
|
|
1054
|
+
* Only the provided keys are prefixed; all others are left unchanged.
|
|
1055
|
+
*
|
|
1056
|
+
* @param obj The source object
|
|
1057
|
+
* @param prefix The prefix to add (e.g., '$')
|
|
1058
|
+
* @param keys The keys to prefix (e.g., ['expand', 'filter'])
|
|
1059
|
+
* @returns A new object with specified keys prefixed
|
|
1060
|
+
*
|
|
1061
|
+
* @example
|
|
1062
|
+
* addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
|
|
1063
|
+
*/
|
|
1064
|
+
function addPrefixToKeys(obj, prefix, keys) {
|
|
1065
|
+
const result = {};
|
|
1066
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
1067
|
+
if (keys.includes(key)) {
|
|
1068
|
+
result[`${prefix}${key}`] = value;
|
|
1069
|
+
}
|
|
1070
|
+
else {
|
|
1071
|
+
result[key] = value;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
return result;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* Constants used throughout the pagination system
|
|
1079
|
+
*/
|
|
1080
|
+
/** Maximum number of items that can be requested in a single page */
|
|
1081
|
+
const MAX_PAGE_SIZE = 1000;
|
|
1082
|
+
/** Default page size when jumpToPage is used without specifying pageSize */
|
|
1083
|
+
const DEFAULT_PAGE_SIZE = 50;
|
|
1084
|
+
/** Default field name for items in a paginated response */
|
|
1085
|
+
const DEFAULT_ITEMS_FIELD = 'value';
|
|
1086
|
+
/** Default field name for total count in a paginated response */
|
|
1087
|
+
const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
|
|
1088
|
+
/**
|
|
1089
|
+
* Limits the page size to the maximum allowed value
|
|
1090
|
+
* @param pageSize - Requested page size
|
|
1091
|
+
* @returns Limited page size value
|
|
1092
|
+
*/
|
|
1093
|
+
function getLimitedPageSize(pageSize) {
|
|
1094
|
+
if (pageSize === undefined || pageSize === null) {
|
|
1095
|
+
return DEFAULT_PAGE_SIZE;
|
|
1096
|
+
}
|
|
1097
|
+
return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
/**
|
|
1101
|
+
* Helper functions for pagination that can be used across services
|
|
1102
|
+
*/
|
|
1103
|
+
class PaginationHelpers {
|
|
1104
|
+
/**
|
|
1105
|
+
* Checks if any pagination parameters are provided
|
|
1106
|
+
*
|
|
1107
|
+
* @param options - The options object to check
|
|
1108
|
+
* @returns True if any pagination parameter is defined, false otherwise
|
|
1109
|
+
*/
|
|
1110
|
+
static hasPaginationParameters(options = {}) {
|
|
1111
|
+
const { cursor, pageSize, jumpToPage } = options;
|
|
1112
|
+
return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Parse a pagination cursor string into cursor data
|
|
1116
|
+
*/
|
|
1117
|
+
static parseCursor(cursorString) {
|
|
1118
|
+
try {
|
|
1119
|
+
const cursorData = JSON.parse(decodeBase64(cursorString));
|
|
1120
|
+
return cursorData;
|
|
1121
|
+
}
|
|
1122
|
+
catch {
|
|
1123
|
+
throw new Error('Invalid pagination cursor');
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Validates cursor format and structure
|
|
1128
|
+
*
|
|
1129
|
+
* @param paginationOptions - The pagination options containing the cursor
|
|
1130
|
+
* @param paginationType - Optional pagination type to validate against
|
|
1131
|
+
*/
|
|
1132
|
+
static validateCursor(paginationOptions, paginationType) {
|
|
1133
|
+
if (paginationOptions.cursor !== undefined) {
|
|
1134
|
+
if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
|
|
1135
|
+
throw new Error('cursor must contain a valid cursor string');
|
|
1136
|
+
}
|
|
1137
|
+
try {
|
|
1138
|
+
// Try to parse the cursor to validate it
|
|
1139
|
+
const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
|
|
1140
|
+
// If type is provided, validate cursor contains expected type information
|
|
1141
|
+
if (paginationType) {
|
|
1142
|
+
if (!cursorData.type) {
|
|
1143
|
+
throw new Error('Invalid cursor: missing pagination type');
|
|
1144
|
+
}
|
|
1145
|
+
// Check pagination type compatibility
|
|
1146
|
+
if (cursorData.type !== paginationType) {
|
|
1147
|
+
throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
catch (error) {
|
|
1152
|
+
if (error instanceof Error) {
|
|
1153
|
+
// If it's already our error with specific message, pass it through
|
|
1154
|
+
if (error.message.startsWith('Invalid cursor') ||
|
|
1155
|
+
error.message.startsWith('Pagination type mismatch')) {
|
|
1156
|
+
throw error;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
throw new Error('Invalid pagination cursor format');
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Comprehensive validation for pagination options
|
|
1165
|
+
*
|
|
1166
|
+
* @param options - The pagination options to validate
|
|
1167
|
+
* @param paginationType - The pagination type these options will be used with
|
|
1168
|
+
* @returns Processed pagination parameters ready for use
|
|
1169
|
+
*/
|
|
1170
|
+
static validatePaginationOptions(options, paginationType) {
|
|
1171
|
+
// Validate pageSize
|
|
1172
|
+
if (options.pageSize !== undefined && options.pageSize <= 0) {
|
|
1173
|
+
throw new Error('pageSize must be a positive number');
|
|
1174
|
+
}
|
|
1175
|
+
// Validate jumpToPage
|
|
1176
|
+
if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
|
|
1177
|
+
throw new Error('jumpToPage must be a positive number');
|
|
1178
|
+
}
|
|
1179
|
+
// Validate cursor
|
|
1180
|
+
PaginationHelpers.validateCursor(options, paginationType);
|
|
1181
|
+
// Validate service compatibility
|
|
1182
|
+
if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
|
|
1183
|
+
throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
|
|
1184
|
+
}
|
|
1185
|
+
// Get processed parameters
|
|
1186
|
+
return PaginationHelpers.getRequestParameters(options, paginationType);
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* Convert a unified pagination options to service-specific parameters
|
|
1190
|
+
*/
|
|
1191
|
+
static getRequestParameters(options, paginationType) {
|
|
1192
|
+
// Handle jumpToPage
|
|
1193
|
+
if (options.jumpToPage !== undefined) {
|
|
1194
|
+
const jumpToPageOptions = {
|
|
1195
|
+
pageSize: options.pageSize,
|
|
1196
|
+
pageNumber: options.jumpToPage
|
|
1197
|
+
};
|
|
1198
|
+
return filterUndefined(jumpToPageOptions);
|
|
1199
|
+
}
|
|
1200
|
+
// If no cursor is provided, it's a first page request
|
|
1201
|
+
if (!options.cursor) {
|
|
1202
|
+
const firstPageOptions = {
|
|
1203
|
+
pageSize: options.pageSize,
|
|
1204
|
+
// Only set pageNumber for OFFSET pagination
|
|
1205
|
+
pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
|
|
1206
|
+
};
|
|
1207
|
+
return filterUndefined(firstPageOptions);
|
|
1208
|
+
}
|
|
1209
|
+
// Parse the cursor
|
|
1210
|
+
try {
|
|
1211
|
+
const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
|
|
1212
|
+
const cursorBasedOptions = {
|
|
1213
|
+
pageSize: cursorData.pageSize || options.pageSize,
|
|
1214
|
+
pageNumber: cursorData.pageNumber,
|
|
1215
|
+
continuationToken: cursorData.continuationToken,
|
|
1216
|
+
type: cursorData.type,
|
|
1217
|
+
};
|
|
1218
|
+
return filterUndefined(cursorBasedOptions);
|
|
1219
|
+
}
|
|
1220
|
+
catch {
|
|
1221
|
+
throw new Error('Invalid pagination cursor');
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* Helper method for paginated resource retrieval
|
|
1226
|
+
*
|
|
1227
|
+
* @param params - Parameters for pagination
|
|
1228
|
+
* @returns Promise resolving to a paginated result
|
|
1229
|
+
*/
|
|
1230
|
+
static async getAllPaginated(params) {
|
|
1231
|
+
const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
|
|
1232
|
+
const endpoint = getEndpoint(folderId);
|
|
1233
|
+
const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
|
|
1234
|
+
const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
|
|
1235
|
+
headers,
|
|
1236
|
+
params: additionalParams,
|
|
1237
|
+
pagination: {
|
|
1238
|
+
paginationType: options.paginationType || PaginationType.OFFSET,
|
|
1239
|
+
itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
|
|
1240
|
+
totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
|
|
1241
|
+
continuationTokenField: options.continuationTokenField,
|
|
1242
|
+
paginationParams: options.paginationParams
|
|
1243
|
+
}
|
|
1244
|
+
});
|
|
1245
|
+
// Parse items - automatically handle JSON string responses
|
|
1246
|
+
const rawItems = paginatedResponse.items;
|
|
1247
|
+
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1248
|
+
const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1249
|
+
return {
|
|
1250
|
+
...paginatedResponse,
|
|
1251
|
+
items: transformedItems
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Helper method for non-paginated resource retrieval
|
|
1256
|
+
*
|
|
1257
|
+
* @param params - Parameters for non-paginated resource retrieval
|
|
1258
|
+
* @returns Promise resolving to an object with data and totalCount
|
|
1259
|
+
*/
|
|
1260
|
+
static async getAllNonPaginated(params) {
|
|
1261
|
+
const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
|
|
1262
|
+
// Set default field names
|
|
1263
|
+
const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
|
|
1264
|
+
const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
|
|
1265
|
+
// Determine endpoint and headers based on folderId
|
|
1266
|
+
const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
|
|
1267
|
+
const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
|
|
1268
|
+
// Make the API call based on method
|
|
1269
|
+
let response;
|
|
1270
|
+
if (method === HTTP_METHODS.POST) {
|
|
1271
|
+
response = await serviceAccess.post(endpoint, additionalParams, { headers });
|
|
1272
|
+
}
|
|
1273
|
+
else {
|
|
1274
|
+
response = await serviceAccess.get(endpoint, {
|
|
1275
|
+
params: additionalParams,
|
|
1276
|
+
headers
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
// Extract and transform items from response
|
|
1280
|
+
const rawItems = response.data?.[itemsField];
|
|
1281
|
+
const totalCount = response.data?.[totalCountField];
|
|
1282
|
+
// Parse items - automatically handle JSON string responses
|
|
1283
|
+
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1284
|
+
const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1285
|
+
return {
|
|
1286
|
+
items,
|
|
1287
|
+
totalCount
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* Centralized getAll implementation that handles both paginated and non-paginated requests
|
|
1292
|
+
*
|
|
1293
|
+
* @param config - Configuration for the getAll operation
|
|
1294
|
+
* @param options - Request options including pagination parameters
|
|
1295
|
+
* @returns Promise resolving to either paginated or non-paginated response based on options
|
|
1296
|
+
*/
|
|
1297
|
+
static async getAll(config, options) {
|
|
1298
|
+
const optionsWithDefaults = options || {};
|
|
1299
|
+
const { folderId, ...restOptions } = optionsWithDefaults;
|
|
1300
|
+
const cursor = options?.cursor;
|
|
1301
|
+
const pageSize = options?.pageSize;
|
|
1302
|
+
const jumpToPage = options?.jumpToPage;
|
|
1303
|
+
// Determine if pagination is requested
|
|
1304
|
+
const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
|
|
1305
|
+
// Process parameters (custom processing if provided, otherwise default)
|
|
1306
|
+
let processedOptions = restOptions;
|
|
1307
|
+
if (config.processParametersFn) {
|
|
1308
|
+
processedOptions = config.processParametersFn(restOptions, folderId);
|
|
1309
|
+
}
|
|
1310
|
+
// Apply ODATA prefix to keys (excluding specified keys)
|
|
1311
|
+
const excludeKeys = config.excludeFromPrefix || [];
|
|
1312
|
+
const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
|
|
1313
|
+
const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
|
|
1314
|
+
// Default pagination options
|
|
1315
|
+
const paginationOptions = {
|
|
1316
|
+
paginationType: PaginationType.OFFSET,
|
|
1317
|
+
itemsField: DEFAULT_ITEMS_FIELD,
|
|
1318
|
+
totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
|
|
1319
|
+
...config.pagination
|
|
1320
|
+
};
|
|
1321
|
+
// Paginated flow
|
|
1322
|
+
if (isPaginationRequested) {
|
|
1323
|
+
return PaginationHelpers.getAllPaginated({
|
|
1324
|
+
serviceAccess: config.serviceAccess,
|
|
1325
|
+
getEndpoint: config.getEndpoint,
|
|
1326
|
+
folderId,
|
|
1327
|
+
paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
|
|
1328
|
+
additionalParams: prefixedOptions,
|
|
1329
|
+
transformFn: config.transformFn,
|
|
1330
|
+
method: config.method,
|
|
1331
|
+
options: {
|
|
1332
|
+
...paginationOptions,
|
|
1333
|
+
paginationParams: config.pagination?.paginationParams
|
|
1334
|
+
}
|
|
1335
|
+
}); // Type assertion needed due to conditional return
|
|
1336
|
+
}
|
|
1337
|
+
// Non-paginated flow
|
|
1338
|
+
const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
|
|
1339
|
+
return PaginationHelpers.getAllNonPaginated({
|
|
1340
|
+
serviceAccess: config.serviceAccess,
|
|
1341
|
+
getAllEndpoint: config.getEndpoint(),
|
|
1342
|
+
getByFolderEndpoint: byFolderEndpoint,
|
|
1343
|
+
folderId,
|
|
1344
|
+
additionalParams: prefixedOptions,
|
|
1345
|
+
transformFn: config.transformFn,
|
|
1346
|
+
method: config.method,
|
|
1347
|
+
options: {
|
|
1348
|
+
itemsField: paginationOptions.itemsField,
|
|
1349
|
+
totalCountField: paginationOptions.totalCountField
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/**
|
|
1356
|
+
* SDK Internals Registry - Internal registry for SDK instances
|
|
1357
|
+
*
|
|
1358
|
+
* This class is NOT exported in the public API.
|
|
1359
|
+
* It provides a secure way to share SDK internals between
|
|
1360
|
+
* the UiPath class and service classes without exposing them publicly.
|
|
1361
|
+
*
|
|
1362
|
+
* @internal
|
|
1363
|
+
*/
|
|
1364
|
+
// Global symbol key to ensure WeakMap is shared across module instances
|
|
1365
|
+
// This prevents issues when core and service modules are bundled separately
|
|
1366
|
+
const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
|
|
1367
|
+
// Get or create the global WeakMap store
|
|
1368
|
+
const getGlobalStore = () => {
|
|
1369
|
+
const globalObj = globalThis;
|
|
1370
|
+
if (!globalObj[REGISTRY_KEY]) {
|
|
1371
|
+
globalObj[REGISTRY_KEY] = new WeakMap();
|
|
1372
|
+
}
|
|
1373
|
+
return globalObj[REGISTRY_KEY];
|
|
1374
|
+
};
|
|
1375
|
+
/**
|
|
1376
|
+
* Internal registry for SDK private components.
|
|
1377
|
+
* Uses WeakMap to prevent memory leaks - entries are automatically
|
|
1378
|
+
* garbage collected when the SDK instance is no longer referenced.
|
|
1379
|
+
*
|
|
1380
|
+
* Uses a global singleton pattern to ensure the same WeakMap is shared
|
|
1381
|
+
* across separately bundled modules (core, entities, tasks, etc.).
|
|
1382
|
+
*
|
|
1383
|
+
* @internal - Not exported in public API
|
|
1384
|
+
*/
|
|
1385
|
+
class SDKInternalsRegistry {
|
|
1386
|
+
// Use global store to ensure sharing across module bundles
|
|
1387
|
+
static get store() {
|
|
1388
|
+
return getGlobalStore();
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Register SDK instance internals
|
|
1392
|
+
* Called by UiPath constructor
|
|
1393
|
+
*/
|
|
1394
|
+
static set(instance, internals) {
|
|
1395
|
+
this.store.set(instance, internals);
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* Retrieve SDK instance internals
|
|
1399
|
+
* Called by BaseService constructor
|
|
1400
|
+
*/
|
|
1401
|
+
static get(instance) {
|
|
1402
|
+
const internals = this.store.get(instance);
|
|
1403
|
+
if (!internals) {
|
|
1404
|
+
throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
|
|
1405
|
+
}
|
|
1406
|
+
return internals;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
var _BaseService_apiClient;
|
|
1411
|
+
/**
|
|
1412
|
+
* Base class for all UiPath SDK services.
|
|
1413
|
+
*
|
|
1414
|
+
* Provides common functionality for authentication, configuration, and API communication.
|
|
1415
|
+
* All service classes extend this base to inherit dependency injection and HTTP client access.
|
|
1416
|
+
*
|
|
1417
|
+
* This class implements the dependency injection pattern where services receive a configured
|
|
1418
|
+
* UiPath instance. The ApiClient is created internally and handles all HTTP operations
|
|
1419
|
+
* including authentication token management.
|
|
1420
|
+
*
|
|
1421
|
+
* @remarks
|
|
1422
|
+
* Service classes should extend this base and call `super(uiPath)` in their constructor.
|
|
1423
|
+
* Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
|
|
1424
|
+
*
|
|
1425
|
+
*/
|
|
1426
|
+
class BaseService {
|
|
1427
|
+
/**
|
|
1428
|
+
* Creates a base service instance with dependency injection.
|
|
1429
|
+
*
|
|
1430
|
+
* Extracts configuration, execution context, and token manager from the UiPath instance
|
|
1431
|
+
* to initialize an authenticated API client. The ApiClient handles all HTTP operations
|
|
1432
|
+
* and token management internally.
|
|
1433
|
+
*
|
|
1434
|
+
* @param instance - UiPath SDK instance providing authentication and configuration.
|
|
1435
|
+
* Services receive this via dependency injection in the modular pattern.
|
|
1436
|
+
*
|
|
1437
|
+
* @example
|
|
1438
|
+
* ```typescript
|
|
1439
|
+
* // Services automatically call this via super()
|
|
1440
|
+
* export class EntityService extends BaseService {
|
|
1441
|
+
* constructor(instance: IUiPath) {
|
|
1442
|
+
* super(instance); // Initializes the internal ApiClient
|
|
1443
|
+
* }
|
|
1444
|
+
* }
|
|
1445
|
+
*
|
|
1446
|
+
* // Usage in modular pattern
|
|
1447
|
+
* import { UiPath } from '@uipath/uipath-typescript/core';
|
|
1448
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
1449
|
+
*
|
|
1450
|
+
* const sdk = new UiPath(config);
|
|
1451
|
+
* await sdk.initialize();
|
|
1452
|
+
* const entities = new Entities(sdk);
|
|
1453
|
+
* ```
|
|
1454
|
+
*/
|
|
1455
|
+
constructor(instance) {
|
|
1456
|
+
// Private field - not visible via Object.keys() or any reflection
|
|
1457
|
+
_BaseService_apiClient.set(this, void 0);
|
|
1458
|
+
const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
|
|
1459
|
+
__classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* Gets a valid authentication token, refreshing if necessary.
|
|
1463
|
+
* Use this when you need to manually add Authorization headers (e.g., direct uploads).
|
|
1464
|
+
*
|
|
1465
|
+
* @returns Promise resolving to a valid access token string
|
|
1466
|
+
* @throws AuthenticationError if no token is available or refresh fails
|
|
1467
|
+
*/
|
|
1468
|
+
async getValidAuthToken() {
|
|
1469
|
+
return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
|
|
1470
|
+
}
|
|
1471
|
+
/**
|
|
1472
|
+
* Creates a service accessor for pagination helpers
|
|
1473
|
+
* This allows pagination helpers to access protected methods without making them public
|
|
1474
|
+
*/
|
|
1475
|
+
createPaginationServiceAccess() {
|
|
1476
|
+
return {
|
|
1477
|
+
get: (path, options) => this.get(path, options || {}),
|
|
1478
|
+
post: (path, body, options) => this.post(path, body, options || {}),
|
|
1479
|
+
requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
|
|
1480
|
+
};
|
|
1481
|
+
}
|
|
1482
|
+
async request(method, path, options = {}) {
|
|
1483
|
+
switch (method.toUpperCase()) {
|
|
1484
|
+
case 'GET':
|
|
1485
|
+
return this.get(path, options);
|
|
1486
|
+
case 'POST':
|
|
1487
|
+
return this.post(path, options.body, options);
|
|
1488
|
+
case 'PUT':
|
|
1489
|
+
return this.put(path, options.body, options);
|
|
1490
|
+
case 'PATCH':
|
|
1491
|
+
return this.patch(path, options.body, options);
|
|
1492
|
+
case 'DELETE':
|
|
1493
|
+
return this.delete(path, options);
|
|
1494
|
+
default:
|
|
1495
|
+
throw new Error(`Unsupported HTTP method: ${method}`);
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
async requestWithSpec(spec) {
|
|
1499
|
+
if (!spec.method || !spec.url) {
|
|
1500
|
+
throw new Error('Request spec must include method and url');
|
|
1501
|
+
}
|
|
1502
|
+
return this.request(spec.method, spec.url, spec);
|
|
1503
|
+
}
|
|
1504
|
+
async get(path, options = {}) {
|
|
1505
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
|
|
1506
|
+
return { data: response };
|
|
1507
|
+
}
|
|
1508
|
+
async post(path, data, options = {}) {
|
|
1509
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
|
|
1510
|
+
return { data: response };
|
|
1511
|
+
}
|
|
1512
|
+
async put(path, data, options = {}) {
|
|
1513
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
|
|
1514
|
+
return { data: response };
|
|
1515
|
+
}
|
|
1516
|
+
async patch(path, data, options = {}) {
|
|
1517
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
|
|
1518
|
+
return { data: response };
|
|
1519
|
+
}
|
|
1520
|
+
async delete(path, options = {}) {
|
|
1521
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
|
|
1522
|
+
return { data: response };
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Execute a request with cursor-based pagination
|
|
1526
|
+
*/
|
|
1527
|
+
async requestWithPagination(method, path, paginationOptions, options) {
|
|
1528
|
+
const paginationType = options.pagination.paginationType;
|
|
1529
|
+
// Validate and prepare pagination parameters
|
|
1530
|
+
const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
|
|
1531
|
+
// Prepare request parameters based on pagination type
|
|
1532
|
+
const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
|
|
1533
|
+
// For POST requests, merge pagination params into body; for GET, use query params
|
|
1534
|
+
if (method.toUpperCase() === 'POST') {
|
|
1535
|
+
const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
|
|
1536
|
+
options.body = {
|
|
1537
|
+
...existingBody,
|
|
1538
|
+
...options.params,
|
|
1539
|
+
...requestParams
|
|
1540
|
+
};
|
|
1541
|
+
}
|
|
1542
|
+
else {
|
|
1543
|
+
// Merge pagination parameters with existing parameters
|
|
1544
|
+
options.params = {
|
|
1545
|
+
...options.params,
|
|
1546
|
+
...requestParams
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
// Make the request
|
|
1550
|
+
const response = await this.request(method, path, options);
|
|
1551
|
+
// Extract data from the response and create page result
|
|
1552
|
+
return this.createPaginatedResponseFromResponse(response, params, paginationType, {
|
|
1553
|
+
itemsField: options.pagination.itemsField,
|
|
1554
|
+
totalCountField: options.pagination.totalCountField,
|
|
1555
|
+
continuationTokenField: options.pagination.continuationTokenField
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Validates and prepares pagination parameters from options
|
|
1560
|
+
*/
|
|
1561
|
+
validateAndPreparePaginationParams(paginationType, paginationOptions) {
|
|
1562
|
+
return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Prepares request parameters for pagination based on pagination type
|
|
1566
|
+
*/
|
|
1567
|
+
preparePaginationRequestParams(paginationType, params, paginationConfig) {
|
|
1568
|
+
const requestParams = {};
|
|
1569
|
+
let limitedPageSize;
|
|
1570
|
+
const paginationParams = paginationConfig?.paginationParams;
|
|
1571
|
+
switch (paginationType) {
|
|
1572
|
+
case PaginationType.OFFSET:
|
|
1573
|
+
limitedPageSize = getLimitedPageSize(params.pageSize);
|
|
1574
|
+
const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
|
|
1575
|
+
const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
|
|
1576
|
+
const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
|
|
1577
|
+
requestParams[pageSizeParam] = limitedPageSize;
|
|
1578
|
+
if (params.pageNumber && params.pageNumber > 1) {
|
|
1579
|
+
requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
|
|
1580
|
+
}
|
|
1581
|
+
// Include total count for ODATA APIs
|
|
1582
|
+
{
|
|
1583
|
+
requestParams[countParam] = true;
|
|
1584
|
+
}
|
|
1585
|
+
break;
|
|
1586
|
+
case PaginationType.TOKEN:
|
|
1587
|
+
const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
|
|
1588
|
+
const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
|
|
1589
|
+
if (params.pageSize) {
|
|
1590
|
+
requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
|
|
1591
|
+
}
|
|
1592
|
+
if (params.continuationToken) {
|
|
1593
|
+
requestParams[tokenParam] = params.continuationToken;
|
|
1594
|
+
}
|
|
1595
|
+
break;
|
|
1596
|
+
}
|
|
1597
|
+
return requestParams;
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* Creates a paginated response from API response
|
|
1601
|
+
*/
|
|
1602
|
+
createPaginatedResponseFromResponse(response, params, paginationType, fields) {
|
|
1603
|
+
// Extract fields from response
|
|
1604
|
+
const itemsField = fields.itemsField ||
|
|
1605
|
+
(paginationType === PaginationType.TOKEN ? 'items' : 'value');
|
|
1606
|
+
const totalCountField = fields.totalCountField || 'totalRecordCount';
|
|
1607
|
+
const continuationTokenField = fields.continuationTokenField || 'continuationToken';
|
|
1608
|
+
// Extract items and metadata
|
|
1609
|
+
const items = response.data[itemsField] || [];
|
|
1610
|
+
const totalCount = response.data[totalCountField];
|
|
1611
|
+
const continuationToken = response.data[continuationTokenField];
|
|
1612
|
+
// Determine if there are more pages
|
|
1613
|
+
const hasMore = this.determineHasMorePages(paginationType, {
|
|
1614
|
+
totalCount,
|
|
1615
|
+
pageSize: params.pageSize,
|
|
1616
|
+
currentPage: params.pageNumber || 1,
|
|
1617
|
+
itemsCount: items.length,
|
|
1618
|
+
continuationToken
|
|
1619
|
+
});
|
|
1620
|
+
// Create and return the page result
|
|
1621
|
+
return PaginationManager.createPaginatedResponse({
|
|
1622
|
+
pageInfo: {
|
|
1623
|
+
hasMore,
|
|
1624
|
+
totalCount,
|
|
1625
|
+
currentPage: params.pageNumber,
|
|
1626
|
+
pageSize: params.pageSize,
|
|
1627
|
+
continuationToken
|
|
1628
|
+
},
|
|
1629
|
+
type: paginationType,
|
|
1630
|
+
}, items);
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* Determines if there are more pages based on pagination type and metadata
|
|
1634
|
+
*/
|
|
1635
|
+
determineHasMorePages(paginationType, info) {
|
|
1636
|
+
switch (paginationType) {
|
|
1637
|
+
case PaginationType.OFFSET:
|
|
1638
|
+
const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
1639
|
+
// If totalCount is available, use it for precise calculation
|
|
1640
|
+
if (info.totalCount !== undefined) {
|
|
1641
|
+
return (info.currentPage * effectivePageSize) < info.totalCount;
|
|
1642
|
+
}
|
|
1643
|
+
// Fallback when totalCount is not available
|
|
1644
|
+
// NOTE: This code path should rarely be executed as the APIs typically return totalCount
|
|
1645
|
+
return info.itemsCount === effectivePageSize;
|
|
1646
|
+
case PaginationType.TOKEN:
|
|
1647
|
+
return !!info.continuationToken;
|
|
1648
|
+
default:
|
|
1649
|
+
return false;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
_BaseService_apiClient = new WeakMap();
|
|
1654
|
+
|
|
1655
|
+
/**
|
|
1656
|
+
* Creates entity methods that can be attached to entity data
|
|
1657
|
+
*
|
|
1658
|
+
* @param entityData - The entity metadata
|
|
1659
|
+
* @param service - The entity service instance
|
|
1660
|
+
* @returns Object containing entity methods
|
|
1661
|
+
*/
|
|
1662
|
+
function createEntityMethods(entityData, service) {
|
|
1663
|
+
return {
|
|
1664
|
+
async insertRecord(data, options) {
|
|
1665
|
+
if (!entityData.id)
|
|
1666
|
+
throw new Error('Entity ID is undefined');
|
|
1667
|
+
return service.insertRecordById(entityData.id, data, options);
|
|
1668
|
+
},
|
|
1669
|
+
async insertRecords(data, options) {
|
|
1670
|
+
if (!entityData.id)
|
|
1671
|
+
throw new Error('Entity ID is undefined');
|
|
1672
|
+
return service.insertRecordsById(entityData.id, data, options);
|
|
1673
|
+
},
|
|
1674
|
+
async updateRecords(data, options) {
|
|
1675
|
+
if (!entityData.id)
|
|
1676
|
+
throw new Error('Entity ID is undefined');
|
|
1677
|
+
return service.updateRecordsById(entityData.id, data, options);
|
|
1678
|
+
},
|
|
1679
|
+
async deleteRecords(recordIds, options) {
|
|
1680
|
+
if (!entityData.id)
|
|
1681
|
+
throw new Error('Entity ID is undefined');
|
|
1682
|
+
return service.deleteRecordsById(entityData.id, recordIds, options);
|
|
1683
|
+
},
|
|
1684
|
+
async getAllRecords(options) {
|
|
1685
|
+
if (!entityData.id)
|
|
1686
|
+
throw new Error('Entity ID is undefined');
|
|
1687
|
+
return service.getAllRecords(entityData.id, options);
|
|
1688
|
+
},
|
|
1689
|
+
async getRecord(recordId, options) {
|
|
1690
|
+
if (!entityData.id)
|
|
1691
|
+
throw new Error('Entity ID is undefined');
|
|
1692
|
+
if (!recordId)
|
|
1693
|
+
throw new Error('Record ID is undefined');
|
|
1694
|
+
return service.getRecordById(entityData.id, recordId, options);
|
|
1695
|
+
},
|
|
1696
|
+
async downloadAttachment(recordId, fieldName) {
|
|
1697
|
+
if (!entityData.name)
|
|
1698
|
+
throw new Error('Entity name is undefined');
|
|
1699
|
+
return service.downloadAttachment({
|
|
1700
|
+
entityName: entityData.name,
|
|
1701
|
+
recordId,
|
|
1702
|
+
fieldName
|
|
1703
|
+
});
|
|
1704
|
+
},
|
|
1705
|
+
async insert(data, options) {
|
|
1706
|
+
return this.insertRecord(data, options);
|
|
1707
|
+
},
|
|
1708
|
+
async batchInsert(data, options) {
|
|
1709
|
+
return this.insertRecords(data, options);
|
|
1710
|
+
},
|
|
1711
|
+
async update(data, options) {
|
|
1712
|
+
return this.updateRecords(data, options);
|
|
1713
|
+
},
|
|
1714
|
+
async delete(recordIds, options) {
|
|
1715
|
+
return this.deleteRecords(recordIds, options);
|
|
1716
|
+
},
|
|
1717
|
+
async getRecords(options) {
|
|
1718
|
+
return this.getAllRecords(options);
|
|
1719
|
+
}
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Creates an actionable entity metadata by combining entity with operational methods
|
|
1724
|
+
*
|
|
1725
|
+
* @param entityData - Entity metadata
|
|
1726
|
+
* @param service - The entity service instance
|
|
1727
|
+
* @returns Entity metadata with added methods
|
|
1728
|
+
*/
|
|
1729
|
+
function createEntityWithMethods(entityData, service) {
|
|
1730
|
+
const methods = createEntityMethods(entityData, service);
|
|
1731
|
+
return Object.assign({}, entityData, methods);
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
/**
|
|
1735
|
+
* API Endpoint Constants
|
|
1736
|
+
* Centralized location for all API endpoints used throughout the SDK
|
|
1737
|
+
*/
|
|
1738
|
+
/**
|
|
1739
|
+
* Base path constants for different services
|
|
1740
|
+
*/
|
|
1741
|
+
const DATAFABRIC_BASE = 'datafabric_';
|
|
1742
|
+
/**
|
|
1743
|
+
* Data Fabric Service Endpoints
|
|
1744
|
+
*/
|
|
1745
|
+
const DATA_FABRIC_ENDPOINTS = {
|
|
1746
|
+
ENTITY: {
|
|
1747
|
+
GET_ALL: `${DATAFABRIC_BASE}/api/Entity`,
|
|
1748
|
+
GET_ENTITY_RECORDS: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/read`,
|
|
1749
|
+
GET_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/Entity/${entityId}`,
|
|
1750
|
+
GET_RECORD_BY_ID: (entityId, recordId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/read/${recordId}`,
|
|
1751
|
+
INSERT_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/insert`,
|
|
1752
|
+
BATCH_INSERT_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/insert-batch`,
|
|
1753
|
+
UPDATE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/update-batch`,
|
|
1754
|
+
DELETE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/delete-batch`,
|
|
1755
|
+
DOWNLOAD_ATTACHMENT: (entityName, recordId, fieldName) => `${DATAFABRIC_BASE}/api/Attachment/${entityName}/${recordId}/${fieldName}`,
|
|
1756
|
+
},
|
|
1757
|
+
CHOICESETS: {
|
|
1758
|
+
GET_ALL: `${DATAFABRIC_BASE}/api/Entity/choiceset`,
|
|
1759
|
+
GET_BY_ID: (choiceSetId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${choiceSetId}/query_expansion`,
|
|
1760
|
+
},
|
|
1761
|
+
};
|
|
1762
|
+
|
|
1763
|
+
/**
|
|
1764
|
+
* Creates query parameters object from key-value pairs, filtering out undefined values
|
|
1765
|
+
* @param paramsObj - Object containing parameter key-value pairs
|
|
1766
|
+
* @returns Parameters object with undefined values filtered out
|
|
1767
|
+
*
|
|
1768
|
+
* @example
|
|
1769
|
+
* ```typescript
|
|
1770
|
+
* // Entity service parameters
|
|
1771
|
+
* const params = createParams({
|
|
1772
|
+
* start: 0,
|
|
1773
|
+
* limit: 10,
|
|
1774
|
+
* expansionLevel: 1
|
|
1775
|
+
* });
|
|
1776
|
+
*
|
|
1777
|
+
* // With optional/undefined values (automatically filtered)
|
|
1778
|
+
* const params = createParams({
|
|
1779
|
+
* start: options.start, // Could be undefined
|
|
1780
|
+
* limit: options.limit, // Could be undefined
|
|
1781
|
+
* expansionLevel: options.expansionLevel // Could be undefined
|
|
1782
|
+
* });
|
|
1783
|
+
*
|
|
1784
|
+
* // Empty params
|
|
1785
|
+
* const params = createParams();
|
|
1786
|
+
* ```
|
|
1787
|
+
*/
|
|
1788
|
+
function createParams(paramsObj = {}) {
|
|
1789
|
+
const params = {};
|
|
1790
|
+
for (const [key, value] of Object.entries(paramsObj)) {
|
|
1791
|
+
if (value !== undefined && value !== null) {
|
|
1792
|
+
params[key] = value;
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
return params;
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
/**
|
|
1799
|
+
* Entity field type names
|
|
1800
|
+
*/
|
|
1801
|
+
var EntityFieldDataType;
|
|
1802
|
+
(function (EntityFieldDataType) {
|
|
1803
|
+
EntityFieldDataType["UUID"] = "UUID";
|
|
1804
|
+
EntityFieldDataType["STRING"] = "STRING";
|
|
1805
|
+
EntityFieldDataType["INTEGER"] = "INTEGER";
|
|
1806
|
+
EntityFieldDataType["DATETIME"] = "DATETIME";
|
|
1807
|
+
EntityFieldDataType["DATETIME_WITH_TZ"] = "DATETIME_WITH_TZ";
|
|
1808
|
+
EntityFieldDataType["DECIMAL"] = "DECIMAL";
|
|
1809
|
+
EntityFieldDataType["FLOAT"] = "FLOAT";
|
|
1810
|
+
EntityFieldDataType["DOUBLE"] = "DOUBLE";
|
|
1811
|
+
EntityFieldDataType["DATE"] = "DATE";
|
|
1812
|
+
EntityFieldDataType["BOOLEAN"] = "BOOLEAN";
|
|
1813
|
+
EntityFieldDataType["BIG_INTEGER"] = "BIG_INTEGER";
|
|
1814
|
+
EntityFieldDataType["MULTILINE_TEXT"] = "MULTILINE_TEXT";
|
|
1815
|
+
})(EntityFieldDataType || (EntityFieldDataType = {}));
|
|
1816
|
+
/**
|
|
1817
|
+
* Entity type enum
|
|
1818
|
+
*/
|
|
1819
|
+
var EntityType;
|
|
1820
|
+
(function (EntityType) {
|
|
1821
|
+
EntityType["Entity"] = "Entity";
|
|
1822
|
+
EntityType["ChoiceSet"] = "ChoiceSet";
|
|
1823
|
+
EntityType["InternalEntity"] = "InternalEntity";
|
|
1824
|
+
EntityType["SystemEntity"] = "SystemEntity";
|
|
1825
|
+
})(EntityType || (EntityType = {}));
|
|
1826
|
+
/**
|
|
1827
|
+
* Reference types for fields
|
|
1828
|
+
*/
|
|
1829
|
+
var ReferenceType;
|
|
1830
|
+
(function (ReferenceType) {
|
|
1831
|
+
ReferenceType["ManyToOne"] = "ManyToOne";
|
|
1832
|
+
})(ReferenceType || (ReferenceType = {}));
|
|
1833
|
+
/**
|
|
1834
|
+
* Field display types
|
|
1835
|
+
*/
|
|
1836
|
+
var FieldDisplayType;
|
|
1837
|
+
(function (FieldDisplayType) {
|
|
1838
|
+
FieldDisplayType["Basic"] = "Basic";
|
|
1839
|
+
FieldDisplayType["Relationship"] = "Relationship";
|
|
1840
|
+
FieldDisplayType["File"] = "File";
|
|
1841
|
+
FieldDisplayType["ChoiceSetSingle"] = "ChoiceSetSingle";
|
|
1842
|
+
FieldDisplayType["ChoiceSetMultiple"] = "ChoiceSetMultiple";
|
|
1843
|
+
FieldDisplayType["AutoNumber"] = "AutoNumber";
|
|
1844
|
+
})(FieldDisplayType || (FieldDisplayType = {}));
|
|
1845
|
+
/**
|
|
1846
|
+
* Data direction type for external fields
|
|
1847
|
+
*/
|
|
1848
|
+
var DataDirectionType;
|
|
1849
|
+
(function (DataDirectionType) {
|
|
1850
|
+
DataDirectionType["ReadOnly"] = "ReadOnly";
|
|
1851
|
+
DataDirectionType["ReadAndWrite"] = "ReadAndWrite";
|
|
1852
|
+
})(DataDirectionType || (DataDirectionType = {}));
|
|
1853
|
+
/**
|
|
1854
|
+
* Join type for source join criteria
|
|
1855
|
+
*/
|
|
1856
|
+
var JoinType;
|
|
1857
|
+
(function (JoinType) {
|
|
1858
|
+
JoinType["LeftJoin"] = "LeftJoin";
|
|
1859
|
+
})(JoinType || (JoinType = {}));
|
|
1860
|
+
|
|
1861
|
+
/**
|
|
1862
|
+
* Entity field data types (SQL types from API)
|
|
1863
|
+
*/
|
|
1864
|
+
var SqlFieldType;
|
|
1865
|
+
(function (SqlFieldType) {
|
|
1866
|
+
SqlFieldType["UNIQUEIDENTIFIER"] = "UNIQUEIDENTIFIER";
|
|
1867
|
+
SqlFieldType["NVARCHAR"] = "NVARCHAR";
|
|
1868
|
+
SqlFieldType["INT"] = "INT";
|
|
1869
|
+
SqlFieldType["DATETIME2"] = "DATETIME2";
|
|
1870
|
+
SqlFieldType["DATETIMEOFFSET"] = "DATETIMEOFFSET";
|
|
1871
|
+
SqlFieldType["FLOAT"] = "FLOAT";
|
|
1872
|
+
SqlFieldType["REAL"] = "REAL";
|
|
1873
|
+
SqlFieldType["BIGINT"] = "BIGINT";
|
|
1874
|
+
SqlFieldType["DATE"] = "DATE";
|
|
1875
|
+
SqlFieldType["BIT"] = "BIT";
|
|
1876
|
+
SqlFieldType["DECIMAL"] = "DECIMAL";
|
|
1877
|
+
SqlFieldType["MULTILINE"] = "MULTILINE";
|
|
1878
|
+
})(SqlFieldType || (SqlFieldType = {}));
|
|
1879
|
+
/**
|
|
1880
|
+
* Maps fields for Entities
|
|
1881
|
+
*/
|
|
1882
|
+
const EntityMap = {
|
|
1883
|
+
createTime: 'createdTime',
|
|
1884
|
+
updateTime: 'updatedTime',
|
|
1885
|
+
sqlType: 'fieldDataType',
|
|
1886
|
+
fieldDefinition: 'fieldMetaData'
|
|
1887
|
+
};
|
|
1888
|
+
/**
|
|
1889
|
+
* Maps SQL field types to friendly display names
|
|
1890
|
+
*/
|
|
1891
|
+
const EntityFieldTypeMap = {
|
|
1892
|
+
[SqlFieldType.UNIQUEIDENTIFIER]: EntityFieldDataType.UUID,
|
|
1893
|
+
[SqlFieldType.NVARCHAR]: EntityFieldDataType.STRING,
|
|
1894
|
+
[SqlFieldType.INT]: EntityFieldDataType.INTEGER,
|
|
1895
|
+
[SqlFieldType.DATETIME2]: EntityFieldDataType.DATETIME,
|
|
1896
|
+
[SqlFieldType.DATETIMEOFFSET]: EntityFieldDataType.DATETIME_WITH_TZ,
|
|
1897
|
+
[SqlFieldType.FLOAT]: EntityFieldDataType.FLOAT,
|
|
1898
|
+
[SqlFieldType.REAL]: EntityFieldDataType.DOUBLE,
|
|
1899
|
+
[SqlFieldType.BIGINT]: EntityFieldDataType.BIG_INTEGER,
|
|
1900
|
+
[SqlFieldType.DATE]: EntityFieldDataType.DATE,
|
|
1901
|
+
[SqlFieldType.BIT]: EntityFieldDataType.BOOLEAN,
|
|
1902
|
+
[SqlFieldType.DECIMAL]: EntityFieldDataType.DECIMAL,
|
|
1903
|
+
[SqlFieldType.MULTILINE]: EntityFieldDataType.MULTILINE_TEXT
|
|
1904
|
+
};
|
|
1905
|
+
|
|
1906
|
+
/**
|
|
1907
|
+
* SDK Telemetry constants
|
|
1908
|
+
*/
|
|
1909
|
+
// Connection string placeholder that will be replaced during build
|
|
1910
|
+
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";
|
|
1911
|
+
// SDK Version placeholder
|
|
1912
|
+
const SDK_VERSION = "1.0.0";
|
|
1913
|
+
const VERSION = "Version";
|
|
1914
|
+
const SERVICE = "Service";
|
|
1915
|
+
const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
|
|
1916
|
+
const CLOUD_TENANT_NAME = "CloudTenantName";
|
|
1917
|
+
const CLOUD_URL = "CloudUrl";
|
|
1918
|
+
const CLOUD_CLIENT_ID = "CloudClientId";
|
|
1919
|
+
const CLOUD_REDIRECT_URI = "CloudRedirectUri";
|
|
1920
|
+
const APP_NAME = "ApplicationName";
|
|
1921
|
+
const CLOUD_ROLE_NAME = "uipath-ts-sdk";
|
|
1922
|
+
// Service and logger names
|
|
1923
|
+
const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
|
|
1924
|
+
const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
|
|
1925
|
+
// Event names
|
|
1926
|
+
const SDK_RUN_EVENT = "Sdk.Run";
|
|
1927
|
+
// Default value for unknown/empty attributes
|
|
1928
|
+
const UNKNOWN = "";
|
|
1929
|
+
|
|
1930
|
+
/**
|
|
1931
|
+
* Log exporter that sends ALL logs as Application Insights custom events
|
|
1932
|
+
*/
|
|
1933
|
+
class ApplicationInsightsEventExporter {
|
|
1934
|
+
constructor(connectionString) {
|
|
1935
|
+
this.connectionString = connectionString;
|
|
1936
|
+
}
|
|
1937
|
+
export(logs, resultCallback) {
|
|
1938
|
+
try {
|
|
1939
|
+
logs.forEach(logRecord => {
|
|
1940
|
+
this.sendAsCustomEvent(logRecord);
|
|
1941
|
+
});
|
|
1942
|
+
resultCallback({ code: 0 });
|
|
1943
|
+
}
|
|
1944
|
+
catch (error) {
|
|
1945
|
+
console.debug('Failed to export logs to Application Insights:', error);
|
|
1946
|
+
resultCallback({ code: 2, error });
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
shutdown() {
|
|
1950
|
+
return Promise.resolve();
|
|
1951
|
+
}
|
|
1952
|
+
sendAsCustomEvent(logRecord) {
|
|
1953
|
+
// Get event name from body or attributes
|
|
1954
|
+
const eventName = logRecord.body || SDK_RUN_EVENT;
|
|
1955
|
+
const payload = {
|
|
1956
|
+
name: 'Microsoft.ApplicationInsights.Event',
|
|
1957
|
+
time: new Date().toISOString(),
|
|
1958
|
+
iKey: this.extractInstrumentationKey(),
|
|
1959
|
+
data: {
|
|
1960
|
+
baseType: 'EventData',
|
|
1961
|
+
baseData: {
|
|
1962
|
+
ver: 2,
|
|
1963
|
+
name: eventName,
|
|
1964
|
+
properties: this.convertAttributesToProperties(logRecord.attributes || {})
|
|
1965
|
+
}
|
|
1966
|
+
},
|
|
1967
|
+
tags: {
|
|
1968
|
+
'ai.cloud.role': CLOUD_ROLE_NAME,
|
|
1969
|
+
'ai.cloud.roleInstance': SDK_VERSION
|
|
1970
|
+
}
|
|
1971
|
+
};
|
|
1972
|
+
this.sendToApplicationInsights(payload);
|
|
1973
|
+
}
|
|
1974
|
+
extractInstrumentationKey() {
|
|
1975
|
+
const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
|
|
1976
|
+
return match ? match[1] : '';
|
|
1977
|
+
}
|
|
1978
|
+
convertAttributesToProperties(attributes) {
|
|
1979
|
+
const properties = {};
|
|
1980
|
+
Object.entries(attributes || {}).forEach(([key, value]) => {
|
|
1981
|
+
properties[key] = String(value);
|
|
1982
|
+
});
|
|
1983
|
+
return properties;
|
|
1984
|
+
}
|
|
1985
|
+
async sendToApplicationInsights(payload) {
|
|
1986
|
+
try {
|
|
1987
|
+
const ingestionEndpoint = this.extractIngestionEndpoint();
|
|
1988
|
+
if (!ingestionEndpoint) {
|
|
1989
|
+
console.debug('No ingestion endpoint found in connection string');
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1992
|
+
const url = `${ingestionEndpoint}/v2/track`;
|
|
1993
|
+
const response = await fetch(url, {
|
|
1994
|
+
method: 'POST',
|
|
1995
|
+
headers: {
|
|
1996
|
+
'Content-Type': 'application/json',
|
|
1997
|
+
},
|
|
1998
|
+
body: JSON.stringify(payload)
|
|
1999
|
+
});
|
|
2000
|
+
if (!response.ok) {
|
|
2001
|
+
console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
catch (error) {
|
|
2005
|
+
console.debug('Error sending event telemetry to Application Insights:', error);
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
extractIngestionEndpoint() {
|
|
2009
|
+
const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
|
|
2010
|
+
return match ? match[1] : '';
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
/**
|
|
2014
|
+
* Singleton telemetry client
|
|
2015
|
+
*/
|
|
2016
|
+
class TelemetryClient {
|
|
2017
|
+
constructor() {
|
|
2018
|
+
this.isInitialized = false;
|
|
2019
|
+
}
|
|
2020
|
+
static getInstance() {
|
|
2021
|
+
if (!TelemetryClient.instance) {
|
|
2022
|
+
TelemetryClient.instance = new TelemetryClient();
|
|
2023
|
+
}
|
|
2024
|
+
return TelemetryClient.instance;
|
|
2025
|
+
}
|
|
2026
|
+
/**
|
|
2027
|
+
* Initialize telemetry
|
|
2028
|
+
*/
|
|
2029
|
+
initialize(config) {
|
|
2030
|
+
if (this.isInitialized) {
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
this.isInitialized = true;
|
|
2034
|
+
if (config) {
|
|
2035
|
+
this.telemetryContext = config;
|
|
2036
|
+
}
|
|
2037
|
+
try {
|
|
2038
|
+
const connectionString = this.getConnectionString();
|
|
2039
|
+
if (!connectionString) {
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
this.setupTelemetryProvider(connectionString);
|
|
2043
|
+
}
|
|
2044
|
+
catch (error) {
|
|
2045
|
+
// Silent failure - telemetry errors shouldn't break functionality
|
|
2046
|
+
console.debug('Failed to initialize OpenTelemetry:', error);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
getConnectionString() {
|
|
2050
|
+
const connectionString = CONNECTION_STRING;
|
|
2051
|
+
return connectionString;
|
|
2052
|
+
}
|
|
2053
|
+
setupTelemetryProvider(connectionString) {
|
|
2054
|
+
const exporter = new ApplicationInsightsEventExporter(connectionString);
|
|
2055
|
+
const processor = new BatchLogRecordProcessor(exporter);
|
|
2056
|
+
this.logProvider = new LoggerProvider({
|
|
2057
|
+
processors: [processor]
|
|
2058
|
+
});
|
|
2059
|
+
this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* Track a telemetry event
|
|
2063
|
+
*/
|
|
2064
|
+
track(eventName, name, extraAttributes = {}) {
|
|
2065
|
+
try {
|
|
2066
|
+
// Skip if logger not initialized
|
|
2067
|
+
if (!this.logger) {
|
|
2068
|
+
return;
|
|
2069
|
+
}
|
|
2070
|
+
const finalDisplayName = name || eventName;
|
|
2071
|
+
const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
|
|
2072
|
+
// Emit as log
|
|
2073
|
+
this.logger.emit({
|
|
2074
|
+
body: finalDisplayName,
|
|
2075
|
+
attributes: attributes,
|
|
2076
|
+
timestamp: Date.now(),
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
catch (error) {
|
|
2080
|
+
// Silent failure
|
|
2081
|
+
console.debug('Failed to track telemetry event:', error);
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
/**
|
|
2085
|
+
* Get enriched attributes for telemetry events
|
|
2086
|
+
*/
|
|
2087
|
+
getEnrichedAttributes(extraAttributes, eventName) {
|
|
2088
|
+
const attributes = {
|
|
2089
|
+
...extraAttributes,
|
|
2090
|
+
[APP_NAME]: SDK_SERVICE_NAME,
|
|
2091
|
+
[VERSION]: SDK_VERSION,
|
|
2092
|
+
[SERVICE]: eventName,
|
|
2093
|
+
[CLOUD_URL]: this.createCloudUrl(),
|
|
2094
|
+
[CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
|
|
2095
|
+
[CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
|
|
2096
|
+
[CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
|
|
2097
|
+
[CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
|
|
2098
|
+
};
|
|
2099
|
+
return attributes;
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Create cloud URL from base URL, organization ID, and tenant ID
|
|
2103
|
+
*/
|
|
2104
|
+
createCloudUrl() {
|
|
2105
|
+
const baseUrl = this.telemetryContext?.baseUrl;
|
|
2106
|
+
const orgId = this.telemetryContext?.orgName;
|
|
2107
|
+
const tenantId = this.telemetryContext?.tenantName;
|
|
2108
|
+
if (!baseUrl || !orgId || !tenantId) {
|
|
2109
|
+
return UNKNOWN;
|
|
2110
|
+
}
|
|
2111
|
+
return `${baseUrl}/${orgId}/${tenantId}`;
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
// Export singleton instance
|
|
2115
|
+
const telemetryClient = TelemetryClient.getInstance();
|
|
2116
|
+
|
|
2117
|
+
/**
|
|
2118
|
+
* SDK Track decorator and function for telemetry
|
|
2119
|
+
*/
|
|
2120
|
+
/**
|
|
2121
|
+
* Common tracking logic shared between method and function decorators
|
|
2122
|
+
*/
|
|
2123
|
+
function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
|
|
2124
|
+
return function (...args) {
|
|
2125
|
+
// Determine if we should track this call
|
|
2126
|
+
let shouldTrack = true;
|
|
2127
|
+
if (opts.condition !== undefined) {
|
|
2128
|
+
if (typeof opts.condition === 'function') {
|
|
2129
|
+
shouldTrack = opts.condition.apply(this, args);
|
|
2130
|
+
}
|
|
2131
|
+
else {
|
|
2132
|
+
shouldTrack = opts.condition;
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
// Track the event if enabled
|
|
2136
|
+
if (shouldTrack) {
|
|
2137
|
+
// Use the full name provided in the decorator (e.g., "Queue.GetAll")
|
|
2138
|
+
const serviceMethod = typeof nameOrOptions === 'string'
|
|
2139
|
+
? nameOrOptions
|
|
2140
|
+
: fallbackName;
|
|
2141
|
+
// Use 'Sdk.Run' as the name and serviceMethod as the service
|
|
2142
|
+
telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
|
|
2143
|
+
}
|
|
2144
|
+
// Execute the original function
|
|
2145
|
+
return originalFunction.apply(this, args);
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* Track decorator that can be used to automatically track function calls
|
|
2150
|
+
*
|
|
2151
|
+
* Usage:
|
|
2152
|
+
* @track("Service.Method")
|
|
2153
|
+
* function myFunction() { ... }
|
|
2154
|
+
*
|
|
2155
|
+
* @track("Queue.GetAll")
|
|
2156
|
+
* async getAll() { ... }
|
|
2157
|
+
*
|
|
2158
|
+
* @track("Tasks.Create")
|
|
2159
|
+
* async create() { ... }
|
|
2160
|
+
*
|
|
2161
|
+
* @track("Assets.Update", { condition: false })
|
|
2162
|
+
* function myFunction() { ... }
|
|
2163
|
+
*
|
|
2164
|
+
* @track("Processes.Start", { attributes: { customProp: "value" } })
|
|
2165
|
+
* function myFunction() { ... }
|
|
2166
|
+
*/
|
|
2167
|
+
function track(nameOrOptions, options) {
|
|
2168
|
+
return function decorator(_target, propertyKey, descriptor) {
|
|
2169
|
+
const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
|
|
2170
|
+
if (descriptor && typeof descriptor.value === 'function') {
|
|
2171
|
+
// Method decorator
|
|
2172
|
+
descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
|
|
2173
|
+
return descriptor;
|
|
2174
|
+
}
|
|
2175
|
+
// Function decorator
|
|
2176
|
+
return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
/**
|
|
2181
|
+
* Service for interacting with the Data Fabric Entity API
|
|
2182
|
+
*/
|
|
2183
|
+
class EntityService extends BaseService {
|
|
2184
|
+
/**
|
|
2185
|
+
* Gets entity metadata by entity ID with attached operation methods
|
|
2186
|
+
*
|
|
2187
|
+
* @param id - UUID of the entity
|
|
2188
|
+
* @returns Promise resolving to entity metadata with schema information and operation methods
|
|
2189
|
+
*
|
|
2190
|
+
* @example
|
|
2191
|
+
* ```typescript
|
|
2192
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2193
|
+
*
|
|
2194
|
+
* const entities = new Entities(sdk);
|
|
2195
|
+
* const entity = await entities.getById("<entityId>");
|
|
2196
|
+
*
|
|
2197
|
+
* // Call operations directly on the entity
|
|
2198
|
+
* const records = await entity.getAllRecords();
|
|
2199
|
+
*
|
|
2200
|
+
* // Insert a single record
|
|
2201
|
+
* const insertResult = await entity.insertRecord({ name: "John", age: 30 });
|
|
2202
|
+
*
|
|
2203
|
+
* // Or batch insert multiple records
|
|
2204
|
+
* const batchResult = await entity.insertRecords([
|
|
2205
|
+
* { name: "Jane", age: 25 },
|
|
2206
|
+
* { name: "Bob", age: 35 }
|
|
2207
|
+
* ]);
|
|
2208
|
+
* ```
|
|
2209
|
+
*/
|
|
2210
|
+
async getById(id) {
|
|
2211
|
+
// Get entity metadata
|
|
2212
|
+
const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_BY_ID(id));
|
|
2213
|
+
// Apply EntityMap transformations
|
|
2214
|
+
const metadata = transformData(response.data, EntityMap);
|
|
2215
|
+
// Transform metadata with field mappers
|
|
2216
|
+
this.applyFieldMappings(metadata);
|
|
2217
|
+
// Return the entity metadata with methods attached
|
|
2218
|
+
return createEntityWithMethods(metadata, this);
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2221
|
+
* Gets entity records by entity ID
|
|
2222
|
+
*
|
|
2223
|
+
* @param entityId - UUID of the entity
|
|
2224
|
+
* @param options - Query options including expansionLevel and pagination options
|
|
2225
|
+
* @returns Promise resolving to an array of entity records or paginated response
|
|
2226
|
+
*
|
|
2227
|
+
* @example
|
|
2228
|
+
* ```typescript
|
|
2229
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2230
|
+
*
|
|
2231
|
+
* const entities = new Entities(sdk);
|
|
2232
|
+
*
|
|
2233
|
+
* // Basic usage (non-paginated)
|
|
2234
|
+
* const records = await entities.getAllRecords("<entityId>");
|
|
2235
|
+
*
|
|
2236
|
+
* // With expansion level
|
|
2237
|
+
* const records = await entities.getAllRecords("<entityId>", {
|
|
2238
|
+
* expansionLevel: 1
|
|
2239
|
+
* });
|
|
2240
|
+
*
|
|
2241
|
+
* // With pagination
|
|
2242
|
+
* const paginatedResponse = await entities.getAllRecords("<entityId>", {
|
|
2243
|
+
* pageSize: 50,
|
|
2244
|
+
* expansionLevel: 1
|
|
2245
|
+
* });
|
|
2246
|
+
*
|
|
2247
|
+
* // Navigate to next page
|
|
2248
|
+
* const nextPage = await entities.getAllRecords("<entityId>", {
|
|
2249
|
+
* cursor: paginatedResponse.nextCursor,
|
|
2250
|
+
* expansionLevel: 1
|
|
2251
|
+
* });
|
|
2252
|
+
* ```
|
|
2253
|
+
*/
|
|
2254
|
+
async getAllRecords(entityId, options) {
|
|
2255
|
+
return PaginationHelpers.getAll({
|
|
2256
|
+
serviceAccess: this.createPaginationServiceAccess(),
|
|
2257
|
+
getEndpoint: () => DATA_FABRIC_ENDPOINTS.ENTITY.GET_ENTITY_RECORDS(entityId),
|
|
2258
|
+
pagination: {
|
|
2259
|
+
paginationType: PaginationType.OFFSET,
|
|
2260
|
+
itemsField: ENTITY_PAGINATION.ITEMS_FIELD,
|
|
2261
|
+
totalCountField: ENTITY_PAGINATION.TOTAL_COUNT_FIELD,
|
|
2262
|
+
paginationParams: {
|
|
2263
|
+
pageSizeParam: ENTITY_OFFSET_PARAMS.PAGE_SIZE_PARAM,
|
|
2264
|
+
offsetParam: ENTITY_OFFSET_PARAMS.OFFSET_PARAM,
|
|
2265
|
+
countParam: ENTITY_OFFSET_PARAMS.COUNT_PARAM
|
|
2266
|
+
}
|
|
2267
|
+
},
|
|
2268
|
+
excludeFromPrefix: ['expansionLevel'] // Don't add ODATA prefix to expansionLevel
|
|
2269
|
+
}, options);
|
|
2270
|
+
}
|
|
2271
|
+
/**
|
|
2272
|
+
* Gets a single entity record by entity ID and record ID
|
|
2273
|
+
*
|
|
2274
|
+
* @param entityId - UUID of the entity
|
|
2275
|
+
* @param recordId - UUID of the record
|
|
2276
|
+
* @param options - Query options including expansionLevel
|
|
2277
|
+
* @returns Promise resolving to the entity record
|
|
2278
|
+
*
|
|
2279
|
+
* @example
|
|
2280
|
+
* ```typescript
|
|
2281
|
+
* // Basic usage
|
|
2282
|
+
* const record = await sdk.entities.getRecordById(<entityId>, <recordId>);
|
|
2283
|
+
*
|
|
2284
|
+
* // With expansion level
|
|
2285
|
+
* const record = await sdk.entities.getRecordById(<entityId>, <recordId>, {
|
|
2286
|
+
* expansionLevel: 1
|
|
2287
|
+
* });
|
|
2288
|
+
* ```
|
|
2289
|
+
*/
|
|
2290
|
+
async getRecordById(entityId, recordId, options = {}) {
|
|
2291
|
+
const params = createParams({
|
|
2292
|
+
expansionLevel: options.expansionLevel
|
|
2293
|
+
});
|
|
2294
|
+
const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_RECORD_BY_ID(entityId, recordId), { params });
|
|
2295
|
+
// Convert PascalCase response to camelCase
|
|
2296
|
+
const camelResponse = pascalToCamelCaseKeys(response.data);
|
|
2297
|
+
// Apply EntityMap transformations
|
|
2298
|
+
const transformedResponse = transformData(camelResponse, EntityMap);
|
|
2299
|
+
return transformedResponse;
|
|
2300
|
+
}
|
|
2301
|
+
/**
|
|
2302
|
+
* Inserts a single record into an entity by entity ID
|
|
2303
|
+
*
|
|
2304
|
+
* @param entityId - UUID of the entity
|
|
2305
|
+
* @param data - Record to insert
|
|
2306
|
+
* @param options - Insert options
|
|
2307
|
+
* @returns Promise resolving to the inserted record with generated record ID
|
|
2308
|
+
*
|
|
2309
|
+
* @example
|
|
2310
|
+
* ```typescript
|
|
2311
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2312
|
+
*
|
|
2313
|
+
* const entities = new Entities(sdk);
|
|
2314
|
+
*
|
|
2315
|
+
* // Basic usage
|
|
2316
|
+
* const result = await entities.insertRecordById("<entityId>", { name: "John", age: 30 });
|
|
2317
|
+
*
|
|
2318
|
+
* // With options
|
|
2319
|
+
* const result = await entities.insertRecordById("<entityId>", { name: "John", age: 30 }, {
|
|
2320
|
+
* expansionLevel: 1
|
|
2321
|
+
* });
|
|
2322
|
+
* ```
|
|
2323
|
+
*/
|
|
2324
|
+
async insertRecordById(id, data, options = {}) {
|
|
2325
|
+
const params = createParams({
|
|
2326
|
+
expansionLevel: options.expansionLevel
|
|
2327
|
+
});
|
|
2328
|
+
const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.INSERT_BY_ID(id), data, {
|
|
2329
|
+
params,
|
|
2330
|
+
...options
|
|
2331
|
+
});
|
|
2332
|
+
// Convert PascalCase response to camelCase
|
|
2333
|
+
const camelResponse = pascalToCamelCaseKeys(response.data);
|
|
2334
|
+
return camelResponse;
|
|
2335
|
+
}
|
|
2336
|
+
/**
|
|
2337
|
+
* Inserts data into an entity by entity ID using batch insert
|
|
2338
|
+
*
|
|
2339
|
+
* @param entityId - UUID of the entity
|
|
2340
|
+
* @param data - Array of records to insert
|
|
2341
|
+
* @param options - Insert options
|
|
2342
|
+
* @returns Promise resolving to insert response
|
|
2343
|
+
*
|
|
2344
|
+
* @example
|
|
2345
|
+
* ```typescript
|
|
2346
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2347
|
+
*
|
|
2348
|
+
* const entities = new Entities(sdk);
|
|
2349
|
+
*
|
|
2350
|
+
* // Basic usage
|
|
2351
|
+
* const result = await entities.insertRecordsById("<entityId>", [
|
|
2352
|
+
* { name: "John", age: 30 },
|
|
2353
|
+
* { name: "Jane", age: 25 }
|
|
2354
|
+
* ]);
|
|
2355
|
+
*
|
|
2356
|
+
* // With options
|
|
2357
|
+
* const result = await entities.insertRecordsById("<entityId>", [
|
|
2358
|
+
* { name: "John", age: 30 },
|
|
2359
|
+
* { name: "Jane", age: 25 }
|
|
2360
|
+
* ], {
|
|
2361
|
+
* expansionLevel: 1,
|
|
2362
|
+
* failOnFirst: true
|
|
2363
|
+
* });
|
|
2364
|
+
* ```
|
|
2365
|
+
*/
|
|
2366
|
+
async insertRecordsById(id, data, options = {}) {
|
|
2367
|
+
const params = createParams({
|
|
2368
|
+
expansionLevel: options.expansionLevel,
|
|
2369
|
+
failOnFirst: options.failOnFirst
|
|
2370
|
+
});
|
|
2371
|
+
const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.BATCH_INSERT_BY_ID(id), data, {
|
|
2372
|
+
params,
|
|
2373
|
+
...options
|
|
2374
|
+
});
|
|
2375
|
+
// Convert PascalCase response to camelCase
|
|
2376
|
+
const camelResponse = pascalToCamelCaseKeys(response.data);
|
|
2377
|
+
return camelResponse;
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* Updates data in an entity by entity ID
|
|
2381
|
+
*
|
|
2382
|
+
* @param entityId - UUID of the entity
|
|
2383
|
+
* @param data - Array of records to update. Each record MUST contain the record Id,
|
|
2384
|
+
* otherwise the update will fail.
|
|
2385
|
+
* @param options - Update options
|
|
2386
|
+
* @returns Promise resolving to update response
|
|
2387
|
+
*
|
|
2388
|
+
* @example
|
|
2389
|
+
* ```typescript
|
|
2390
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2391
|
+
*
|
|
2392
|
+
* const entities = new Entities(sdk);
|
|
2393
|
+
*
|
|
2394
|
+
* // Basic usage
|
|
2395
|
+
* const result = await entities.updateRecordsById("<entityId>", [
|
|
2396
|
+
* { Id: "123", name: "John Updated", age: 31 },
|
|
2397
|
+
* { Id: "456", name: "Jane Updated", age: 26 }
|
|
2398
|
+
* ]);
|
|
2399
|
+
*
|
|
2400
|
+
* // With options
|
|
2401
|
+
* const result = await entities.updateRecordsById("<entityId>", [
|
|
2402
|
+
* { Id: "123", name: "John Updated", age: 31 },
|
|
2403
|
+
* { Id: "456", name: "Jane Updated", age: 26 }
|
|
2404
|
+
* ], {
|
|
2405
|
+
* expansionLevel: 1,
|
|
2406
|
+
* failOnFirst: true
|
|
2407
|
+
* });
|
|
2408
|
+
* ```
|
|
2409
|
+
*/
|
|
2410
|
+
async updateRecordsById(id, data, options = {}) {
|
|
2411
|
+
const params = createParams({
|
|
2412
|
+
expansionLevel: options.expansionLevel,
|
|
2413
|
+
failOnFirst: options.failOnFirst
|
|
2414
|
+
});
|
|
2415
|
+
const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPDATE_BY_ID(id), data, {
|
|
2416
|
+
params,
|
|
2417
|
+
...options
|
|
2418
|
+
});
|
|
2419
|
+
// Convert PascalCase response to camelCase
|
|
2420
|
+
const camelResponse = pascalToCamelCaseKeys(response.data);
|
|
2421
|
+
return camelResponse;
|
|
2422
|
+
}
|
|
2423
|
+
/**
|
|
2424
|
+
* Deletes data from an entity by entity ID
|
|
2425
|
+
*
|
|
2426
|
+
* @param entityId - UUID of the entity
|
|
2427
|
+
* @param recordIds - Array of record UUIDs to delete
|
|
2428
|
+
* @param options - Delete options
|
|
2429
|
+
* @returns Promise resolving to delete response
|
|
2430
|
+
*
|
|
2431
|
+
* @example
|
|
2432
|
+
* ```typescript
|
|
2433
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2434
|
+
*
|
|
2435
|
+
* const entities = new Entities(sdk);
|
|
2436
|
+
*
|
|
2437
|
+
* // Basic usage
|
|
2438
|
+
* const result = await entities.deleteRecordsById("<entityId>", [
|
|
2439
|
+
* "<recordId-1>", "<recordId-2>"
|
|
2440
|
+
* ]);
|
|
2441
|
+
* ```
|
|
2442
|
+
*/
|
|
2443
|
+
async deleteRecordsById(id, recordIds, options = {}) {
|
|
2444
|
+
const params = createParams({
|
|
2445
|
+
failOnFirst: options.failOnFirst
|
|
2446
|
+
});
|
|
2447
|
+
const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE_BY_ID(id), recordIds, {
|
|
2448
|
+
params,
|
|
2449
|
+
...options
|
|
2450
|
+
});
|
|
2451
|
+
// Convert PascalCase response to camelCase
|
|
2452
|
+
const camelResponse = pascalToCamelCaseKeys(response.data);
|
|
2453
|
+
return camelResponse;
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Gets all entities in the system
|
|
2457
|
+
*
|
|
2458
|
+
* @returns Promise resolving to an array of entity metadata
|
|
2459
|
+
*
|
|
2460
|
+
* @example
|
|
2461
|
+
* ```typescript
|
|
2462
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2463
|
+
*
|
|
2464
|
+
* const entities = new Entities(sdk);
|
|
2465
|
+
*
|
|
2466
|
+
* // Get all entities
|
|
2467
|
+
* const allEntities = await entities.getAll();
|
|
2468
|
+
*
|
|
2469
|
+
* // Call operations on an entity
|
|
2470
|
+
* const records = await allEntities[0].getAllRecords();
|
|
2471
|
+
* ```
|
|
2472
|
+
*/
|
|
2473
|
+
async getAll() {
|
|
2474
|
+
const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_ALL);
|
|
2475
|
+
// Apply transformations
|
|
2476
|
+
const entities = response.data.map(entity => {
|
|
2477
|
+
// Transform each entity
|
|
2478
|
+
const metadata = transformData(entity, EntityMap);
|
|
2479
|
+
this.applyFieldMappings(metadata);
|
|
2480
|
+
// Attach entity methods
|
|
2481
|
+
return createEntityWithMethods(metadata, this);
|
|
2482
|
+
});
|
|
2483
|
+
return entities;
|
|
2484
|
+
}
|
|
2485
|
+
/**
|
|
2486
|
+
* Downloads an attachment from an entity record field
|
|
2487
|
+
*
|
|
2488
|
+
* @param options - Options containing entityName, recordId, and fieldName
|
|
2489
|
+
* @returns Promise resolving to Blob containing the file content
|
|
2490
|
+
*
|
|
2491
|
+
* @example
|
|
2492
|
+
* ```typescript
|
|
2493
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
2494
|
+
*
|
|
2495
|
+
* const entities = new Entities(sdk);
|
|
2496
|
+
*
|
|
2497
|
+
* // Download attachment for a specific record and field
|
|
2498
|
+
* const blob = await entities.downloadAttachment({
|
|
2499
|
+
* entityName: 'Invoice',
|
|
2500
|
+
* recordId: '<record-uuid>',
|
|
2501
|
+
* fieldName: 'Documents'
|
|
2502
|
+
* });
|
|
2503
|
+
*/
|
|
2504
|
+
async downloadAttachment(options) {
|
|
2505
|
+
const { entityName, recordId, fieldName } = options;
|
|
2506
|
+
const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.DOWNLOAD_ATTACHMENT(entityName, recordId, fieldName), {
|
|
2507
|
+
responseType: RESPONSE_TYPES.BLOB
|
|
2508
|
+
});
|
|
2509
|
+
return response.data;
|
|
2510
|
+
}
|
|
2511
|
+
/**
|
|
2512
|
+
* @hidden
|
|
2513
|
+
* @deprecated Use {@link getAllRecords} instead.
|
|
2514
|
+
*/
|
|
2515
|
+
async getRecordsById(entityId, options) {
|
|
2516
|
+
return this.getAllRecords(entityId, options);
|
|
2517
|
+
}
|
|
2518
|
+
/**
|
|
2519
|
+
* @hidden
|
|
2520
|
+
* @deprecated Use {@link insertRecordById} instead.
|
|
2521
|
+
*/
|
|
2522
|
+
async insertById(id, data, options = {}) {
|
|
2523
|
+
return this.insertRecordById(id, data, options);
|
|
2524
|
+
}
|
|
2525
|
+
/**
|
|
2526
|
+
* @hidden
|
|
2527
|
+
* @deprecated Use {@link insertRecordsById} instead.
|
|
2528
|
+
*/
|
|
2529
|
+
async batchInsertById(id, data, options = {}) {
|
|
2530
|
+
return this.insertRecordsById(id, data, options);
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2533
|
+
* @hidden
|
|
2534
|
+
* @deprecated Use {@link updateRecordsById} instead.
|
|
2535
|
+
*/
|
|
2536
|
+
async updateById(id, data, options = {}) {
|
|
2537
|
+
return this.updateRecordsById(id, data, options);
|
|
2538
|
+
}
|
|
2539
|
+
/**
|
|
2540
|
+
* @hidden
|
|
2541
|
+
* @deprecated Use {@link deleteRecordsById} instead.
|
|
2542
|
+
*/
|
|
2543
|
+
async deleteById(id, recordIds, options = {}) {
|
|
2544
|
+
return this.deleteRecordsById(id, recordIds, options);
|
|
2545
|
+
}
|
|
2546
|
+
/**
|
|
2547
|
+
* Orchestrates all field mapping transformations
|
|
2548
|
+
*
|
|
2549
|
+
* @param metadata - Entity metadata to transform
|
|
2550
|
+
* @private
|
|
2551
|
+
*/
|
|
2552
|
+
applyFieldMappings(metadata) {
|
|
2553
|
+
this.mapFieldTypes(metadata);
|
|
2554
|
+
this.mapExternalFields(metadata);
|
|
2555
|
+
}
|
|
2556
|
+
/**
|
|
2557
|
+
* Maps SQL field types to friendly EntityFieldTypes
|
|
2558
|
+
*
|
|
2559
|
+
* @param metadata - Entity metadata with fields
|
|
2560
|
+
* @private
|
|
2561
|
+
*/
|
|
2562
|
+
mapFieldTypes(metadata) {
|
|
2563
|
+
if (!metadata.fields?.length)
|
|
2564
|
+
return;
|
|
2565
|
+
metadata.fields = metadata.fields.map(field => {
|
|
2566
|
+
// Rename sqlType to fieldDataType
|
|
2567
|
+
let transformedField = transformData(field, EntityMap);
|
|
2568
|
+
// Map SQL field type to friendly name
|
|
2569
|
+
if (transformedField.fieldDataType?.name) {
|
|
2570
|
+
const sqlTypeName = transformedField.fieldDataType.name;
|
|
2571
|
+
if (EntityFieldTypeMap[sqlTypeName]) {
|
|
2572
|
+
transformedField.fieldDataType.name = EntityFieldTypeMap[sqlTypeName];
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
this.transformNestedReferences(transformedField);
|
|
2576
|
+
return transformedField;
|
|
2577
|
+
});
|
|
2578
|
+
}
|
|
2579
|
+
/**
|
|
2580
|
+
* Transforms nested reference objects in field metadata
|
|
2581
|
+
*/
|
|
2582
|
+
transformNestedReferences(field) {
|
|
2583
|
+
if (field.referenceEntity) {
|
|
2584
|
+
field.referenceEntity = transformData(field.referenceEntity, EntityMap);
|
|
2585
|
+
}
|
|
2586
|
+
if (field.referenceChoiceSet) {
|
|
2587
|
+
field.referenceChoiceSet = transformData(field.referenceChoiceSet, EntityMap);
|
|
2588
|
+
}
|
|
2589
|
+
if (field.referenceField?.definition) {
|
|
2590
|
+
field.referenceField.definition = transformData(field.referenceField.definition, EntityMap);
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
/**
|
|
2594
|
+
* Maps external field names to consistent naming
|
|
2595
|
+
*
|
|
2596
|
+
* @param metadata - Entity metadata with externalFields
|
|
2597
|
+
* @private
|
|
2598
|
+
*/
|
|
2599
|
+
mapExternalFields(metadata) {
|
|
2600
|
+
if (!metadata.externalFields?.length)
|
|
2601
|
+
return;
|
|
2602
|
+
metadata.externalFields = metadata.externalFields.map(externalSource => {
|
|
2603
|
+
if (externalSource.fields?.length) {
|
|
2604
|
+
externalSource.fields = externalSource.fields.map(field => {
|
|
2605
|
+
const transformedField = transformData(field, EntityMap);
|
|
2606
|
+
if (transformedField.fieldMetaData) {
|
|
2607
|
+
transformedField.fieldMetaData = transformData(transformedField.fieldMetaData, EntityMap);
|
|
2608
|
+
this.transformNestedReferences(transformedField.fieldMetaData);
|
|
2609
|
+
}
|
|
2610
|
+
return transformedField;
|
|
2611
|
+
});
|
|
2612
|
+
}
|
|
2613
|
+
return externalSource;
|
|
2614
|
+
});
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
__decorate([
|
|
2618
|
+
track('Entities.GetById')
|
|
2619
|
+
], EntityService.prototype, "getById", null);
|
|
2620
|
+
__decorate([
|
|
2621
|
+
track('Entities.GetAllRecords')
|
|
2622
|
+
], EntityService.prototype, "getAllRecords", null);
|
|
2623
|
+
__decorate([
|
|
2624
|
+
track('Entities.GetRecordById')
|
|
2625
|
+
], EntityService.prototype, "getRecordById", null);
|
|
2626
|
+
__decorate([
|
|
2627
|
+
track('Entities.InsertRecordById')
|
|
2628
|
+
], EntityService.prototype, "insertRecordById", null);
|
|
2629
|
+
__decorate([
|
|
2630
|
+
track('Entities.InsertRecordsById')
|
|
2631
|
+
], EntityService.prototype, "insertRecordsById", null);
|
|
2632
|
+
__decorate([
|
|
2633
|
+
track('Entities.UpdateRecordsById')
|
|
2634
|
+
], EntityService.prototype, "updateRecordsById", null);
|
|
2635
|
+
__decorate([
|
|
2636
|
+
track('Entities.DeleteRecordsById')
|
|
2637
|
+
], EntityService.prototype, "deleteRecordsById", null);
|
|
2638
|
+
__decorate([
|
|
2639
|
+
track('Entities.GetAll')
|
|
2640
|
+
], EntityService.prototype, "getAll", null);
|
|
2641
|
+
__decorate([
|
|
2642
|
+
track('Entities.DownloadAttachment')
|
|
2643
|
+
], EntityService.prototype, "downloadAttachment", null);
|
|
2644
|
+
|
|
2645
|
+
class ChoiceSetService extends BaseService {
|
|
2646
|
+
/**
|
|
2647
|
+
* Gets all choice sets in the system
|
|
2648
|
+
*
|
|
2649
|
+
* @returns Promise resolving to an array of choice set metadata
|
|
2650
|
+
*
|
|
2651
|
+
* @example
|
|
2652
|
+
* ```typescript
|
|
2653
|
+
* import { ChoiceSets } from '@uipath/uipath-typescript/entities';
|
|
2654
|
+
*
|
|
2655
|
+
* const choiceSets = new ChoiceSets(sdk);
|
|
2656
|
+
*
|
|
2657
|
+
* // Get all choice sets
|
|
2658
|
+
* const allChoiceSets = await choiceSets.getAll();
|
|
2659
|
+
*
|
|
2660
|
+
* // Iterate through choice sets
|
|
2661
|
+
* allChoiceSets.forEach(choiceSet => {
|
|
2662
|
+
* console.log(`ChoiceSet: ${choiceSet.displayName} (${choiceSet.name})`);
|
|
2663
|
+
* console.log(`Description: ${choiceSet.description}`);
|
|
2664
|
+
* });
|
|
2665
|
+
* ```
|
|
2666
|
+
*/
|
|
2667
|
+
async getAll() {
|
|
2668
|
+
const rawResponse = await this.get(DATA_FABRIC_ENDPOINTS.CHOICESETS.GET_ALL);
|
|
2669
|
+
// Transform field names
|
|
2670
|
+
const data = rawResponse.data || [];
|
|
2671
|
+
return data.map(choiceSet => transformData(choiceSet, EntityMap));
|
|
2672
|
+
}
|
|
2673
|
+
/**
|
|
2674
|
+
* Gets choice set values by choice set ID with optional pagination
|
|
2675
|
+
*
|
|
2676
|
+
* The method returns either:
|
|
2677
|
+
* - A NonPaginatedResponse with items array (when no pagination parameters are provided)
|
|
2678
|
+
* - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
|
|
2679
|
+
*
|
|
2680
|
+
* @param choiceSetId - UUID of the choice set
|
|
2681
|
+
* @param options - Pagination options
|
|
2682
|
+
* @returns Promise resolving to choice set values or paginated result
|
|
2683
|
+
*
|
|
2684
|
+
* @example
|
|
2685
|
+
* ```typescript
|
|
2686
|
+
* import { ChoiceSets } from '@uipath/uipath-typescript/choicesets';
|
|
2687
|
+
*
|
|
2688
|
+
* const choiceSets = new ChoiceSets(sdk);
|
|
2689
|
+
*
|
|
2690
|
+
* // First, get the choice set ID using getAll()
|
|
2691
|
+
* const allChoiceSets = await choiceSets.getAll();
|
|
2692
|
+
* const expenseTypes = allChoiceSets.find(cs => cs.name === 'ExpenseTypes');
|
|
2693
|
+
* const choiceSetId = expenseTypes.id;
|
|
2694
|
+
*
|
|
2695
|
+
* // Get all values (non-paginated)
|
|
2696
|
+
* const values = await choiceSets.getById(choiceSetId);
|
|
2697
|
+
*
|
|
2698
|
+
* // Iterate through choice set values
|
|
2699
|
+
* for (const value of values.items) {
|
|
2700
|
+
* console.log(`Value: ${value.displayName} (${value.name})`);
|
|
2701
|
+
* }
|
|
2702
|
+
*
|
|
2703
|
+
* // First page with pagination
|
|
2704
|
+
* const page1 = await choiceSets.getById(choiceSetId, { pageSize: 10 });
|
|
2705
|
+
*
|
|
2706
|
+
* // Navigate using cursor
|
|
2707
|
+
* if (page1.hasNextPage) {
|
|
2708
|
+
* const page2 = await choiceSets.getById(choiceSetId, { cursor: page1.nextCursor });
|
|
2709
|
+
* }
|
|
2710
|
+
* ```
|
|
2711
|
+
*/
|
|
2712
|
+
async getById(choiceSetId, options) {
|
|
2713
|
+
// Transform a single item from PascalCase to camelCase
|
|
2714
|
+
const transformFn = (item) => {
|
|
2715
|
+
const camelCased = pascalToCamelCaseKeys(item);
|
|
2716
|
+
return transformData(camelCased, EntityMap);
|
|
2717
|
+
};
|
|
2718
|
+
return PaginationHelpers.getAll({
|
|
2719
|
+
serviceAccess: this.createPaginationServiceAccess(),
|
|
2720
|
+
getEndpoint: () => DATA_FABRIC_ENDPOINTS.CHOICESETS.GET_BY_ID(choiceSetId),
|
|
2721
|
+
transformFn,
|
|
2722
|
+
method: HTTP_METHODS.POST,
|
|
2723
|
+
pagination: {
|
|
2724
|
+
paginationType: PaginationType.OFFSET,
|
|
2725
|
+
itemsField: CHOICESET_VALUES_PAGINATION.ITEMS_FIELD,
|
|
2726
|
+
totalCountField: CHOICESET_VALUES_PAGINATION.TOTAL_COUNT_FIELD,
|
|
2727
|
+
paginationParams: {
|
|
2728
|
+
pageSizeParam: ENTITY_OFFSET_PARAMS.PAGE_SIZE_PARAM,
|
|
2729
|
+
offsetParam: ENTITY_OFFSET_PARAMS.OFFSET_PARAM,
|
|
2730
|
+
countParam: ENTITY_OFFSET_PARAMS.COUNT_PARAM
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
}, options);
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
__decorate([
|
|
2737
|
+
track('Choicesets.GetAll')
|
|
2738
|
+
], ChoiceSetService.prototype, "getAll", null);
|
|
2739
|
+
__decorate([
|
|
2740
|
+
track('Choicesets.GetById')
|
|
2741
|
+
], ChoiceSetService.prototype, "getById", null);
|
|
2742
|
+
|
|
2743
|
+
export { ChoiceSetService, ChoiceSetService as ChoiceSets, DataDirectionType, EntityService as Entities, EntityFieldDataType, EntityService, EntityType, FieldDisplayType, JoinType, ReferenceType, createEntityWithMethods };
|