@uipath/uipath-typescript 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3885,6 +3885,7 @@ class ExecutionContext {
3885
3885
  * Checks if code is running in a browser environment
3886
3886
  */
3887
3887
  const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
3888
+ const isInActionCenter = isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
3888
3889
 
3889
3890
  /**
3890
3891
  * Session storage keys used by the auth module
@@ -4201,6 +4202,102 @@ function getErrorDetails(error) {
4201
4202
  };
4202
4203
  }
4203
4204
 
4205
+ var ActionCenterEventNames;
4206
+ (function (ActionCenterEventNames) {
4207
+ ActionCenterEventNames["TOKENREFRESHED"] = "AC.tokenRefreshed";
4208
+ ActionCenterEventNames["REFRESHTOKEN"] = "AC.refreshToken";
4209
+ })(ActionCenterEventNames || (ActionCenterEventNames = {}));
4210
+
4211
+ const AUTHENTICATION_TIMEOUT = 8000;
4212
+ class ActionCenterTokenManager {
4213
+ constructor(config, onTokenRefreshed) {
4214
+ this.config = config;
4215
+ this.onTokenRefreshed = onTokenRefreshed;
4216
+ this.parentOrigin = new URLSearchParams(window.location.search).get('basedomain');
4217
+ this.refreshPromise = null;
4218
+ }
4219
+ async refreshAccessToken(tokenInfo) {
4220
+ if (!this.isTokenExpired(tokenInfo)) {
4221
+ return tokenInfo.token;
4222
+ }
4223
+ if (this.refreshPromise) {
4224
+ return this.refreshPromise;
4225
+ }
4226
+ this.refreshPromise = new Promise((resolve, reject) => {
4227
+ const content = {
4228
+ clientId: this.config.clientId,
4229
+ scope: this.config.scope,
4230
+ };
4231
+ this.sendMessageToParent(ActionCenterEventNames.REFRESHTOKEN, content);
4232
+ const messageListener = (event) => {
4233
+ if (event.origin !== this.parentOrigin)
4234
+ return;
4235
+ if (event.data?.eventType !== ActionCenterEventNames.TOKENREFRESHED)
4236
+ return;
4237
+ clearTimeout(timer);
4238
+ if (event.data?.content?.token) {
4239
+ const { accessToken, expiresAt } = event.data.content.token;
4240
+ this.onTokenRefreshed({ token: accessToken, type: 'secret', expiresAt });
4241
+ resolve(accessToken);
4242
+ }
4243
+ else {
4244
+ reject(new AuthenticationError({
4245
+ message: 'Failed to fetch access token',
4246
+ statusCode: HttpStatus.UNAUTHORIZED,
4247
+ }));
4248
+ }
4249
+ this.refreshPromise = null;
4250
+ this.cleanup(messageListener);
4251
+ };
4252
+ const timer = setTimeout(() => {
4253
+ reject(new AuthenticationError({
4254
+ message: 'Failed to fetch access token',
4255
+ statusCode: HttpStatus.UNAUTHORIZED,
4256
+ }));
4257
+ this.refreshPromise = null;
4258
+ this.cleanup(messageListener);
4259
+ }, AUTHENTICATION_TIMEOUT);
4260
+ window.addEventListener('message', messageListener);
4261
+ });
4262
+ return this.refreshPromise;
4263
+ }
4264
+ isTokenExpired(tokenInfo) {
4265
+ if (!tokenInfo?.expiresAt) {
4266
+ return true;
4267
+ }
4268
+ return new Date() >= tokenInfo.expiresAt;
4269
+ }
4270
+ sendMessageToParent(eventType, content) {
4271
+ if (window.parent && this.isValidOrigin(this.parentOrigin)) {
4272
+ try {
4273
+ window.parent.postMessage({ eventType, content }, this.parentOrigin);
4274
+ }
4275
+ catch (error) {
4276
+ console.warn('Failed to send message to Action Center', JSON.stringify(error));
4277
+ }
4278
+ }
4279
+ }
4280
+ cleanup(messageListener) {
4281
+ window.removeEventListener('message', messageListener);
4282
+ }
4283
+ isValidOrigin(origin) {
4284
+ const ALLOWED_ORIGINS = ['https://alpha.uipath.com', 'https://staging.uipath.com', 'https://cloud.uipath.com'];
4285
+ if (!origin) {
4286
+ return false;
4287
+ }
4288
+ if (ALLOWED_ORIGINS.includes(origin)) {
4289
+ return true;
4290
+ }
4291
+ try {
4292
+ const url = new URL(origin);
4293
+ return url.hostname === 'localhost';
4294
+ }
4295
+ catch {
4296
+ return false;
4297
+ }
4298
+ }
4299
+ }
4300
+
4204
4301
  /**
4205
4302
  * TokenManager is responsible for managing authentication tokens.
4206
4303
  * It provides token operations for a specific client ID.
@@ -4219,6 +4316,11 @@ class TokenManager {
4219
4316
  this.config = config;
4220
4317
  this.isOAuth = isOAuth;
4221
4318
  this.refreshPromise = null;
4319
+ this.actionCenterTokenManager = null;
4320
+ if (isInActionCenter) {
4321
+ this.actionCenterTokenManager = new ActionCenterTokenManager(config, (tokenInfo) => this.setToken(tokenInfo));
4322
+ this.isOAuth = false;
4323
+ }
4222
4324
  }
4223
4325
  /**
4224
4326
  * Checks if a token is expired
@@ -4246,6 +4348,9 @@ class TokenManager {
4246
4348
  message: 'No authentication token available. Make sure to initialize the SDK first.'
4247
4349
  });
4248
4350
  }
4351
+ if (this.actionCenterTokenManager) {
4352
+ return await this.actionCenterTokenManager.refreshAccessToken(tokenInfo);
4353
+ }
4249
4354
  // For secret-based tokens, they never expire
4250
4355
  if (tokenInfo.type === 'secret') {
4251
4356
  return tokenInfo.token;
@@ -4390,9 +4495,6 @@ class TokenManager {
4390
4495
  clearToken() {
4391
4496
  this.currentToken = undefined;
4392
4497
  this.executionContext.set('tokenInfo', undefined);
4393
- const headers = this.executionContext.getHeaders();
4394
- delete headers['Authorization'];
4395
- this.executionContext.setHeaders(headers);
4396
4498
  // Remove from session storage if this is an OAuth token
4397
4499
  if (isBrowser && this.isOAuth) {
4398
4500
  try {
@@ -4408,10 +4510,6 @@ class TokenManager {
4408
4510
  */
4409
4511
  _updateExecutionContext(tokenInfo) {
4410
4512
  this.executionContext.set('tokenInfo', tokenInfo);
4411
- // Update authorization header
4412
- this.executionContext.setHeaders({
4413
- 'Authorization': `Bearer ${tokenInfo.token}`
4414
- });
4415
4513
  }
4416
4514
  /**
4417
4515
  * Refreshes the access token using the stored refresh token.
@@ -4595,6 +4693,7 @@ const DATA_FABRIC_ENDPOINTS = {
4595
4693
  UPDATE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/update-batch`,
4596
4694
  DELETE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/delete-batch`,
4597
4695
  DOWNLOAD_ATTACHMENT: (entityName, recordId, fieldName) => `${DATAFABRIC_BASE}/api/Attachment/${entityName}/${recordId}/${fieldName}`,
4696
+ UPLOAD_ATTACHMENT: (entityName, recordId, fieldName) => `${DATAFABRIC_BASE}/api/Attachment/${entityName}/${recordId}/${fieldName}`,
4598
4697
  },
4599
4698
  CHOICESETS: {
4600
4699
  GET_ALL: `${DATAFABRIC_BASE}/api/Entity/choiceset`,
@@ -4615,8 +4714,15 @@ const IDENTITY_ENDPOINTS = {
4615
4714
 
4616
4715
  class AuthService {
4617
4716
  constructor(config, executionContext) {
4618
- // Check if we should use stored OAuth context instead of provided config
4619
- const storedContext = AuthService.getStoredOAuthContext();
4717
+ // Only use stored OAuth context when completing an active callback (URL has ?code=).
4718
+ // If stored context exists but we're NOT in a callback, it's stale from a
4719
+ // failed/abandoned flow (e.g. scope mismatch, invalid redirect URI) and must
4720
+ // be cleared so the fresh config takes effect.
4721
+ const isCallback = AuthService.isInOAuthCallback();
4722
+ const storedContext = isCallback ? AuthService.getStoredOAuthContext() : null;
4723
+ if (!isCallback) {
4724
+ AuthService._clearStoredOAuthContext();
4725
+ }
4620
4726
  const effectiveConfig = storedContext ? AuthService._mergeConfigWithContext(config, storedContext) : config;
4621
4727
  this.config = effectiveConfig;
4622
4728
  const isOAuth = hasOAuthConfig(effectiveConfig);
@@ -4663,6 +4769,22 @@ class AuthService {
4663
4769
  return null;
4664
4770
  }
4665
4771
  }
4772
+ /**
4773
+ * Clear stale OAuth context from session storage.
4774
+ * Called when there is no active OAuth callback, meaning any stored context
4775
+ * is left over from a failed or abandoned flow.
4776
+ */
4777
+ static _clearStoredOAuthContext() {
4778
+ if (!isBrowser)
4779
+ return;
4780
+ try {
4781
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
4782
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4783
+ }
4784
+ catch {
4785
+ // Ignore storage errors
4786
+ }
4787
+ }
4666
4788
  /**
4667
4789
  * Merges provided config with stored OAuth context, prioritizing stored values
4668
4790
  */
@@ -4971,13 +5093,41 @@ class AuthService {
4971
5093
  }
4972
5094
  }
4973
5095
 
5096
+ /**
5097
+ * Check if config has all required base fields
5098
+ */
5099
+ function hasRequiredBaseFields(config) {
5100
+ return Boolean(config.baseUrl && config.orgName && config.tenantName);
5101
+ }
5102
+ /**
5103
+ * Check if config has exactly one authentication method (secret XOR oauth)
5104
+ * Returns true if exactly one auth method is present, false otherwise
5105
+ */
5106
+ function hasValidAuthConfig(config) {
5107
+ const hasSecret = hasSecretConfig(config);
5108
+ const hasOAuth = hasOAuthConfig(config);
5109
+ // XOR: exactly one auth method, not both, not neither
5110
+ return hasSecret !== hasOAuth;
5111
+ }
4974
5112
  function validateConfig(config) {
4975
- if (!config.baseUrl || !config.orgName || !config.tenantName) {
5113
+ if (!hasRequiredBaseFields(config)) {
4976
5114
  throw new Error('Missing required configuration: baseUrl, orgName, and tenantName are required');
4977
5115
  }
4978
- if (!hasSecretConfig(config) && !hasOAuthConfig(config)) {
4979
- throw new Error('Invalid configuration: must provide either secret or (clientId, redirectUri, and scope)');
5116
+ const hasSecret = hasSecretConfig(config);
5117
+ const hasOAuth = hasOAuthConfig(config);
5118
+ if (hasSecret && hasOAuth) {
5119
+ throw new Error('Invalid configuration: cannot provide both secret and OAuth credentials. Choose one authentication method.');
4980
5120
  }
5121
+ if (!hasSecret && !hasOAuth) {
5122
+ throw new Error('Invalid configuration: must provide either secret or OAuth credentials (clientId, redirectUri, and scope)');
5123
+ }
5124
+ }
5125
+ /**
5126
+ * Check if partial config has all required fields for a complete SDK config
5127
+ * Requires base fields and exactly one authentication method (secret XOR oauth)
5128
+ */
5129
+ function isCompleteConfig(config) {
5130
+ return hasRequiredBaseFields(config) && hasValidAuthConfig(config);
4981
5131
  }
4982
5132
  function normalizeBaseUrl(url) {
4983
5133
  return url.endsWith('/') ? url.slice(0, -1) : url;
@@ -4989,7 +5139,7 @@ function normalizeBaseUrl(url) {
4989
5139
  // Connection string placeholder that will be replaced during build
4990
5140
  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";
4991
5141
  // SDK Version placeholder
4992
- const SDK_VERSION = "1.1.1";
5142
+ const SDK_VERSION = "1.1.3";
4993
5143
  const VERSION = "Version";
4994
5144
  const SERVICE = "Service";
4995
5145
  const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
@@ -5318,19 +5468,71 @@ class SDKInternalsRegistry {
5318
5468
  }
5319
5469
  }
5320
5470
 
5321
- var _UiPath_config, _UiPath_authService, _UiPath_initialized;
5471
+ /**
5472
+ * UiPath meta tag names for runtime configuration.
5473
+ *
5474
+ * These meta tags are injected at deployment time by the Apps Service
5475
+ * to configure SDK authentication and asset resolution in production.
5476
+ */
5477
+ exports.UiPathMetaTags = void 0;
5478
+ (function (UiPathMetaTags) {
5479
+ // SDK/OAuth configuration
5480
+ UiPathMetaTags["CLIENT_ID"] = "uipath:client-id";
5481
+ UiPathMetaTags["SCOPE"] = "uipath:scope";
5482
+ UiPathMetaTags["ORG_NAME"] = "uipath:org-name";
5483
+ UiPathMetaTags["TENANT_NAME"] = "uipath:tenant-name";
5484
+ UiPathMetaTags["BASE_URL"] = "uipath:base-url";
5485
+ UiPathMetaTags["REDIRECT_URI"] = "uipath:redirect-uri";
5486
+ // Asset resolution and routing
5487
+ UiPathMetaTags["CDN_BASE"] = "uipath:cdn-base";
5488
+ UiPathMetaTags["APP_BASE"] = "uipath:app-base";
5489
+ })(exports.UiPathMetaTags || (exports.UiPathMetaTags = {}));
5490
+
5491
+ /**
5492
+ * Get the content of a meta tag by name.
5493
+ * Returns undefined if not in browser environment or meta tag is not found.
5494
+ */
5495
+ function getMetaTagContent(name) {
5496
+ if (!isBrowser)
5497
+ return undefined;
5498
+ return document.querySelector(`meta[name="${name}"]`)?.content;
5499
+ }
5500
+ /**
5501
+ * Load configuration from HTML meta tags injected at runtime.
5502
+ * These meta tags are injected by @uipath/coded-apps during build
5503
+ * or by the Apps service during deployment.
5504
+ *
5505
+ * Returns partial config with values found, or null if no meta tags present.
5506
+ */
5507
+ function loadFromMetaTags() {
5508
+ if (!isBrowser)
5509
+ return null;
5510
+ const config = {
5511
+ clientId: getMetaTagContent(exports.UiPathMetaTags.CLIENT_ID),
5512
+ scope: getMetaTagContent(exports.UiPathMetaTags.SCOPE),
5513
+ orgName: getMetaTagContent(exports.UiPathMetaTags.ORG_NAME),
5514
+ tenantName: getMetaTagContent(exports.UiPathMetaTags.TENANT_NAME),
5515
+ baseUrl: getMetaTagContent(exports.UiPathMetaTags.BASE_URL),
5516
+ redirectUri: getMetaTagContent(exports.UiPathMetaTags.REDIRECT_URI),
5517
+ };
5518
+ const hasAnyValue = Object.values(config).some(Boolean);
5519
+ return hasAnyValue ? config : null;
5520
+ }
5521
+
5522
+ var _UiPath_instances, _UiPath_config, _UiPath_authService, _UiPath_initialized, _UiPath_partialConfig, _UiPath_initializeWithConfig, _UiPath_loadConfig;
5322
5523
  /**
5323
5524
  * UiPath - Core SDK class for authentication and configuration management.
5324
5525
  *
5325
5526
  * Handles authentication, configuration, and provides access to SDK internals
5326
5527
  * for service instantiation in the modular pattern.
5327
5528
  *
5529
+ * Supports two usage patterns:
5530
+ * 1. Full config in constructor — for server-side or explicit configuration
5531
+ * 2. No config / partial config — loads from meta tags injected by @uipath/coded-apps plugin
5532
+ *
5328
5533
  * @example
5329
5534
  * ```typescript
5330
- * // Modular pattern
5331
- * import { UiPath } from '@uipath/uipath-typescript/core';
5332
- * import { Entities } from '@uipath/uipath-typescript/entities';
5333
- *
5535
+ * // Explicit config
5334
5536
  * const sdk = new UiPath({
5335
5537
  * baseUrl: 'https://cloud.uipath.com',
5336
5538
  * orgName: 'myorg',
@@ -5339,70 +5541,47 @@ var _UiPath_config, _UiPath_authService, _UiPath_initialized;
5339
5541
  * redirectUri: 'http://localhost:3000/callback',
5340
5542
  * scope: 'OR.Users OR.Robots'
5341
5543
  * });
5342
- *
5343
5544
  * await sdk.initialize();
5545
+ * ```
5344
5546
  *
5345
- * const entitiesService = new Entities(sdk);
5346
- * const allEntities = await entitiesService.getAll();
5547
+ * @example
5548
+ * ```typescript
5549
+ * // Auto-load from meta tags (coded apps)
5550
+ * const sdk = new UiPath();
5551
+ * await sdk.initialize();
5347
5552
  * ```
5348
5553
  */
5349
5554
  let UiPath$1 = class UiPath {
5350
5555
  constructor(config) {
5556
+ _UiPath_instances.add(this);
5351
5557
  // Private fields - true runtime privacy, not visible via Object.keys()
5352
5558
  _UiPath_config.set(this, void 0);
5353
5559
  _UiPath_authService.set(this, void 0);
5354
5560
  _UiPath_initialized.set(this, false);
5355
- // Validate and normalize the configuration
5356
- validateConfig(config);
5357
- const hasSecretAuth = hasSecretConfig(config);
5358
- const hasOAuthAuth = hasOAuthConfig(config);
5359
- // Initialize core components
5360
- const internalConfig = new UiPathConfig({
5361
- baseUrl: normalizeBaseUrl(config.baseUrl),
5362
- orgName: config.orgName,
5363
- tenantName: config.tenantName,
5364
- secret: hasSecretAuth ? config.secret : undefined,
5365
- clientId: hasOAuthAuth ? config.clientId : undefined,
5366
- redirectUri: hasOAuthAuth ? config.redirectUri : undefined,
5367
- scope: hasOAuthAuth ? config.scope : undefined
5368
- });
5369
- const executionContext = new ExecutionContext();
5370
- __classPrivateFieldSet(this, _UiPath_authService, new AuthService(internalConfig, executionContext), "f");
5371
- __classPrivateFieldSet(this, _UiPath_config, internalConfig, "f");
5372
- // Store internals in SDKInternalsRegistry (not visible on instance)
5373
- SDKInternalsRegistry.set(this, {
5374
- config: internalConfig,
5375
- context: executionContext,
5376
- tokenManager: __classPrivateFieldGet(this, _UiPath_authService, "f").getTokenManager()
5377
- });
5378
- // Expose read-only config for user convenience
5379
- this.config = {
5380
- baseUrl: internalConfig.baseUrl,
5381
- orgName: internalConfig.orgName,
5382
- tenantName: internalConfig.tenantName
5383
- };
5384
- // Initialize telemetry with SDK configuration
5385
- telemetryClient.initialize({
5386
- baseUrl: config.baseUrl,
5387
- orgName: config.orgName,
5388
- tenantName: config.tenantName,
5389
- clientId: hasOAuthAuth ? config.clientId : undefined,
5390
- redirectUri: hasOAuthAuth ? config.redirectUri : undefined
5391
- });
5392
- // Track SDK initialization
5393
- trackEvent('Sdk.Auth');
5394
- // Auto-initialize for secret-based auth
5395
- if (hasSecretAuth) {
5396
- __classPrivateFieldGet(this, _UiPath_authService, "f").authenticateWithSecret(config.secret);
5397
- __classPrivateFieldSet(this, _UiPath_initialized, true, "f");
5561
+ _UiPath_partialConfig.set(this, void 0);
5562
+ // Load configuration from meta tags
5563
+ const configFromMetaTags = loadFromMetaTags();
5564
+ // Merge configuration: constructor config overrides meta tags
5565
+ const mergedConfig = config ? { ...configFromMetaTags, ...config } : configFromMetaTags;
5566
+ if (mergedConfig && isCompleteConfig(mergedConfig)) {
5567
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, mergedConfig);
5568
+ }
5569
+ else if (config) {
5570
+ __classPrivateFieldSet(this, _UiPath_partialConfig, config, "f");
5398
5571
  }
5399
5572
  }
5400
5573
  /**
5401
5574
  * Initialize the SDK based on the provided configuration.
5402
5575
  * This method handles both OAuth flow initiation and completion automatically.
5403
5576
  * For secret-based authentication, initialization is automatic and this returns immediately.
5577
+ * If no config was provided in constructor, loads from meta tags.
5404
5578
  */
5405
5579
  async initialize() {
5580
+ // Load config from meta tags if not provided in constructor
5581
+ if (!__classPrivateFieldGet(this, _UiPath_config, "f")) {
5582
+ const loadedConfig = __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_loadConfig).call(this);
5583
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, loadedConfig);
5584
+ }
5406
5585
  // For secret-based auth, it's already initialized in constructor
5407
5586
  if (hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
5408
5587
  return;
@@ -5449,6 +5628,11 @@ let UiPath$1 = class UiPath {
5449
5628
  if (!AuthService.isInOAuthCallback()) {
5450
5629
  throw new Error('Not in OAuth callback state. Call initialize() first to start OAuth flow.');
5451
5630
  }
5631
+ // Load config if not yet initialized
5632
+ if (!__classPrivateFieldGet(this, _UiPath_config, "f")) {
5633
+ const loadedConfig = __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_loadConfig).call(this);
5634
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, loadedConfig);
5635
+ }
5452
5636
  try {
5453
5637
  const success = await __classPrivateFieldGet(this, _UiPath_authService, "f").authenticate(__classPrivateFieldGet(this, _UiPath_config, "f"));
5454
5638
  if (success && this.isAuthenticated()) {
@@ -5466,13 +5650,13 @@ let UiPath$1 = class UiPath {
5466
5650
  * Check if the user is authenticated (has valid token)
5467
5651
  */
5468
5652
  isAuthenticated() {
5469
- return __classPrivateFieldGet(this, _UiPath_authService, "f").hasValidToken();
5653
+ return __classPrivateFieldGet(this, _UiPath_authService, "f")?.hasValidToken() ?? false;
5470
5654
  }
5471
5655
  /**
5472
5656
  * Get the current authentication token
5473
5657
  */
5474
5658
  getToken() {
5475
- return __classPrivateFieldGet(this, _UiPath_authService, "f").getToken();
5659
+ return __classPrivateFieldGet(this, _UiPath_authService, "f")?.getToken();
5476
5660
  }
5477
5661
  /**
5478
5662
  * Logout from the SDK, clearing all authentication state.
@@ -5480,14 +5664,71 @@ let UiPath$1 = class UiPath {
5480
5664
  */
5481
5665
  logout() {
5482
5666
  // Secret-based auth has no session to end — skip silently
5483
- if (hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
5667
+ if (__classPrivateFieldGet(this, _UiPath_config, "f") && hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
5484
5668
  return;
5485
5669
  }
5486
- __classPrivateFieldGet(this, _UiPath_authService, "f").logout();
5670
+ __classPrivateFieldGet(this, _UiPath_authService, "f")?.logout();
5487
5671
  __classPrivateFieldSet(this, _UiPath_initialized, false, "f");
5488
5672
  }
5489
5673
  };
5490
- _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap();
5674
+ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap(), _UiPath_partialConfig = new WeakMap(), _UiPath_instances = new WeakSet(), _UiPath_initializeWithConfig = function _UiPath_initializeWithConfig(config) {
5675
+ // Validate and normalize the configuration
5676
+ validateConfig(config);
5677
+ const hasSecretAuth = hasSecretConfig(config);
5678
+ const hasOAuthAuth = hasOAuthConfig(config);
5679
+ // Initialize core components
5680
+ const internalConfig = new UiPathConfig({
5681
+ baseUrl: normalizeBaseUrl(config.baseUrl),
5682
+ orgName: config.orgName,
5683
+ tenantName: config.tenantName,
5684
+ secret: hasSecretAuth ? config.secret : undefined,
5685
+ clientId: hasOAuthAuth ? config.clientId : undefined,
5686
+ redirectUri: hasOAuthAuth ? config.redirectUri : undefined,
5687
+ scope: hasOAuthAuth ? config.scope : undefined
5688
+ });
5689
+ const executionContext = new ExecutionContext();
5690
+ __classPrivateFieldSet(this, _UiPath_authService, new AuthService(internalConfig, executionContext), "f");
5691
+ __classPrivateFieldSet(this, _UiPath_config, internalConfig, "f");
5692
+ // Store internals in SDKInternalsRegistry (not visible on instance)
5693
+ SDKInternalsRegistry.set(this, {
5694
+ config: internalConfig,
5695
+ context: executionContext,
5696
+ tokenManager: __classPrivateFieldGet(this, _UiPath_authService, "f").getTokenManager()
5697
+ });
5698
+ // Expose read-only config for user convenience
5699
+ this.config = {
5700
+ baseUrl: internalConfig.baseUrl,
5701
+ orgName: internalConfig.orgName,
5702
+ tenantName: internalConfig.tenantName
5703
+ };
5704
+ // Initialize telemetry with SDK configuration
5705
+ telemetryClient.initialize({
5706
+ baseUrl: config.baseUrl,
5707
+ orgName: config.orgName,
5708
+ tenantName: config.tenantName,
5709
+ clientId: hasOAuthAuth ? config.clientId : undefined,
5710
+ redirectUri: hasOAuthAuth ? config.redirectUri : undefined
5711
+ });
5712
+ // Track SDK initialization
5713
+ trackEvent('Sdk.Auth');
5714
+ /** Auto-initialize for secret-based auth
5715
+ * When viewed in Action Center, initialize tokenInfo with empty token. When an sdk call is made Action Center passes the token to sdk.
5716
+ */
5717
+ if (hasSecretAuth || isInActionCenter) {
5718
+ __classPrivateFieldGet(this, _UiPath_authService, "f").authenticateWithSecret(config.secret ?? '');
5719
+ __classPrivateFieldSet(this, _UiPath_initialized, true, "f");
5720
+ }
5721
+ }, _UiPath_loadConfig = function _UiPath_loadConfig() {
5722
+ // Load from meta tags
5723
+ const metaConfig = loadFromMetaTags();
5724
+ // Merge with any partial config from constructor (constructor overrides meta tags)
5725
+ const merged = { ...metaConfig, ...__classPrivateFieldGet(this, _UiPath_partialConfig, "f") };
5726
+ if (!isCompleteConfig(merged)) {
5727
+ throw new Error('UiPath SDK configuration not found. ' +
5728
+ 'Ensure @uipath/coded-apps plugin is set up in your bundler to inject configuration during development and build.');
5729
+ }
5730
+ return merged;
5731
+ };
5491
5732
 
5492
5733
  /**
5493
5734
  * Type guards for error response types
@@ -5766,15 +6007,6 @@ class ApiClient {
5766
6007
  async getDefaultHeaders() {
5767
6008
  // Get headers from execution context first
5768
6009
  const contextHeaders = this.executionContext.getHeaders();
5769
- // If Authorization header is already set in context, use that
5770
- if (contextHeaders['Authorization']) {
5771
- return {
5772
- ...contextHeaders,
5773
- 'Content-Type': CONTENT_TYPES.JSON,
5774
- ...this.defaultHeaders,
5775
- ...this.clientConfig.headers
5776
- };
5777
- }
5778
6010
  const token = await this.getValidToken();
5779
6011
  return {
5780
6012
  ...contextHeaders,
@@ -5789,8 +6021,13 @@ class ApiClient {
5789
6021
  const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
5790
6022
  // Construct URL with org and tenant names
5791
6023
  const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
6024
+ const isFormData = options.body instanceof FormData;
6025
+ const defaultHeaders = await this.getDefaultHeaders();
6026
+ if (isFormData) {
6027
+ delete defaultHeaders['Content-Type'];
6028
+ }
5792
6029
  const headers = {
5793
- ...await this.getDefaultHeaders(),
6030
+ ...defaultHeaders,
5794
6031
  ...options.headers
5795
6032
  };
5796
6033
  // Convert params to URLSearchParams
@@ -5801,11 +6038,15 @@ class ApiClient {
5801
6038
  });
5802
6039
  }
5803
6040
  const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
6041
+ let body = undefined;
6042
+ if (options.body) {
6043
+ body = isFormData ? options.body : JSON.stringify(options.body);
6044
+ }
5804
6045
  try {
5805
6046
  const response = await fetch(fullUrl, {
5806
6047
  method,
5807
6048
  headers,
5808
- body: options.body ? JSON.stringify(options.body) : undefined,
6049
+ body,
5809
6050
  signal: options.signal
5810
6051
  });
5811
6052
  if (!response.ok) {
@@ -7096,6 +7337,17 @@ function createEntityMethods(entityData, service) {
7096
7337
  fieldName
7097
7338
  });
7098
7339
  },
7340
+ async uploadAttachment(recordId, fieldName, file, expansionLevel) {
7341
+ if (!entityData.name)
7342
+ throw new Error('Entity name is undefined');
7343
+ return service.uploadAttachment({
7344
+ entityName: entityData.name,
7345
+ recordId,
7346
+ fieldName,
7347
+ file,
7348
+ expansionLevel
7349
+ });
7350
+ },
7099
7351
  async insert(data, options) {
7100
7352
  return this.insertRecord(data, options);
7101
7353
  },
@@ -7599,6 +7851,42 @@ class EntityService extends BaseService {
7599
7851
  });
7600
7852
  return response.data;
7601
7853
  }
7854
+ /**
7855
+ * Uploads an attachment to a File-type field of an entity record
7856
+ *
7857
+ * @param options - Options containing entityName, recordId, fieldName, file, and optional expansionLevel
7858
+ * @returns Promise resolving to the upload response
7859
+ *
7860
+ * @example
7861
+ * ```typescript
7862
+ * import { Entities } from '@uipath/uipath-typescript/entities';
7863
+ *
7864
+ * const entities = new Entities(sdk);
7865
+ *
7866
+ * // Upload a file attachment
7867
+ * const response = await entities.uploadAttachment({
7868
+ * entityName: 'Invoice',
7869
+ * recordId: '<record-uuid>',
7870
+ * fieldName: 'Documents',
7871
+ * file: file
7872
+ * });
7873
+ * ```
7874
+ */
7875
+ async uploadAttachment(options) {
7876
+ const { entityName, recordId, fieldName, file, expansionLevel } = options;
7877
+ const formData = new FormData();
7878
+ if (file instanceof Uint8Array) {
7879
+ formData.append('file', new Blob([file.buffer]));
7880
+ }
7881
+ else {
7882
+ formData.append('file', file);
7883
+ }
7884
+ const params = createParams({ expansionLevel });
7885
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPLOAD_ATTACHMENT(entityName, recordId, fieldName), formData, { params });
7886
+ // Convert PascalCase response to camelCase
7887
+ const camelResponse = pascalToCamelCaseKeys(response.data);
7888
+ return camelResponse;
7889
+ }
7602
7890
  /**
7603
7891
  * @hidden
7604
7892
  * @deprecated Use {@link getAllRecords} instead.
@@ -7732,6 +8020,9 @@ __decorate([
7732
8020
  __decorate([
7733
8021
  track('Entities.DownloadAttachment')
7734
8022
  ], EntityService.prototype, "downloadAttachment", null);
8023
+ __decorate([
8024
+ track('Entities.UploadAttachment')
8025
+ ], EntityService.prototype, "uploadAttachment", null);
7735
8026
 
7736
8027
  class ChoiceSetService extends BaseService {
7737
8028
  /**
@@ -11118,6 +11409,81 @@ const UserSettingsMap = {
11118
11409
  ...CommonFieldMap
11119
11410
  };
11120
11411
 
11412
+ /**
11413
+ * Asset resolution utilities for UiPath Coded Apps
11414
+ *
11415
+ * These helpers enable developers to write code that works identically
11416
+ * in local development and production environments.
11417
+ *
11418
+ * Values are read from meta tags injected at deployment:
11419
+ * - <meta name="uipath:cdn-base" content="https://cdn.example.com/appId/folder">
11420
+ * - <meta name="uipath:app-base" content="/org/apps_/.../public">
11421
+ */
11422
+ /**
11423
+ * Resolves an asset path to the CDN URL (if available)
11424
+ *
11425
+ * In local development: returns path as-is (loads from local dev server)
11426
+ * In production: prepends CDN base URL from meta tag
11427
+ *
11428
+ * @param path - The asset path (e.g., './assets/logo.png' or '/assets/logo.png')
11429
+ * @returns The resolved asset URL
11430
+ *
11431
+ * @example
11432
+ * ```tsx
11433
+ * import { getAsset } from '@uipath/uipath-typescript';
11434
+ * import logoPath from './assets/logo.png';
11435
+ *
11436
+ * function MyComponent() {
11437
+ * return <img src={getAsset(logoPath)} alt="Logo" />;
11438
+ * }
11439
+ * ```
11440
+ */
11441
+ function getAsset(path) {
11442
+ // If path is already an absolute URL, return as-is
11443
+ if (path.startsWith('http://') || path.startsWith('https://')) {
11444
+ return path;
11445
+ }
11446
+ const cdnBase = getMetaTagContent(exports.UiPathMetaTags.CDN_BASE);
11447
+ if (!cdnBase)
11448
+ return path;
11449
+ // Normalize CDN base URL to remove trailing slash
11450
+ const normalizedCdnBase = normalizeBaseUrl(cdnBase);
11451
+ // Normalize path to ensure it starts with /
11452
+ let normalizedPath = path;
11453
+ if (normalizedPath.startsWith('./')) {
11454
+ normalizedPath = normalizedPath.substring(1); // ./assets -> /assets
11455
+ }
11456
+ else if (!normalizedPath.startsWith('/')) {
11457
+ normalizedPath = '/' + normalizedPath; // assets -> /assets
11458
+ }
11459
+ return normalizedCdnBase + normalizedPath;
11460
+ }
11461
+ /**
11462
+ * Returns the app base path for router configuration
11463
+ *
11464
+ * In local development: returns '/'
11465
+ * In production: returns the deployed app path from meta tag
11466
+ *
11467
+ * @returns The app base path
11468
+ *
11469
+ * @example
11470
+ * ```tsx
11471
+ * import { getAppBase } from '@uipath/uipath-typescript';
11472
+ * import { BrowserRouter } from 'react-router-dom';
11473
+ *
11474
+ * function App() {
11475
+ * return (
11476
+ * <BrowserRouter basename={getAppBase()}>
11477
+ * {/* routes *\/}
11478
+ * </BrowserRouter>
11479
+ * );
11480
+ * }
11481
+ * ```
11482
+ */
11483
+ function getAppBase() {
11484
+ return getMetaTagContent(exports.UiPathMetaTags.APP_BASE) || '/';
11485
+ }
11486
+
11121
11487
  exports.APP_NAME = APP_NAME;
11122
11488
  exports.AgentMap = AgentMap;
11123
11489
  exports.AuthenticationError = AuthenticationError;
@@ -11160,6 +11526,8 @@ exports.createEntityWithMethods = createEntityWithMethods;
11160
11526
  exports.createProcessInstanceWithMethods = createProcessInstanceWithMethods;
11161
11527
  exports.createProcessWithMethods = createProcessWithMethods;
11162
11528
  exports.createTaskWithMethods = createTaskWithMethods;
11529
+ exports.getAppBase = getAppBase;
11530
+ exports.getAsset = getAsset;
11163
11531
  exports.getErrorDetails = getErrorDetails;
11164
11532
  exports.getLimitedPageSize = getLimitedPageSize;
11165
11533
  exports.isAuthenticationError = isAuthenticationError;
@@ -11170,6 +11538,7 @@ exports.isRateLimitError = isRateLimitError;
11170
11538
  exports.isServerError = isServerError;
11171
11539
  exports.isUiPathError = isUiPathError;
11172
11540
  exports.isValidationError = isValidationError;
11541
+ exports.loadFromMetaTags = loadFromMetaTags;
11173
11542
  exports.telemetryClient = telemetryClient;
11174
11543
  exports.track = track;
11175
11544
  exports.trackEvent = trackEvent;