@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.umd.js CHANGED
@@ -3887,6 +3887,7 @@
3887
3887
  * Checks if code is running in a browser environment
3888
3888
  */
3889
3889
  const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
3890
+ const isInActionCenter = isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
3890
3891
 
3891
3892
  /**
3892
3893
  * Session storage keys used by the auth module
@@ -4203,6 +4204,102 @@
4203
4204
  };
4204
4205
  }
4205
4206
 
4207
+ var ActionCenterEventNames;
4208
+ (function (ActionCenterEventNames) {
4209
+ ActionCenterEventNames["TOKENREFRESHED"] = "AC.tokenRefreshed";
4210
+ ActionCenterEventNames["REFRESHTOKEN"] = "AC.refreshToken";
4211
+ })(ActionCenterEventNames || (ActionCenterEventNames = {}));
4212
+
4213
+ const AUTHENTICATION_TIMEOUT = 8000;
4214
+ class ActionCenterTokenManager {
4215
+ constructor(config, onTokenRefreshed) {
4216
+ this.config = config;
4217
+ this.onTokenRefreshed = onTokenRefreshed;
4218
+ this.parentOrigin = new URLSearchParams(window.location.search).get('basedomain');
4219
+ this.refreshPromise = null;
4220
+ }
4221
+ async refreshAccessToken(tokenInfo) {
4222
+ if (!this.isTokenExpired(tokenInfo)) {
4223
+ return tokenInfo.token;
4224
+ }
4225
+ if (this.refreshPromise) {
4226
+ return this.refreshPromise;
4227
+ }
4228
+ this.refreshPromise = new Promise((resolve, reject) => {
4229
+ const content = {
4230
+ clientId: this.config.clientId,
4231
+ scope: this.config.scope,
4232
+ };
4233
+ this.sendMessageToParent(ActionCenterEventNames.REFRESHTOKEN, content);
4234
+ const messageListener = (event) => {
4235
+ if (event.origin !== this.parentOrigin)
4236
+ return;
4237
+ if (event.data?.eventType !== ActionCenterEventNames.TOKENREFRESHED)
4238
+ return;
4239
+ clearTimeout(timer);
4240
+ if (event.data?.content?.token) {
4241
+ const { accessToken, expiresAt } = event.data.content.token;
4242
+ this.onTokenRefreshed({ token: accessToken, type: 'secret', expiresAt });
4243
+ resolve(accessToken);
4244
+ }
4245
+ else {
4246
+ reject(new AuthenticationError({
4247
+ message: 'Failed to fetch access token',
4248
+ statusCode: HttpStatus.UNAUTHORIZED,
4249
+ }));
4250
+ }
4251
+ this.refreshPromise = null;
4252
+ this.cleanup(messageListener);
4253
+ };
4254
+ const timer = setTimeout(() => {
4255
+ reject(new AuthenticationError({
4256
+ message: 'Failed to fetch access token',
4257
+ statusCode: HttpStatus.UNAUTHORIZED,
4258
+ }));
4259
+ this.refreshPromise = null;
4260
+ this.cleanup(messageListener);
4261
+ }, AUTHENTICATION_TIMEOUT);
4262
+ window.addEventListener('message', messageListener);
4263
+ });
4264
+ return this.refreshPromise;
4265
+ }
4266
+ isTokenExpired(tokenInfo) {
4267
+ if (!tokenInfo?.expiresAt) {
4268
+ return true;
4269
+ }
4270
+ return new Date() >= tokenInfo.expiresAt;
4271
+ }
4272
+ sendMessageToParent(eventType, content) {
4273
+ if (window.parent && this.isValidOrigin(this.parentOrigin)) {
4274
+ try {
4275
+ window.parent.postMessage({ eventType, content }, this.parentOrigin);
4276
+ }
4277
+ catch (error) {
4278
+ console.warn('Failed to send message to Action Center', JSON.stringify(error));
4279
+ }
4280
+ }
4281
+ }
4282
+ cleanup(messageListener) {
4283
+ window.removeEventListener('message', messageListener);
4284
+ }
4285
+ isValidOrigin(origin) {
4286
+ const ALLOWED_ORIGINS = ['https://alpha.uipath.com', 'https://staging.uipath.com', 'https://cloud.uipath.com'];
4287
+ if (!origin) {
4288
+ return false;
4289
+ }
4290
+ if (ALLOWED_ORIGINS.includes(origin)) {
4291
+ return true;
4292
+ }
4293
+ try {
4294
+ const url = new URL(origin);
4295
+ return url.hostname === 'localhost';
4296
+ }
4297
+ catch {
4298
+ return false;
4299
+ }
4300
+ }
4301
+ }
4302
+
4206
4303
  /**
4207
4304
  * TokenManager is responsible for managing authentication tokens.
4208
4305
  * It provides token operations for a specific client ID.
@@ -4221,6 +4318,11 @@
4221
4318
  this.config = config;
4222
4319
  this.isOAuth = isOAuth;
4223
4320
  this.refreshPromise = null;
4321
+ this.actionCenterTokenManager = null;
4322
+ if (isInActionCenter) {
4323
+ this.actionCenterTokenManager = new ActionCenterTokenManager(config, (tokenInfo) => this.setToken(tokenInfo));
4324
+ this.isOAuth = false;
4325
+ }
4224
4326
  }
4225
4327
  /**
4226
4328
  * Checks if a token is expired
@@ -4248,6 +4350,9 @@
4248
4350
  message: 'No authentication token available. Make sure to initialize the SDK first.'
4249
4351
  });
4250
4352
  }
4353
+ if (this.actionCenterTokenManager) {
4354
+ return await this.actionCenterTokenManager.refreshAccessToken(tokenInfo);
4355
+ }
4251
4356
  // For secret-based tokens, they never expire
4252
4357
  if (tokenInfo.type === 'secret') {
4253
4358
  return tokenInfo.token;
@@ -4392,9 +4497,6 @@
4392
4497
  clearToken() {
4393
4498
  this.currentToken = undefined;
4394
4499
  this.executionContext.set('tokenInfo', undefined);
4395
- const headers = this.executionContext.getHeaders();
4396
- delete headers['Authorization'];
4397
- this.executionContext.setHeaders(headers);
4398
4500
  // Remove from session storage if this is an OAuth token
4399
4501
  if (isBrowser && this.isOAuth) {
4400
4502
  try {
@@ -4410,10 +4512,6 @@
4410
4512
  */
4411
4513
  _updateExecutionContext(tokenInfo) {
4412
4514
  this.executionContext.set('tokenInfo', tokenInfo);
4413
- // Update authorization header
4414
- this.executionContext.setHeaders({
4415
- 'Authorization': `Bearer ${tokenInfo.token}`
4416
- });
4417
4515
  }
4418
4516
  /**
4419
4517
  * Refreshes the access token using the stored refresh token.
@@ -4597,6 +4695,7 @@
4597
4695
  UPDATE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/update-batch`,
4598
4696
  DELETE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/delete-batch`,
4599
4697
  DOWNLOAD_ATTACHMENT: (entityName, recordId, fieldName) => `${DATAFABRIC_BASE}/api/Attachment/${entityName}/${recordId}/${fieldName}`,
4698
+ UPLOAD_ATTACHMENT: (entityName, recordId, fieldName) => `${DATAFABRIC_BASE}/api/Attachment/${entityName}/${recordId}/${fieldName}`,
4600
4699
  },
4601
4700
  CHOICESETS: {
4602
4701
  GET_ALL: `${DATAFABRIC_BASE}/api/Entity/choiceset`,
@@ -4617,8 +4716,15 @@
4617
4716
 
4618
4717
  class AuthService {
4619
4718
  constructor(config, executionContext) {
4620
- // Check if we should use stored OAuth context instead of provided config
4621
- const storedContext = AuthService.getStoredOAuthContext();
4719
+ // Only use stored OAuth context when completing an active callback (URL has ?code=).
4720
+ // If stored context exists but we're NOT in a callback, it's stale from a
4721
+ // failed/abandoned flow (e.g. scope mismatch, invalid redirect URI) and must
4722
+ // be cleared so the fresh config takes effect.
4723
+ const isCallback = AuthService.isInOAuthCallback();
4724
+ const storedContext = isCallback ? AuthService.getStoredOAuthContext() : null;
4725
+ if (!isCallback) {
4726
+ AuthService._clearStoredOAuthContext();
4727
+ }
4622
4728
  const effectiveConfig = storedContext ? AuthService._mergeConfigWithContext(config, storedContext) : config;
4623
4729
  this.config = effectiveConfig;
4624
4730
  const isOAuth = hasOAuthConfig(effectiveConfig);
@@ -4665,6 +4771,22 @@
4665
4771
  return null;
4666
4772
  }
4667
4773
  }
4774
+ /**
4775
+ * Clear stale OAuth context from session storage.
4776
+ * Called when there is no active OAuth callback, meaning any stored context
4777
+ * is left over from a failed or abandoned flow.
4778
+ */
4779
+ static _clearStoredOAuthContext() {
4780
+ if (!isBrowser)
4781
+ return;
4782
+ try {
4783
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
4784
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4785
+ }
4786
+ catch {
4787
+ // Ignore storage errors
4788
+ }
4789
+ }
4668
4790
  /**
4669
4791
  * Merges provided config with stored OAuth context, prioritizing stored values
4670
4792
  */
@@ -4973,14 +5095,42 @@
4973
5095
  }
4974
5096
  }
4975
5097
 
5098
+ /**
5099
+ * Check if config has all required base fields
5100
+ */
5101
+ function hasRequiredBaseFields(config) {
5102
+ return Boolean(config.baseUrl && config.orgName && config.tenantName);
5103
+ }
5104
+ /**
5105
+ * Check if config has exactly one authentication method (secret XOR oauth)
5106
+ * Returns true if exactly one auth method is present, false otherwise
5107
+ */
5108
+ function hasValidAuthConfig(config) {
5109
+ const hasSecret = hasSecretConfig(config);
5110
+ const hasOAuth = hasOAuthConfig(config);
5111
+ // XOR: exactly one auth method, not both, not neither
5112
+ return hasSecret !== hasOAuth;
5113
+ }
4976
5114
  function validateConfig(config) {
4977
- if (!config.baseUrl || !config.orgName || !config.tenantName) {
5115
+ if (!hasRequiredBaseFields(config)) {
4978
5116
  throw new Error('Missing required configuration: baseUrl, orgName, and tenantName are required');
4979
5117
  }
4980
- if (!hasSecretConfig(config) && !hasOAuthConfig(config)) {
4981
- throw new Error('Invalid configuration: must provide either secret or (clientId, redirectUri, and scope)');
5118
+ const hasSecret = hasSecretConfig(config);
5119
+ const hasOAuth = hasOAuthConfig(config);
5120
+ if (hasSecret && hasOAuth) {
5121
+ throw new Error('Invalid configuration: cannot provide both secret and OAuth credentials. Choose one authentication method.');
5122
+ }
5123
+ if (!hasSecret && !hasOAuth) {
5124
+ throw new Error('Invalid configuration: must provide either secret or OAuth credentials (clientId, redirectUri, and scope)');
4982
5125
  }
4983
5126
  }
5127
+ /**
5128
+ * Check if partial config has all required fields for a complete SDK config
5129
+ * Requires base fields and exactly one authentication method (secret XOR oauth)
5130
+ */
5131
+ function isCompleteConfig(config) {
5132
+ return hasRequiredBaseFields(config) && hasValidAuthConfig(config);
5133
+ }
4984
5134
  function normalizeBaseUrl(url) {
4985
5135
  return url.endsWith('/') ? url.slice(0, -1) : url;
4986
5136
  }
@@ -8746,7 +8896,7 @@
8746
8896
  // Connection string placeholder that will be replaced during build
8747
8897
  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";
8748
8898
  // SDK Version placeholder
8749
- const SDK_VERSION = "1.1.1";
8899
+ const SDK_VERSION = "1.1.3";
8750
8900
  const VERSION = "Version";
8751
8901
  const SERVICE = "Service";
8752
8902
  const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
@@ -9075,19 +9225,71 @@
9075
9225
  }
9076
9226
  }
9077
9227
 
9078
- var _UiPath_config, _UiPath_authService, _UiPath_initialized;
9228
+ /**
9229
+ * UiPath meta tag names for runtime configuration.
9230
+ *
9231
+ * These meta tags are injected at deployment time by the Apps Service
9232
+ * to configure SDK authentication and asset resolution in production.
9233
+ */
9234
+ exports.UiPathMetaTags = void 0;
9235
+ (function (UiPathMetaTags) {
9236
+ // SDK/OAuth configuration
9237
+ UiPathMetaTags["CLIENT_ID"] = "uipath:client-id";
9238
+ UiPathMetaTags["SCOPE"] = "uipath:scope";
9239
+ UiPathMetaTags["ORG_NAME"] = "uipath:org-name";
9240
+ UiPathMetaTags["TENANT_NAME"] = "uipath:tenant-name";
9241
+ UiPathMetaTags["BASE_URL"] = "uipath:base-url";
9242
+ UiPathMetaTags["REDIRECT_URI"] = "uipath:redirect-uri";
9243
+ // Asset resolution and routing
9244
+ UiPathMetaTags["CDN_BASE"] = "uipath:cdn-base";
9245
+ UiPathMetaTags["APP_BASE"] = "uipath:app-base";
9246
+ })(exports.UiPathMetaTags || (exports.UiPathMetaTags = {}));
9247
+
9248
+ /**
9249
+ * Get the content of a meta tag by name.
9250
+ * Returns undefined if not in browser environment or meta tag is not found.
9251
+ */
9252
+ function getMetaTagContent(name) {
9253
+ if (!isBrowser)
9254
+ return undefined;
9255
+ return document.querySelector(`meta[name="${name}"]`)?.content;
9256
+ }
9257
+ /**
9258
+ * Load configuration from HTML meta tags injected at runtime.
9259
+ * These meta tags are injected by @uipath/coded-apps during build
9260
+ * or by the Apps service during deployment.
9261
+ *
9262
+ * Returns partial config with values found, or null if no meta tags present.
9263
+ */
9264
+ function loadFromMetaTags() {
9265
+ if (!isBrowser)
9266
+ return null;
9267
+ const config = {
9268
+ clientId: getMetaTagContent(exports.UiPathMetaTags.CLIENT_ID),
9269
+ scope: getMetaTagContent(exports.UiPathMetaTags.SCOPE),
9270
+ orgName: getMetaTagContent(exports.UiPathMetaTags.ORG_NAME),
9271
+ tenantName: getMetaTagContent(exports.UiPathMetaTags.TENANT_NAME),
9272
+ baseUrl: getMetaTagContent(exports.UiPathMetaTags.BASE_URL),
9273
+ redirectUri: getMetaTagContent(exports.UiPathMetaTags.REDIRECT_URI),
9274
+ };
9275
+ const hasAnyValue = Object.values(config).some(Boolean);
9276
+ return hasAnyValue ? config : null;
9277
+ }
9278
+
9279
+ var _UiPath_instances, _UiPath_config, _UiPath_authService, _UiPath_initialized, _UiPath_partialConfig, _UiPath_initializeWithConfig, _UiPath_loadConfig;
9079
9280
  /**
9080
9281
  * UiPath - Core SDK class for authentication and configuration management.
9081
9282
  *
9082
9283
  * Handles authentication, configuration, and provides access to SDK internals
9083
9284
  * for service instantiation in the modular pattern.
9084
9285
  *
9286
+ * Supports two usage patterns:
9287
+ * 1. Full config in constructor — for server-side or explicit configuration
9288
+ * 2. No config / partial config — loads from meta tags injected by @uipath/coded-apps plugin
9289
+ *
9085
9290
  * @example
9086
9291
  * ```typescript
9087
- * // Modular pattern
9088
- * import { UiPath } from '@uipath/uipath-typescript/core';
9089
- * import { Entities } from '@uipath/uipath-typescript/entities';
9090
- *
9292
+ * // Explicit config
9091
9293
  * const sdk = new UiPath({
9092
9294
  * baseUrl: 'https://cloud.uipath.com',
9093
9295
  * orgName: 'myorg',
@@ -9096,70 +9298,47 @@
9096
9298
  * redirectUri: 'http://localhost:3000/callback',
9097
9299
  * scope: 'OR.Users OR.Robots'
9098
9300
  * });
9099
- *
9100
9301
  * await sdk.initialize();
9302
+ * ```
9101
9303
  *
9102
- * const entitiesService = new Entities(sdk);
9103
- * const allEntities = await entitiesService.getAll();
9304
+ * @example
9305
+ * ```typescript
9306
+ * // Auto-load from meta tags (coded apps)
9307
+ * const sdk = new UiPath();
9308
+ * await sdk.initialize();
9104
9309
  * ```
9105
9310
  */
9106
9311
  let UiPath$1 = class UiPath {
9107
9312
  constructor(config) {
9313
+ _UiPath_instances.add(this);
9108
9314
  // Private fields - true runtime privacy, not visible via Object.keys()
9109
9315
  _UiPath_config.set(this, void 0);
9110
9316
  _UiPath_authService.set(this, void 0);
9111
9317
  _UiPath_initialized.set(this, false);
9112
- // Validate and normalize the configuration
9113
- validateConfig(config);
9114
- const hasSecretAuth = hasSecretConfig(config);
9115
- const hasOAuthAuth = hasOAuthConfig(config);
9116
- // Initialize core components
9117
- const internalConfig = new UiPathConfig({
9118
- baseUrl: normalizeBaseUrl(config.baseUrl),
9119
- orgName: config.orgName,
9120
- tenantName: config.tenantName,
9121
- secret: hasSecretAuth ? config.secret : undefined,
9122
- clientId: hasOAuthAuth ? config.clientId : undefined,
9123
- redirectUri: hasOAuthAuth ? config.redirectUri : undefined,
9124
- scope: hasOAuthAuth ? config.scope : undefined
9125
- });
9126
- const executionContext = new ExecutionContext();
9127
- __classPrivateFieldSet(this, _UiPath_authService, new AuthService(internalConfig, executionContext), "f");
9128
- __classPrivateFieldSet(this, _UiPath_config, internalConfig, "f");
9129
- // Store internals in SDKInternalsRegistry (not visible on instance)
9130
- SDKInternalsRegistry.set(this, {
9131
- config: internalConfig,
9132
- context: executionContext,
9133
- tokenManager: __classPrivateFieldGet(this, _UiPath_authService, "f").getTokenManager()
9134
- });
9135
- // Expose read-only config for user convenience
9136
- this.config = {
9137
- baseUrl: internalConfig.baseUrl,
9138
- orgName: internalConfig.orgName,
9139
- tenantName: internalConfig.tenantName
9140
- };
9141
- // Initialize telemetry with SDK configuration
9142
- telemetryClient.initialize({
9143
- baseUrl: config.baseUrl,
9144
- orgName: config.orgName,
9145
- tenantName: config.tenantName,
9146
- clientId: hasOAuthAuth ? config.clientId : undefined,
9147
- redirectUri: hasOAuthAuth ? config.redirectUri : undefined
9148
- });
9149
- // Track SDK initialization
9150
- trackEvent('Sdk.Auth');
9151
- // Auto-initialize for secret-based auth
9152
- if (hasSecretAuth) {
9153
- __classPrivateFieldGet(this, _UiPath_authService, "f").authenticateWithSecret(config.secret);
9154
- __classPrivateFieldSet(this, _UiPath_initialized, true, "f");
9318
+ _UiPath_partialConfig.set(this, void 0);
9319
+ // Load configuration from meta tags
9320
+ const configFromMetaTags = loadFromMetaTags();
9321
+ // Merge configuration: constructor config overrides meta tags
9322
+ const mergedConfig = config ? { ...configFromMetaTags, ...config } : configFromMetaTags;
9323
+ if (mergedConfig && isCompleteConfig(mergedConfig)) {
9324
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, mergedConfig);
9325
+ }
9326
+ else if (config) {
9327
+ __classPrivateFieldSet(this, _UiPath_partialConfig, config, "f");
9155
9328
  }
9156
9329
  }
9157
9330
  /**
9158
9331
  * Initialize the SDK based on the provided configuration.
9159
9332
  * This method handles both OAuth flow initiation and completion automatically.
9160
9333
  * For secret-based authentication, initialization is automatic and this returns immediately.
9334
+ * If no config was provided in constructor, loads from meta tags.
9161
9335
  */
9162
9336
  async initialize() {
9337
+ // Load config from meta tags if not provided in constructor
9338
+ if (!__classPrivateFieldGet(this, _UiPath_config, "f")) {
9339
+ const loadedConfig = __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_loadConfig).call(this);
9340
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, loadedConfig);
9341
+ }
9163
9342
  // For secret-based auth, it's already initialized in constructor
9164
9343
  if (hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
9165
9344
  return;
@@ -9206,6 +9385,11 @@
9206
9385
  if (!AuthService.isInOAuthCallback()) {
9207
9386
  throw new Error('Not in OAuth callback state. Call initialize() first to start OAuth flow.');
9208
9387
  }
9388
+ // Load config if not yet initialized
9389
+ if (!__classPrivateFieldGet(this, _UiPath_config, "f")) {
9390
+ const loadedConfig = __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_loadConfig).call(this);
9391
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, loadedConfig);
9392
+ }
9209
9393
  try {
9210
9394
  const success = await __classPrivateFieldGet(this, _UiPath_authService, "f").authenticate(__classPrivateFieldGet(this, _UiPath_config, "f"));
9211
9395
  if (success && this.isAuthenticated()) {
@@ -9223,13 +9407,13 @@
9223
9407
  * Check if the user is authenticated (has valid token)
9224
9408
  */
9225
9409
  isAuthenticated() {
9226
- return __classPrivateFieldGet(this, _UiPath_authService, "f").hasValidToken();
9410
+ return __classPrivateFieldGet(this, _UiPath_authService, "f")?.hasValidToken() ?? false;
9227
9411
  }
9228
9412
  /**
9229
9413
  * Get the current authentication token
9230
9414
  */
9231
9415
  getToken() {
9232
- return __classPrivateFieldGet(this, _UiPath_authService, "f").getToken();
9416
+ return __classPrivateFieldGet(this, _UiPath_authService, "f")?.getToken();
9233
9417
  }
9234
9418
  /**
9235
9419
  * Logout from the SDK, clearing all authentication state.
@@ -9237,14 +9421,71 @@
9237
9421
  */
9238
9422
  logout() {
9239
9423
  // Secret-based auth has no session to end — skip silently
9240
- if (hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
9424
+ if (__classPrivateFieldGet(this, _UiPath_config, "f") && hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
9241
9425
  return;
9242
9426
  }
9243
- __classPrivateFieldGet(this, _UiPath_authService, "f").logout();
9427
+ __classPrivateFieldGet(this, _UiPath_authService, "f")?.logout();
9244
9428
  __classPrivateFieldSet(this, _UiPath_initialized, false, "f");
9245
9429
  }
9246
9430
  };
9247
- _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap();
9431
+ _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) {
9432
+ // Validate and normalize the configuration
9433
+ validateConfig(config);
9434
+ const hasSecretAuth = hasSecretConfig(config);
9435
+ const hasOAuthAuth = hasOAuthConfig(config);
9436
+ // Initialize core components
9437
+ const internalConfig = new UiPathConfig({
9438
+ baseUrl: normalizeBaseUrl(config.baseUrl),
9439
+ orgName: config.orgName,
9440
+ tenantName: config.tenantName,
9441
+ secret: hasSecretAuth ? config.secret : undefined,
9442
+ clientId: hasOAuthAuth ? config.clientId : undefined,
9443
+ redirectUri: hasOAuthAuth ? config.redirectUri : undefined,
9444
+ scope: hasOAuthAuth ? config.scope : undefined
9445
+ });
9446
+ const executionContext = new ExecutionContext();
9447
+ __classPrivateFieldSet(this, _UiPath_authService, new AuthService(internalConfig, executionContext), "f");
9448
+ __classPrivateFieldSet(this, _UiPath_config, internalConfig, "f");
9449
+ // Store internals in SDKInternalsRegistry (not visible on instance)
9450
+ SDKInternalsRegistry.set(this, {
9451
+ config: internalConfig,
9452
+ context: executionContext,
9453
+ tokenManager: __classPrivateFieldGet(this, _UiPath_authService, "f").getTokenManager()
9454
+ });
9455
+ // Expose read-only config for user convenience
9456
+ this.config = {
9457
+ baseUrl: internalConfig.baseUrl,
9458
+ orgName: internalConfig.orgName,
9459
+ tenantName: internalConfig.tenantName
9460
+ };
9461
+ // Initialize telemetry with SDK configuration
9462
+ telemetryClient.initialize({
9463
+ baseUrl: config.baseUrl,
9464
+ orgName: config.orgName,
9465
+ tenantName: config.tenantName,
9466
+ clientId: hasOAuthAuth ? config.clientId : undefined,
9467
+ redirectUri: hasOAuthAuth ? config.redirectUri : undefined
9468
+ });
9469
+ // Track SDK initialization
9470
+ trackEvent('Sdk.Auth');
9471
+ /** Auto-initialize for secret-based auth
9472
+ * When viewed in Action Center, initialize tokenInfo with empty token. When an sdk call is made Action Center passes the token to sdk.
9473
+ */
9474
+ if (hasSecretAuth || isInActionCenter) {
9475
+ __classPrivateFieldGet(this, _UiPath_authService, "f").authenticateWithSecret(config.secret ?? '');
9476
+ __classPrivateFieldSet(this, _UiPath_initialized, true, "f");
9477
+ }
9478
+ }, _UiPath_loadConfig = function _UiPath_loadConfig() {
9479
+ // Load from meta tags
9480
+ const metaConfig = loadFromMetaTags();
9481
+ // Merge with any partial config from constructor (constructor overrides meta tags)
9482
+ const merged = { ...metaConfig, ...__classPrivateFieldGet(this, _UiPath_partialConfig, "f") };
9483
+ if (!isCompleteConfig(merged)) {
9484
+ throw new Error('UiPath SDK configuration not found. ' +
9485
+ 'Ensure @uipath/coded-apps plugin is set up in your bundler to inject configuration during development and build.');
9486
+ }
9487
+ return merged;
9488
+ };
9248
9489
 
9249
9490
  /**
9250
9491
  * Type guards for error response types
@@ -9523,15 +9764,6 @@
9523
9764
  async getDefaultHeaders() {
9524
9765
  // Get headers from execution context first
9525
9766
  const contextHeaders = this.executionContext.getHeaders();
9526
- // If Authorization header is already set in context, use that
9527
- if (contextHeaders['Authorization']) {
9528
- return {
9529
- ...contextHeaders,
9530
- 'Content-Type': CONTENT_TYPES.JSON,
9531
- ...this.defaultHeaders,
9532
- ...this.clientConfig.headers
9533
- };
9534
- }
9535
9767
  const token = await this.getValidToken();
9536
9768
  return {
9537
9769
  ...contextHeaders,
@@ -9546,8 +9778,13 @@
9546
9778
  const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
9547
9779
  // Construct URL with org and tenant names
9548
9780
  const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
9781
+ const isFormData = options.body instanceof FormData;
9782
+ const defaultHeaders = await this.getDefaultHeaders();
9783
+ if (isFormData) {
9784
+ delete defaultHeaders['Content-Type'];
9785
+ }
9549
9786
  const headers = {
9550
- ...await this.getDefaultHeaders(),
9787
+ ...defaultHeaders,
9551
9788
  ...options.headers
9552
9789
  };
9553
9790
  // Convert params to URLSearchParams
@@ -9558,11 +9795,15 @@
9558
9795
  });
9559
9796
  }
9560
9797
  const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
9798
+ let body = undefined;
9799
+ if (options.body) {
9800
+ body = isFormData ? options.body : JSON.stringify(options.body);
9801
+ }
9561
9802
  try {
9562
9803
  const response = await fetch(fullUrl, {
9563
9804
  method,
9564
9805
  headers,
9565
- body: options.body ? JSON.stringify(options.body) : undefined,
9806
+ body,
9566
9807
  signal: options.signal
9567
9808
  });
9568
9809
  if (!response.ok) {
@@ -10853,6 +11094,17 @@
10853
11094
  fieldName
10854
11095
  });
10855
11096
  },
11097
+ async uploadAttachment(recordId, fieldName, file, expansionLevel) {
11098
+ if (!entityData.name)
11099
+ throw new Error('Entity name is undefined');
11100
+ return service.uploadAttachment({
11101
+ entityName: entityData.name,
11102
+ recordId,
11103
+ fieldName,
11104
+ file,
11105
+ expansionLevel
11106
+ });
11107
+ },
10856
11108
  async insert(data, options) {
10857
11109
  return this.insertRecord(data, options);
10858
11110
  },
@@ -11356,6 +11608,42 @@
11356
11608
  });
11357
11609
  return response.data;
11358
11610
  }
11611
+ /**
11612
+ * Uploads an attachment to a File-type field of an entity record
11613
+ *
11614
+ * @param options - Options containing entityName, recordId, fieldName, file, and optional expansionLevel
11615
+ * @returns Promise resolving to the upload response
11616
+ *
11617
+ * @example
11618
+ * ```typescript
11619
+ * import { Entities } from '@uipath/uipath-typescript/entities';
11620
+ *
11621
+ * const entities = new Entities(sdk);
11622
+ *
11623
+ * // Upload a file attachment
11624
+ * const response = await entities.uploadAttachment({
11625
+ * entityName: 'Invoice',
11626
+ * recordId: '<record-uuid>',
11627
+ * fieldName: 'Documents',
11628
+ * file: file
11629
+ * });
11630
+ * ```
11631
+ */
11632
+ async uploadAttachment(options) {
11633
+ const { entityName, recordId, fieldName, file, expansionLevel } = options;
11634
+ const formData = new FormData();
11635
+ if (file instanceof Uint8Array) {
11636
+ formData.append('file', new Blob([file.buffer]));
11637
+ }
11638
+ else {
11639
+ formData.append('file', file);
11640
+ }
11641
+ const params = createParams({ expansionLevel });
11642
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPLOAD_ATTACHMENT(entityName, recordId, fieldName), formData, { params });
11643
+ // Convert PascalCase response to camelCase
11644
+ const camelResponse = pascalToCamelCaseKeys(response.data);
11645
+ return camelResponse;
11646
+ }
11359
11647
  /**
11360
11648
  * @hidden
11361
11649
  * @deprecated Use {@link getAllRecords} instead.
@@ -11489,6 +11777,9 @@
11489
11777
  __decorate([
11490
11778
  track('Entities.DownloadAttachment')
11491
11779
  ], EntityService.prototype, "downloadAttachment", null);
11780
+ __decorate([
11781
+ track('Entities.UploadAttachment')
11782
+ ], EntityService.prototype, "uploadAttachment", null);
11492
11783
 
11493
11784
  class ChoiceSetService extends BaseService {
11494
11785
  /**
@@ -14875,6 +15166,81 @@
14875
15166
  ...CommonFieldMap
14876
15167
  };
14877
15168
 
15169
+ /**
15170
+ * Asset resolution utilities for UiPath Coded Apps
15171
+ *
15172
+ * These helpers enable developers to write code that works identically
15173
+ * in local development and production environments.
15174
+ *
15175
+ * Values are read from meta tags injected at deployment:
15176
+ * - <meta name="uipath:cdn-base" content="https://cdn.example.com/appId/folder">
15177
+ * - <meta name="uipath:app-base" content="/org/apps_/.../public">
15178
+ */
15179
+ /**
15180
+ * Resolves an asset path to the CDN URL (if available)
15181
+ *
15182
+ * In local development: returns path as-is (loads from local dev server)
15183
+ * In production: prepends CDN base URL from meta tag
15184
+ *
15185
+ * @param path - The asset path (e.g., './assets/logo.png' or '/assets/logo.png')
15186
+ * @returns The resolved asset URL
15187
+ *
15188
+ * @example
15189
+ * ```tsx
15190
+ * import { getAsset } from '@uipath/uipath-typescript';
15191
+ * import logoPath from './assets/logo.png';
15192
+ *
15193
+ * function MyComponent() {
15194
+ * return <img src={getAsset(logoPath)} alt="Logo" />;
15195
+ * }
15196
+ * ```
15197
+ */
15198
+ function getAsset(path) {
15199
+ // If path is already an absolute URL, return as-is
15200
+ if (path.startsWith('http://') || path.startsWith('https://')) {
15201
+ return path;
15202
+ }
15203
+ const cdnBase = getMetaTagContent(exports.UiPathMetaTags.CDN_BASE);
15204
+ if (!cdnBase)
15205
+ return path;
15206
+ // Normalize CDN base URL to remove trailing slash
15207
+ const normalizedCdnBase = normalizeBaseUrl(cdnBase);
15208
+ // Normalize path to ensure it starts with /
15209
+ let normalizedPath = path;
15210
+ if (normalizedPath.startsWith('./')) {
15211
+ normalizedPath = normalizedPath.substring(1); // ./assets -> /assets
15212
+ }
15213
+ else if (!normalizedPath.startsWith('/')) {
15214
+ normalizedPath = '/' + normalizedPath; // assets -> /assets
15215
+ }
15216
+ return normalizedCdnBase + normalizedPath;
15217
+ }
15218
+ /**
15219
+ * Returns the app base path for router configuration
15220
+ *
15221
+ * In local development: returns '/'
15222
+ * In production: returns the deployed app path from meta tag
15223
+ *
15224
+ * @returns The app base path
15225
+ *
15226
+ * @example
15227
+ * ```tsx
15228
+ * import { getAppBase } from '@uipath/uipath-typescript';
15229
+ * import { BrowserRouter } from 'react-router-dom';
15230
+ *
15231
+ * function App() {
15232
+ * return (
15233
+ * <BrowserRouter basename={getAppBase()}>
15234
+ * {/* routes *\/}
15235
+ * </BrowserRouter>
15236
+ * );
15237
+ * }
15238
+ * ```
15239
+ */
15240
+ function getAppBase() {
15241
+ return getMetaTagContent(exports.UiPathMetaTags.APP_BASE) || '/';
15242
+ }
15243
+
14878
15244
  exports.APP_NAME = APP_NAME;
14879
15245
  exports.AgentMap = AgentMap;
14880
15246
  exports.AuthenticationError = AuthenticationError;
@@ -14917,6 +15283,8 @@
14917
15283
  exports.createProcessInstanceWithMethods = createProcessInstanceWithMethods;
14918
15284
  exports.createProcessWithMethods = createProcessWithMethods;
14919
15285
  exports.createTaskWithMethods = createTaskWithMethods;
15286
+ exports.getAppBase = getAppBase;
15287
+ exports.getAsset = getAsset;
14920
15288
  exports.getErrorDetails = getErrorDetails;
14921
15289
  exports.getLimitedPageSize = getLimitedPageSize;
14922
15290
  exports.isAuthenticationError = isAuthenticationError;
@@ -14927,6 +15295,7 @@
14927
15295
  exports.isServerError = isServerError;
14928
15296
  exports.isUiPathError = isUiPathError;
14929
15297
  exports.isValidationError = isValidationError;
15298
+ exports.loadFromMetaTags = loadFromMetaTags;
14930
15299
  exports.telemetryClient = telemetryClient;
14931
15300
  exports.track = track;
14932
15301
  exports.trackEvent = trackEvent;