@uipath/uipath-typescript 1.0.0-beta.13 → 1.0.0-beta.15

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.
@@ -2,28 +2,8 @@
2
2
 
3
3
  var zod = require('zod');
4
4
  var sdkLogs = require('@opentelemetry/sdk-logs');
5
- var mimeTypes = require('mime-types');
6
5
  var axios = require('axios');
7
6
 
8
- function _interopNamespaceDefault(e) {
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () { return e[k]; }
17
- });
18
- }
19
- });
20
- }
21
- n.default = e;
22
- return Object.freeze(n);
23
- }
24
-
25
- var mimeTypes__namespace = /*#__PURE__*/_interopNamespaceDefault(mimeTypes);
26
-
27
7
  zod.z.object({
28
8
  baseUrl: zod.z.string().url().default('https://cloud.uipath.com'),
29
9
  orgName: zod.z.string().min(1),
@@ -581,7 +561,7 @@ class ErrorFactory {
581
561
  * Creates appropriate error instance based on HTTP status code
582
562
  */
583
563
  static createFromHttpStatus(statusCode, errorInfo) {
584
- const { message, requestId, details } = errorInfo;
564
+ const { message, requestId } = errorInfo;
585
565
  // Map status codes to error types
586
566
  switch (statusCode) {
587
567
  case HttpStatus.BAD_REQUEST:
@@ -999,6 +979,8 @@ function createHeaders(headersObj) {
999
979
  * Prefix used for OData query parameters
1000
980
  */
1001
981
  const ODATA_PREFIX = '$';
982
+ const UNKNOWN$1 = 'Unknown';
983
+ const NO_INSTANCE = 'no-instance';
1002
984
  /**
1003
985
  * OData pagination constants
1004
986
  */
@@ -1491,12 +1473,12 @@ class PaginationHelpers {
1491
1473
  throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1492
1474
  }
1493
1475
  // Get processed parameters
1494
- return PaginationHelpers.getRequestParameters(options);
1476
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1495
1477
  }
1496
1478
  /**
1497
1479
  * Convert a unified pagination options to service-specific parameters
1498
1480
  */
1499
- static getRequestParameters(options) {
1481
+ static getRequestParameters(options, paginationType) {
1500
1482
  // Handle jumpToPage
1501
1483
  if (options.jumpToPage !== undefined) {
1502
1484
  const jumpToPageOptions = {
@@ -1509,7 +1491,8 @@ class PaginationHelpers {
1509
1491
  if (!options.cursor) {
1510
1492
  const firstPageOptions = {
1511
1493
  pageSize: options.pageSize,
1512
- pageNumber: 1
1494
+ // Only set pageNumber for OFFSET pagination
1495
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1513
1496
  };
1514
1497
  return filterUndefined(firstPageOptions);
1515
1498
  }
@@ -1800,7 +1783,7 @@ class BaseService {
1800
1783
  pageInfo: {
1801
1784
  hasMore,
1802
1785
  totalCount,
1803
- currentPage: params.pageNumber || 1,
1786
+ currentPage: params.pageNumber,
1804
1787
  pageSize: params.pageSize,
1805
1788
  continuationToken
1806
1789
  },
@@ -2092,8 +2075,11 @@ class TokenManager {
2092
2075
  * Maestro Process Service Endpoints
2093
2076
  */
2094
2077
  const MAESTRO_ENDPOINTS = {
2078
+ BASE_PATH: 'pims_/api/v1',
2095
2079
  PROCESSES: {
2096
- GET_ALL: 'pims_/api/v1/processes/summary'},
2080
+ GET_ALL: 'pims_/api/v1/processes/summary',
2081
+ GET_SETTINGS: (processKey) => `pims_/api/v1/processes/${processKey}/settings`,
2082
+ },
2097
2083
  INSTANCES: {
2098
2084
  GET_ALL: 'pims_/api/v1/instances',
2099
2085
  GET_BY_ID: (instanceId) => `pims_/api/v1/instances/${instanceId}`,
@@ -2104,6 +2090,15 @@ const MAESTRO_ENDPOINTS = {
2104
2090
  PAUSE: (instanceId) => `pims_/api/v1/instances/${instanceId}/pause`,
2105
2091
  RESUME: (instanceId) => `pims_/api/v1/instances/${instanceId}/resume`,
2106
2092
  },
2093
+ INCIDENTS: {
2094
+ GET_ALL: 'pims_/api/v1/incidents/summary',
2095
+ GET_BY_PROCESS: (processKey) => `pims_/api/v1/incidents/process/${processKey}`,
2096
+ GET_BY_INSTANCE: (instanceId) => `pims_/api/v1/instances/${instanceId}/incidents`,
2097
+ },
2098
+ CASES: {
2099
+ GET_CASE_JSON: (instanceId) => `pims_/api/v1/cases/${instanceId}/case-json`,
2100
+ GET_ELEMENT_EXECUTIONS: (instanceId) => `pims_/api/v1alpha1/element-executions/case-instances/${instanceId}`,
2101
+ },
2107
2102
  };
2108
2103
  /**
2109
2104
  * Task Service (Action Center) Endpoints
@@ -2111,7 +2106,7 @@ const MAESTRO_ENDPOINTS = {
2111
2106
  const TASK_ENDPOINTS = {
2112
2107
  CREATE_GENERIC_TASK: '/tasks/GenericTasks/CreateTask',
2113
2108
  GET_TASK_USERS: (folderId) => `/odata/Tasks/UiPath.Server.Configuration.OData.GetTaskUsers(organizationUnitId=${folderId})`,
2114
- GET_TASKS_ACROSS_FOLDERS: '/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFolders',
2109
+ GET_TASKS_ACROSS_FOLDERS: '/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFoldersForAdmin',
2115
2110
  GET_BY_ID: (id) => `/odata/Tasks(${id})`,
2116
2111
  ASSIGN_TASKS: '/odata/Tasks/UiPath.Server.Configuration.OData.AssignTasks',
2117
2112
  REASSIGN_TASKS: '/odata/Tasks/UiPath.Server.Configuration.OData.ReassignTasks',
@@ -2179,11 +2174,66 @@ const ASSET_ENDPOINTS = {
2179
2174
 
2180
2175
  class AuthService extends BaseService {
2181
2176
  constructor(config, executionContext) {
2182
- const isOAuth = hasOAuthConfig(config);
2183
- const tokenManager = new TokenManager(executionContext, config, isOAuth);
2184
- super(config, executionContext, tokenManager);
2177
+ // Check if we should use stored OAuth context instead of provided config
2178
+ const storedContext = AuthService.getStoredOAuthContext();
2179
+ const effectiveConfig = storedContext ? AuthService._mergeConfigWithContext(config, storedContext) : config;
2180
+ const isOAuth = hasOAuthConfig(effectiveConfig);
2181
+ const tokenManager = new TokenManager(executionContext, effectiveConfig, isOAuth);
2182
+ super(effectiveConfig, executionContext, tokenManager);
2185
2183
  this.tokenManager = tokenManager;
2186
2184
  }
2185
+ /**
2186
+ * Check if we're in an OAuth callback state
2187
+ */
2188
+ static isInOAuthCallback() {
2189
+ if (!isBrowser)
2190
+ return false;
2191
+ const urlParams = new URLSearchParams(window.location.search);
2192
+ const code = urlParams.get('code');
2193
+ const hasCodeVerifier = sessionStorage.getItem('uipath_sdk_code_verifier');
2194
+ return !!(code && hasCodeVerifier);
2195
+ }
2196
+ /**
2197
+ * Get stored OAuth context
2198
+ */
2199
+ static getStoredOAuthContext() {
2200
+ if (!isBrowser) {
2201
+ return null;
2202
+ }
2203
+ try {
2204
+ const stored = sessionStorage.getItem('uipath_sdk_oauth_context');
2205
+ if (!stored) {
2206
+ return null;
2207
+ }
2208
+ const context = JSON.parse(stored);
2209
+ // Validate required fields
2210
+ if (!context.codeVerifier || !context.clientId || !context.redirectUri ||
2211
+ !context.baseUrl || !context.orgName) {
2212
+ sessionStorage.removeItem('uipath_sdk_oauth_context');
2213
+ return null;
2214
+ }
2215
+ return context;
2216
+ }
2217
+ catch (error) {
2218
+ sessionStorage.removeItem('uipath_sdk_oauth_context');
2219
+ console.warn('Failed to parse stored OAuth context from session storage', error);
2220
+ return null;
2221
+ }
2222
+ }
2223
+ /**
2224
+ * Merges provided config with stored OAuth context, prioritizing stored values
2225
+ */
2226
+ static _mergeConfigWithContext(config, context) {
2227
+ return {
2228
+ ...config,
2229
+ baseUrl: context.baseUrl,
2230
+ orgName: context.orgName,
2231
+ tenantName: context.tenantName,
2232
+ clientId: context.clientId,
2233
+ redirectUri: context.redirectUri,
2234
+ scope: context.scope
2235
+ };
2236
+ }
2187
2237
  /**
2188
2238
  * Get the token manager instance
2189
2239
  */
@@ -2199,13 +2249,34 @@ class AuthService extends BaseService {
2199
2249
  * In an OAuth flow, this method will trigger a page redirect and the promise will not resolve.
2200
2250
  */
2201
2251
  async authenticate(config) {
2202
- // Try to load token from storage first (only works for OAuth tokens)
2252
+ if (!isBrowser) {
2253
+ return false;
2254
+ }
2255
+ // First priority: Complete OAuth callback if we detect it
2256
+ if (AuthService.isInOAuthCallback()) {
2257
+ const urlParams = new URLSearchParams(window.location.search);
2258
+ const code = urlParams.get('code');
2259
+ if (!code) {
2260
+ throw new Error('Authorization code missing in OAuth callback');
2261
+ }
2262
+ // Check if token already exists (prevents duplicate processing)
2263
+ if (this.tokenManager.hasValidToken()) {
2264
+ return true;
2265
+ }
2266
+ // Ensure we have OAuth config for callback completion
2267
+ if (!hasOAuthConfig(config)) {
2268
+ throw new Error('OAuth configuration incomplete: clientId, redirectUri, and scope are required for OAuth callback');
2269
+ }
2270
+ const result = await this._authenticateWithOAuth(config.clientId, config.redirectUri, config.scope);
2271
+ return result;
2272
+ }
2273
+ // Secondly: Try to load existing valid token from storage
2203
2274
  const loadedFromStorage = this.tokenManager.loadFromStorage();
2204
2275
  // If we have a valid token from storage, return true
2205
2276
  if (loadedFromStorage && this.tokenManager.hasValidToken()) {
2206
2277
  return true;
2207
2278
  }
2208
- // If we don't have a valid token from storage, authenticate with OAuth
2279
+ // Start new OAuth flow if config has OAuth fields
2209
2280
  if (hasOAuthConfig(config)) {
2210
2281
  return await this._authenticateWithOAuth(config.clientId, config.redirectUri, config.scope);
2211
2282
  }
@@ -2388,6 +2459,17 @@ class AuthService extends BaseService {
2388
2459
  async _initiateOAuthFlow(clientId, redirectUri, scope) {
2389
2460
  const codeVerifier = this.generateCodeVerifier();
2390
2461
  const codeChallenge = await this.generateCodeChallenge(codeVerifier);
2462
+ // Store complete OAuth context for callback completion
2463
+ const oauthContext = {
2464
+ codeVerifier,
2465
+ clientId,
2466
+ redirectUri,
2467
+ baseUrl: this.config.baseUrl,
2468
+ orgName: this.config.orgName,
2469
+ tenantName: this.config.tenantName,
2470
+ scope
2471
+ };
2472
+ sessionStorage.setItem('uipath_sdk_oauth_context', JSON.stringify(oauthContext));
2391
2473
  sessionStorage.setItem('uipath_sdk_code_verifier', codeVerifier);
2392
2474
  const authUrl = this.getAuthorizationUrl({
2393
2475
  clientId,
@@ -2402,13 +2484,15 @@ class AuthService extends BaseService {
2402
2484
  if (!codeVerifier) {
2403
2485
  throw new Error('Code verifier not found in session storage. Authentication may have been interrupted.');
2404
2486
  }
2405
- sessionStorage.removeItem('uipath_sdk_code_verifier');
2406
2487
  await this._getAccessToken({
2407
2488
  clientId,
2408
2489
  redirectUri,
2409
2490
  code,
2410
2491
  codeVerifier
2411
2492
  });
2493
+ // Clear OAuth context and code verifier after successful token exchange
2494
+ sessionStorage.removeItem('uipath_sdk_oauth_context');
2495
+ sessionStorage.removeItem('uipath_sdk_code_verifier');
2412
2496
  const url = new URL(window.location.href);
2413
2497
  url.searchParams.delete('code');
2414
2498
  url.searchParams.delete('state');
@@ -2637,7 +2721,7 @@ const EntityFieldTypeMap = {
2637
2721
  // Connection string placeholder that will be replaced during build
2638
2722
  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";
2639
2723
  // SDK Version placeholder
2640
- const SDK_VERSION = "1.0.0-beta.13";
2724
+ const SDK_VERSION = "1.0.0-beta.15";
2641
2725
  const VERSION = "Version";
2642
2726
  const SERVICE = "Service";
2643
2727
  const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
@@ -3222,46 +3306,161 @@ __decorate([
3222
3306
  ], EntityService.prototype, "getAll", null);
3223
3307
 
3224
3308
  /**
3225
- * Service for interacting with Maestro Processes
3309
+ * Maestro Process Models
3310
+ * Model classes for Maestro processes
3226
3311
  */
3227
- class MaestroProcessesService extends BaseService {
3312
+ /**
3313
+ * Creates methods for a process object
3314
+ *
3315
+ * @param processData - The process data (response from API)
3316
+ * @param service - The process service instance
3317
+ * @returns Object containing process methods
3318
+ */
3319
+ function createProcessMethods(processData, service) {
3320
+ return {
3321
+ async getIncidents() {
3322
+ if (!processData.processKey)
3323
+ throw new Error('Process key is undefined');
3324
+ if (!processData.folderKey)
3325
+ throw new Error('Folder key is undefined');
3326
+ return service.getIncidents(processData.processKey, processData.folderKey);
3327
+ }
3328
+ };
3329
+ }
3330
+ /**
3331
+ * Creates an actionable process by combining API process data with operational methods.
3332
+ *
3333
+ * @param processData - The process data from API
3334
+ * @param service - The process service instance
3335
+ * @returns A process object with added methods
3336
+ */
3337
+ function createProcessWithMethods(processData, service) {
3338
+ const methods = createProcessMethods(processData, service);
3339
+ return Object.assign({}, processData, methods);
3340
+ }
3341
+
3342
+ /**
3343
+ * Maps fields for Incident entities
3344
+ */
3345
+ const ProcessIncidentMap = {
3346
+ errorTimeUtc: 'errorTime'
3347
+ };
3348
+ /**
3349
+ * Maps fields for Incident Summary entities
3350
+ */
3351
+ const ProcessIncidentSummaryMap = {
3352
+ firstTimeUtc: 'firstOccuranceTime'
3353
+ };
3354
+
3355
+ /**
3356
+ * Helpers for fetching BPMN XML and extracting element details used to annotate responses
3357
+ */
3358
+ class BpmnHelpers {
3228
3359
  /**
3229
- * @hideconstructor
3360
+ * Parse BPMN XML and extract element id → {name,type} used for incidents
3230
3361
  */
3231
- constructor(config, executionContext, tokenManager) {
3232
- super(config, executionContext, tokenManager);
3362
+ static parseBpmnElementsForIncidents(bpmnXml) {
3363
+ const elementInfo = {};
3364
+ try {
3365
+ // Find <bpmn:...> start tags and capture the element type.
3366
+ // Then read 'id' and 'name' attributes from each tag.
3367
+ const bpmnOpenTagRegex = /<bpmn:([A-Za-z][\w.-]*)\b[^>]*>/g;
3368
+ for (const tagMatch of bpmnXml.matchAll(bpmnOpenTagRegex)) {
3369
+ const [fullTag, elementType] = tagMatch;
3370
+ // Extract attributes from the current tag text.
3371
+ const idMatch = /\bid\s*=\s*"([^"]*)"/.exec(fullTag);
3372
+ if (!idMatch) {
3373
+ continue;
3374
+ }
3375
+ const elementId = idMatch[1];
3376
+ const nameMatch = /\bname\s*=\s*"([^"]*)"/.exec(fullTag);
3377
+ const name = nameMatch ? nameMatch[1] : '';
3378
+ // Convert BPMN element type to human-readable format
3379
+ const activityType = this.formatActivityTypeForIncidents(elementType);
3380
+ const activityName = name || elementId;
3381
+ elementInfo[elementId] = {
3382
+ type: activityType,
3383
+ name: activityName
3384
+ };
3385
+ }
3386
+ }
3387
+ catch (error) {
3388
+ console.warn('Failed to parse BPMN XML for incidents:', error);
3389
+ }
3390
+ return elementInfo;
3233
3391
  }
3234
3392
  /**
3235
- * Get all processes with their instance statistics
3236
- * @returns Promise resolving to array of MaestroProcess objects
3237
- *
3238
- * @example
3239
- * ```typescript
3240
- * // Get all processes
3241
- * const processes = await sdk.maestro.processes.getAll();
3242
- *
3243
- * // Access process information
3244
- * for (const process of processes) {
3245
- * console.log(`Process: ${process.processKey}`);
3246
- * console.log(`Running instances: ${process.runningCount}`);
3247
- * console.log(`Faulted instances: ${process.faultedCount}`);
3248
- * }
3249
- *
3250
- * ```
3393
+ * Format BPMN element type to human-readable activity type for incidents
3251
3394
  */
3252
- async getAll() {
3253
- const response = await this.get(MAESTRO_ENDPOINTS.PROCESSES.GET_ALL);
3254
- // Extract processes array from response data and add name field
3255
- const processes = response.data?.processes || [];
3256
- return processes.map(process => ({
3257
- ...process,
3258
- name: process.packageId
3395
+ static formatActivityTypeForIncidents(elementType) {
3396
+ // Convert camelCase BPMN element types to human-readable format
3397
+ // e.g., "serviceTask" -> "Service Task", "exclusiveGateway" -> "Exclusive Gateway"
3398
+ return elementType
3399
+ .replace(/([A-Z])/g, ' $1') // Add space before uppercase letters
3400
+ .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
3401
+ .trim(); // Remove any leading/trailing spaces
3402
+ }
3403
+ /**
3404
+ * Fetch BPMN via getBpmn and add element name/type to each incident
3405
+ */
3406
+ static async enrichIncidentsWithBpmnData(incidents, folderKey, service) {
3407
+ // Check if all incidents have the same instanceId
3408
+ const uniqueInstanceIds = [...new Set(incidents.map(i => i.instanceId))];
3409
+ if (uniqueInstanceIds.length === 1) {
3410
+ // Single instance optimization (in case of process instance incidents)
3411
+ const elementInfo = await this.getBpmnElementInfo(uniqueInstanceIds[0], folderKey, service);
3412
+ return incidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
3413
+ }
3414
+ else {
3415
+ // Multiple instances optimization (in case of process incidents)
3416
+ return this.enrichMultipleInstanceIncidents(incidents, folderKey, service);
3417
+ }
3418
+ }
3419
+ /**
3420
+ * When incidents span multiple instances, fetch BPMN per instance and annotate
3421
+ */
3422
+ static async enrichMultipleInstanceIncidents(incidents, folderKey, service) {
3423
+ const groups = incidents.reduce((acc, incident) => {
3424
+ const id = incident.instanceId || NO_INSTANCE;
3425
+ (acc[id] = acc[id] || []).push(incident);
3426
+ return acc;
3427
+ }, {});
3428
+ const results = await Promise.all(Object.entries(groups).map(async (entry) => {
3429
+ const [instanceId, groupIncidents] = entry;
3430
+ const elementInfo = await this.getBpmnElementInfo(instanceId, folderKey, service);
3431
+ return groupIncidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
3259
3432
  }));
3433
+ return results.flat();
3434
+ }
3435
+ /**
3436
+ * Retrieve BPMN XML for an instance and derive element id → {name,type}
3437
+ */
3438
+ static async getBpmnElementInfo(instanceId, folderKey, service) {
3439
+ if (!instanceId || instanceId === NO_INSTANCE) {
3440
+ return {};
3441
+ }
3442
+ try {
3443
+ const bpmnXml = await service.getBpmn(instanceId, folderKey);
3444
+ return this.parseBpmnElementsForIncidents(bpmnXml);
3445
+ }
3446
+ catch (error) {
3447
+ console.warn(`Failed to get BPMN for instance ${instanceId}:`, error);
3448
+ return {};
3449
+ }
3450
+ }
3451
+ /**
3452
+ * Transform a raw incident by attaching element name/type from BPMN
3453
+ */
3454
+ static transformIncidentWithBpmn(incident, elementInfo) {
3455
+ const element = elementInfo[incident.elementId];
3456
+ const transformed = transformData(incident, ProcessIncidentMap);
3457
+ return {
3458
+ ...transformed,
3459
+ incidentElementActivityType: element?.type || UNKNOWN$1,
3460
+ incidentElementActivityName: element?.name || UNKNOWN$1
3461
+ };
3260
3462
  }
3261
3463
  }
3262
- __decorate([
3263
- track('MaestroProcesses.GetAll')
3264
- ], MaestroProcessesService.prototype, "getAll", null);
3265
3464
 
3266
3465
  /**
3267
3466
  * Creates methods for a process instance
@@ -3275,17 +3474,49 @@ function createProcessInstanceMethods(instanceData, service) {
3275
3474
  async cancel(options) {
3276
3475
  if (!instanceData.instanceId)
3277
3476
  throw new Error('Process instance ID is undefined');
3477
+ if (!instanceData.folderKey)
3478
+ throw new Error('Process instance folder key is undefined');
3278
3479
  return service.cancel(instanceData.instanceId, instanceData.folderKey, options);
3279
3480
  },
3280
3481
  async pause(options) {
3281
3482
  if (!instanceData.instanceId)
3282
3483
  throw new Error('Process instance ID is undefined');
3484
+ if (!instanceData.folderKey)
3485
+ throw new Error('Process instance folder key is undefined');
3283
3486
  return service.pause(instanceData.instanceId, instanceData.folderKey, options);
3284
3487
  },
3285
3488
  async resume(options) {
3286
3489
  if (!instanceData.instanceId)
3287
3490
  throw new Error('Process instance ID is undefined');
3491
+ if (!instanceData.folderKey)
3492
+ throw new Error('Process instance folder key is undefined');
3288
3493
  return service.resume(instanceData.instanceId, instanceData.folderKey, options);
3494
+ },
3495
+ async getIncidents() {
3496
+ if (!instanceData.instanceId)
3497
+ throw new Error('Process instance ID is undefined');
3498
+ if (!instanceData.folderKey)
3499
+ throw new Error('Process instance folder key is undefined');
3500
+ return service.getIncidents(instanceData.instanceId, instanceData.folderKey);
3501
+ },
3502
+ async getExecutionHistory() {
3503
+ if (!instanceData.instanceId)
3504
+ throw new Error('Process instance ID is undefined');
3505
+ return service.getExecutionHistory(instanceData.instanceId);
3506
+ },
3507
+ async getBpmn() {
3508
+ if (!instanceData.instanceId)
3509
+ throw new Error('Process instance ID is undefined');
3510
+ if (!instanceData.folderKey)
3511
+ throw new Error('Process instance folder key is undefined');
3512
+ return service.getBpmn(instanceData.instanceId, instanceData.folderKey);
3513
+ },
3514
+ async getVariables(options) {
3515
+ if (!instanceData.instanceId)
3516
+ throw new Error('Process instance ID is undefined');
3517
+ if (!instanceData.folderKey)
3518
+ throw new Error('Process instance folder key is undefined');
3519
+ return service.getVariables(instanceData.instanceId, instanceData.folderKey, options);
3289
3520
  }
3290
3521
  };
3291
3522
  }
@@ -3301,6 +3532,155 @@ function createProcessInstanceWithMethods(instanceData, service) {
3301
3532
  return Object.assign({}, instanceData, methods);
3302
3533
  }
3303
3534
 
3535
+ /**
3536
+ * Process Incident Status
3537
+ */
3538
+ exports.ProcessIncidentStatus = void 0;
3539
+ (function (ProcessIncidentStatus) {
3540
+ ProcessIncidentStatus["Open"] = "Open";
3541
+ ProcessIncidentStatus["Closed"] = "Closed";
3542
+ })(exports.ProcessIncidentStatus || (exports.ProcessIncidentStatus = {}));
3543
+ /**
3544
+ * Process Incident Type
3545
+ */
3546
+ exports.ProcessIncidentType = void 0;
3547
+ (function (ProcessIncidentType) {
3548
+ ProcessIncidentType["System"] = "System";
3549
+ ProcessIncidentType["User"] = "User";
3550
+ ProcessIncidentType["Deployment"] = "Deployment";
3551
+ })(exports.ProcessIncidentType || (exports.ProcessIncidentType = {}));
3552
+ /**
3553
+ * Process Incident Severity
3554
+ */
3555
+ exports.ProcessIncidentSeverity = void 0;
3556
+ (function (ProcessIncidentSeverity) {
3557
+ ProcessIncidentSeverity["Error"] = "Error";
3558
+ ProcessIncidentSeverity["Warning"] = "Warning";
3559
+ })(exports.ProcessIncidentSeverity || (exports.ProcessIncidentSeverity = {}));
3560
+ /**
3561
+ * Process Incident Debug Mode
3562
+ */
3563
+ exports.DebugMode = void 0;
3564
+ (function (DebugMode) {
3565
+ DebugMode["None"] = "None";
3566
+ DebugMode["Default"] = "Default";
3567
+ DebugMode["StepByStep"] = "StepByStep";
3568
+ DebugMode["SingleStep"] = "SingleStep";
3569
+ })(exports.DebugMode || (exports.DebugMode = {}));
3570
+
3571
+ /**
3572
+ * Case Instance Types
3573
+ * Types and interfaces for Maestro case instance management
3574
+ */
3575
+ /**
3576
+ * Case stage task type
3577
+ */
3578
+ exports.StageTaskType = void 0;
3579
+ (function (StageTaskType) {
3580
+ StageTaskType["EXTERNAL_AGENT"] = "external-agent";
3581
+ StageTaskType["RPA"] = "rpa";
3582
+ StageTaskType["AGENTIC_PROCESS"] = "process";
3583
+ StageTaskType["AGENT"] = "agent";
3584
+ StageTaskType["ACTION"] = "action";
3585
+ StageTaskType["API_WORKFLOW"] = "api-workflow";
3586
+ })(exports.StageTaskType || (exports.StageTaskType = {}));
3587
+ /**
3588
+ * Escalation recipient scope
3589
+ */
3590
+ exports.EscalationRecipientScope = void 0;
3591
+ (function (EscalationRecipientScope) {
3592
+ EscalationRecipientScope["USER"] = "user";
3593
+ EscalationRecipientScope["USER_GROUP"] = "usergroup";
3594
+ })(exports.EscalationRecipientScope || (exports.EscalationRecipientScope = {}));
3595
+ /**
3596
+ * Escalation action type
3597
+ */
3598
+ exports.EscalationActionType = void 0;
3599
+ (function (EscalationActionType) {
3600
+ EscalationActionType["NOTIFICATION"] = "notification";
3601
+ })(exports.EscalationActionType || (exports.EscalationActionType = {}));
3602
+ /**
3603
+ * Escalation rule trigger type
3604
+ */
3605
+ exports.EscalationTriggerType = void 0;
3606
+ (function (EscalationTriggerType) {
3607
+ EscalationTriggerType["SLA_BREACHED"] = "sla-breached";
3608
+ EscalationTriggerType["AT_RISK"] = "at-risk";
3609
+ })(exports.EscalationTriggerType || (exports.EscalationTriggerType = {}));
3610
+ /**
3611
+ * SLA duration unit
3612
+ */
3613
+ exports.SLADurationUnit = void 0;
3614
+ (function (SLADurationUnit) {
3615
+ SLADurationUnit["HOURS"] = "h";
3616
+ SLADurationUnit["DAYS"] = "d";
3617
+ SLADurationUnit["WEEKS"] = "w";
3618
+ SLADurationUnit["MONTHS"] = "m";
3619
+ })(exports.SLADurationUnit || (exports.SLADurationUnit = {}));
3620
+
3621
+ /**
3622
+ * Creates methods for a case instance
3623
+ *
3624
+ * @param instanceData - The case instance data (response from API)
3625
+ * @param service - The case instance service instance
3626
+ * @returns Object containing case instance methods
3627
+ */
3628
+ function createCaseInstanceMethods(instanceData, service) {
3629
+ return {
3630
+ async close(options) {
3631
+ if (!instanceData.instanceId)
3632
+ throw new Error('Case instance ID is undefined');
3633
+ if (!instanceData.folderKey)
3634
+ throw new Error('Case instance folder key is undefined');
3635
+ return service.close(instanceData.instanceId, instanceData.folderKey, options);
3636
+ },
3637
+ async pause(options) {
3638
+ if (!instanceData.instanceId)
3639
+ throw new Error('Case instance ID is undefined');
3640
+ if (!instanceData.folderKey)
3641
+ throw new Error('Case instance folder key is undefined');
3642
+ return service.pause(instanceData.instanceId, instanceData.folderKey, options);
3643
+ },
3644
+ async resume(options) {
3645
+ if (!instanceData.instanceId)
3646
+ throw new Error('Case instance ID is undefined');
3647
+ if (!instanceData.folderKey)
3648
+ throw new Error('Case instance folder key is undefined');
3649
+ return service.resume(instanceData.instanceId, instanceData.folderKey, options);
3650
+ },
3651
+ async getExecutionHistory() {
3652
+ if (!instanceData.instanceId)
3653
+ throw new Error('Case instance ID is undefined');
3654
+ if (!instanceData.folderKey)
3655
+ throw new Error('Case instance folder key is undefined');
3656
+ return service.getExecutionHistory(instanceData.instanceId, instanceData.folderKey);
3657
+ },
3658
+ async getStages() {
3659
+ if (!instanceData.instanceId)
3660
+ throw new Error('Case instance ID is undefined');
3661
+ if (!instanceData.folderKey)
3662
+ throw new Error('Case instance folder key is undefined');
3663
+ return service.getStages(instanceData.instanceId, instanceData.folderKey);
3664
+ },
3665
+ async getActionTasks(options) {
3666
+ if (!instanceData.instanceId)
3667
+ throw new Error('Case instance ID is undefined');
3668
+ return service.getActionTasks(instanceData.instanceId, options);
3669
+ }
3670
+ };
3671
+ }
3672
+ /**
3673
+ * Creates an actionable case instance by combining API case instance data with operational methods.
3674
+ *
3675
+ * @param instanceData - The case instance data from API
3676
+ * @param service - The case instance service instance
3677
+ * @returns A case instance object with added methods
3678
+ */
3679
+ function createCaseInstanceWithMethods(instanceData, service) {
3680
+ const methods = createCaseInstanceMethods(instanceData, service);
3681
+ return Object.assign({}, instanceData, methods);
3682
+ }
3683
+
3304
3684
  /**
3305
3685
  * Maps fields for Process Instance entities to ensure consistent naming
3306
3686
  */
@@ -3583,6 +3963,19 @@ class ProcessInstancesService extends BaseService {
3583
3963
  };
3584
3964
  return variablesResponse;
3585
3965
  }
3966
+ /**
3967
+ * Get incidents for a process instance
3968
+ * @param instanceId The ID of the instance to get incidents for
3969
+ * @param folderKey The folder key for authorization
3970
+ * @returns Promise<ProcessIncidentGetResponse[]>
3971
+ */
3972
+ async getIncidents(instanceId, folderKey) {
3973
+ const rawResponse = await this.get(MAESTRO_ENDPOINTS.INCIDENTS.GET_BY_INSTANCE(instanceId), {
3974
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3975
+ });
3976
+ // Filter out excluded fields and transform response, then enrich with BPMN data
3977
+ return BpmnHelpers.enrichIncidentsWithBpmnData(rawResponse.data || [], folderKey, this);
3978
+ }
3586
3979
  }
3587
3980
  __decorate([
3588
3981
  track('ProcessInstances.GetAll')
@@ -3608,50 +4001,118 @@ __decorate([
3608
4001
  __decorate([
3609
4002
  track('ProcessInstances.GetVariables')
3610
4003
  ], ProcessInstancesService.prototype, "getVariables", null);
4004
+ __decorate([
4005
+ track('ProcessInstances.GetIncidents')
4006
+ ], ProcessInstancesService.prototype, "getIncidents", null);
3611
4007
 
3612
4008
  /**
3613
- * Base service for services that need folder-specific functionality
4009
+ * Service for interacting with Maestro Processes
3614
4010
  */
3615
- class FolderScopedService extends BaseService {
4011
+ class MaestroProcessesService extends BaseService {
4012
+ /**
4013
+ * @hideconstructor
4014
+ */
3616
4015
  constructor(config, executionContext, tokenManager) {
3617
4016
  super(config, executionContext, tokenManager);
4017
+ this.processInstancesService = new ProcessInstancesService(config, executionContext, tokenManager);
3618
4018
  }
3619
4019
  /**
3620
- * Gets resources in a folder with optional query parameters
4020
+ * Get all processes with their instance statistics
4021
+ * @returns Promise resolving to array of MaestroProcess objects
3621
4022
  *
3622
- * @param endpoint - API endpoint to call
3623
- * @param folderId - required folder ID
3624
- * @param options - Query options
3625
- * @param transformFn - Optional function to transform the response data
3626
- * @returns Promise resolving to an array of resources
4023
+ * @example
4024
+ * ```typescript
4025
+ * // Get all processes
4026
+ * const processes = await sdk.maestro.processes.getAll();
4027
+ *
4028
+ * // Access process information
4029
+ * for (const process of processes) {
4030
+ * console.log(`Process: ${process.processKey}`);
4031
+ * console.log(`Running instances: ${process.runningCount}`);
4032
+ * console.log(`Faulted instances: ${process.faultedCount}`);
4033
+ * }
4034
+ *
4035
+ * ```
3627
4036
  */
3628
- async _getByFolder(endpoint, folderId, options = {}, transformFn) {
3629
- const headers = createHeaders({ [FOLDER_ID]: folderId });
3630
- const keysToPrefix = Object.keys(options);
3631
- const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
3632
- const response = await this.get(endpoint, {
3633
- params: apiOptions,
3634
- headers
4037
+ async getAll() {
4038
+ const response = await this.get(MAESTRO_ENDPOINTS.PROCESSES.GET_ALL);
4039
+ // Extract processes array from response data and add name field
4040
+ const processes = response.data?.processes || [];
4041
+ const processesWithName = processes.map(process => ({
4042
+ ...process,
4043
+ name: process.packageId
4044
+ }));
4045
+ // Add methods to each process
4046
+ return processesWithName.map(process => createProcessWithMethods(process, this));
4047
+ }
4048
+ /**
4049
+ * Get incidents for a specific process
4050
+ */
4051
+ async getIncidents(processKey, folderKey) {
4052
+ const rawResponse = await this.get(MAESTRO_ENDPOINTS.INCIDENTS.GET_BY_PROCESS(processKey), {
4053
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
3635
4054
  });
3636
- if (transformFn) {
3637
- return response.data?.value.map(transformFn);
3638
- }
3639
- return response.data?.value;
4055
+ // Fetch BPMN XML and add element name/type to each incident
4056
+ return BpmnHelpers.enrichIncidentsWithBpmnData(rawResponse.data || [], folderKey, this.processInstancesService);
3640
4057
  }
3641
4058
  }
4059
+ __decorate([
4060
+ track('MaestroProcesses.GetAll')
4061
+ ], MaestroProcessesService.prototype, "getAll", null);
4062
+ __decorate([
4063
+ track('MaestroProcesses.GetIncidents')
4064
+ ], MaestroProcessesService.prototype, "getIncidents", null);
3642
4065
 
3643
4066
  /**
3644
- * Maps fields for Asset entities to ensure consistent naming
4067
+ * Service class for Maestro Process Incidents
3645
4068
  */
3646
- const AssetMap = {
3647
- creationTime: 'createdTime',
3648
- lastModificationTime: 'lastModifiedTime'
3649
- };
4069
+ class ProcessIncidentsService extends BaseService {
4070
+ /**
4071
+ * Get all process incidents across all folders
4072
+ *
4073
+ * @returns Promise resolving to array of process incident
4074
+ * {@link ProcessIncidentGetAllResponse}
4075
+ * @example
4076
+ * ```typescript
4077
+ * // Get all process incidents across all folders
4078
+ * const incidents = await sdk.maestro.processes.incidents.getAll();
4079
+ *
4080
+ * // Access process incident information
4081
+ * for (const incident of incidents) {
4082
+ * console.log(`Process: ${incident.processKey}`);
4083
+ * console.log(`Error: ${incident.errorMessage}`);
4084
+ * console.log(`Count: ${incident.count}`);
4085
+ * console.log(`First occurrence: ${incident.firstOccuranceTime}`);
4086
+ * }
4087
+ * ```
4088
+ */
4089
+ async getAll() {
4090
+ const rawResponse = await this.get(MAESTRO_ENDPOINTS.INCIDENTS.GET_ALL);
4091
+ // Transform field names
4092
+ const data = rawResponse.data || [];
4093
+ return data.map(incident => transformData(incident, ProcessIncidentSummaryMap));
4094
+ }
4095
+ }
4096
+ __decorate([
4097
+ track('ProcessIncidents.getAll')
4098
+ ], ProcessIncidentsService.prototype, "getAll", null);
3650
4099
 
3651
4100
  /**
3652
- * Service for interacting with UiPath Orchestrator Assets API
4101
+ * Internal types for Maestro Cases
4102
+ * These types are used internally by the cases service
3653
4103
  */
3654
- class AssetService extends FolderScopedService {
4104
+ /**
4105
+ * Process type enum for filtering
4106
+ */
4107
+ var ProcessType;
4108
+ (function (ProcessType) {
4109
+ ProcessType["CaseManagement"] = "CaseManagement";
4110
+ })(ProcessType || (ProcessType = {}));
4111
+
4112
+ /**
4113
+ * Service for interacting with UiPath Maestro Cases
4114
+ */
4115
+ class CasesService extends BaseService {
3655
4116
  /**
3656
4117
  * @hideconstructor
3657
4118
  */
@@ -3659,195 +4120,348 @@ class AssetService extends FolderScopedService {
3659
4120
  super(config, executionContext, tokenManager);
3660
4121
  }
3661
4122
  /**
3662
- * Gets all assets across folders with optional filtering and folder scoping
3663
- *
3664
- * @signature getAll(options?) -> Promise<AssetGetResponse[]>
3665
- * @param options Query options including optional folderId and pagination options
3666
- * @returns Promise resolving to array of assets or paginated response
4123
+ * Get all case management processes with their instance statistics
4124
+ * @returns Promise resolving to array of Case objects
3667
4125
  *
3668
4126
  * @example
3669
4127
  * ```typescript
3670
- * // Standard array return
3671
- * const assets = await sdk.assets.getAll();
3672
- *
3673
- * // With folder
3674
- * const folderAssets = await sdk.assets.getAll({ folderId: 123 });
3675
- *
3676
- * // First page with pagination
3677
- * const page1 = await sdk.assets.getAll({ pageSize: 10 });
4128
+ * // Get all case management processes
4129
+ * const cases = await sdk.maestro.cases.getAll();
3678
4130
  *
3679
- * // Navigate using cursor
3680
- * if (page1.hasNextPage) {
3681
- * const page2 = await sdk.assets.getAll({ cursor: page1.nextCursor });
4131
+ * // Access case information
4132
+ * for (const caseProcess of cases) {
4133
+ * console.log(`Case Process: ${caseProcess.processKey}`);
4134
+ * console.log(`Running instances: ${caseProcess.runningCount}`);
4135
+ * console.log(`Completed instances: ${caseProcess.completedCount}`);
3682
4136
  * }
3683
4137
  *
3684
- * // Jump to specific page
3685
- * const page5 = await sdk.assets.getAll({
3686
- * jumpToPage: 5,
3687
- * pageSize: 10
3688
- * });
3689
4138
  * ```
3690
4139
  */
3691
- async getAll(options) {
3692
- // Transformation function for assets
3693
- const transformAssetResponse = (asset) => transformData(pascalToCamelCaseKeys(asset), AssetMap);
3694
- return PaginationHelpers.getAll({
3695
- serviceAccess: this.createPaginationServiceAccess(),
3696
- getEndpoint: (folderId) => folderId ? ASSET_ENDPOINTS.GET_BY_FOLDER : ASSET_ENDPOINTS.GET_ALL,
3697
- getByFolderEndpoint: ASSET_ENDPOINTS.GET_BY_FOLDER,
3698
- transformFn: transformAssetResponse,
3699
- pagination: {
3700
- paginationType: PaginationType.OFFSET,
3701
- itemsField: ODATA_PAGINATION.ITEMS_FIELD,
3702
- totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
3703
- paginationParams: {
3704
- pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
3705
- offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
3706
- countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
3707
- }
3708
- }
3709
- }, options);
4140
+ async getAll() {
4141
+ const params = createParams({
4142
+ processType: ProcessType.CaseManagement
4143
+ });
4144
+ const response = await this.get(MAESTRO_ENDPOINTS.PROCESSES.GET_ALL, { params });
4145
+ // Extract processes array from response data and add name field
4146
+ const cases = response.data?.processes || [];
4147
+ return cases.map(caseItem => ({
4148
+ ...caseItem,
4149
+ name: this.extractCaseName(caseItem.packageId)
4150
+ }));
3710
4151
  }
3711
4152
  /**
3712
- * Gets a single asset by ID
3713
- *
3714
- * @param id - Asset ID
3715
- * @param folderId - Required folder ID
3716
- * @param options - Optional query parameters (expand, select)
3717
- * @returns Promise resolving to a single asset
3718
- *
3719
- * @example
3720
- * ```typescript
3721
- * // Get asset by ID
3722
- * const asset = await sdk.assets.getById(123, 456);
3723
- * ```
4153
+ * Extract a readable case name from the packageId
4154
+ * @param packageId - The full package identifier
4155
+ * @returns A human-readable case name
4156
+ * @private
3724
4157
  */
3725
- async getById(id, folderId, options = {}) {
3726
- const headers = createHeaders({ [FOLDER_ID]: folderId });
3727
- const keysToPrefix = Object.keys(options);
3728
- const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
3729
- const response = await this.get(ASSET_ENDPOINTS.GET_BY_ID(id), {
3730
- headers,
3731
- params: apiOptions
3732
- });
3733
- const transformedAsset = transformData(pascalToCamelCaseKeys(response.data), AssetMap);
3734
- return transformedAsset;
4158
+ extractCaseName(packageId) {
4159
+ // Check if packageId contains "CaseManagement."
4160
+ const caseManagementIndex = packageId.indexOf('CaseManagement.');
4161
+ if (caseManagementIndex !== -1) {
4162
+ // Extract everything after "CaseManagement."
4163
+ const afterCaseManagement = packageId.substring(caseManagementIndex + 'CaseManagement.'.length);
4164
+ // Replace hyphens with spaces for better readability
4165
+ return afterCaseManagement.replace(/-/g, ' ');
4166
+ }
4167
+ // If no "CaseManagement.", return the whole packageId
4168
+ return packageId;
3735
4169
  }
3736
4170
  }
3737
4171
  __decorate([
3738
- track('Assets.GetAll')
3739
- ], AssetService.prototype, "getAll", null);
3740
- __decorate([
3741
- track('Assets.GetById')
3742
- ], AssetService.prototype, "getById", null);
4172
+ track('Cases.GetAll')
4173
+ ], CasesService.prototype, "getAll", null);
3743
4174
 
3744
4175
  /**
3745
- * Maps fields for Bucket entities to ensure consistent naming
4176
+ * Maps fields for Case Instance entities to ensure consistent naming
3746
4177
  */
3747
- const BucketMap = {
3748
- fullPath: 'path',
3749
- items: 'blobItems',
3750
- verb: 'httpMethod'
4178
+ const CaseInstanceMap = {
4179
+ startedTimeUtc: 'startedTime',
4180
+ completedTimeUtc: 'completedTime',
4181
+ expiryTimeUtc: 'expiredTime',
4182
+ createdAt: 'createdTime',
4183
+ updatedAt: 'updatedTime',
4184
+ externalId: 'caseId',
4185
+ };
4186
+ /**
4187
+ * Maps fields for Case App Config
4188
+ */
4189
+ const CaseAppConfigMap = {
4190
+ sections: 'overview',
4191
+ };
4192
+ /**
4193
+ * Maps fields for Stage SLA configuration
4194
+ */
4195
+ const StageSLAMap = {
4196
+ count: 'length',
4197
+ unit: 'duration',
4198
+ };
4199
+ /**
4200
+ * Maps UTC time fields to simpler field names
4201
+ * Used for transforming execution history responses
4202
+ */
4203
+ const TimeFieldTransformMap = {
4204
+ startedTimeUtc: 'startedTime',
4205
+ completedTimeUtc: 'completedTime',
4206
+ };
4207
+ /**
4208
+ * Constants for case instance stage processing
4209
+ */
4210
+ const CASE_STAGE_CONSTANTS = {
4211
+ TRIGGER_NODE_TYPE: 'case-management:Trigger',
4212
+ UNDEFINED_VALUE: 'Undefined',
4213
+ NOT_STARTED_STATUS: 'Not Started'
3751
4214
  };
4215
+ /**
4216
+ * Function to generate case instance task filter by case instance ID
4217
+ */
4218
+ const CASE_INSTANCE_TASK_FILTER = (caseInstanceId) => `Tags/any(tags:tags/DisplayName eq '${caseInstanceId}') and (IsDeleted eq false)`;
4219
+ /**
4220
+ * Default expand parameters for case instance tasks
4221
+ */
4222
+ const CASE_INSTANCE_TASK_EXPAND = 'AssignedToUser,Activities';
4223
+
4224
+ exports.TaskType = void 0;
4225
+ (function (TaskType) {
4226
+ TaskType["Form"] = "FormTask";
4227
+ TaskType["External"] = "ExternalTask";
4228
+ TaskType["App"] = "AppTask";
4229
+ })(exports.TaskType || (exports.TaskType = {}));
4230
+ exports.TaskPriority = void 0;
4231
+ (function (TaskPriority) {
4232
+ TaskPriority["Low"] = "Low";
4233
+ TaskPriority["Medium"] = "Medium";
4234
+ TaskPriority["High"] = "High";
4235
+ TaskPriority["Critical"] = "Critical";
4236
+ })(exports.TaskPriority || (exports.TaskPriority = {}));
4237
+ exports.TaskStatus = void 0;
4238
+ (function (TaskStatus) {
4239
+ TaskStatus["Unassigned"] = "Unassigned";
4240
+ TaskStatus["Pending"] = "Pending";
4241
+ TaskStatus["Completed"] = "Completed";
4242
+ })(exports.TaskStatus || (exports.TaskStatus = {}));
4243
+ exports.TaskSlaCriteria = void 0;
4244
+ (function (TaskSlaCriteria) {
4245
+ TaskSlaCriteria["TaskCreated"] = "TaskCreated";
4246
+ TaskSlaCriteria["TaskAssigned"] = "TaskAssigned";
4247
+ TaskSlaCriteria["TaskCompleted"] = "TaskCompleted";
4248
+ })(exports.TaskSlaCriteria || (exports.TaskSlaCriteria = {}));
4249
+ exports.TaskSlaStatus = void 0;
4250
+ (function (TaskSlaStatus) {
4251
+ TaskSlaStatus["OverdueLater"] = "OverdueLater";
4252
+ TaskSlaStatus["OverdueSoon"] = "OverdueSoon";
4253
+ TaskSlaStatus["Overdue"] = "Overdue";
4254
+ TaskSlaStatus["CompletedInTime"] = "CompletedInTime";
4255
+ })(exports.TaskSlaStatus || (exports.TaskSlaStatus = {}));
4256
+ exports.TaskSourceName = void 0;
4257
+ (function (TaskSourceName) {
4258
+ TaskSourceName["Agent"] = "Agent";
4259
+ TaskSourceName["Workflow"] = "Workflow";
4260
+ TaskSourceName["Maestro"] = "Maestro";
4261
+ TaskSourceName["Default"] = "Default";
4262
+ })(exports.TaskSourceName || (exports.TaskSourceName = {}));
4263
+ /**
4264
+ * Task activity types
4265
+ */
4266
+ exports.TaskActivityType = void 0;
4267
+ (function (TaskActivityType) {
4268
+ TaskActivityType["Created"] = "Created";
4269
+ TaskActivityType["Assigned"] = "Assigned";
4270
+ TaskActivityType["Reassigned"] = "Reassigned";
4271
+ TaskActivityType["Unassigned"] = "Unassigned";
4272
+ TaskActivityType["Saved"] = "Saved";
4273
+ TaskActivityType["Forwarded"] = "Forwarded";
4274
+ TaskActivityType["Completed"] = "Completed";
4275
+ TaskActivityType["Commented"] = "Commented";
4276
+ TaskActivityType["Deleted"] = "Deleted";
4277
+ TaskActivityType["BulkSaved"] = "BulkSaved";
4278
+ TaskActivityType["BulkCompleted"] = "BulkCompleted";
4279
+ TaskActivityType["FirstOpened"] = "FirstOpened";
4280
+ })(exports.TaskActivityType || (exports.TaskActivityType = {}));
3752
4281
 
3753
- // Import file-type dynamically to avoid issues in browser environment
3754
- // This variable will hold the fileTypeFromBuffer function when in Node.js environment
3755
- let fileTypeFromBuffer;
3756
- // Only import in Node.js environment
3757
- if (!isBrowser) {
3758
- import('file-type').then(module => {
3759
- fileTypeFromBuffer = module.fileTypeFromBuffer;
3760
- }).catch(err => {
3761
- console.debug('Could not load file-type module:', err);
3762
- });
4282
+ /**
4283
+ * Creates methods for a task
4284
+ *
4285
+ * @param taskData - The task data (response from API)
4286
+ * @param service - The task service instance
4287
+ * @returns Object containing task methods
4288
+ */
4289
+ function createTaskMethods(taskData, service) {
4290
+ return {
4291
+ async assign(options) {
4292
+ if (!taskData.id)
4293
+ throw new Error('Task ID is undefined');
4294
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
4295
+ ? { taskId: taskData.id, userId: options.userId }
4296
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
4297
+ return service.assign(assignmentOptions);
4298
+ },
4299
+ async reassign(options) {
4300
+ if (!taskData.id)
4301
+ throw new Error('Task ID is undefined');
4302
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
4303
+ ? { taskId: taskData.id, userId: options.userId }
4304
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
4305
+ return service.reassign(assignmentOptions);
4306
+ },
4307
+ async unassign() {
4308
+ if (!taskData.id)
4309
+ throw new Error('Task ID is undefined');
4310
+ return service.unassign(taskData.id);
4311
+ },
4312
+ async complete(options) {
4313
+ if (!taskData.id)
4314
+ throw new Error('Task ID is undefined');
4315
+ const folderId = taskData.folderId;
4316
+ if (!folderId)
4317
+ throw new Error('Folder ID is required');
4318
+ return service.complete({
4319
+ type: options.type,
4320
+ taskId: taskData.id,
4321
+ data: options.data,
4322
+ action: options.action
4323
+ }, folderId);
4324
+ }
4325
+ };
3763
4326
  }
3764
- class BucketService extends FolderScopedService {
4327
+ /**
4328
+ * Creates an actionable task by combining API task data with operational methods.
4329
+ *
4330
+ * @param taskData - The task data from API
4331
+ * @param service - The task service instance
4332
+ * @returns A task object with added methods
4333
+ */
4334
+ function createTaskWithMethods(taskData, service) {
4335
+ const methods = createTaskMethods(taskData, service);
4336
+ return Object.assign({}, taskData, methods);
4337
+ }
4338
+
4339
+ /**
4340
+ * Maps numeric TaskStatus values (from API) to TaskStatus enum values.
4341
+ * Extend this file with additional field mappings as needed.
4342
+ */
4343
+ const TaskStatusMap = {
4344
+ 0: exports.TaskStatus.Unassigned,
4345
+ 1: exports.TaskStatus.Pending,
4346
+ 2: exports.TaskStatus.Completed,
4347
+ };
4348
+ // Field mapping for time-related fields to ensure consistent naming
4349
+ const TaskMap = {
4350
+ completionTime: 'completedTime',
4351
+ deletionTime: 'deletedTime',
4352
+ lastModificationTime: 'lastModifiedTime',
4353
+ creationTime: 'createdTime',
4354
+ organizationUnitId: 'folderId'
4355
+ };
4356
+ /**
4357
+ * Default expand parameters
4358
+ */
4359
+ const DEFAULT_TASK_EXPAND = 'AssignedToUser,CreatorUser,LastModifierUser';
4360
+
4361
+ /**
4362
+ * Service for interacting with UiPath Tasks API
4363
+ */
4364
+ class TaskService extends BaseService {
3765
4365
  /**
3766
4366
  * @hideconstructor
3767
4367
  */
3768
4368
  constructor(config, executionContext, tokenManager) {
3769
4369
  super(config, executionContext, tokenManager);
3770
- this.tokenManager = tokenManager;
4370
+ /**
4371
+ * Process parameters for task queries with folder filtering
4372
+ * @param options - The REST API options to process
4373
+ * @param folderId - Optional folder ID to filter by
4374
+ * @returns Processed options with folder filtering applied if needed
4375
+ * @private
4376
+ */
4377
+ this.processTaskParameters = (options, folderId) => {
4378
+ // Add default expand parameters
4379
+ const processedOptions = this.addDefaultExpand(options);
4380
+ if (folderId) {
4381
+ // Create or add to existing filter for folder-specific queries
4382
+ if (processedOptions.filter) {
4383
+ processedOptions.filter = `${processedOptions.filter} and organizationUnitId eq ${folderId}`;
4384
+ }
4385
+ else {
4386
+ processedOptions.filter = `organizationUnitId eq ${folderId}`;
4387
+ }
4388
+ }
4389
+ return processedOptions;
4390
+ };
3771
4391
  }
3772
4392
  /**
3773
- * Gets a bucket by ID
3774
- * @param bucketId - The ID of the bucket to retrieve
3775
- * @param folderId - Folder ID for organization unit context
3776
- * @param options - Optional query parameters (expand, select)
3777
- * @returns Promise resolving to the bucket
3778
- *
3779
- * @example
4393
+ * Creates a new task
4394
+ * @param task - The task to be created
4395
+ * @param folderId - Required folder ID
4396
+ * @returns Promise resolving to the created task
4397
+ *
4398
+ * @example
3780
4399
  * ```typescript
3781
- * // Get bucket by ID
3782
- * const bucket = await sdk.buckets.getById(123, 456);
4400
+ * const task = await sdk.tasks.create({
4401
+ * title: "My Task",
4402
+ * priority: TaskPriority.Medium,
4403
+ * data: { key: "value" }
4404
+ * }, 123); // folderId is required
3783
4405
  * ```
3784
4406
  */
3785
- async getById(id, folderId, options = {}) {
3786
- if (!id) {
3787
- throw new ValidationError({ message: 'bucketId is required for getById' });
3788
- }
3789
- if (!folderId) {
3790
- throw new ValidationError({ message: 'folderId is required for getById' });
3791
- }
4407
+ async create(task, folderId) {
3792
4408
  const headers = createHeaders({ [FOLDER_ID]: folderId });
3793
- // Prefix all keys in options with $ for OData
3794
- const keysToPrefix = Object.keys(options);
3795
- const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
3796
- const response = await this.get(BUCKET_ENDPOINTS.GET_BY_ID(id), {
3797
- params: apiOptions,
3798
- headers
3799
- });
3800
- // Transform response from PascalCase to camelCase
3801
- return pascalToCamelCaseKeys(response.data);
4409
+ const externalTask = {
4410
+ ...task,
4411
+ type: exports.TaskType.External //currently only external task is supported
4412
+ };
4413
+ const response = await this.post(TASK_ENDPOINTS.CREATE_GENERIC_TASK, externalTask, { headers });
4414
+ // Transform time fields for consistency
4415
+ const normalizedData = transformData(response.data, TaskMap);
4416
+ const transformedData = applyDataTransforms(normalizedData, { field: 'status', valueMap: TaskStatusMap });
4417
+ return createTaskWithMethods(transformedData, this);
3802
4418
  }
3803
4419
  /**
3804
- * Gets all buckets across folders with optional filtering and folder scoping
4420
+ * Gets users in the given folder who have Tasks.View and Tasks.Edit permissions
3805
4421
  *
3806
4422
  * The method returns either:
3807
- * - An array of buckets (when no pagination parameters are provided)
4423
+ * - An array of users (when no pagination parameters are provided)
3808
4424
  * - A paginated result with navigation cursors (when any pagination parameter is provided)
3809
4425
  *
3810
- * @param options - Query options including optional folderId
3811
- * @returns Promise resolving to an array of buckets or paginated result
4426
+ * @param folderId - The folder ID to get users from
4427
+ * @param options - Optional query and pagination parameters
4428
+ * @returns Promise resolving to an array of users or paginated result
3812
4429
  *
3813
4430
  * @example
3814
4431
  * ```typescript
3815
- * // Get all buckets across folders
3816
- * const buckets = await sdk.buckets.getAll();
3817
- *
3818
- * // Get buckets within a specific folder
3819
- * const buckets = await sdk.buckets.getAll({
3820
- * folderId: 123
3821
- * });
4432
+ * // Standard array return
4433
+ * const users = await sdk.tasks.getUsers(123);
3822
4434
  *
3823
- * // Get buckets with filtering
3824
- * const buckets = await sdk.buckets.getAll({
3825
- * filter: "name eq 'MyBucket'"
4435
+ * // Get users with filtering
4436
+ * const users = await sdk.tasks.getUsers(123, {
4437
+ * filter: "name eq 'abc'"
3826
4438
  * });
3827
4439
  *
3828
4440
  * // First page with pagination
3829
- * const page1 = await sdk.buckets.getAll({ pageSize: 10 });
4441
+ * const page1 = await sdk.tasks.getUsers(123, { pageSize: 10 });
3830
4442
  *
3831
4443
  * // Navigate using cursor
3832
4444
  * if (page1.hasNextPage) {
3833
- * const page2 = await sdk.buckets.getAll({ cursor: page1.nextCursor });
4445
+ * const page2 = await sdk.tasks.getUsers(123, { cursor: page1.nextCursor });
3834
4446
  * }
3835
4447
  *
3836
4448
  * // Jump to specific page
3837
- * const page5 = await sdk.buckets.getAll({
4449
+ * const page5 = await sdk.tasks.getUsers(123, {
3838
4450
  * jumpToPage: 5,
3839
4451
  * pageSize: 10
3840
4452
  * });
3841
4453
  * ```
3842
4454
  */
3843
- async getAll(options) {
3844
- // Transformation function for buckets
3845
- const transformBucketResponse = (bucket) => pascalToCamelCaseKeys(bucket);
4455
+ async getUsers(folderId, options) {
4456
+ // Transformation function for users
4457
+ const transformUserResponse = (user) => pascalToCamelCaseKeys(user);
4458
+ // Add folderId to options so the centralized helper can handle it properly
4459
+ const optionsWithFolder = { ...options, folderId };
3846
4460
  return PaginationHelpers.getAll({
3847
4461
  serviceAccess: this.createPaginationServiceAccess(),
3848
- getEndpoint: (folderId) => folderId ? BUCKET_ENDPOINTS.GET_BY_FOLDER : BUCKET_ENDPOINTS.GET_ALL,
3849
- getByFolderEndpoint: BUCKET_ENDPOINTS.GET_BY_FOLDER,
3850
- transformFn: transformBucketResponse,
4462
+ getEndpoint: (folderId) => TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use folderId from centralized helper
4463
+ getByFolderEndpoint: TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use the passed folderId
4464
+ transformFn: transformUserResponse,
3851
4465
  pagination: {
3852
4466
  paginationType: PaginationType.OFFSET,
3853
4467
  itemsField: ODATA_PAGINATION.ITEMS_FIELD,
@@ -3858,498 +4472,799 @@ class BucketService extends FolderScopedService {
3858
4472
  countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
3859
4473
  }
3860
4474
  }
3861
- }, options);
4475
+ }, optionsWithFolder);
3862
4476
  }
3863
4477
  /**
3864
- * Gets metadata for files in a bucket with optional filtering and pagination
4478
+ * Gets tasks across folders with optional filtering and folder scoping
3865
4479
  *
3866
4480
  * The method returns either:
3867
- * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
3868
- * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
4481
+ * - An array of tasks (when no pagination parameters are provided)
4482
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
3869
4483
  *
3870
- * @param bucketId - The ID of the bucket to get file metadata from
3871
- * @param folderId - Required folder ID for organization unit context
3872
- * @param options - Optional parameters for filtering, pagination and access URL generation
3873
- * @returns Promise resolving to the list of file metadata in the bucket or paginated result
4484
+ * @param options - Query options including optional folderId and pagination options
4485
+ * @returns Promise resolving to an array of tasks or paginated result
3874
4486
  *
3875
4487
  * @example
3876
4488
  * ```typescript
3877
- * // Get metadata for all files in a bucket
3878
- * const fileMetadata = await sdk.buckets.getFileMetaData(123, 456);
4489
+ * // Standard array return
4490
+ * const tasks = await sdk.tasks.getAll();
3879
4491
  *
3880
- * // Get file metadata with a specific prefix
3881
- * const fileMetadata = await sdk.buckets.getFileMetaData(123, 456, {
3882
- * prefix: '/folder1'
4492
+ * // Get tasks within a specific folder
4493
+ * const tasks = await sdk.tasks.getAll({
4494
+ * folderId: 123
3883
4495
  * });
3884
4496
  *
3885
4497
  * // First page with pagination
3886
- * const page1 = await sdk.buckets.getFileMetaData(123, 456, { pageSize: 10 });
4498
+ * const page1 = await sdk.tasks.getAll({ pageSize: 10 });
3887
4499
  *
3888
4500
  * // Navigate using cursor
3889
4501
  * if (page1.hasNextPage) {
3890
- * const page2 = await sdk.buckets.getFileMetaData(123, 456, { cursor: page1.nextCursor });
4502
+ * const page2 = await sdk.tasks.getAll({ cursor: page1.nextCursor });
3891
4503
  * }
4504
+ *
4505
+ * // Jump to specific page
4506
+ * const page5 = await sdk.tasks.getAll({
4507
+ * jumpToPage: 5,
4508
+ * pageSize: 10
4509
+ * });
3892
4510
  * ```
3893
4511
  */
3894
- async getFileMetaData(bucketId, folderId, options) {
3895
- if (!bucketId) {
3896
- throw new ValidationError({ message: 'bucketId is required for getFileMetaData' });
3897
- }
3898
- if (!folderId) {
3899
- throw new ValidationError({ message: 'folderId is required for getFileMetaData' });
3900
- }
3901
- // Transformation function for blob items
3902
- const transformBlobItem = (item) => transformData(item, BucketMap);
4512
+ async getAll(options) {
4513
+ // Transformation function for tasks
4514
+ const transformTaskResponse = (task) => {
4515
+ const transformedTask = transformData(pascalToCamelCaseKeys(task), TaskMap);
4516
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
4517
+ };
3903
4518
  return PaginationHelpers.getAll({
3904
4519
  serviceAccess: this.createPaginationServiceAccess(),
3905
- getEndpoint: () => BUCKET_ENDPOINTS.GET_FILE_META_DATA(bucketId),
3906
- transformFn: transformBlobItem,
4520
+ getEndpoint: () => TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS,
4521
+ transformFn: transformTaskResponse,
4522
+ processParametersFn: this.processTaskParameters,
4523
+ excludeFromPrefix: ['event'], // Exclude 'event' key from ODATA prefix transformation
3907
4524
  pagination: {
3908
- paginationType: PaginationType.TOKEN,
3909
- itemsField: BUCKET_PAGINATION.ITEMS_FIELD,
3910
- continuationTokenField: BUCKET_PAGINATION.CONTINUATION_TOKEN_FIELD,
4525
+ paginationType: PaginationType.OFFSET,
4526
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
4527
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
3911
4528
  paginationParams: {
3912
- pageSizeParam: BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM,
3913
- tokenParam: BUCKET_TOKEN_PARAMS.TOKEN_PARAM
4529
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM, // OData OFFSET parameter
4530
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM, // OData OFFSET parameter
4531
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM // OData OFFSET parameter
3914
4532
  }
3915
- },
3916
- excludeFromPrefix: ['prefix'] // Bucket-specific param, not OData
3917
- }, { ...options, folderId });
4533
+ }
4534
+ }, options);
3918
4535
  }
3919
4536
  /**
3920
- * Uploads a file to a bucket
4537
+ * Gets a task by ID
4538
+ * IMPORTANT: For form tasks, folderId must be provided.
3921
4539
  *
3922
- * @param options - Options for file upload including bucket ID, folder ID, path, content, and optional parameters
3923
- * @returns Promise resolving to a response with success status and HTTP status code
4540
+ * @param id - The ID of the task to retrieve
4541
+ * @param options - Optional query parameters
4542
+ * @param folderId - Optional folder ID (REQUIRED for form tasks)
4543
+ * @returns Promise resolving to the task (form tasks will return form-specific data)
3924
4544
  *
3925
4545
  * @example
3926
4546
  * ```typescript
3927
- * // Upload a file from browser
3928
- * const file = new File(['file content'], 'example.txt');
3929
- * const result = await sdk.buckets.uploadFile({
3930
- * bucketId: 123,
3931
- * folderId: 456,
3932
- * path: '/folder/example.txt',
3933
- * content: file
3934
- * });
4547
+ * // Get task by ID
4548
+ * const task = await sdk.tasks.getById(123);
3935
4549
  *
3936
- * // In Node env with explicit content type
3937
- * const buffer = Buffer.from('file content');
3938
- * const result = await sdk.buckets.uploadFile({
3939
- * bucketId: 123,
3940
- * folderId: 456,
3941
- * path: '/folder/example.txt',
3942
- * content: buffer,
3943
- * contentType: 'text/plain'
3944
- * });
4550
+ * // If the task is a form task, it will automatically return form-specific data
3945
4551
  * ```
3946
4552
  */
3947
- async uploadFile(options) {
3948
- const { bucketId, folderId, path, content, contentType } = options;
3949
- if (!bucketId) {
3950
- throw new ValidationError({ message: 'bucketId is required for uploadFile' });
3951
- }
3952
- if (!folderId) {
3953
- throw new ValidationError({ message: 'folderId is required for uploadFile' });
3954
- }
3955
- if (!path) {
3956
- throw new ValidationError({ message: 'path is required for uploadFile' });
3957
- }
3958
- if (!content) {
3959
- throw new ValidationError({ message: 'content is required for uploadFile' });
3960
- }
3961
- try {
3962
- // Get write URI for upload with detected content type if not provided
3963
- let detectedContentType = contentType;
3964
- if (!detectedContentType) {
3965
- detectedContentType = await this._determineContentType(content, path);
3966
- }
3967
- const uriResponse = await this._getWriteUri({
3968
- bucketId,
3969
- folderId,
3970
- path,
3971
- contentType: detectedContentType
3972
- });
3973
- // Upload file to the provided URI
3974
- const response = await this._uploadToUri(uriResponse, content, detectedContentType);
3975
- return {
3976
- success: response.status >= 200 && response.status < 300,
3977
- statusCode: response.status
3978
- };
3979
- }
3980
- catch (error) {
3981
- throw error;
4553
+ async getById(id, options = {}, folderId) {
4554
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
4555
+ // Add default expand parameters
4556
+ const modifiedOptions = this.addDefaultExpand(options);
4557
+ // prefix all keys in options
4558
+ const keysToPrefix = Object.keys(modifiedOptions);
4559
+ const apiOptions = addPrefixToKeys(modifiedOptions, ODATA_PREFIX, keysToPrefix);
4560
+ const response = await this.get(TASK_ENDPOINTS.GET_BY_ID(id), {
4561
+ params: apiOptions,
4562
+ headers
4563
+ });
4564
+ // Transform response from PascalCase to camelCase and normalize time fields
4565
+ const transformedTask = transformData(pascalToCamelCaseKeys(response.data), TaskMap);
4566
+ // Check if this is a form task and get form-specific data if it is
4567
+ if (transformedTask.type === exports.TaskType.Form) {
4568
+ const formOptions = { expandOnFormLayout: true };
4569
+ return this.getFormTaskById(id, folderId || transformedTask.folderId, formOptions);
3982
4570
  }
4571
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
3983
4572
  }
3984
4573
  /**
3985
- * Determines the content type of the file based on the content and path
3986
- * Uses a hybrid approach:
3987
- * 1. Checks Blob/File type if available (browser)
3988
- * 2. Uses content-based detection with file-type (primarily Node.js)
3989
- * 3. Falls back to extension-based detection with mime-types
3990
- * 4. Finally defaults to application/octet-stream
4574
+ * Assigns tasks to users
3991
4575
  *
3992
- * @param content - The file content
3993
- * @param path - The file path
3994
- * @returns The determined content type or default
4576
+ * @param taskAssignments - Single task assignment or array of task assignments
4577
+ * @returns Promise resolving to array of task assignment results
4578
+ *
4579
+ * @example
4580
+ * ```typescript
4581
+ * // Assign a single task to a user by ID
4582
+ * const result = await sdk.tasks.assign({
4583
+ * taskId: 123,
4584
+ * userId: 456
4585
+ * });
4586
+ *
4587
+ * // Assign a single task to a user by email
4588
+ * const result = await sdk.tasks.assign({
4589
+ * taskId: 123,
4590
+ * userNameOrEmail: "user@example.com"
4591
+ * });
4592
+ *
4593
+ * // Assign multiple tasks
4594
+ * const result = await sdk.tasks.assign([
4595
+ * {
4596
+ * taskId: 123,
4597
+ * userId: 456
4598
+ * },
4599
+ * {
4600
+ * taskId: 789,
4601
+ * userNameOrEmail: "user@example.com"
4602
+ * }
4603
+ * ]);
4604
+ * ```
3995
4605
  */
3996
- async _determineContentType(content, path) {
3997
- // 1. If content is a File or Blob with type, use that (works in browser)
3998
- if ('type' in content && content.type) {
3999
- return content.type;
4000
- }
4001
- // 2. Try content-based detection (primarily for Node.js)
4002
- if (content instanceof Buffer && fileTypeFromBuffer) {
4003
- try {
4004
- const fileTypeResult = await fileTypeFromBuffer(content);
4005
- if (fileTypeResult?.mime) {
4006
- return fileTypeResult.mime;
4007
- }
4008
- }
4009
- catch (error) {
4010
- // Silently continue to next detection method if this fails
4011
- console.debug('Content-based type detection failed:', error);
4012
- }
4013
- }
4014
- // 3. Try to infer from file extension using mime-types library
4015
- const mimeType = mimeTypes__namespace.lookup(path);
4016
- if (mimeType) {
4017
- return mimeType;
4018
- }
4019
- // 4. Final fallback
4020
- return CONTENT_TYPES.OCTET_STREAM;
4021
- }
4606
+ async assign(taskAssignments) {
4607
+ // Normalize input to array
4608
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
4609
+ const options = {
4610
+ taskAssignments: assignmentArray
4611
+ };
4612
+ // Convert options to PascalCase for API
4613
+ const pascalOptions = camelToPascalCaseKeys(options);
4614
+ const response = await this.post(TASK_ENDPOINTS.ASSIGN_TASKS, pascalOptions);
4615
+ // Transform response from PascalCase to camelCase
4616
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
4617
+ // Process OData array response - empty array = success, non-empty = error
4618
+ return processODataArrayResponse(transformedResponse, assignmentArray);
4619
+ }
4022
4620
  /**
4023
- * Uploads content to the provided URI
4024
- * @param uriResponse - Response from getWriteUri containing URL and headers
4025
- * @param content - The content to upload
4026
- * @param contentType - The content type of the file
4027
- * @returns The response from the upload request with status info
4621
+ * Reassigns tasks to new users
4622
+ *
4623
+ * @param taskAssignments - Single task assignment or array of task assignments
4624
+ * @returns Promise resolving to array of task assignment results
4625
+ *
4626
+ * @example
4627
+ * ```typescript
4628
+ * // Reassign a single task to a user by ID
4629
+ * const result = await sdk.tasks.reassign({
4630
+ * taskId: 123,
4631
+ * userId: 456
4632
+ * });
4633
+ *
4634
+ * // Reassign a single task to a user by email
4635
+ * const result = await sdk.tasks.reassign({
4636
+ * taskId: 123,
4637
+ * userNameOrEmail: "user@example.com"
4638
+ * });
4639
+ *
4640
+ * // Reassign multiple tasks
4641
+ * const result = await sdk.tasks.reassign([
4642
+ * {
4643
+ * taskId: 123,
4644
+ * userId: 456
4645
+ * },
4646
+ * {
4647
+ * taskId: 789,
4648
+ * userNameOrEmail: "user@example.com"
4649
+ * }
4650
+ * ]);
4651
+ * ```
4028
4652
  */
4029
- async _uploadToUri(uriResponse, content, contentType) {
4030
- const { uri, headers = {}, requiresAuth } = uriResponse;
4031
- if (!uri) {
4032
- throw new ValidationError({ message: 'Upload URI not available', statusCode: HttpStatus.BAD_REQUEST });
4033
- }
4034
- // Create headers for the request
4035
- let requestHeaders = { ...headers };
4036
- // Ensure content-type is set if provided
4037
- if (contentType && !requestHeaders['content-type']) {
4038
- requestHeaders['content-type'] = contentType;
4039
- }
4040
- // Add auth header if required
4041
- if (requiresAuth) {
4042
- try {
4043
- const tokenInfo = this.executionContext.get('tokenInfo');
4044
- if (!tokenInfo) {
4045
- throw new AuthenticationError({ message: 'No authentication token available. Make sure to initialize the SDK first.' });
4046
- }
4047
- let token;
4048
- // For secret-based tokens, they never expire so use directly
4049
- if (tokenInfo.type === 'secret') {
4050
- token = tokenInfo.token;
4051
- }
4052
- // For non-secret tokens, check expiration and refresh if needed
4053
- else if (!this.tokenManager.isTokenExpired(tokenInfo)) {
4054
- token = tokenInfo.token;
4055
- }
4056
- else {
4057
- const newToken = await this.tokenManager.refreshAccessToken();
4058
- token = newToken.access_token;
4059
- }
4060
- requestHeaders['Authorization'] = `Bearer ${token}`;
4061
- }
4062
- catch (error) {
4063
- throw new AuthenticationError({
4064
- message: `Authentication required but failed: ${error instanceof Error ? error.message : ''}`,
4065
- statusCode: HttpStatus.UNAUTHORIZED
4066
- });
4067
- }
4068
- }
4069
- return axios.put(uri, content, {
4070
- headers: createHeaders(requestHeaders)
4071
- });
4653
+ async reassign(taskAssignments) {
4654
+ // Normalize input to array
4655
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
4656
+ const options = {
4657
+ taskAssignments: assignmentArray
4658
+ };
4659
+ // Convert options to PascalCase for API
4660
+ const pascalOptions = camelToPascalCaseKeys(options);
4661
+ const response = await this.post(TASK_ENDPOINTS.REASSIGN_TASKS, pascalOptions);
4662
+ // Transform response from PascalCase to camelCase
4663
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
4664
+ // Process OData array response - empty array = success, non-empty = error
4665
+ return processODataArrayResponse(transformedResponse, assignmentArray);
4072
4666
  }
4073
4667
  /**
4074
- * Private method to handle common URI request logic
4075
- * @param endpoint - The API endpoint to call
4076
- * @param bucketId - The bucket ID
4077
- * @param folderId - The folder ID
4078
- * @param path - The file path
4079
- * @param queryOptions - Additional query parameters
4080
- * @returns Promise resolving to blob file access information
4668
+ * Unassigns tasks (removes current assignees)
4669
+ *
4670
+ * @param taskIds - Single task ID or array of task IDs to unassign
4671
+ * @returns Promise resolving to array of task assignment results
4672
+ *
4673
+ * @example
4674
+ * ```typescript
4675
+ * // Unassign a single task
4676
+ * const result = await sdk.tasks.unassign(123);
4677
+ *
4678
+ * // Unassign multiple tasks
4679
+ * const result = await sdk.tasks.unassign([123, 456, 789]);
4680
+ * ```
4081
4681
  */
4082
- async _getUri(endpoint, bucketId, folderId, path, queryOptions = {}) {
4083
- if (!bucketId) {
4084
- throw new ValidationError({ message: 'bucketId is required for getUri' });
4085
- }
4086
- if (!folderId) {
4087
- throw new ValidationError({ message: 'folderId is required for getUri' });
4088
- }
4089
- if (!path) {
4090
- throw new ValidationError({ message: 'path is required for getUri' });
4091
- }
4092
- // Create headers with required folder ID
4093
- const headers = createHeaders({ [FOLDER_ID]: folderId });
4094
- // Filter out undefined values and build query params
4095
- const queryParams = filterUndefined({
4096
- path,
4097
- ...queryOptions
4098
- });
4099
- // Make the API call to get URI
4100
- const response = await this.get(endpoint, {
4101
- params: queryParams,
4102
- headers
4103
- });
4104
- const transformedData = transformData(pascalToCamelCaseKeys(response.data), BucketMap);
4105
- // Convert headers from array-based to record if needed
4106
- if (transformedData.headers && 'keys' in transformedData.headers && 'values' in transformedData.headers) {
4107
- transformedData.headers = arrayDictionaryToRecord(transformedData.headers);
4108
- }
4109
- return transformedData;
4682
+ async unassign(taskIds) {
4683
+ // Normalize input to array
4684
+ const taskIdArray = Array.isArray(taskIds) ? taskIds : [taskIds];
4685
+ const options = {
4686
+ taskIds: taskIdArray
4687
+ };
4688
+ const response = await this.post(TASK_ENDPOINTS.UNASSIGN_TASKS, options);
4689
+ // Transform response from PascalCase to camelCase
4690
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
4691
+ // Process OData array response - empty array = success, non-empty = error
4692
+ // Return the task IDs that were unassigned
4693
+ return processODataArrayResponse(transformedResponse, taskIdArray.map(id => ({ taskId: id })));
4110
4694
  }
4111
4695
  /**
4112
- * Gets a direct download URL for a file in the bucket
4696
+ * Completes a task with the specified type and data
4113
4697
  *
4114
- * @param options - Contains bucketId, folderId, file path and optional expiry time
4115
- * @returns Promise resolving to blob file access information
4698
+ * @param options - The completion options including task type, taskId, data, and action
4699
+ * @param folderId - Required folder ID
4700
+ * @returns Promise resolving to completion result
4116
4701
  *
4117
4702
  * @example
4118
4703
  * ```typescript
4119
- * // Get download URL for a file
4120
- * const fileAccess = await sdk.buckets.getReadUri({
4121
- * bucketId: 123,
4122
- * folderId: 456,
4123
- * path: '/folder/file.pdf'
4124
- * });
4704
+ * // Complete an app task
4705
+ * await sdk.tasks.complete({
4706
+ * type: TaskType.App,
4707
+ * taskId: 456,
4708
+ * data: {},
4709
+ * action: "submit"
4710
+ * }, 123); // folderId is required
4711
+ *
4712
+ * // Complete an external task
4713
+ * await sdk.tasks.complete({
4714
+ * type: TaskType.External,
4715
+ * taskId: 789
4716
+ * }, 123); // folderId is required
4125
4717
  * ```
4126
4718
  */
4127
- async getReadUri(options) {
4128
- const { bucketId, folderId, path, expiryInMinutes, ...restOptions } = options;
4129
- const queryOptions = {
4130
- expiryInMinutes,
4131
- ...addPrefixToKeys(restOptions, ODATA_PREFIX, Object.keys(restOptions))
4719
+ async complete(options, folderId) {
4720
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
4721
+ let endpoint;
4722
+ switch (options.type) {
4723
+ case exports.TaskType.Form:
4724
+ endpoint = TASK_ENDPOINTS.COMPLETE_FORM_TASK;
4725
+ break;
4726
+ case exports.TaskType.App:
4727
+ endpoint = TASK_ENDPOINTS.COMPLETE_APP_TASK;
4728
+ break;
4729
+ default:
4730
+ endpoint = TASK_ENDPOINTS.COMPLETE_GENERIC_TASK;
4731
+ break;
4732
+ }
4733
+ // CompleteAppTask returns 204 no content
4734
+ await this.post(endpoint, options, { headers });
4735
+ // Return success with the request context data
4736
+ return {
4737
+ success: true,
4738
+ data: options
4132
4739
  };
4133
- return this._getUri(BUCKET_ENDPOINTS.GET_READ_URI(bucketId), bucketId, folderId, path, queryOptions);
4134
4740
  }
4135
4741
  /**
4136
- * Gets a direct upload URL for a file in the bucket
4742
+ * Gets a form task by ID (private method)
4137
4743
  *
4138
- * @param options - Contains bucketId, folderId, file path, optional expiry time and content type
4139
- * @returns Promise resolving to blob file access information
4744
+ * @param id - The ID of the form task to retrieve
4745
+ * @param folderId - Required folder ID
4746
+ * @param options - Optional query parameters
4747
+ * @returns Promise resolving to the form task
4140
4748
  */
4141
- async _getWriteUri(options) {
4142
- const { bucketId, folderId, path, expiryInMinutes, contentType, ...restOptions } = options;
4143
- const queryOptions = {
4144
- expiryInMinutes,
4145
- contentType,
4146
- ...addPrefixToKeys(restOptions, ODATA_PREFIX, Object.keys(restOptions))
4147
- };
4148
- return this._getUri(BUCKET_ENDPOINTS.GET_WRITE_URI(bucketId), bucketId, folderId, path, queryOptions);
4749
+ async getFormTaskById(id, folderId, options = {}) {
4750
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
4751
+ const response = await this.get(TASK_ENDPOINTS.GET_TASK_FORM_BY_ID, {
4752
+ params: {
4753
+ taskId: id,
4754
+ ...options
4755
+ },
4756
+ headers
4757
+ });
4758
+ const transformedFormTask = transformData(response.data, TaskMap);
4759
+ return createTaskWithMethods(applyDataTransforms(transformedFormTask, { field: 'status', valueMap: TaskStatusMap }), this);
4760
+ }
4761
+ /**
4762
+ * Adds default expand parameters to options
4763
+ * @param options - The options object to add default expand to
4764
+ * @returns Options with default expand parameters added
4765
+ * @private
4766
+ */
4767
+ addDefaultExpand(options) {
4768
+ const processedOptions = { ...options };
4769
+ processedOptions.expand = processedOptions.expand
4770
+ ? `${DEFAULT_TASK_EXPAND},${processedOptions.expand}`
4771
+ : DEFAULT_TASK_EXPAND;
4772
+ return processedOptions;
4149
4773
  }
4150
4774
  }
4151
4775
  __decorate([
4152
- track('Buckets.GetById')
4153
- ], BucketService.prototype, "getById", null);
4776
+ track('Tasks.Create')
4777
+ ], TaskService.prototype, "create", null);
4154
4778
  __decorate([
4155
- track('Buckets.GetAll')
4156
- ], BucketService.prototype, "getAll", null);
4779
+ track('Tasks.GetUsers')
4780
+ ], TaskService.prototype, "getUsers", null);
4157
4781
  __decorate([
4158
- track('Buckets.GetFileMetaData')
4159
- ], BucketService.prototype, "getFileMetaData", null);
4782
+ track('Tasks.GetAll')
4783
+ ], TaskService.prototype, "getAll", null);
4160
4784
  __decorate([
4161
- track('Buckets.UploadFile')
4162
- ], BucketService.prototype, "uploadFile", null);
4785
+ track('Tasks.GetById')
4786
+ ], TaskService.prototype, "getById", null);
4163
4787
  __decorate([
4164
- track('Buckets.GetReadUri')
4165
- ], BucketService.prototype, "getReadUri", null);
4788
+ track('Tasks.Assign')
4789
+ ], TaskService.prototype, "assign", null);
4790
+ __decorate([
4791
+ track('Tasks.Reassign')
4792
+ ], TaskService.prototype, "reassign", null);
4793
+ __decorate([
4794
+ track('Tasks.Unassign')
4795
+ ], TaskService.prototype, "unassign", null);
4796
+ __decorate([
4797
+ track('Tasks.Complete')
4798
+ ], TaskService.prototype, "complete", null);
4166
4799
 
4167
- /**
4168
- * Maps fields for Process entities to ensure consistent naming
4169
- */
4170
- const ProcessMap = {
4171
- lastModificationTime: 'lastModifiedTime',
4172
- creationTime: 'createdTime',
4173
- organizationUnitId: 'folderId',
4174
- organizationUnitFullyQualifiedName: 'folderName',
4175
- releaseKey: 'processKey',
4176
- releaseName: 'processName',
4177
- releaseVersionId: 'processVersionId',
4178
- processType: 'packageType',
4179
- processKey: 'packageKey',
4180
- processVersion: 'packageVersion',
4181
- isProcessDeleted: 'isPackageDeleted',
4182
- };
4183
-
4184
- /**
4185
- * Service for interacting with UiPath Orchestrator Processes API
4186
- */
4187
- class ProcessService extends BaseService {
4800
+ class CaseInstancesService extends BaseService {
4188
4801
  /**
4189
4802
  * @hideconstructor
4190
4803
  */
4191
4804
  constructor(config, executionContext, tokenManager) {
4192
4805
  super(config, executionContext, tokenManager);
4806
+ this.taskService = new TaskService(config, executionContext, tokenManager);
4193
4807
  }
4194
4808
  /**
4195
- * Gets all processes across folders with optional filtering and folder scoping
4809
+ * Get all case instances with optional filtering and pagination
4196
4810
  *
4197
4811
  * The method returns either:
4198
- * - An array of processes (when no pagination parameters are provided)
4199
- * - A paginated result with navigation cursors (when any pagination parameter is provided)
4812
+ * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
4813
+ * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
4200
4814
  *
4201
- * @param options - Query options including optional folderId
4202
- * @returns Promise resolving to an array of processes or paginated result
4815
+ * @param options -Query parameters for filtering instances and pagination
4816
+ * @returns Promise resolving to case instances or paginated result
4203
4817
  *
4204
4818
  * @example
4205
4819
  * ```typescript
4206
- * // Standard array return
4207
- * const processes = await sdk.processes.getAll();
4820
+ * // Get all case instances (non-paginated)
4821
+ * const instances = await sdk.maestro.cases.instances.getAll();
4208
4822
  *
4209
- * // Get processes within a specific folder
4210
- * const processes = await sdk.processes.getAll({
4211
- * folderId: 123
4212
- * });
4823
+ * // Close faulted instances using methods directly on instances
4824
+ * for (const instance of instances.items) {
4825
+ * if (instance.latestRunStatus === 'Faulted') {
4826
+ * await instance.close({ comment: 'Closing faulted case instance' });
4827
+ * }
4828
+ * }
4213
4829
  *
4214
- * // Get processes with filtering
4215
- * const processes = await sdk.processes.getAll({
4216
- * filter: "name eq 'MyProcess'"
4830
+ * // With filtering
4831
+ * const instances = await sdk.maestro.cases.instances.getAll({
4832
+ * processKey: 'MyCaseProcess'
4217
4833
  * });
4218
4834
  *
4219
4835
  * // First page with pagination
4220
- * const page1 = await sdk.processes.getAll({ pageSize: 10 });
4836
+ * const page1 = await sdk.maestro.cases.instances.getAll({ pageSize: 10 });
4221
4837
  *
4222
4838
  * // Navigate using cursor
4223
4839
  * if (page1.hasNextPage) {
4224
- * const page2 = await sdk.processes.getAll({ cursor: page1.nextCursor });
4840
+ * const page2 = await sdk.maestro.cases.instances.getAll({ cursor: page1.nextCursor });
4225
4841
  * }
4226
- *
4227
- * // Jump to specific page
4228
- * const page5 = await sdk.processes.getAll({
4229
- * jumpToPage: 5,
4230
- * pageSize: 10
4231
- * });
4232
4842
  * ```
4233
4843
  */
4234
4844
  async getAll(options) {
4235
- // Transformation function for processes
4236
- const transformProcessResponse = (process) => transformData(pascalToCamelCaseKeys(process), ProcessMap);
4237
- return PaginationHelpers.getAll({
4845
+ // Add processType filter to only get case management instances
4846
+ const enhancedOptions = {
4847
+ ...options,
4848
+ processType: ProcessType.CaseManagement
4849
+ };
4850
+ // Base transformation function for case instances (synchronous)
4851
+ const transformCaseInstance = (item) => {
4852
+ const rawInstance = transformData(item, CaseInstanceMap);
4853
+ return createCaseInstanceWithMethods(rawInstance, this);
4854
+ };
4855
+ // Get the paginated result with basic transformation
4856
+ const result = await PaginationHelpers.getAll({
4238
4857
  serviceAccess: this.createPaginationServiceAccess(),
4239
- getEndpoint: () => PROCESS_ENDPOINTS.GET_ALL,
4240
- getByFolderEndpoint: PROCESS_ENDPOINTS.GET_ALL, // Processes use same endpoint for both
4241
- transformFn: transformProcessResponse,
4858
+ getEndpoint: () => MAESTRO_ENDPOINTS.INSTANCES.GET_ALL,
4859
+ transformFn: transformCaseInstance,
4242
4860
  pagination: {
4243
- paginationType: PaginationType.OFFSET,
4244
- itemsField: ODATA_PAGINATION.ITEMS_FIELD,
4245
- totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
4861
+ paginationType: PaginationType.TOKEN,
4862
+ itemsField: PROCESS_INSTANCE_PAGINATION.ITEMS_FIELD,
4863
+ continuationTokenField: PROCESS_INSTANCE_PAGINATION.CONTINUATION_TOKEN_FIELD,
4246
4864
  paginationParams: {
4247
- pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
4248
- offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
4249
- countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
4865
+ pageSizeParam: PROCESS_INSTANCE_TOKEN_PARAMS.PAGE_SIZE_PARAM,
4866
+ tokenParam: PROCESS_INSTANCE_TOKEN_PARAMS.TOKEN_PARAM
4250
4867
  }
4251
- }
4252
- }, options);
4868
+ },
4869
+ excludeFromPrefix: Object.keys(enhancedOptions || {})
4870
+ }, enhancedOptions);
4871
+ // Enhance instances with case JSON data if requested
4872
+ if (result.items && result.items.length > 0) {
4873
+ const enhancedItems = await this.enhanceInstancesWithCaseJson(result.items);
4874
+ return {
4875
+ ...result,
4876
+ items: enhancedItems
4877
+ };
4878
+ }
4879
+ return result;
4253
4880
  }
4254
4881
  /**
4255
- * Starts a process execution (job)
4256
- *
4257
- * @param request - Process start request body
4258
- * @param folderId - Required folder ID
4259
- * @param options - Optional query parameters
4260
- * @returns Promise resolving to the created jobs
4261
- *
4262
- * @example
4263
- * ```typescript
4264
- * // Start a process by process key
4265
- * const jobs = await sdk.processes.start({
4266
- * processKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
4267
- * }, 123); // folderId is required
4268
- *
4269
- * // Start a process by name with specific robots
4270
- * const jobs = await sdk.processes.start({
4271
- * processName: "MyProcess"
4272
- * }, 123); // folderId is required
4273
- * ```
4882
+ * Get a case instance by ID with operation methods (close, pause, resume)
4883
+ * @param instanceId - The ID of the instance to retrieve
4884
+ * @param folderKey - Required folder key
4885
+ * @returns Promise<CaseInstanceGetResponse>
4274
4886
  */
4275
- async start(request, folderId, options = {}) {
4276
- const headers = createHeaders({ [FOLDER_ID]: folderId });
4277
- // Transform processKey/processName to releaseKey/releaseName for API compatibility
4278
- const apiRequest = { ...request };
4279
- // Create a reverse mapping using ProcessMap
4280
- const reversedPropertiesMap = reverseMap(ProcessMap);
4281
- // Apply transformations for any client properties found in the request
4282
- Object.entries(reversedPropertiesMap).forEach(([clientKey, apiKey]) => {
4283
- if (clientKey in apiRequest) {
4284
- apiRequest[apiKey] = apiRequest[clientKey];
4285
- delete apiRequest[clientKey];
4887
+ async getById(instanceId, folderKey) {
4888
+ const response = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_BY_ID(instanceId), {
4889
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
4890
+ });
4891
+ const transformedInstance = transformData(response.data, CaseInstanceMap);
4892
+ const instanceWithMethods = createCaseInstanceWithMethods(transformedInstance, this);
4893
+ // Enhance with case JSON data
4894
+ return this.enhanceInstanceWithCaseJson(instanceWithMethods);
4895
+ }
4896
+ /**
4897
+ * Enhance a single case instance with case JSON data
4898
+ * @param instance - The case instance to enhance
4899
+ * @returns Promise resolving to enhanced instance
4900
+ * @private
4901
+ */
4902
+ async enhanceInstanceWithCaseJson(instance) {
4903
+ if (!instance.folderKey) {
4904
+ return instance;
4905
+ }
4906
+ try {
4907
+ const caseJson = await this.getCaseJson(instance.instanceId, instance.folderKey);
4908
+ if (caseJson && caseJson.root) {
4909
+ // Transform caseAppConfig
4910
+ const transformedCaseAppConfig = caseJson.root.caseAppConfig ? (() => {
4911
+ const transformed = transformData(caseJson.root.caseAppConfig, CaseAppConfigMap);
4912
+ // Remove id field from each overview item
4913
+ if (transformed.overview) {
4914
+ transformed.overview = transformed.overview.map(({ id, ...rest }) => rest);
4915
+ }
4916
+ return transformed;
4917
+ })() : undefined;
4918
+ return {
4919
+ ...instance,
4920
+ ...(transformedCaseAppConfig && { caseAppConfig: transformedCaseAppConfig }),
4921
+ ...(caseJson.root.name && { caseType: caseJson.root.name }),
4922
+ ...(caseJson.root.description && { caseTitle: caseJson.root.description })
4923
+ };
4286
4924
  }
4925
+ }
4926
+ catch (error) {
4927
+ console.debug(`Failed to fetch case JSON for instance ${instance.instanceId}:`, error);
4928
+ }
4929
+ return instance;
4930
+ }
4931
+ /**
4932
+ * Enhance multiple case instances with case JSON data
4933
+ * @param instances - Array of case instances to enhance
4934
+ * @returns Promise resolving to array of enhanced instances
4935
+ * @private
4936
+ */
4937
+ async enhanceInstancesWithCaseJson(instances) {
4938
+ return Promise.all(instances.map(instance => this.enhanceInstanceWithCaseJson(instance)));
4939
+ }
4940
+ /**
4941
+ * Get case JSON for a specific instance
4942
+ * @param instanceId - The case instance ID
4943
+ * @param folderKey - Required folder key
4944
+ * @returns Promise resolving to case JSON data
4945
+ * @private
4946
+ */
4947
+ async getCaseJson(instanceId, folderKey) {
4948
+ try {
4949
+ const response = await this.get(MAESTRO_ENDPOINTS.CASES.GET_CASE_JSON(instanceId), {
4950
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
4951
+ });
4952
+ return response.data;
4953
+ }
4954
+ catch (error) {
4955
+ // Return null if the case JSON is not available
4956
+ return null;
4957
+ }
4958
+ }
4959
+ /**
4960
+ * Close a case instance
4961
+ * @param instanceId - The ID of the instance to cancel
4962
+ * @param folderKey - Required folder key
4963
+ * @param options - Optional cancellation options with comment
4964
+ * @returns Promise resolving to operation result with updated instance data
4965
+ */
4966
+ async close(instanceId, folderKey, options) {
4967
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.CANCEL(instanceId), options || {}, {
4968
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
4287
4969
  });
4288
- // Convert to PascalCase for API
4289
- const pascalOptions = camelToPascalCaseKeys(apiRequest);
4290
- // Create the request object according to API spec
4291
- const requestBody = {
4292
- startInfo: pascalOptions
4970
+ return {
4971
+ success: true,
4972
+ data: response.data
4293
4973
  };
4294
- // Prefix all query parameter keys with '$' for OData
4295
- const keysToPrefix = Object.keys(options);
4296
- const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
4297
- const response = await this.post(PROCESS_ENDPOINTS.START_PROCESS, requestBody, {
4298
- params: apiOptions,
4299
- headers
4974
+ }
4975
+ /**
4976
+ * Pause a case instance
4977
+ * @param instanceId - The ID of the instance to pause
4978
+ * @param folderKey - Required folder key
4979
+ * @param options - Optional pause options with comment
4980
+ * @returns Promise resolving to operation result with updated instance data
4981
+ */
4982
+ async pause(instanceId, folderKey, options) {
4983
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.PAUSE(instanceId), options || {}, {
4984
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
4300
4985
  });
4301
- const transformedProcess = response.data?.value.map(process => transformData(pascalToCamelCaseKeys(process), ProcessMap));
4302
- return transformedProcess;
4986
+ return {
4987
+ success: true,
4988
+ data: response.data
4989
+ };
4303
4990
  }
4304
4991
  /**
4305
- * Gets a single process by ID
4306
- *
4307
- * @param id - Process ID
4308
- * @param folderId - Required folder ID
4309
- * @param options - Optional query parameters
4310
- * @returns Promise resolving to a single process
4311
- *
4992
+ * Resume a case instance
4993
+ * @param instanceId - The ID of the instance to resume
4994
+ * @param folderKey - Required folder key
4995
+ * @param options - Optional resume options with comment
4996
+ * @returns Promise resolving to operation result with updated instance data
4997
+ */
4998
+ async resume(instanceId, folderKey, options) {
4999
+ const response = await this.post(MAESTRO_ENDPOINTS.INSTANCES.RESUME(instanceId), options || {}, {
5000
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
5001
+ });
5002
+ return {
5003
+ success: true,
5004
+ data: response.data
5005
+ };
5006
+ }
5007
+ /**
5008
+ * Get execution history for a case instance
5009
+ * @param instanceId - The ID of the case instance
5010
+ * @param folderKey - Required folder key
5011
+ * @returns Promise resolving to instance execution history
4312
5012
  * @example
4313
5013
  * ```typescript
4314
- * // Get process by ID
4315
- * const process = await sdk.processes.getById(123, 456);
5014
+ * // Get execution history for a case instance
5015
+ * const history = await sdk.maestro.cases.instances.getExecutionHistory(
5016
+ * 'instance-id',
5017
+ * 'folder-key'
5018
+ * );
4316
5019
  * ```
4317
5020
  */
4318
- async getById(id, folderId, options = {}) {
4319
- const headers = createHeaders({ [FOLDER_ID]: folderId });
4320
- const keysToPrefix = Object.keys(options);
4321
- const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
4322
- const response = await this.get(PROCESS_ENDPOINTS.GET_BY_ID(id), {
4323
- headers,
4324
- params: apiOptions
5021
+ async getExecutionHistory(instanceId, folderKey) {
5022
+ const response = await this.get(MAESTRO_ENDPOINTS.CASES.GET_ELEMENT_EXECUTIONS(instanceId), {
5023
+ headers: createHeaders({ [FOLDER_KEY]: folderKey })
4325
5024
  });
4326
- const transformedProcess = transformData(pascalToCamelCaseKeys(response.data), ProcessMap);
4327
- return transformedProcess;
5025
+ // Transform the main response
5026
+ const transformedResponse = transformData(response.data, TimeFieldTransformMap);
5027
+ // Transform each element execution and its nested element runs
5028
+ if (transformedResponse.elementExecutions && Array.isArray(transformedResponse.elementExecutions)) {
5029
+ transformedResponse.elementExecutions = transformedResponse.elementExecutions.map((execution) => {
5030
+ // Transform the element execution itself
5031
+ const transformedExecution = transformData(execution, TimeFieldTransformMap);
5032
+ // Transform nested element runs if they exist
5033
+ if (transformedExecution.elementRuns && Array.isArray(transformedExecution.elementRuns)) {
5034
+ transformedExecution.elementRuns = transformedExecution.elementRuns.map((run) => transformData(run, TimeFieldTransformMap));
5035
+ }
5036
+ return transformedExecution;
5037
+ });
5038
+ }
5039
+ return transformedResponse;
5040
+ }
5041
+ /**
5042
+ * Get case stages with their associated tasks and execution status
5043
+ * @param caseInstanceId - The ID of the case instance
5044
+ * @param folderKey - Required folder key
5045
+ * @returns Promise resolving to an array of case stages, each containing their tasks with execution details
5046
+ */
5047
+ async getStages(caseInstanceId, folderKey) {
5048
+ // Fetch both execution history and case JSON in parallel, but handle execution failures gracefully
5049
+ const [executionHistoryResponse, caseJsonResponse] = await Promise.allSettled([
5050
+ this.getExecutionHistory(caseInstanceId, folderKey),
5051
+ this.getCaseJson(caseInstanceId, folderKey)
5052
+ ]);
5053
+ // Extract execution history if successful, otherwise use null
5054
+ const executionHistory = executionHistoryResponse.status === 'fulfilled'
5055
+ ? executionHistoryResponse.value
5056
+ : null;
5057
+ // Extract case JSON - the null check below will handle failures
5058
+ const caseJson = caseJsonResponse.status === 'fulfilled'
5059
+ ? caseJsonResponse.value
5060
+ : null;
5061
+ if (!caseJson || !caseJson.nodes) {
5062
+ return [];
5063
+ }
5064
+ // Create lookup maps for efficient data access
5065
+ const executionMap = this.createExecutionMap(executionHistory);
5066
+ const bindingsMap = this.createBindingsMap(caseJson);
5067
+ // Process nodes to extract stages (exclude triggers)
5068
+ const stages = caseJson.nodes
5069
+ .filter((node) => node.type !== CASE_STAGE_CONSTANTS.TRIGGER_NODE_TYPE)
5070
+ .map((node) => this.createStageFromNode(node, executionMap, bindingsMap));
5071
+ return stages;
5072
+ }
5073
+ /**
5074
+ * Create a map of element ID to execution data
5075
+ * @param executionHistory - The execution history response
5076
+ * @returns Map of elementId to execution metadata
5077
+ * @private
5078
+ */
5079
+ createExecutionMap(executionHistory) {
5080
+ const executionMap = new Map();
5081
+ if (executionHistory?.elementExecutions) {
5082
+ for (const execution of executionHistory.elementExecutions) {
5083
+ executionMap.set(execution.elementId, execution);
5084
+ }
5085
+ }
5086
+ return executionMap;
5087
+ }
5088
+ /**
5089
+ * Create a map of binding IDs to their values
5090
+ * @param caseJsonResponse - The case JSON response
5091
+ * @returns Map of binding ID to binding object
5092
+ * @private
5093
+ */
5094
+ createBindingsMap(caseJsonResponse) {
5095
+ const bindingsMap = new Map();
5096
+ if (caseJsonResponse?.root?.data?.uipath?.bindings) {
5097
+ for (const binding of caseJsonResponse.root.data.uipath.bindings) {
5098
+ if (binding.id) {
5099
+ bindingsMap.set(binding.id, binding);
5100
+ }
5101
+ }
5102
+ }
5103
+ return bindingsMap;
5104
+ }
5105
+ /**
5106
+ * Resolve binding values from binding expressions
5107
+ * @param value - The value that may contain binding references
5108
+ * @param bindingsMap - Map of binding IDs to binding objects
5109
+ * @returns Resolved value
5110
+ * @private
5111
+ */
5112
+ resolveBinding(value, bindingsMap) {
5113
+ if (typeof value === 'string' && value.startsWith('=bindings.')) {
5114
+ const bindingId = value.substring('=bindings.'.length);
5115
+ const binding = bindingsMap.get(bindingId);
5116
+ return binding?.default || binding?.name || value;
5117
+ }
5118
+ return value;
5119
+ }
5120
+ /**
5121
+ * Process tasks for a stage node
5122
+ * @param node - The stage node containing tasks
5123
+ * @param executionMap - Map of element IDs to execution data
5124
+ * @param bindingsMap - Map of binding IDs to binding objects
5125
+ * @returns Processed tasks array
5126
+ * @private
5127
+ */
5128
+ processTasks(node, executionMap, bindingsMap) {
5129
+ if (!node.data?.tasks || !Array.isArray(node.data.tasks)) {
5130
+ return [];
5131
+ }
5132
+ return node.data.tasks.map((taskGroup) => {
5133
+ if (Array.isArray(taskGroup)) {
5134
+ return taskGroup.map((task) => {
5135
+ const taskId = task.id;
5136
+ // Find the execution data using the task's id
5137
+ const taskExecution = taskId ? executionMap.get(taskId) : undefined;
5138
+ // Resolve task name from bindings
5139
+ let taskName = task.displayName;
5140
+ if (!taskName && task.data?.name) {
5141
+ taskName = this.resolveBinding(task.data.name, bindingsMap);
5142
+ }
5143
+ const stageTask = {
5144
+ id: taskId || task.elementId || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
5145
+ name: taskName || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
5146
+ completedTime: taskExecution?.completedTime || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
5147
+ startedTime: taskExecution?.startedTime || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
5148
+ status: taskExecution?.status || CASE_STAGE_CONSTANTS.NOT_STARTED_STATUS,
5149
+ type: task.type || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE
5150
+ };
5151
+ return stageTask;
5152
+ });
5153
+ }
5154
+ return [];
5155
+ });
5156
+ }
5157
+ /**
5158
+ * Create a stage from a case node
5159
+ * @param node - The case node to process
5160
+ * @param executionMap - Map of element IDs to execution data
5161
+ * @param bindingsMap - Map of binding IDs to binding objects
5162
+ * @returns CaseGetStageResponse object
5163
+ * @private
5164
+ */
5165
+ createStageFromNode(node, executionMap, bindingsMap) {
5166
+ const execution = executionMap.get(node.id);
5167
+ const stage = {
5168
+ id: node.id,
5169
+ name: node.data?.label || CASE_STAGE_CONSTANTS.UNDEFINED_VALUE,
5170
+ sla: node.data?.sla ? transformData(node.data.sla, StageSLAMap) : undefined,
5171
+ status: execution?.status || CASE_STAGE_CONSTANTS.NOT_STARTED_STATUS,
5172
+ tasks: this.processTasks(node, executionMap, bindingsMap)
5173
+ };
5174
+ return stage;
5175
+ }
5176
+ /**
5177
+ * Get human in the loop tasks associated with a case instance
5178
+ * @param caseInstanceId - The ID of the case instance
5179
+ * @param options - Optional filtering and pagination options
5180
+ * @returns Promise resolving to human in the loop tasks associated with the case instance
5181
+ */
5182
+ async getActionTasks(caseInstanceId, options) {
5183
+ // Build filter to match tasks by case instance ID using tags
5184
+ const tagFilter = CASE_INSTANCE_TASK_FILTER(caseInstanceId);
5185
+ // Combine with any existing filter
5186
+ const filter = options?.filter
5187
+ ? `(${tagFilter}) and (${options.filter})`
5188
+ : tagFilter;
5189
+ // Add expand to include AssignedToUser and Activities
5190
+ const expand = CASE_INSTANCE_TASK_EXPAND;
5191
+ // Prepare the enhanced options with proper typing
5192
+ const enhancedOptions = {
5193
+ ...options,
5194
+ filter,
5195
+ expand
5196
+ };
5197
+ return await this.taskService.getAll(enhancedOptions);
4328
5198
  }
4329
5199
  }
4330
5200
  __decorate([
4331
- track('Processes.GetAll')
4332
- ], ProcessService.prototype, "getAll", null);
5201
+ track('CaseInstances.GetAll')
5202
+ ], CaseInstancesService.prototype, "getAll", null);
4333
5203
  __decorate([
4334
- track('Processes.Start')
4335
- ], ProcessService.prototype, "start", null);
5204
+ track('CaseInstances.GetById')
5205
+ ], CaseInstancesService.prototype, "getById", null);
4336
5206
  __decorate([
4337
- track('Processes.GetById')
4338
- ], ProcessService.prototype, "getById", null);
5207
+ track('CaseInstances.Close')
5208
+ ], CaseInstancesService.prototype, "close", null);
5209
+ __decorate([
5210
+ track('CaseInstances.Pause')
5211
+ ], CaseInstancesService.prototype, "pause", null);
5212
+ __decorate([
5213
+ track('CaseInstances.Resume')
5214
+ ], CaseInstancesService.prototype, "resume", null);
5215
+ __decorate([
5216
+ track('CaseInstances.GetExecutionHistory')
5217
+ ], CaseInstancesService.prototype, "getExecutionHistory", null);
5218
+ __decorate([
5219
+ track('CaseInstances.GetStages')
5220
+ ], CaseInstancesService.prototype, "getStages", null);
5221
+ __decorate([
5222
+ track('CaseInstances.GetActionTasks')
5223
+ ], CaseInstancesService.prototype, "getActionTasks", null);
4339
5224
 
4340
5225
  /**
4341
- * Maps fields for Queue entities to ensure consistent naming
5226
+ * Base service for services that need folder-specific functionality
4342
5227
  */
4343
- const QueueMap = {
4344
- creationTime: 'createdTime',
4345
- organizationUnitId: 'folderId',
4346
- organizationUnitFullyQualifiedName: 'folderName'
5228
+ class FolderScopedService extends BaseService {
5229
+ constructor(config, executionContext, tokenManager) {
5230
+ super(config, executionContext, tokenManager);
5231
+ }
5232
+ /**
5233
+ * Gets resources in a folder with optional query parameters
5234
+ *
5235
+ * @param endpoint - API endpoint to call
5236
+ * @param folderId - required folder ID
5237
+ * @param options - Query options
5238
+ * @param transformFn - Optional function to transform the response data
5239
+ * @returns Promise resolving to an array of resources
5240
+ */
5241
+ async _getByFolder(endpoint, folderId, options = {}, transformFn) {
5242
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
5243
+ const keysToPrefix = Object.keys(options);
5244
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
5245
+ const response = await this.get(endpoint, {
5246
+ params: apiOptions,
5247
+ headers
5248
+ });
5249
+ if (transformFn) {
5250
+ return response.data?.value.map(transformFn);
5251
+ }
5252
+ return response.data?.value;
5253
+ }
5254
+ }
5255
+
5256
+ /**
5257
+ * Maps fields for Asset entities to ensure consistent naming
5258
+ */
5259
+ const AssetMap = {
5260
+ creationTime: 'createdTime',
5261
+ lastModificationTime: 'lastModifiedTime'
4347
5262
  };
4348
5263
 
4349
5264
  /**
4350
- * Service for interacting with UiPath Orchestrator Queues API
5265
+ * Service for interacting with UiPath Orchestrator Assets API
4351
5266
  */
4352
- class QueueService extends FolderScopedService {
5267
+ class AssetService extends FolderScopedService {
4353
5268
  /**
4354
5269
  * @hideconstructor
4355
5270
  */
@@ -4357,53 +5272,43 @@ class QueueService extends FolderScopedService {
4357
5272
  super(config, executionContext, tokenManager);
4358
5273
  }
4359
5274
  /**
4360
- * Gets all queues across folders with optional filtering and folder scoping
4361
- *
4362
- * The method returns either:
4363
- * - An array of queues (when no pagination parameters are provided)
4364
- * - A paginated result with navigation cursors (when any pagination parameter is provided)
5275
+ * Gets all assets across folders with optional filtering and folder scoping
4365
5276
  *
4366
- * @param options - Query options including optional folderId
4367
- * @returns Promise resolving to an array of queues or paginated result
5277
+ * @signature getAll(options?) -> Promise<AssetGetResponse[]>
5278
+ * @param options Query options including optional folderId and pagination options
5279
+ * @returns Promise resolving to array of assets or paginated response
4368
5280
  *
4369
5281
  * @example
4370
5282
  * ```typescript
4371
5283
  * // Standard array return
4372
- * const queues = await sdk.queues.getAll();
4373
- *
4374
- * // Get queues within a specific folder
4375
- * const queues = await sdk.queues.getAll({
4376
- * folderId: 123
4377
- * });
5284
+ * const assets = await sdk.assets.getAll();
4378
5285
  *
4379
- * // Get queues with filtering
4380
- * const queues = await sdk.queues.getAll({
4381
- * filter: "name eq 'MyQueue'"
4382
- * });
5286
+ * // With folder
5287
+ * const folderAssets = await sdk.assets.getAll({ folderId: 123 });
4383
5288
  *
4384
5289
  * // First page with pagination
4385
- * const page1 = await sdk.queues.getAll({ pageSize: 10 });
5290
+ * const page1 = await sdk.assets.getAll({ pageSize: 10 });
4386
5291
  *
4387
5292
  * // Navigate using cursor
4388
5293
  * if (page1.hasNextPage) {
4389
- * const page2 = await sdk.queues.getAll({ cursor: page1.nextCursor });
5294
+ * const page2 = await sdk.assets.getAll({ cursor: page1.nextCursor });
4390
5295
  * }
4391
5296
  *
4392
5297
  * // Jump to specific page
4393
- * const page5 = await sdk.queues.getAll({
5298
+ * const page5 = await sdk.assets.getAll({
4394
5299
  * jumpToPage: 5,
4395
5300
  * pageSize: 10
4396
5301
  * });
4397
5302
  * ```
4398
5303
  */
4399
5304
  async getAll(options) {
4400
- // Transformation function for queues
4401
- const transformQueueResponse = (queue) => transformData(pascalToCamelCaseKeys(queue), QueueMap);
5305
+ // Transformation function for assets
5306
+ const transformAssetResponse = (asset) => transformData(pascalToCamelCaseKeys(asset), AssetMap);
4402
5307
  return PaginationHelpers.getAll({
4403
5308
  serviceAccess: this.createPaginationServiceAccess(),
4404
- getEndpoint: (folderId) => folderId ? QUEUE_ENDPOINTS.GET_BY_FOLDER : QUEUE_ENDPOINTS.GET_ALL,
4405
- getByFolderEndpoint: QUEUE_ENDPOINTS.GET_BY_FOLDER,
4406
- transformFn: transformQueueResponse,
5309
+ getEndpoint: (folderId) => folderId ? ASSET_ENDPOINTS.GET_BY_FOLDER : ASSET_ENDPOINTS.GET_ALL,
5310
+ getByFolderEndpoint: ASSET_ENDPOINTS.GET_BY_FOLDER,
5311
+ transformFn: transformAssetResponse,
4407
5312
  pagination: {
4408
5313
  paginationType: PaginationType.OFFSET,
4409
5314
  itemsField: ODATA_PAGINATION.ITEMS_FIELD,
@@ -4417,579 +5322,681 @@ class QueueService extends FolderScopedService {
4417
5322
  }, options);
4418
5323
  }
4419
5324
  /**
4420
- * Gets a single queue by ID
5325
+ * Gets a single asset by ID
4421
5326
  *
4422
- * @param id - Queue ID
5327
+ * @param id - Asset ID
4423
5328
  * @param folderId - Required folder ID
4424
- * @returns Promise resolving to a queue definition
5329
+ * @param options - Optional query parameters (expand, select)
5330
+ * @returns Promise resolving to a single asset
4425
5331
  *
4426
5332
  * @example
4427
5333
  * ```typescript
4428
- * // Get queue by ID
4429
- * const queue = await sdk.queues.getById(123, 456);
5334
+ * // Get asset by ID
5335
+ * const asset = await sdk.assets.getById(123, 456);
4430
5336
  * ```
4431
5337
  */
4432
5338
  async getById(id, folderId, options = {}) {
4433
5339
  const headers = createHeaders({ [FOLDER_ID]: folderId });
4434
5340
  const keysToPrefix = Object.keys(options);
4435
5341
  const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
4436
- const response = await this.get(QUEUE_ENDPOINTS.GET_BY_ID(id), {
5342
+ const response = await this.get(ASSET_ENDPOINTS.GET_BY_ID(id), {
4437
5343
  headers,
4438
5344
  params: apiOptions
4439
5345
  });
4440
- return transformData(pascalToCamelCaseKeys(response.data), QueueMap);
5346
+ const transformedAsset = transformData(pascalToCamelCaseKeys(response.data), AssetMap);
5347
+ return transformedAsset;
4441
5348
  }
4442
5349
  }
4443
5350
  __decorate([
4444
- track('Queues.GetAll')
4445
- ], QueueService.prototype, "getAll", null);
5351
+ track('Assets.GetAll')
5352
+ ], AssetService.prototype, "getAll", null);
4446
5353
  __decorate([
4447
- track('Queues.GetById')
4448
- ], QueueService.prototype, "getById", null);
4449
-
4450
- exports.TaskType = void 0;
4451
- (function (TaskType) {
4452
- TaskType["Form"] = "FormTask";
4453
- TaskType["External"] = "ExternalTask";
4454
- TaskType["App"] = "AppTask";
4455
- })(exports.TaskType || (exports.TaskType = {}));
4456
- exports.TaskPriority = void 0;
4457
- (function (TaskPriority) {
4458
- TaskPriority["Low"] = "Low";
4459
- TaskPriority["Medium"] = "Medium";
4460
- TaskPriority["High"] = "High";
4461
- TaskPriority["Critical"] = "Critical";
4462
- })(exports.TaskPriority || (exports.TaskPriority = {}));
4463
- exports.TaskStatus = void 0;
4464
- (function (TaskStatus) {
4465
- TaskStatus["Unassigned"] = "Unassigned";
4466
- TaskStatus["Pending"] = "Pending";
4467
- TaskStatus["Completed"] = "Completed";
4468
- })(exports.TaskStatus || (exports.TaskStatus = {}));
4469
- exports.TaskSlaCriteria = void 0;
4470
- (function (TaskSlaCriteria) {
4471
- TaskSlaCriteria["TaskCreated"] = "TaskCreated";
4472
- TaskSlaCriteria["TaskAssigned"] = "TaskAssigned";
4473
- TaskSlaCriteria["TaskCompleted"] = "TaskCompleted";
4474
- })(exports.TaskSlaCriteria || (exports.TaskSlaCriteria = {}));
4475
- exports.TaskSlaStatus = void 0;
4476
- (function (TaskSlaStatus) {
4477
- TaskSlaStatus["OverdueLater"] = "OverdueLater";
4478
- TaskSlaStatus["OverdueSoon"] = "OverdueSoon";
4479
- TaskSlaStatus["Overdue"] = "Overdue";
4480
- TaskSlaStatus["CompletedInTime"] = "CompletedInTime";
4481
- })(exports.TaskSlaStatus || (exports.TaskSlaStatus = {}));
4482
- exports.TaskSourceName = void 0;
4483
- (function (TaskSourceName) {
4484
- TaskSourceName["Agent"] = "Agent";
4485
- TaskSourceName["Workflow"] = "Workflow";
4486
- TaskSourceName["Maestro"] = "Maestro";
4487
- TaskSourceName["Default"] = "Default";
4488
- })(exports.TaskSourceName || (exports.TaskSourceName = {}));
4489
-
4490
- /**
4491
- * Creates methods for a task
4492
- *
4493
- * @param taskData - The task data (response from API)
4494
- * @param service - The task service instance
4495
- * @returns Object containing task methods
4496
- */
4497
- function createTaskMethods(taskData, service) {
4498
- return {
4499
- async assign(options) {
4500
- if (!taskData.id)
4501
- throw new Error('Task ID is undefined');
4502
- const assignmentOptions = {
4503
- taskId: taskData.id,
4504
- userId: options.userId || 0, // Will be handled by userNameOrEmail if userId is not provided, 0 is considered as invalid user id
4505
- userNameOrEmail: options.userNameOrEmail
4506
- };
4507
- return service.assign(assignmentOptions, taskData.organizationUnitId);
4508
- },
4509
- async reassign(options) {
4510
- if (!taskData.id)
4511
- throw new Error('Task ID is undefined');
4512
- const assignmentOptions = {
4513
- taskId: taskData.id,
4514
- userId: options.userId || 0, // Will be handled by userNameOrEmail if userId is not provided, 0 is considered as invalid user id
4515
- userNameOrEmail: options.userNameOrEmail
4516
- };
4517
- return service.reassign(assignmentOptions, taskData.organizationUnitId);
4518
- },
4519
- async unassign() {
4520
- if (!taskData.id)
4521
- throw new Error('Task ID is undefined');
4522
- return service.unassign(taskData.id, taskData.organizationUnitId);
4523
- },
4524
- async complete(options) {
4525
- if (!taskData.id)
4526
- throw new Error('Task ID is undefined');
4527
- const folderId = taskData.organizationUnitId;
4528
- if (!folderId)
4529
- throw new Error('Folder ID is required');
4530
- return service.complete(options.type, {
4531
- taskId: taskData.id,
4532
- data: options.data,
4533
- action: options.action
4534
- }, folderId);
4535
- }
4536
- };
4537
- }
4538
- /**
4539
- * Creates an actionable task by combining API task data with operational methods.
4540
- *
4541
- * @param taskData - The task data from API
4542
- * @param service - The task service instance
4543
- * @returns A task object with added methods
4544
- */
4545
- function createTaskWithMethods(taskData, service) {
4546
- const methods = createTaskMethods(taskData, service);
4547
- return Object.assign({}, taskData, methods);
4548
- }
5354
+ track('Assets.GetById')
5355
+ ], AssetService.prototype, "getById", null);
4549
5356
 
4550
5357
  /**
4551
- * Maps numeric TaskStatus values (from API) to TaskStatus enum values.
4552
- * Extend this file with additional field mappings as needed.
5358
+ * Maps fields for Bucket entities to ensure consistent naming
4553
5359
  */
4554
- const TaskStatusMap = {
4555
- 0: exports.TaskStatus.Unassigned,
4556
- 1: exports.TaskStatus.Pending,
4557
- 2: exports.TaskStatus.Completed,
4558
- };
4559
- // Field mapping for time-related fields to ensure consistent naming
4560
- const TaskTimeMap = {
4561
- completionTime: 'completedTime',
4562
- deletionTime: 'deletedTime',
4563
- lastModificationTime: 'lastModifiedTime',
4564
- creationTime: 'createdTime',
5360
+ const BucketMap = {
5361
+ fullPath: 'path',
5362
+ items: 'blobItems',
5363
+ verb: 'httpMethod'
4565
5364
  };
4566
5365
 
4567
- /**
4568
- * Service for interacting with UiPath Tasks API
4569
- */
4570
- class TaskService extends BaseService {
5366
+ class BucketService extends FolderScopedService {
4571
5367
  /**
4572
5368
  * @hideconstructor
4573
5369
  */
4574
5370
  constructor(config, executionContext, tokenManager) {
4575
5371
  super(config, executionContext, tokenManager);
4576
- /**
4577
- * Process parameters for task queries with folder filtering
4578
- * @param options - The REST API options to process
4579
- * @param folderId - Optional folder ID to filter by
4580
- * @returns Processed options with folder filtering applied if needed
4581
- * @private
4582
- */
4583
- this.processTaskParameters = (options, folderId) => {
4584
- const processedOptions = { ...options };
4585
- if (folderId) {
4586
- // Create or add to existing filter for folder-specific queries
4587
- if (processedOptions.filter) {
4588
- processedOptions.filter = `${processedOptions.filter} and organizationUnitId eq ${folderId}`;
4589
- }
4590
- else {
4591
- processedOptions.filter = `organizationUnitId eq ${folderId}`;
4592
- }
4593
- }
4594
- return processedOptions;
4595
- };
5372
+ this.tokenManager = tokenManager;
4596
5373
  }
4597
5374
  /**
4598
- * Creates a new task
4599
- * @param task - The task to be created
4600
- * @param folderId - Required folder ID
4601
- * @returns Promise resolving to the created task
4602
- *
4603
- * @example
4604
- * ```typescript
4605
- * const task = await sdk.tasks.create({
4606
- * title: "My Task",
4607
- * priority: TaskPriority.Medium,
4608
- * data: { key: "value" }
4609
- * }, 123); // folderId is required
4610
- * ```
5375
+ * Gets a bucket by ID
5376
+ * @param bucketId - The ID of the bucket to retrieve
5377
+ * @param folderId - Folder ID for organization unit context
5378
+ * @param options - Optional query parameters (expand, select)
5379
+ * @returns Promise resolving to the bucket
5380
+ *
5381
+ * @example
5382
+ * ```typescript
5383
+ * // Get bucket by ID
5384
+ * const bucket = await sdk.buckets.getById(123, 456);
5385
+ * ```
5386
+ */
5387
+ async getById(id, folderId, options = {}) {
5388
+ if (!id) {
5389
+ throw new ValidationError({ message: 'bucketId is required for getById' });
5390
+ }
5391
+ if (!folderId) {
5392
+ throw new ValidationError({ message: 'folderId is required for getById' });
5393
+ }
5394
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
5395
+ // Prefix all keys in options with $ for OData
5396
+ const keysToPrefix = Object.keys(options);
5397
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
5398
+ const response = await this.get(BUCKET_ENDPOINTS.GET_BY_ID(id), {
5399
+ params: apiOptions,
5400
+ headers
5401
+ });
5402
+ // Transform response from PascalCase to camelCase
5403
+ return pascalToCamelCaseKeys(response.data);
5404
+ }
5405
+ /**
5406
+ * Gets all buckets across folders with optional filtering and folder scoping
5407
+ *
5408
+ * The method returns either:
5409
+ * - An array of buckets (when no pagination parameters are provided)
5410
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
5411
+ *
5412
+ * @param options - Query options including optional folderId
5413
+ * @returns Promise resolving to an array of buckets or paginated result
5414
+ *
5415
+ * @example
5416
+ * ```typescript
5417
+ * // Get all buckets across folders
5418
+ * const buckets = await sdk.buckets.getAll();
5419
+ *
5420
+ * // Get buckets within a specific folder
5421
+ * const buckets = await sdk.buckets.getAll({
5422
+ * folderId: 123
5423
+ * });
5424
+ *
5425
+ * // Get buckets with filtering
5426
+ * const buckets = await sdk.buckets.getAll({
5427
+ * filter: "name eq 'MyBucket'"
5428
+ * });
5429
+ *
5430
+ * // First page with pagination
5431
+ * const page1 = await sdk.buckets.getAll({ pageSize: 10 });
5432
+ *
5433
+ * // Navigate using cursor
5434
+ * if (page1.hasNextPage) {
5435
+ * const page2 = await sdk.buckets.getAll({ cursor: page1.nextCursor });
5436
+ * }
5437
+ *
5438
+ * // Jump to specific page
5439
+ * const page5 = await sdk.buckets.getAll({
5440
+ * jumpToPage: 5,
5441
+ * pageSize: 10
5442
+ * });
5443
+ * ```
5444
+ */
5445
+ async getAll(options) {
5446
+ // Transformation function for buckets
5447
+ const transformBucketResponse = (bucket) => pascalToCamelCaseKeys(bucket);
5448
+ return PaginationHelpers.getAll({
5449
+ serviceAccess: this.createPaginationServiceAccess(),
5450
+ getEndpoint: (folderId) => folderId ? BUCKET_ENDPOINTS.GET_BY_FOLDER : BUCKET_ENDPOINTS.GET_ALL,
5451
+ getByFolderEndpoint: BUCKET_ENDPOINTS.GET_BY_FOLDER,
5452
+ transformFn: transformBucketResponse,
5453
+ pagination: {
5454
+ paginationType: PaginationType.OFFSET,
5455
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
5456
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
5457
+ paginationParams: {
5458
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
5459
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
5460
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
5461
+ }
5462
+ }
5463
+ }, options);
5464
+ }
5465
+ /**
5466
+ * Gets metadata for files in a bucket with optional filtering and pagination
5467
+ *
5468
+ * The method returns either:
5469
+ * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
5470
+ * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
5471
+ *
5472
+ * @param bucketId - The ID of the bucket to get file metadata from
5473
+ * @param folderId - Required folder ID for organization unit context
5474
+ * @param options - Optional parameters for filtering, pagination and access URL generation
5475
+ * @returns Promise resolving to the list of file metadata in the bucket or paginated result
5476
+ *
5477
+ * @example
5478
+ * ```typescript
5479
+ * // Get metadata for all files in a bucket
5480
+ * const fileMetadata = await sdk.buckets.getFileMetaData(123, 456);
5481
+ *
5482
+ * // Get file metadata with a specific prefix
5483
+ * const fileMetadata = await sdk.buckets.getFileMetaData(123, 456, {
5484
+ * prefix: '/folder1'
5485
+ * });
5486
+ *
5487
+ * // First page with pagination
5488
+ * const page1 = await sdk.buckets.getFileMetaData(123, 456, { pageSize: 10 });
5489
+ *
5490
+ * // Navigate using cursor
5491
+ * if (page1.hasNextPage) {
5492
+ * const page2 = await sdk.buckets.getFileMetaData(123, 456, { cursor: page1.nextCursor });
5493
+ * }
5494
+ * ```
5495
+ */
5496
+ async getFileMetaData(bucketId, folderId, options) {
5497
+ if (!bucketId) {
5498
+ throw new ValidationError({ message: 'bucketId is required for getFileMetaData' });
5499
+ }
5500
+ if (!folderId) {
5501
+ throw new ValidationError({ message: 'folderId is required for getFileMetaData' });
5502
+ }
5503
+ // Transformation function for blob items
5504
+ const transformBlobItem = (item) => transformData(item, BucketMap);
5505
+ return PaginationHelpers.getAll({
5506
+ serviceAccess: this.createPaginationServiceAccess(),
5507
+ getEndpoint: () => BUCKET_ENDPOINTS.GET_FILE_META_DATA(bucketId),
5508
+ transformFn: transformBlobItem,
5509
+ pagination: {
5510
+ paginationType: PaginationType.TOKEN,
5511
+ itemsField: BUCKET_PAGINATION.ITEMS_FIELD,
5512
+ continuationTokenField: BUCKET_PAGINATION.CONTINUATION_TOKEN_FIELD,
5513
+ paginationParams: {
5514
+ pageSizeParam: BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM,
5515
+ tokenParam: BUCKET_TOKEN_PARAMS.TOKEN_PARAM
5516
+ }
5517
+ },
5518
+ excludeFromPrefix: ['prefix'] // Bucket-specific param, not OData
5519
+ }, { ...options, folderId });
5520
+ }
5521
+ /**
5522
+ * Uploads a file to a bucket
5523
+ *
5524
+ * @param options - Options for file upload including bucket ID, folder ID, path, content, and optional parameters
5525
+ * @returns Promise resolving to a response with success status and HTTP status code
5526
+ *
5527
+ * @example
5528
+ * ```typescript
5529
+ * // Upload a file from browser
5530
+ * const file = new File(['file content'], 'example.txt');
5531
+ * const result = await sdk.buckets.uploadFile({
5532
+ * bucketId: 123,
5533
+ * folderId: 456,
5534
+ * path: '/folder/example.txt',
5535
+ * content: file
5536
+ * });
5537
+ *
5538
+ * // In Node env with Buffer
5539
+ * const buffer = Buffer.from('file content');
5540
+ * const result = await sdk.buckets.uploadFile({
5541
+ * bucketId: 123,
5542
+ * folderId: 456,
5543
+ * path: '/folder/example.txt',
5544
+ * content: buffer
5545
+ * });
5546
+ * ```
5547
+ */
5548
+ async uploadFile(options) {
5549
+ const { bucketId, folderId, path, content } = options;
5550
+ if (!bucketId) {
5551
+ throw new ValidationError({ message: 'bucketId is required for uploadFile' });
5552
+ }
5553
+ if (!folderId) {
5554
+ throw new ValidationError({ message: 'folderId is required for uploadFile' });
5555
+ }
5556
+ if (!path) {
5557
+ throw new ValidationError({ message: 'path is required for uploadFile' });
5558
+ }
5559
+ if (!content) {
5560
+ throw new ValidationError({ message: 'content is required for uploadFile' });
5561
+ }
5562
+ try {
5563
+ const uriResponse = await this._getWriteUri({
5564
+ bucketId,
5565
+ folderId,
5566
+ path,
5567
+ });
5568
+ // Upload file to the provided URI
5569
+ const response = await this._uploadToUri(uriResponse, content);
5570
+ return {
5571
+ success: response.status >= 200 && response.status < 300,
5572
+ statusCode: response.status
5573
+ };
5574
+ }
5575
+ catch (error) {
5576
+ throw error;
5577
+ }
5578
+ }
5579
+ /**
5580
+ * Gets a direct download URL for a file in the bucket
5581
+ *
5582
+ * @param options - Contains bucketId, folderId, file path and optional expiry time
5583
+ * @returns Promise resolving to blob file access information
5584
+ *
5585
+ * @example
5586
+ * ```typescript
5587
+ * // Get download URL for a file
5588
+ * const fileAccess = await sdk.buckets.getReadUri({
5589
+ * bucketId: 123,
5590
+ * folderId: 456,
5591
+ * path: '/folder/file.pdf'
5592
+ * });
5593
+ * ```
5594
+ */
5595
+ async getReadUri(options) {
5596
+ const { bucketId, folderId, path, expiryInMinutes, ...restOptions } = options;
5597
+ const queryOptions = {
5598
+ expiryInMinutes,
5599
+ ...addPrefixToKeys(restOptions, ODATA_PREFIX, Object.keys(restOptions))
5600
+ };
5601
+ return this._getUri(BUCKET_ENDPOINTS.GET_READ_URI(bucketId), bucketId, folderId, path, queryOptions);
5602
+ }
5603
+ /**
5604
+ * Uploads content to the provided URI
5605
+ * @param uriResponse - Response from getWriteUri containing URL and headers
5606
+ * @param content - The content to upload
5607
+ * @returns The response from the upload request with status info
5608
+ */
5609
+ async _uploadToUri(uriResponse, content) {
5610
+ const { uri, headers = {}, requiresAuth } = uriResponse;
5611
+ if (!uri) {
5612
+ throw new ValidationError({ message: 'Upload URI not available', statusCode: HttpStatus.BAD_REQUEST });
5613
+ }
5614
+ // Create headers for the request
5615
+ let requestHeaders = { ...headers };
5616
+ // Add auth header if required
5617
+ if (requiresAuth) {
5618
+ try {
5619
+ const tokenInfo = this.executionContext.get('tokenInfo');
5620
+ if (!tokenInfo) {
5621
+ throw new AuthenticationError({ message: 'No authentication token available. Make sure to initialize the SDK first.' });
5622
+ }
5623
+ let token;
5624
+ // For secret-based tokens, they never expire so use directly
5625
+ if (tokenInfo.type === 'secret') {
5626
+ token = tokenInfo.token;
5627
+ }
5628
+ // For non-secret tokens, check expiration and refresh if needed
5629
+ else if (!this.tokenManager.isTokenExpired(tokenInfo)) {
5630
+ token = tokenInfo.token;
5631
+ }
5632
+ else {
5633
+ const newToken = await this.tokenManager.refreshAccessToken();
5634
+ token = newToken.access_token;
5635
+ }
5636
+ requestHeaders['Authorization'] = `Bearer ${token}`;
5637
+ }
5638
+ catch (error) {
5639
+ throw new AuthenticationError({
5640
+ message: `Authentication required but failed: ${error instanceof Error ? error.message : ''}`,
5641
+ statusCode: HttpStatus.UNAUTHORIZED
5642
+ });
5643
+ }
5644
+ }
5645
+ return axios.put(uri, content, {
5646
+ headers: createHeaders(requestHeaders)
5647
+ });
5648
+ }
5649
+ /**
5650
+ * Private method to handle common URI request logic
5651
+ * @param endpoint - The API endpoint to call
5652
+ * @param bucketId - The bucket ID
5653
+ * @param folderId - The folder ID
5654
+ * @param path - The file path
5655
+ * @param queryOptions - Additional query parameters
5656
+ * @returns Promise resolving to blob file access information
5657
+ */
5658
+ async _getUri(endpoint, bucketId, folderId, path, queryOptions = {}) {
5659
+ if (!bucketId) {
5660
+ throw new ValidationError({ message: 'bucketId is required for getUri' });
5661
+ }
5662
+ if (!folderId) {
5663
+ throw new ValidationError({ message: 'folderId is required for getUri' });
5664
+ }
5665
+ if (!path) {
5666
+ throw new ValidationError({ message: 'path is required for getUri' });
5667
+ }
5668
+ // Create headers with required folder ID
5669
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
5670
+ // Filter out undefined values and build query params
5671
+ const queryParams = filterUndefined({
5672
+ path,
5673
+ ...queryOptions
5674
+ });
5675
+ // Make the API call to get URI
5676
+ const response = await this.get(endpoint, {
5677
+ params: queryParams,
5678
+ headers
5679
+ });
5680
+ const transformedData = transformData(pascalToCamelCaseKeys(response.data), BucketMap);
5681
+ // Convert headers from array-based to record if needed
5682
+ if (transformedData.headers && 'keys' in transformedData.headers && 'values' in transformedData.headers) {
5683
+ transformedData.headers = arrayDictionaryToRecord(transformedData.headers);
5684
+ }
5685
+ return transformedData;
5686
+ }
5687
+ /**
5688
+ * Gets a direct upload URL for a file in the bucket
5689
+ *
5690
+ * @param options - Contains bucketId, folderId, file path, optional expiry time
5691
+ * @returns Promise resolving to blob file access information
5692
+ */
5693
+ async _getWriteUri(options) {
5694
+ const { bucketId, folderId, path, expiryInMinutes, ...restOptions } = options;
5695
+ const queryOptions = {
5696
+ expiryInMinutes,
5697
+ ...addPrefixToKeys(restOptions, ODATA_PREFIX, Object.keys(restOptions))
5698
+ };
5699
+ return this._getUri(BUCKET_ENDPOINTS.GET_WRITE_URI(bucketId), bucketId, folderId, path, queryOptions);
5700
+ }
5701
+ }
5702
+ __decorate([
5703
+ track('Buckets.GetById')
5704
+ ], BucketService.prototype, "getById", null);
5705
+ __decorate([
5706
+ track('Buckets.GetAll')
5707
+ ], BucketService.prototype, "getAll", null);
5708
+ __decorate([
5709
+ track('Buckets.GetFileMetaData')
5710
+ ], BucketService.prototype, "getFileMetaData", null);
5711
+ __decorate([
5712
+ track('Buckets.UploadFile')
5713
+ ], BucketService.prototype, "uploadFile", null);
5714
+ __decorate([
5715
+ track('Buckets.GetReadUri')
5716
+ ], BucketService.prototype, "getReadUri", null);
5717
+
5718
+ /**
5719
+ * Maps fields for Process entities to ensure consistent naming
5720
+ */
5721
+ const ProcessMap = {
5722
+ lastModificationTime: 'lastModifiedTime',
5723
+ creationTime: 'createdTime',
5724
+ organizationUnitId: 'folderId',
5725
+ organizationUnitFullyQualifiedName: 'folderName',
5726
+ releaseKey: 'processKey',
5727
+ releaseName: 'processName',
5728
+ releaseVersionId: 'processVersionId',
5729
+ processType: 'packageType',
5730
+ processKey: 'packageKey',
5731
+ processVersion: 'packageVersion',
5732
+ isProcessDeleted: 'isPackageDeleted',
5733
+ };
5734
+
5735
+ /**
5736
+ * Service for interacting with UiPath Orchestrator Processes API
5737
+ */
5738
+ class ProcessService extends BaseService {
5739
+ /**
5740
+ * @hideconstructor
4611
5741
  */
4612
- async create(task, folderId) {
4613
- const headers = createHeaders({ [FOLDER_ID]: folderId });
4614
- const externalTask = {
4615
- ...task,
4616
- type: exports.TaskType.External //currently only external task is supported
4617
- };
4618
- const response = await this.post(TASK_ENDPOINTS.CREATE_GENERIC_TASK, externalTask, { headers });
4619
- // Transform time fields for consistency
4620
- const normalizedData = transformData(response.data, TaskTimeMap);
4621
- const transformedData = applyDataTransforms(normalizedData, { field: 'status', valueMap: TaskStatusMap });
4622
- return createTaskWithMethods(transformedData, this);
5742
+ constructor(config, executionContext, tokenManager) {
5743
+ super(config, executionContext, tokenManager);
4623
5744
  }
4624
5745
  /**
4625
- * Gets users in the given folder who have Tasks.View and Tasks.Edit permissions
5746
+ * Gets all processes across folders with optional filtering and folder scoping
4626
5747
  *
4627
5748
  * The method returns either:
4628
- * - An array of users (when no pagination parameters are provided)
5749
+ * - An array of processes (when no pagination parameters are provided)
4629
5750
  * - A paginated result with navigation cursors (when any pagination parameter is provided)
4630
5751
  *
4631
- * @param folderId - The folder ID to get users from
4632
- * @param options - Optional query and pagination parameters
4633
- * @returns Promise resolving to an array of users or paginated result
5752
+ * @param options - Query options including optional folderId
5753
+ * @returns Promise resolving to an array of processes or paginated result
4634
5754
  *
4635
5755
  * @example
4636
5756
  * ```typescript
4637
5757
  * // Standard array return
4638
- * const users = await sdk.tasks.getUsers(123);
4639
- *
4640
- * // Get users with filtering
4641
- * const users = await sdk.tasks.getUsers(123, {
4642
- * filter: "name eq 'abc'"
4643
- * });
4644
- *
4645
- * // First page with pagination
4646
- * const page1 = await sdk.tasks.getUsers(123, { pageSize: 10 });
4647
- *
4648
- * // Navigate using cursor
4649
- * if (page1.hasNextPage) {
4650
- * const page2 = await sdk.tasks.getUsers(123, { cursor: page1.nextCursor });
4651
- * }
5758
+ * const processes = await sdk.processes.getAll();
4652
5759
  *
4653
- * // Jump to specific page
4654
- * const page5 = await sdk.tasks.getUsers(123, {
4655
- * jumpToPage: 5,
4656
- * pageSize: 10
5760
+ * // Get processes within a specific folder
5761
+ * const processes = await sdk.processes.getAll({
5762
+ * folderId: 123
4657
5763
  * });
4658
- * ```
4659
- */
4660
- async getUsers(folderId, options) {
4661
- // Transformation function for users
4662
- const transformUserResponse = (user) => pascalToCamelCaseKeys(user);
4663
- // Add folderId to options so the centralized helper can handle it properly
4664
- const optionsWithFolder = { ...options, folderId };
4665
- return PaginationHelpers.getAll({
4666
- serviceAccess: this.createPaginationServiceAccess(),
4667
- getEndpoint: (folderId) => TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use folderId from centralized helper
4668
- getByFolderEndpoint: TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use the passed folderId
4669
- transformFn: transformUserResponse,
4670
- pagination: {
4671
- paginationType: PaginationType.OFFSET,
4672
- itemsField: ODATA_PAGINATION.ITEMS_FIELD,
4673
- totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
4674
- paginationParams: {
4675
- pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
4676
- offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
4677
- countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
4678
- }
4679
- }
4680
- }, optionsWithFolder);
4681
- }
4682
- /**
4683
- * Gets tasks across folders with optional filtering and folder scoping
4684
- *
4685
- * The method returns either:
4686
- * - An array of tasks (when no pagination parameters are provided)
4687
- * - A paginated result with navigation cursors (when any pagination parameter is provided)
4688
5764
  *
4689
- * @param options - Query options including optional folderId and pagination options
4690
- * @returns Promise resolving to an array of tasks or paginated result
4691
- *
4692
- * @example
4693
- * ```typescript
4694
- * // Standard array return
4695
- * const tasks = await sdk.tasks.getAll();
4696
- *
4697
- * // Get tasks within a specific folder
4698
- * const tasks = await sdk.tasks.getAll({
4699
- * folderId: 123
5765
+ * // Get processes with filtering
5766
+ * const processes = await sdk.processes.getAll({
5767
+ * filter: "name eq 'MyProcess'"
4700
5768
  * });
4701
5769
  *
4702
5770
  * // First page with pagination
4703
- * const page1 = await sdk.tasks.getAll({ pageSize: 10 });
5771
+ * const page1 = await sdk.processes.getAll({ pageSize: 10 });
4704
5772
  *
4705
5773
  * // Navigate using cursor
4706
5774
  * if (page1.hasNextPage) {
4707
- * const page2 = await sdk.tasks.getAll({ cursor: page1.nextCursor });
5775
+ * const page2 = await sdk.processes.getAll({ cursor: page1.nextCursor });
4708
5776
  * }
4709
5777
  *
4710
5778
  * // Jump to specific page
4711
- * const page5 = await sdk.tasks.getAll({
5779
+ * const page5 = await sdk.processes.getAll({
4712
5780
  * jumpToPage: 5,
4713
5781
  * pageSize: 10
4714
5782
  * });
4715
5783
  * ```
4716
5784
  */
4717
5785
  async getAll(options) {
4718
- // Transformation function for tasks
4719
- const transformTaskResponse = (task) => {
4720
- const transformedTask = transformData(pascalToCamelCaseKeys(task), TaskTimeMap);
4721
- return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
4722
- };
5786
+ // Transformation function for processes
5787
+ const transformProcessResponse = (process) => transformData(pascalToCamelCaseKeys(process), ProcessMap);
4723
5788
  return PaginationHelpers.getAll({
4724
5789
  serviceAccess: this.createPaginationServiceAccess(),
4725
- getEndpoint: () => TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS,
4726
- transformFn: transformTaskResponse,
4727
- processParametersFn: this.processTaskParameters,
4728
- excludeFromPrefix: ['event'], // Exclude 'event' key from ODATA prefix transformation
5790
+ getEndpoint: () => PROCESS_ENDPOINTS.GET_ALL,
5791
+ getByFolderEndpoint: PROCESS_ENDPOINTS.GET_ALL, // Processes use same endpoint for both
5792
+ transformFn: transformProcessResponse,
4729
5793
  pagination: {
4730
5794
  paginationType: PaginationType.OFFSET,
4731
5795
  itemsField: ODATA_PAGINATION.ITEMS_FIELD,
4732
5796
  totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
4733
5797
  paginationParams: {
4734
- pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM, // OData OFFSET parameter
4735
- offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM, // OData OFFSET parameter
4736
- countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM // OData OFFSET parameter
5798
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
5799
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
5800
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
4737
5801
  }
4738
5802
  }
4739
5803
  }, options);
4740
5804
  }
4741
5805
  /**
4742
- * Gets a task by ID
5806
+ * Starts a process execution (job)
4743
5807
  *
4744
- * @param id - The ID of the task to retrieve
5808
+ * @param request - Process start request body
5809
+ * @param folderId - Required folder ID
4745
5810
  * @param options - Optional query parameters
4746
- * @param folderId - Optional folder ID
4747
- * @returns Promise resolving to the task (form tasks will return form-specific data)
4748
- *
4749
- * @example
4750
- * ```typescript
4751
- * // Get task by ID
4752
- * const task = await sdk.tasks.getById(123);
4753
- *
4754
- * // If the task is a form task, it will automatically return form-specific data
4755
- * ```
4756
- */
4757
- async getById(id, options = {}, folderId) {
4758
- const headers = createHeaders({ [FOLDER_ID]: folderId });
4759
- // prefix all keys in options
4760
- const keysToPrefix = Object.keys(options);
4761
- const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
4762
- const response = await this.get(TASK_ENDPOINTS.GET_BY_ID(id), {
4763
- params: apiOptions,
4764
- headers
4765
- });
4766
- // Transform response from PascalCase to camelCase and normalize time fields
4767
- const transformedTask = transformData(pascalToCamelCaseKeys(response.data), TaskTimeMap);
4768
- // Check if this is a form task and get form-specific data if it is
4769
- if (transformedTask.type === exports.TaskType.Form) {
4770
- const formOptions = { expandOnFormLayout: true };
4771
- return this.getFormTaskById(id, folderId || transformedTask.organizationUnitId, formOptions);
4772
- }
4773
- return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
4774
- }
4775
- /**
4776
- * Assigns tasks to users
4777
- *
4778
- * @param taskAssignments - Single task assignment or array of task assignments
4779
- * @param folderId - Optional folder ID
4780
- * @returns Promise resolving to array of task assignment results
4781
- *
4782
- * @example
4783
- * ```typescript
4784
- * // Assign a single task to a user by ID
4785
- * const result = await sdk.tasks.assign({
4786
- * taskId: 123,
4787
- * userId: 456
4788
- * });
4789
- *
4790
- * // Assign a single task to a user by email
4791
- * const result = await sdk.tasks.assign({
4792
- * taskId: 123,
4793
- * userNameOrEmail: "user@example.com"
4794
- * });
4795
- *
4796
- * // Assign multiple tasks
4797
- * const result = await sdk.tasks.assign([
4798
- * {
4799
- * taskId: 123,
4800
- * userId: 456
4801
- * },
4802
- * {
4803
- * taskId: 789,
4804
- * userNameOrEmail: "user@example.com"
4805
- * }
4806
- * ]);
4807
- * ```
4808
- */
4809
- async assign(taskAssignments, folderId) {
4810
- const headers = createHeaders({ [FOLDER_ID]: folderId });
4811
- // Normalize input to array
4812
- const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
4813
- const options = {
4814
- taskAssignments: assignmentArray
4815
- };
4816
- // Convert options to PascalCase for API
4817
- const pascalOptions = camelToPascalCaseKeys(options);
4818
- const response = await this.post(TASK_ENDPOINTS.ASSIGN_TASKS, pascalOptions, { headers });
4819
- // Transform response from PascalCase to camelCase
4820
- const transformedResponse = pascalToCamelCaseKeys(response.data);
4821
- // Process OData array response - empty array = success, non-empty = error
4822
- return processODataArrayResponse(transformedResponse, assignmentArray);
4823
- }
4824
- /**
4825
- * Reassigns tasks to new users
4826
- *
4827
- * @param taskAssignments - Single task assignment or array of task assignments
4828
- * @param folderId - Optional folder ID
4829
- * @returns Promise resolving to array of task assignment results
5811
+ * @returns Promise resolving to the created jobs
4830
5812
  *
4831
5813
  * @example
4832
5814
  * ```typescript
4833
- * // Reassign a single task to a user by ID
4834
- * const result = await sdk.tasks.reassign({
4835
- * taskId: 123,
4836
- * userId: 456
4837
- * });
4838
- *
4839
- * // Reassign a single task to a user by email
4840
- * const result = await sdk.tasks.reassign({
4841
- * taskId: 123,
4842
- * userNameOrEmail: "user@example.com"
4843
- * });
5815
+ * // Start a process by process key
5816
+ * const jobs = await sdk.processes.start({
5817
+ * processKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
5818
+ * }, 123); // folderId is required
4844
5819
  *
4845
- * // Reassign multiple tasks
4846
- * const result = await sdk.tasks.reassign([
4847
- * {
4848
- * taskId: 123,
4849
- * userId: 456
4850
- * },
4851
- * {
4852
- * taskId: 789,
4853
- * userNameOrEmail: "user@example.com"
4854
- * }
4855
- * ]);
5820
+ * // Start a process by name with specific robots
5821
+ * const jobs = await sdk.processes.start({
5822
+ * processName: "MyProcess"
5823
+ * }, 123); // folderId is required
4856
5824
  * ```
4857
5825
  */
4858
- async reassign(taskAssignments, folderId) {
5826
+ async start(request, folderId, options = {}) {
4859
5827
  const headers = createHeaders({ [FOLDER_ID]: folderId });
4860
- // Normalize input to array
4861
- const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
4862
- const options = {
4863
- taskAssignments: assignmentArray
5828
+ // Transform processKey/processName to releaseKey/releaseName for API compatibility
5829
+ const apiRequest = { ...request };
5830
+ // Create a reverse mapping using ProcessMap
5831
+ const reversedPropertiesMap = reverseMap(ProcessMap);
5832
+ // Apply transformations for any client properties found in the request
5833
+ Object.entries(reversedPropertiesMap).forEach(([clientKey, apiKey]) => {
5834
+ if (clientKey in apiRequest) {
5835
+ apiRequest[apiKey] = apiRequest[clientKey];
5836
+ delete apiRequest[clientKey];
5837
+ }
5838
+ });
5839
+ // Convert to PascalCase for API
5840
+ const pascalOptions = camelToPascalCaseKeys(apiRequest);
5841
+ // Create the request object according to API spec
5842
+ const requestBody = {
5843
+ startInfo: pascalOptions
4864
5844
  };
4865
- // Convert options to PascalCase for API
4866
- const pascalOptions = camelToPascalCaseKeys(options);
4867
- const response = await this.post(TASK_ENDPOINTS.REASSIGN_TASKS, pascalOptions, { headers });
4868
- // Transform response from PascalCase to camelCase
4869
- const transformedResponse = pascalToCamelCaseKeys(response.data);
4870
- // Process OData array response - empty array = success, non-empty = error
4871
- return processODataArrayResponse(transformedResponse, assignmentArray);
5845
+ // Prefix all query parameter keys with '$' for OData
5846
+ const keysToPrefix = Object.keys(options);
5847
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
5848
+ const response = await this.post(PROCESS_ENDPOINTS.START_PROCESS, requestBody, {
5849
+ params: apiOptions,
5850
+ headers
5851
+ });
5852
+ const transformedProcess = response.data?.value.map(process => transformData(pascalToCamelCaseKeys(process), ProcessMap));
5853
+ return transformedProcess;
4872
5854
  }
4873
5855
  /**
4874
- * Unassigns tasks (removes current assignees)
5856
+ * Gets a single process by ID
4875
5857
  *
4876
- * @param taskIds - Single task ID or array of task IDs to unassign
4877
- * @param folderId - Optional folder ID
4878
- * @returns Promise resolving to array of task assignment results
5858
+ * @param id - Process ID
5859
+ * @param folderId - Required folder ID
5860
+ * @param options - Optional query parameters
5861
+ * @returns Promise resolving to a single process
4879
5862
  *
4880
5863
  * @example
4881
5864
  * ```typescript
4882
- * // Unassign a single task
4883
- * const result = await sdk.tasks.unassign(123);
4884
- *
4885
- * // Unassign multiple tasks
4886
- * const result = await sdk.tasks.unassign([123, 456, 789]);
5865
+ * // Get process by ID
5866
+ * const process = await sdk.processes.getById(123, 456);
4887
5867
  * ```
4888
5868
  */
4889
- async unassign(taskIds, folderId) {
5869
+ async getById(id, folderId, options = {}) {
4890
5870
  const headers = createHeaders({ [FOLDER_ID]: folderId });
4891
- // Normalize input to array
4892
- const taskIdArray = Array.isArray(taskIds) ? taskIds : [taskIds];
4893
- const options = {
4894
- taskIds: taskIdArray
4895
- };
4896
- const response = await this.post(TASK_ENDPOINTS.UNASSIGN_TASKS, options, { headers });
4897
- // Transform response from PascalCase to camelCase
4898
- const transformedResponse = pascalToCamelCaseKeys(response.data);
4899
- // Process OData array response - empty array = success, non-empty = error
4900
- // Return the task IDs that were unassigned
4901
- return processODataArrayResponse(transformedResponse, taskIdArray.map(id => ({ taskId: id })));
5871
+ const keysToPrefix = Object.keys(options);
5872
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
5873
+ const response = await this.get(PROCESS_ENDPOINTS.GET_BY_ID(id), {
5874
+ headers,
5875
+ params: apiOptions
5876
+ });
5877
+ const transformedProcess = transformData(pascalToCamelCaseKeys(response.data), ProcessMap);
5878
+ return transformedProcess;
5879
+ }
5880
+ }
5881
+ __decorate([
5882
+ track('Processes.GetAll')
5883
+ ], ProcessService.prototype, "getAll", null);
5884
+ __decorate([
5885
+ track('Processes.Start')
5886
+ ], ProcessService.prototype, "start", null);
5887
+ __decorate([
5888
+ track('Processes.GetById')
5889
+ ], ProcessService.prototype, "getById", null);
5890
+
5891
+ /**
5892
+ * Maps fields for Queue entities to ensure consistent naming
5893
+ */
5894
+ const QueueMap = {
5895
+ creationTime: 'createdTime',
5896
+ organizationUnitId: 'folderId',
5897
+ organizationUnitFullyQualifiedName: 'folderName'
5898
+ };
5899
+
5900
+ /**
5901
+ * Service for interacting with UiPath Orchestrator Queues API
5902
+ */
5903
+ class QueueService extends FolderScopedService {
5904
+ /**
5905
+ * @hideconstructor
5906
+ */
5907
+ constructor(config, executionContext, tokenManager) {
5908
+ super(config, executionContext, tokenManager);
4902
5909
  }
4903
5910
  /**
4904
- * Completes a task with the specified type and data
5911
+ * Gets all queues across folders with optional filtering and folder scoping
4905
5912
  *
4906
- * @param completionType - The type of task (Form, App, or Generic)
4907
- * @param options - The completion options
4908
- * @param folderId - Required folder ID
4909
- * @returns Promise resolving to void
5913
+ * The method returns either:
5914
+ * - An array of queues (when no pagination parameters are provided)
5915
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
5916
+ *
5917
+ * @param options - Query options including optional folderId
5918
+ * @returns Promise resolving to an array of queues or paginated result
4910
5919
  *
4911
5920
  * @example
4912
5921
  * ```typescript
4913
- * // Complete an app task
4914
- * await sdk.tasks.complete(TaskType.App, {
4915
- * taskId: 456,
4916
- * data: {},
4917
- * action: "submit"
4918
- * }, 123); // folderId is required
5922
+ * // Standard array return
5923
+ * const queues = await sdk.queues.getAll();
4919
5924
  *
4920
- * // Complete an external task
4921
- * await sdk.tasks.complete(TaskType.ExternalTask, {
4922
- * taskId: 789
4923
- * }, 123); // folderId is required
5925
+ * // Get queues within a specific folder
5926
+ * const queues = await sdk.queues.getAll({
5927
+ * folderId: 123
5928
+ * });
5929
+ *
5930
+ * // Get queues with filtering
5931
+ * const queues = await sdk.queues.getAll({
5932
+ * filter: "name eq 'MyQueue'"
5933
+ * });
5934
+ *
5935
+ * // First page with pagination
5936
+ * const page1 = await sdk.queues.getAll({ pageSize: 10 });
5937
+ *
5938
+ * // Navigate using cursor
5939
+ * if (page1.hasNextPage) {
5940
+ * const page2 = await sdk.queues.getAll({ cursor: page1.nextCursor });
5941
+ * }
5942
+ *
5943
+ * // Jump to specific page
5944
+ * const page5 = await sdk.queues.getAll({
5945
+ * jumpToPage: 5,
5946
+ * pageSize: 10
5947
+ * });
4924
5948
  * ```
4925
5949
  */
4926
- async complete(completionType, options, folderId) {
4927
- const headers = createHeaders({ [FOLDER_ID]: folderId });
4928
- let endpoint;
4929
- switch (completionType) {
4930
- case exports.TaskType.Form:
4931
- endpoint = TASK_ENDPOINTS.COMPLETE_FORM_TASK;
4932
- break;
4933
- case exports.TaskType.App:
4934
- endpoint = TASK_ENDPOINTS.COMPLETE_APP_TASK;
4935
- break;
4936
- default:
4937
- endpoint = TASK_ENDPOINTS.COMPLETE_GENERIC_TASK;
4938
- break;
4939
- }
4940
- // CompleteAppTask returns 204 no content
4941
- await this.post(endpoint, options, { headers });
4942
- // Return success with the request context data
4943
- return {
4944
- success: true,
4945
- data: options
4946
- };
5950
+ async getAll(options) {
5951
+ // Transformation function for queues
5952
+ const transformQueueResponse = (queue) => transformData(pascalToCamelCaseKeys(queue), QueueMap);
5953
+ return PaginationHelpers.getAll({
5954
+ serviceAccess: this.createPaginationServiceAccess(),
5955
+ getEndpoint: (folderId) => folderId ? QUEUE_ENDPOINTS.GET_BY_FOLDER : QUEUE_ENDPOINTS.GET_ALL,
5956
+ getByFolderEndpoint: QUEUE_ENDPOINTS.GET_BY_FOLDER,
5957
+ transformFn: transformQueueResponse,
5958
+ pagination: {
5959
+ paginationType: PaginationType.OFFSET,
5960
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
5961
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
5962
+ paginationParams: {
5963
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
5964
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
5965
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
5966
+ }
5967
+ }
5968
+ }, options);
4947
5969
  }
4948
5970
  /**
4949
- * Gets a form task by ID (private method)
5971
+ * Gets a single queue by ID
4950
5972
  *
4951
- * @param id - The ID of the form task to retrieve
5973
+ * @param id - Queue ID
4952
5974
  * @param folderId - Required folder ID
4953
- * @param options - Optional query parameters
4954
- * @returns Promise resolving to the form task
5975
+ * @returns Promise resolving to a queue definition
5976
+ *
5977
+ * @example
5978
+ * ```typescript
5979
+ * // Get queue by ID
5980
+ * const queue = await sdk.queues.getById(123, 456);
5981
+ * ```
4955
5982
  */
4956
- async getFormTaskById(id, folderId, options = {}) {
5983
+ async getById(id, folderId, options = {}) {
4957
5984
  const headers = createHeaders({ [FOLDER_ID]: folderId });
4958
- const response = await this.get(TASK_ENDPOINTS.GET_TASK_FORM_BY_ID, {
4959
- params: {
4960
- taskId: id,
4961
- ...options
4962
- },
4963
- headers
5985
+ const keysToPrefix = Object.keys(options);
5986
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
5987
+ const response = await this.get(QUEUE_ENDPOINTS.GET_BY_ID(id), {
5988
+ headers,
5989
+ params: apiOptions
4964
5990
  });
4965
- const transformedFormTask = transformData(response.data, TaskTimeMap);
4966
- return createTaskWithMethods(applyDataTransforms(transformedFormTask, { field: 'status', valueMap: TaskStatusMap }), this);
5991
+ return transformData(pascalToCamelCaseKeys(response.data), QueueMap);
4967
5992
  }
4968
5993
  }
4969
5994
  __decorate([
4970
- track('Tasks.Create')
4971
- ], TaskService.prototype, "create", null);
4972
- __decorate([
4973
- track('Tasks.GetUsers')
4974
- ], TaskService.prototype, "getUsers", null);
4975
- __decorate([
4976
- track('Tasks.GetAll')
4977
- ], TaskService.prototype, "getAll", null);
4978
- __decorate([
4979
- track('Tasks.GetById')
4980
- ], TaskService.prototype, "getById", null);
4981
- __decorate([
4982
- track('Tasks.Assign')
4983
- ], TaskService.prototype, "assign", null);
4984
- __decorate([
4985
- track('Tasks.Reassign')
4986
- ], TaskService.prototype, "reassign", null);
4987
- __decorate([
4988
- track('Tasks.Unassign')
4989
- ], TaskService.prototype, "unassign", null);
5995
+ track('Queues.GetAll')
5996
+ ], QueueService.prototype, "getAll", null);
4990
5997
  __decorate([
4991
- track('Tasks.Complete')
4992
- ], TaskService.prototype, "complete", null);
5998
+ track('Queues.GetById')
5999
+ ], QueueService.prototype, "getById", null);
4993
6000
 
4994
6001
  function validateConfig(config) {
4995
6002
  if (!config.baseUrl || !config.orgName || !config.tenantName) {
@@ -5039,25 +6046,31 @@ class UiPath {
5039
6046
  }
5040
6047
  /**
5041
6048
  * Initialize the SDK based on the provided configuration.
5042
- * This method is only required for OAuth-based authentication.
6049
+ * This method handles both OAuth flow initiation and completion automatically.
5043
6050
  * For secret-based authentication, initialization is automatic.
5044
6051
  */
5045
6052
  async initialize() {
5046
- // If already initialized or using secret auth, return immediately
5047
- if (this.initialized || hasSecretConfig(this.config)) {
6053
+ // For secret-based auth, it's already initialized in constructor
6054
+ if (hasSecretConfig(this.config)) {
5048
6055
  return;
5049
6056
  }
5050
6057
  try {
5051
- // If the OAuth flow redirects, the promise from `authenticate` will not resolve,
5052
- // and execution will stop here.
5053
- const success = await this.authService.authenticate(this.config);
5054
- if (!success || !this.authService.hasValidToken()) {
5055
- // If authenticate() returns false, it means a valid token could not be obtained.
5056
- // This could be due to invalid config or a failure in the OAuth callback.
5057
- // We don't throw an error for the initial OAuth redirect because that won't return.
5058
- throw new Error('Failed to obtain a valid authentication token.');
6058
+ // Check for OAuth callback first
6059
+ if (AuthService.isInOAuthCallback()) {
6060
+ if (await this.completeOAuth()) {
6061
+ return;
6062
+ }
6063
+ }
6064
+ // Check if already authenticated
6065
+ if (this.isAuthenticated()) {
6066
+ this.initialized = true;
6067
+ return;
6068
+ }
6069
+ // Start new OAuth flow
6070
+ await this.authService.authenticate(this.config);
6071
+ if (this.isAuthenticated()) {
6072
+ this.initialized = true;
5059
6073
  }
5060
- this.initialized = true;
5061
6074
  }
5062
6075
  catch (error) {
5063
6076
  const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
@@ -5070,6 +6083,38 @@ class UiPath {
5070
6083
  isInitialized() {
5071
6084
  return this.initialized;
5072
6085
  }
6086
+ /**
6087
+ * Check if we're in an OAuth callback state
6088
+ */
6089
+ isInOAuthCallback() {
6090
+ return AuthService.isInOAuthCallback();
6091
+ }
6092
+ /**
6093
+ * Complete OAuth authentication flow (only call if isInOAuthCallback() is true)
6094
+ */
6095
+ async completeOAuth() {
6096
+ if (!AuthService.isInOAuthCallback()) {
6097
+ throw new Error('Not in OAuth callback state. Call initialize() first to start OAuth flow.');
6098
+ }
6099
+ try {
6100
+ const success = await this.authService.authenticate(this.config);
6101
+ if (success && this.isAuthenticated()) {
6102
+ this.initialized = true;
6103
+ return true;
6104
+ }
6105
+ return false;
6106
+ }
6107
+ catch (error) {
6108
+ const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
6109
+ throw new Error(`Failed to complete OAuth: ${errorMessage}`);
6110
+ }
6111
+ }
6112
+ /**
6113
+ * Check if the user is authenticated (has valid token)
6114
+ */
6115
+ isAuthenticated() {
6116
+ return this.authService.hasValidToken();
6117
+ }
5073
6118
  /**
5074
6119
  * Get the current authentication token
5075
6120
  */
@@ -5096,7 +6141,20 @@ class UiPath {
5096
6141
  /**
5097
6142
  * Access to Process Instances service
5098
6143
  */
5099
- instances: this.getService(ProcessInstancesService)
6144
+ instances: this.getService(ProcessInstancesService),
6145
+ /**
6146
+ * Access to Process Incidents service
6147
+ */
6148
+ incidents: this.getService(ProcessIncidentsService)
6149
+ }),
6150
+ /**
6151
+ * Access to Maestro Cases service
6152
+ */
6153
+ cases: Object.assign(this.getService(CasesService), {
6154
+ /**
6155
+ * Access to Case Instances service
6156
+ */
6157
+ instances: this.getService(CaseInstancesService)
5100
6158
  })
5101
6159
  };
5102
6160
  }
@@ -5326,8 +6384,10 @@ exports.UiPath = UiPath;
5326
6384
  exports.UiPathError = UiPathError;
5327
6385
  exports.VERSION = VERSION;
5328
6386
  exports.ValidationError = ValidationError;
6387
+ exports.createCaseInstanceWithMethods = createCaseInstanceWithMethods;
5329
6388
  exports.createEntityWithMethods = createEntityWithMethods;
5330
6389
  exports.createProcessInstanceWithMethods = createProcessInstanceWithMethods;
6390
+ exports.createProcessWithMethods = createProcessWithMethods;
5331
6391
  exports.createTaskWithMethods = createTaskWithMethods;
5332
6392
  exports.getErrorDetails = getErrorDetails;
5333
6393
  exports.getLimitedPageSize = getLimitedPageSize;