@uipath/uipath-typescript 1.3.11 → 1.4.1

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.
Files changed (59) hide show
  1. package/dist/agent-memory/index.cjs +1772 -0
  2. package/dist/agent-memory/index.d.ts +588 -0
  3. package/dist/agent-memory/index.mjs +1770 -0
  4. package/dist/agents/index.cjs +1995 -0
  5. package/dist/agents/index.d.ts +961 -0
  6. package/dist/agents/index.mjs +1993 -0
  7. package/dist/assets/index.cjs +171 -39
  8. package/dist/assets/index.d.ts +84 -5
  9. package/dist/assets/index.mjs +171 -39
  10. package/dist/attachments/index.cjs +53 -15
  11. package/dist/attachments/index.d.ts +1 -0
  12. package/dist/attachments/index.mjs +53 -15
  13. package/dist/buckets/index.cjs +151 -130
  14. package/dist/buckets/index.d.ts +198 -84
  15. package/dist/buckets/index.mjs +151 -130
  16. package/dist/cases/index.cjs +220 -23
  17. package/dist/cases/index.d.ts +148 -10
  18. package/dist/cases/index.mjs +220 -24
  19. package/dist/conversational-agent/index.cjs +140 -66
  20. package/dist/conversational-agent/index.d.ts +190 -122
  21. package/dist/conversational-agent/index.mjs +140 -66
  22. package/dist/core/index.cjs +445 -108
  23. package/dist/core/index.d.ts +15 -0
  24. package/dist/core/index.mjs +445 -108
  25. package/dist/entities/index.cjs +365 -102
  26. package/dist/entities/index.d.ts +446 -114
  27. package/dist/entities/index.mjs +365 -102
  28. package/dist/feedback/index.cjs +53 -15
  29. package/dist/feedback/index.d.ts +1 -0
  30. package/dist/feedback/index.mjs +53 -15
  31. package/dist/governance/index.cjs +1789 -0
  32. package/dist/governance/index.d.ts +598 -0
  33. package/dist/governance/index.mjs +1787 -0
  34. package/dist/index.cjs +1453 -444
  35. package/dist/index.d.ts +4150 -1742
  36. package/dist/index.mjs +1452 -445
  37. package/dist/index.umd.js +5035 -4009
  38. package/dist/jobs/index.cjs +53 -15
  39. package/dist/jobs/index.d.ts +1 -0
  40. package/dist/jobs/index.mjs +53 -15
  41. package/dist/maestro-processes/index.cjs +189 -27
  42. package/dist/maestro-processes/index.d.ts +131 -9
  43. package/dist/maestro-processes/index.mjs +189 -27
  44. package/dist/orchestrator-du-module/index.cjs +1788 -0
  45. package/dist/orchestrator-du-module/index.d.ts +757 -0
  46. package/dist/orchestrator-du-module/index.mjs +1785 -0
  47. package/dist/processes/index.cjs +53 -15
  48. package/dist/processes/index.d.ts +1 -0
  49. package/dist/processes/index.mjs +53 -15
  50. package/dist/queues/index.cjs +53 -15
  51. package/dist/queues/index.d.ts +1 -0
  52. package/dist/queues/index.mjs +53 -15
  53. package/dist/tasks/index.cjs +116 -19
  54. package/dist/tasks/index.d.ts +110 -4
  55. package/dist/tasks/index.mjs +117 -20
  56. package/dist/traces/index.cjs +340 -15
  57. package/dist/traces/index.d.ts +483 -2
  58. package/dist/traces/index.mjs +339 -16
  59. package/package.json +42 -2
@@ -4013,7 +4013,7 @@ object({
4013
4013
  secret: string().optional(),
4014
4014
  clientId: string().optional(),
4015
4015
  redirectUri: string().url().optional(),
4016
- scope: string().optional()
4016
+ scope: string().optional(),
4017
4017
  });
4018
4018
  class UiPathConfig {
4019
4019
  constructor(options) {
@@ -4064,6 +4064,32 @@ class ExecutionContext {
4064
4064
  */
4065
4065
  const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
4066
4066
  const isInActionCenter = isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
4067
+ const _params = isBrowser ? new URLSearchParams(window.location.search) : null;
4068
+ /**
4069
+ * True when the coded app has been loaded inside a host frame that explicitly
4070
+ * opted into token delegation by adding `?host=embed` to the iframe src URL.
4071
+ */
4072
+ const isHostEmbedded = isBrowser && window.self !== window.top && _params?.get('host') === 'embed';
4073
+ /**
4074
+ * The validated parent origin, read from the `?basedomain=` query param set
4075
+ * by the embedding host in the iframe src URL.
4076
+ * Mirrors the same mechanism used by ActionCenterTokenManager.
4077
+ * Non-null only when `?host=embed` is present and `?basedomain=` is a valid URL.
4078
+ */
4079
+ const embeddingOrigin = (() => {
4080
+ if (!isHostEmbedded)
4081
+ return null;
4082
+ const basedomain = _params?.get('basedomain');
4083
+ if (!basedomain)
4084
+ return null;
4085
+ try {
4086
+ return new URL(basedomain).origin;
4087
+ }
4088
+ catch {
4089
+ console.warn('embeddingOrigin: basedomain query param is not a valid URL', basedomain);
4090
+ return null;
4091
+ }
4092
+ })();
4067
4093
 
4068
4094
  /**
4069
4095
  * Session storage keys used by the auth module
@@ -4451,6 +4477,24 @@ var TaskActivityType;
4451
4477
  TaskActivityType["BulkCompleted"] = "BulkCompleted";
4452
4478
  TaskActivityType["FirstOpened"] = "FirstOpened";
4453
4479
  })(TaskActivityType || (TaskActivityType = {}));
4480
+ /**
4481
+ * Defines how a task assignment is distributed.
4482
+ *
4483
+ * Defaults to {@link TaskAssignmentCriteria.SingleUser} (a direct single-user
4484
+ * assignment) when not specified. The group-based criteria tell Action Center
4485
+ * how to distribute the task across the members of a directory group.
4486
+ */
4487
+ var TaskAssignmentCriteria;
4488
+ (function (TaskAssignmentCriteria) {
4489
+ /** Assigned to a single user, like a direct assignment. */
4490
+ TaskAssignmentCriteria["SingleUser"] = "SingleUser";
4491
+ /** Assigned to the group member with the fewest pending tasks. */
4492
+ TaskAssignmentCriteria["Workload"] = "Workload";
4493
+ /** Assigned to all users in the group. */
4494
+ TaskAssignmentCriteria["AllUsers"] = "AllUsers";
4495
+ /** Assigned in a round-robin manner across the group's members. */
4496
+ TaskAssignmentCriteria["RoundRobin"] = "RoundRobin";
4497
+ })(TaskAssignmentCriteria || (TaskAssignmentCriteria = {}));
4454
4498
 
4455
4499
  /**
4456
4500
  * Base path constants for different services
@@ -4496,6 +4540,105 @@ var ActionCenterEventNames;
4496
4540
  })(ActionCenterEventNames || (ActionCenterEventNames = {}));
4497
4541
 
4498
4542
  const AUTHENTICATION_TIMEOUT = 8000;
4543
+ const ALLOWED_HOST_ORIGINS = new Set([
4544
+ 'https://alpha.uipath.com',
4545
+ 'https://staging.uipath.com',
4546
+ 'https://cloud.uipath.com',
4547
+ ]);
4548
+ /**
4549
+ * Returns true if the origin is a trusted UiPath host that may initiate
4550
+ * token delegation. Mirrors the same allowlist used by ActionCenterTokenManager.
4551
+ */
4552
+ function isValidHostOrigin(origin) {
4553
+ if (!origin)
4554
+ return false;
4555
+ if (ALLOWED_HOST_ORIGINS.has(origin))
4556
+ return true;
4557
+ try {
4558
+ return new URL(origin).hostname === 'localhost';
4559
+ }
4560
+ catch {
4561
+ console.warn('isValidHostOrigin: received a malformed origin URL', origin);
4562
+ return false;
4563
+ }
4564
+ }
4565
+ function isTokenExpired(tokenInfo) {
4566
+ if (!tokenInfo?.expiresAt)
4567
+ return true;
4568
+ return new Date() >= tokenInfo.expiresAt;
4569
+ }
4570
+ /**
4571
+ * The validated host origin when the app is running as a trusted, generic
4572
+ * host-embedded app (`?host=embed&basedomain=<origin>` with an allowlisted
4573
+ * UiPath origin); otherwise null. Shared by TokenManager (to create the
4574
+ * EmbeddedTokenManager) and UiPath init (to seed an empty token so getValidToken
4575
+ * can bootstrap the postMessage token flow), which previously duplicated this
4576
+ * condition inline.
4577
+ */
4578
+ const trustedEmbeddingOrigin = isHostEmbedded && embeddingOrigin && isValidHostOrigin(embeddingOrigin) ? embeddingOrigin : null;
4579
+ /**
4580
+ * Waits for the next window message that satisfies `filter`.
4581
+ * Rejects if the AbortSignal fires before a matching message arrives.
4582
+ */
4583
+ function waitForMessage(filter, signal) {
4584
+ return new Promise((resolve, reject) => {
4585
+ const handler = (event) => {
4586
+ if (!filter(event))
4587
+ return;
4588
+ window.removeEventListener('message', handler);
4589
+ resolve(event);
4590
+ };
4591
+ signal.addEventListener('abort', () => {
4592
+ window.removeEventListener('message', handler);
4593
+ reject(signal.reason);
4594
+ }, { once: true });
4595
+ window.addEventListener('message', handler);
4596
+ });
4597
+ }
4598
+ /**
4599
+ * Sends a token-refresh request to a parent host frame and waits for the
4600
+ * response. Handles timeout, origin filtering, and listener cleanup.
4601
+ *
4602
+ * Both ActionCenterTokenManager and EmbeddedTokenManager delegate to this
4603
+ * function; they differ only in the event names and message shape they use.
4604
+ */
4605
+ function requestHostToken(options) {
4606
+ const { pinnedOrigin, sendRequest, responseEventType, extractToken, onTokenRefreshed } = options;
4607
+ const controller = new AbortController();
4608
+ const cancel = () => controller.abort(new AuthenticationError({
4609
+ message: 'Token refresh cancelled',
4610
+ statusCode: HttpStatus.UNAUTHORIZED,
4611
+ }));
4612
+ const promise = (async () => {
4613
+ const timer = setTimeout(() => controller.abort(new AuthenticationError({
4614
+ message: `Token refresh timed out after ${AUTHENTICATION_TIMEOUT}ms waiting for host response`,
4615
+ statusCode: HttpStatus.UNAUTHORIZED,
4616
+ })), AUTHENTICATION_TIMEOUT);
4617
+ try {
4618
+ // Register listener before sending — avoids any race between send and response
4619
+ const responsePromise = waitForMessage(event => event.origin === pinnedOrigin && event.data?.eventType === responseEventType, controller.signal);
4620
+ sendRequest();
4621
+ const event = await responsePromise;
4622
+ const token = extractToken(event.data);
4623
+ if (!token) {
4624
+ throw new AuthenticationError({
4625
+ message: 'Host responded but did not include a valid access token',
4626
+ statusCode: HttpStatus.UNAUTHORIZED,
4627
+ });
4628
+ }
4629
+ // type: 'secret' intentionally prevents the SDK's internal OAuth refresh path
4630
+ // from running — the host manager owns the refresh cycle via requestHostToken.
4631
+ // This mirrors the same pattern used by ActionCenterTokenManager.
4632
+ onTokenRefreshed({ token: token.accessToken, type: 'secret', expiresAt: token.expiresAt });
4633
+ return token.accessToken;
4634
+ }
4635
+ finally {
4636
+ clearTimeout(timer);
4637
+ }
4638
+ })();
4639
+ return { promise, cancel };
4640
+ }
4641
+
4499
4642
  class ActionCenterTokenManager {
4500
4643
  constructor(config, onTokenRefreshed) {
4501
4644
  this.config = config;
@@ -4504,85 +4647,283 @@ class ActionCenterTokenManager {
4504
4647
  this.refreshPromise = null;
4505
4648
  }
4506
4649
  async refreshAccessToken(tokenInfo) {
4507
- if (!this.isTokenExpired(tokenInfo)) {
4650
+ if (!isTokenExpired(tokenInfo)) {
4508
4651
  return tokenInfo.token;
4509
4652
  }
4510
4653
  if (this.refreshPromise) {
4511
4654
  return this.refreshPromise;
4512
4655
  }
4513
- this.refreshPromise = new Promise((resolve, reject) => {
4514
- const content = {
4656
+ const parentOrigin = this.parentOrigin;
4657
+ if (!parentOrigin) {
4658
+ return Promise.reject(new AuthenticationError({
4659
+ message: 'Cannot refresh token: basedomain query parameter is missing',
4660
+ statusCode: HttpStatus.UNAUTHORIZED,
4661
+ }));
4662
+ }
4663
+ // Guard before requestHostToken registers the inbound listener — an untrusted
4664
+ // basedomain would otherwise leave the listener live for the full timeout window,
4665
+ // accepting a forged TOKENREFRESHED from that origin.
4666
+ if (!isValidHostOrigin(parentOrigin)) {
4667
+ return Promise.reject(new AuthenticationError({
4668
+ message: 'Cannot refresh token: basedomain is not a trusted UiPath host origin',
4669
+ statusCode: HttpStatus.UNAUTHORIZED,
4670
+ }));
4671
+ }
4672
+ const { promise } = requestHostToken({
4673
+ pinnedOrigin: parentOrigin,
4674
+ sendRequest: () => this.sendMessageToParent(ActionCenterEventNames.REFRESHTOKEN, {
4515
4675
  clientId: this.config.clientId,
4516
4676
  scope: this.config.scope,
4517
- };
4518
- this.sendMessageToParent(ActionCenterEventNames.REFRESHTOKEN, content);
4519
- const messageListener = (event) => {
4520
- if (event.origin !== this.parentOrigin)
4521
- return;
4522
- if (event.data?.eventType !== ActionCenterEventNames.TOKENREFRESHED)
4523
- return;
4524
- clearTimeout(timer);
4525
- if (event.data?.content?.token) {
4526
- const { accessToken, expiresAt } = event.data.content.token;
4527
- this.onTokenRefreshed({ token: accessToken, type: 'secret', expiresAt });
4528
- resolve(accessToken);
4529
- }
4530
- else {
4531
- reject(new AuthenticationError({
4532
- message: 'Failed to fetch access token',
4533
- statusCode: HttpStatus.UNAUTHORIZED,
4534
- }));
4535
- }
4536
- this.refreshPromise = null;
4537
- this.cleanup(messageListener);
4538
- };
4539
- const timer = setTimeout(() => {
4540
- reject(new AuthenticationError({
4541
- message: 'Failed to fetch access token',
4542
- statusCode: HttpStatus.UNAUTHORIZED,
4543
- }));
4544
- this.refreshPromise = null;
4545
- this.cleanup(messageListener);
4546
- }, AUTHENTICATION_TIMEOUT);
4547
- window.addEventListener('message', messageListener);
4677
+ }),
4678
+ responseEventType: ActionCenterEventNames.TOKENREFRESHED,
4679
+ extractToken: (data) => {
4680
+ const token = data?.content?.token;
4681
+ if (!token?.accessToken)
4682
+ return undefined;
4683
+ return { accessToken: token.accessToken, expiresAt: token.expiresAt };
4684
+ },
4685
+ onTokenRefreshed: this.onTokenRefreshed,
4548
4686
  });
4549
- return this.refreshPromise;
4550
- }
4551
- isTokenExpired(tokenInfo) {
4552
- if (!tokenInfo?.expiresAt) {
4553
- return true;
4687
+ this.refreshPromise = promise;
4688
+ try {
4689
+ return await this.refreshPromise;
4690
+ }
4691
+ finally {
4692
+ this.refreshPromise = null;
4554
4693
  }
4555
- return new Date() >= tokenInfo.expiresAt;
4556
4694
  }
4557
4695
  sendMessageToParent(eventType, content) {
4558
- if (window.parent && this.isValidOrigin(this.parentOrigin)) {
4696
+ if (window.parent && isValidHostOrigin(this.parentOrigin)) {
4559
4697
  try {
4560
4698
  window.parent.postMessage({ eventType, content }, this.parentOrigin);
4561
4699
  }
4562
4700
  catch (error) {
4563
- console.warn('Failed to send message to Action Center', JSON.stringify(error));
4701
+ console.warn('ActionCenterTokenManager: postMessage to host failed', JSON.stringify(error));
4564
4702
  }
4565
4703
  }
4566
4704
  }
4567
- cleanup(messageListener) {
4568
- window.removeEventListener('message', messageListener);
4705
+ }
4706
+
4707
+ /**
4708
+ * Event names and payload types for the UIP.* postMessage protocol used
4709
+ * when a coded app is embedded inside a UiPath host (e.g. Governance Portal, Insights UI).
4710
+ *
4711
+ * Flow — app-initiated, mirrors the Action Center protocol:
4712
+ * App → Host: UIP.refreshToken (requests a token; carries clientId + scope
4713
+ * so the host knows which OAuth client to use)
4714
+ * Host → App: UIP.tokenRefreshed (delivers the access token)
4715
+ *
4716
+ * Detection: the host signals embedding via `?host=embed&basedomain=<origin>` in
4717
+ * the iframe src URL. No explicit init message from the host is required.
4718
+ */
4719
+ var UipEmbeddedEventNames;
4720
+ (function (UipEmbeddedEventNames) {
4721
+ UipEmbeddedEventNames["REFRESH_TOKEN"] = "UIP.refreshToken";
4722
+ UipEmbeddedEventNames["TOKEN_REFRESHED"] = "UIP.tokenRefreshed";
4723
+ })(UipEmbeddedEventNames || (UipEmbeddedEventNames = {}));
4724
+
4725
+ function parseExpiresAt(raw) {
4726
+ const d = new Date(raw);
4727
+ if (isNaN(d.getTime())) {
4728
+ console.warn('EmbeddedTokenManager: host sent a malformed expiresAt value — treating token as already expired', raw);
4729
+ return new Date(0);
4569
4730
  }
4570
- isValidOrigin(origin) {
4571
- const ALLOWED_ORIGINS = ['https://alpha.uipath.com', 'https://staging.uipath.com', 'https://cloud.uipath.com'];
4572
- if (!origin) {
4573
- return false;
4731
+ return d;
4732
+ }
4733
+ function extractToken(data) {
4734
+ const token = data?.content?.token;
4735
+ if (!token?.accessToken)
4736
+ return undefined;
4737
+ return { accessToken: token.accessToken, expiresAt: parseExpiresAt(token.expiresAt) };
4738
+ }
4739
+ /**
4740
+ * Handles token delegation for coded apps embedded inside a UiPath host
4741
+ * (e.g. Governance Portal, Insights UI).
4742
+ *
4743
+ * Detection: the host signals embedding via `?host=embed&basedomain=<origin>`
4744
+ * in the iframe src URL. `parentOrigin` is read from `?basedomain=` and validated
4745
+ * against the trusted UiPath host allowlist before this manager is constructed.
4746
+ * This mirrors the mechanism used by ActionCenterTokenManager.
4747
+ *
4748
+ * On every token expiry the SDK sends `UIP.refreshToken` with `clientId` and
4749
+ * `scope`; the host performs silent SSO and responds with `UIP.tokenRefreshed`.
4750
+ */
4751
+ class EmbeddedTokenManager {
4752
+ /**
4753
+ * @param parentOrigin Validated UiPath host origin from the `?basedomain=` query parameter.
4754
+ * @param config SDK configuration — `clientId` and `scope` are required and forwarded
4755
+ * in every `UIP.refreshToken` request so the host knows which OAuth client to use.
4756
+ * @param onTokenRefreshed Called with the refreshed TokenInfo so the caller
4757
+ * can persist it in the execution context.
4758
+ * @throws {AuthenticationError} if `config.clientId` or `config.scope` are not set.
4759
+ */
4760
+ constructor(parentOrigin, config, onTokenRefreshed) {
4761
+ this.parentOrigin = parentOrigin;
4762
+ this.onTokenRefreshed = onTokenRefreshed;
4763
+ this.refreshPromise = null;
4764
+ this.cancelRefresh = null;
4765
+ if (!config.clientId || !config.scope) {
4766
+ throw new ValidationError({
4767
+ message: 'EmbeddedTokenManager requires clientId and scope to be configured for host-delegated authentication',
4768
+ });
4574
4769
  }
4575
- if (ALLOWED_ORIGINS.includes(origin)) {
4576
- return true;
4770
+ this.clientId = config.clientId;
4771
+ this.scope = config.scope;
4772
+ }
4773
+ async refreshAccessToken(tokenInfo) {
4774
+ if (!isTokenExpired(tokenInfo)) {
4775
+ return tokenInfo.token;
4577
4776
  }
4777
+ if (this.refreshPromise) {
4778
+ return this.refreshPromise;
4779
+ }
4780
+ const { promise, cancel } = requestHostToken({
4781
+ pinnedOrigin: this.parentOrigin,
4782
+ sendRequest: () => {
4783
+ try {
4784
+ const message = {
4785
+ eventType: UipEmbeddedEventNames.REFRESH_TOKEN,
4786
+ content: { clientId: this.clientId, scope: this.scope },
4787
+ };
4788
+ window.parent.postMessage(message, this.parentOrigin);
4789
+ }
4790
+ catch (error) {
4791
+ console.warn('EmbeddedTokenManager: postMessage to host failed', error);
4792
+ }
4793
+ },
4794
+ responseEventType: UipEmbeddedEventNames.TOKEN_REFRESHED,
4795
+ extractToken,
4796
+ onTokenRefreshed: this.onTokenRefreshed,
4797
+ });
4798
+ this.cancelRefresh = cancel;
4799
+ this.refreshPromise = promise;
4578
4800
  try {
4579
- const url = new URL(origin);
4580
- return url.hostname === 'localhost';
4801
+ return await this.refreshPromise;
4581
4802
  }
4582
- catch {
4583
- return false;
4803
+ finally {
4804
+ this.refreshPromise = null;
4805
+ this.cancelRefresh = null;
4584
4806
  }
4585
4807
  }
4808
+ /** Cancels any in-flight token-refresh request. */
4809
+ destroy() {
4810
+ this.cancelRefresh?.();
4811
+ }
4812
+ }
4813
+
4814
+ /**
4815
+ * SDK Telemetry constants.
4816
+ *
4817
+ * Only the SDK's identity (version, service name, role name, …) lives
4818
+ * here. The Application Insights connection string is injected into
4819
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
4820
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
4821
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
4822
+ * SDK's public API.
4823
+ */
4824
+ /** SDK version placeholder — patched by the SDK publish workflow. */
4825
+ const SDK_VERSION = '1.4.1';
4826
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
4827
+ const SDK_SERVICE_NAME = 'UiPath.TypeScript.Sdk';
4828
+ const SDK_LOGGER_NAME = 'uipath-ts-sdk-telemetry';
4829
+ const SDK_RUN_EVENT = 'Sdk.Run';
4830
+
4831
+ /**
4832
+ * UiPath TypeScript SDK Telemetry
4833
+ *
4834
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
4835
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
4836
+ * does this independently, so events carry their own consumer's identity
4837
+ * and tenant context.
4838
+ */
4839
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
4840
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
4841
+ // from the `UiPath` constructor therefore wires up `@track` decorators
4842
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
4843
+ const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
4844
+ const track = coreTelemetry.createTrack(sdkClient);
4845
+ const trackEvent = coreTelemetry.createTrackEvent(sdkClient);
4846
+ const telemetryClient = {
4847
+ initialize(context) {
4848
+ sdkClient.initialize({
4849
+ sdkVersion: SDK_VERSION,
4850
+ serviceName: SDK_SERVICE_NAME,
4851
+ cloudRoleName: CLOUD_ROLE_NAME,
4852
+ loggerName: SDK_LOGGER_NAME,
4853
+ defaultEventName: SDK_RUN_EVENT,
4854
+ context,
4855
+ });
4856
+ },
4857
+ /**
4858
+ * Sets the authenticated user's id so every subsequently emitted event
4859
+ * carries it as `CloudUserId`.
4860
+ */
4861
+ setUserId(userId) {
4862
+ sdkClient.setUserId(userId);
4863
+ },
4864
+ };
4865
+
4866
+ /**
4867
+ * Base64 encoding/decoding
4868
+ */
4869
+ /**
4870
+ * Decodes a base64 string
4871
+ * @param base64 - The base64 string to decode
4872
+ * @returns Decoded string
4873
+ */
4874
+ function decodeBase64(base64) {
4875
+ let bytes;
4876
+ if (isBrowser) {
4877
+ // Browser environment
4878
+ const binaryString = atob(base64);
4879
+ bytes = new Uint8Array(binaryString.length);
4880
+ for (let i = 0; i < binaryString.length; i++) {
4881
+ bytes[i] = binaryString.charCodeAt(i);
4882
+ }
4883
+ }
4884
+ else {
4885
+ // Node.js environment
4886
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
4887
+ }
4888
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
4889
+ const decoder = new TextDecoder();
4890
+ return decoder.decode(bytes);
4891
+ }
4892
+
4893
+ /**
4894
+ * JWT decoding helpers — payload inspection only, no signature verification.
4895
+ */
4896
+ const BASE64URL_DASH_RE = /-/g;
4897
+ const BASE64URL_UNDERSCORE_RE = /_/g;
4898
+ /**
4899
+ * Converts a base64url-encoded JWT segment to standard base64 with padding.
4900
+ */
4901
+ function base64UrlToBase64(value) {
4902
+ const base64 = value
4903
+ .replace(BASE64URL_DASH_RE, '+')
4904
+ .replace(BASE64URL_UNDERSCORE_RE, '/');
4905
+ return base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
4906
+ }
4907
+ /**
4908
+ * Extracts the user id (`sub` claim) from a JWT access token payload.
4909
+ * Returns an empty string for opaque (non-JWT) tokens or malformed payloads.
4910
+ *
4911
+ * @param token - The access token to inspect
4912
+ * @returns The user id, or an empty string if it cannot be extracted
4913
+ */
4914
+ function extractUserIdFromToken(token) {
4915
+ try {
4916
+ const payload = token.split('.')[1];
4917
+ if (!payload) {
4918
+ return '';
4919
+ }
4920
+ const claims = JSON.parse(decodeBase64(base64UrlToBase64(payload)));
4921
+ const sub = claims['sub'];
4922
+ return typeof sub === 'string' && sub ? sub : '';
4923
+ }
4924
+ catch {
4925
+ return '';
4926
+ }
4586
4927
  }
4587
4928
 
4588
4929
  /**
@@ -4604,10 +4945,15 @@ class TokenManager {
4604
4945
  this.isOAuth = isOAuth;
4605
4946
  this.refreshPromise = null;
4606
4947
  this.actionCenterTokenManager = null;
4948
+ this.embeddedTokenManager = null;
4607
4949
  if (isInActionCenter) {
4608
4950
  this.actionCenterTokenManager = new ActionCenterTokenManager(config, (tokenInfo) => this.setToken(tokenInfo));
4609
4951
  this.isOAuth = false;
4610
4952
  }
4953
+ else if (trustedEmbeddingOrigin) {
4954
+ this.embeddedTokenManager = new EmbeddedTokenManager(trustedEmbeddingOrigin, config, tokenInfo => this.setToken(tokenInfo));
4955
+ this.isOAuth = false;
4956
+ }
4611
4957
  }
4612
4958
  /**
4613
4959
  * Checks if a token is expired
@@ -4638,6 +4984,10 @@ class TokenManager {
4638
4984
  if (this.actionCenterTokenManager) {
4639
4985
  return await this.actionCenterTokenManager.refreshAccessToken(tokenInfo);
4640
4986
  }
4987
+ // Generic embedded path — active whenever the app is embedded in a UiPath host page
4988
+ if (this.embeddedTokenManager) {
4989
+ return await this.embeddedTokenManager.refreshAccessToken(tokenInfo);
4990
+ }
4641
4991
  // For secret-based tokens, they never expire
4642
4992
  if (tokenInfo.type === 'secret') {
4643
4993
  return tokenInfo.token;
@@ -4776,6 +5126,13 @@ class TokenManager {
4776
5126
  }
4777
5127
  return true;
4778
5128
  }
5129
+ /**
5130
+ * Releases resources held by this instance.
5131
+ * Must be called when the TokenManager is no longer needed to prevent listener leaks.
5132
+ */
5133
+ destroy() {
5134
+ this.embeddedTokenManager?.destroy();
5135
+ }
4779
5136
  /**
4780
5137
  * Clears the current token
4781
5138
  */
@@ -4797,6 +5154,7 @@ class TokenManager {
4797
5154
  */
4798
5155
  _updateExecutionContext(tokenInfo) {
4799
5156
  this.executionContext.set('tokenInfo', tokenInfo);
5157
+ telemetryClient.setUserId(extractUserIdFromToken(tokenInfo.token));
4800
5158
  }
4801
5159
  /**
4802
5160
  * Refreshes the access token using the stored refresh token.
@@ -4826,6 +5184,9 @@ class TokenManager {
4826
5184
  * Internal method to perform the actual token refresh
4827
5185
  */
4828
5186
  async _doRefreshToken() {
5187
+ // Destructure before the type guard — hasOAuthConfig narrows this.config to
5188
+ // { clientId, redirectUri, scope } which does not include BaseConfig fields.
5189
+ const { orgName, baseUrl } = this.config;
4829
5190
  // Check if we're in OAuth flow
4830
5191
  if (!hasOAuthConfig(this.config)) {
4831
5192
  throw new Error('refreshAccessToken is only available in OAuth flow');
@@ -4835,13 +5196,12 @@ class TokenManager {
4835
5196
  if (!tokenInfo?.refreshToken) {
4836
5197
  throw new Error('No refresh token available. User may need to re-authenticate.');
4837
5198
  }
4838
- const orgName = this.config.orgName;
4839
5199
  const body = new URLSearchParams({
4840
5200
  grant_type: 'refresh_token',
4841
5201
  client_id: this.config.clientId,
4842
5202
  refresh_token: tokenInfo.refreshToken
4843
5203
  });
4844
- const response = await fetch(`${this.config.baseUrl}/${orgName}/identity_/connect/token`, {
5204
+ const response = await fetch(`${baseUrl}/${orgName}/identity_/connect/token`, {
4845
5205
  method: 'POST',
4846
5206
  headers: {
4847
5207
  'Content-Type': 'application/x-www-form-urlencoded'
@@ -5301,51 +5661,6 @@ function normalizeBaseUrl(url) {
5301
5661
  return url.endsWith('/') ? url.slice(0, -1) : url;
5302
5662
  }
5303
5663
 
5304
- /**
5305
- * SDK Telemetry constants.
5306
- *
5307
- * Only the SDK's identity (version, service name, role name, …) lives
5308
- * here. The Application Insights connection string is injected into
5309
- * `@uipath/core-telemetry` itself at publish time, and the generic attribute
5310
- * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
5311
- * `@uipath/core-telemetry` and consumed there — they are not part of the
5312
- * SDK's public API.
5313
- */
5314
- /** SDK version placeholder — patched by the SDK publish workflow. */
5315
- const SDK_VERSION = '1.3.11';
5316
- const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
5317
- const SDK_SERVICE_NAME = 'UiPath.TypeScript.Sdk';
5318
- const SDK_LOGGER_NAME = 'uipath-ts-sdk-telemetry';
5319
- const SDK_RUN_EVENT = 'Sdk.Run';
5320
-
5321
- /**
5322
- * UiPath TypeScript SDK Telemetry
5323
- *
5324
- * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
5325
- * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
5326
- * does this independently, so events carry their own consumer's identity
5327
- * and tenant context.
5328
- */
5329
- // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
5330
- // same `TelemetryClient` instance at runtime. A single `initialize(...)`
5331
- // from the `UiPath` constructor therefore wires up `@track` decorators
5332
- // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
5333
- const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
5334
- const track = coreTelemetry.createTrack(sdkClient);
5335
- const trackEvent = coreTelemetry.createTrackEvent(sdkClient);
5336
- const telemetryClient = {
5337
- initialize(context) {
5338
- sdkClient.initialize({
5339
- sdkVersion: SDK_VERSION,
5340
- serviceName: SDK_SERVICE_NAME,
5341
- cloudRoleName: CLOUD_ROLE_NAME,
5342
- loggerName: SDK_LOGGER_NAME,
5343
- defaultEventName: SDK_RUN_EVENT,
5344
- context,
5345
- });
5346
- },
5347
- };
5348
-
5349
5664
  /**
5350
5665
  * SDK Internals Registry - Internal registry for SDK instances
5351
5666
  *
@@ -5455,7 +5770,7 @@ function loadFromMetaTags() {
5455
5770
  return hasAnyValue ? config : null;
5456
5771
  }
5457
5772
 
5458
- var _UiPath_instances, _UiPath_config, _UiPath_authService, _UiPath_initialized, _UiPath_partialConfig, _UiPath_multiLogin, _UiPath_metaFolderKey, _UiPath_initializeWithConfig, _UiPath_loadConfig;
5773
+ var _UiPath_instances, _UiPath_config, _UiPath_authService, _UiPath_initialized, _UiPath_partialConfig, _UiPath_multiLogin, _UiPath_metaFolderKey, _UiPath_metaOrgId, _UiPath_metaTenantId, _UiPath_initializeWithConfig, _UiPath_loadConfig;
5459
5774
  /**
5460
5775
  * UiPath - Core SDK class for authentication and configuration management.
5461
5776
  *
@@ -5500,9 +5815,18 @@ class UiPath {
5500
5815
  // deployments). Not accepted via the public constructor; lives here so the
5501
5816
  // SDK can flow it through to BaseService.config without polluting BaseConfig.
5502
5817
  _UiPath_metaFolderKey.set(this, void 0);
5818
+ // Org/tenant ids captured from the meta tags before the constructor config
5819
+ // is merged in. The `uipath:org-name`/`uipath:tenant-name` meta tags always
5820
+ // carry org/tenant *ids* in coded-app deployments, whereas a
5821
+ // constructor-supplied `orgName`/`tenantName` may be actual names — so the
5822
+ // telemetry ids must be read from the meta tags.
5823
+ _UiPath_metaOrgId.set(this, void 0);
5824
+ _UiPath_metaTenantId.set(this, void 0);
5503
5825
  // Load configuration from meta tags
5504
5826
  const configFromMetaTags = loadFromMetaTags();
5505
5827
  __classPrivateFieldSet(this, _UiPath_metaFolderKey, configFromMetaTags?.folderKey, "f");
5828
+ __classPrivateFieldSet(this, _UiPath_metaOrgId, configFromMetaTags?.orgName, "f");
5829
+ __classPrivateFieldSet(this, _UiPath_metaTenantId, configFromMetaTags?.tenantName, "f");
5506
5830
  // Merge configuration: constructor config overrides meta tags
5507
5831
  const mergedConfig = config ? { ...configFromMetaTags, ...config } : configFromMetaTags;
5508
5832
  if (mergedConfig && isCompleteConfig(mergedConfig)) {
@@ -5609,6 +5933,13 @@ class UiPath {
5609
5933
  getToken() {
5610
5934
  return __classPrivateFieldGet(this, _UiPath_authService, "f")?.getToken();
5611
5935
  }
5936
+ /**
5937
+ * Releases resources held by this SDK instance.
5938
+ * Cancels any in-flight token-refresh request. Call this when the coded app is unmounted.
5939
+ */
5940
+ destroy() {
5941
+ __classPrivateFieldGet(this, _UiPath_authService, "f")?.getTokenManager()?.destroy();
5942
+ }
5612
5943
  /**
5613
5944
  * Logout from the SDK, clearing all authentication state.
5614
5945
  * After calling this method, the user will need to re-initialize to authenticate again.
@@ -5631,7 +5962,7 @@ class UiPath {
5631
5962
  __classPrivateFieldGet(this, _UiPath_authService, "f")?.updateToken(tokenInfo);
5632
5963
  }
5633
5964
  }
5634
- _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap(), _UiPath_partialConfig = new WeakMap(), _UiPath_multiLogin = new WeakMap(), _UiPath_metaFolderKey = new WeakMap(), _UiPath_instances = new WeakSet(), _UiPath_initializeWithConfig = function _UiPath_initializeWithConfig(config) {
5965
+ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap(), _UiPath_partialConfig = new WeakMap(), _UiPath_multiLogin = new WeakMap(), _UiPath_metaFolderKey = new WeakMap(), _UiPath_metaOrgId = new WeakMap(), _UiPath_metaTenantId = new WeakMap(), _UiPath_instances = new WeakSet(), _UiPath_initializeWithConfig = function _UiPath_initializeWithConfig(config) {
5635
5966
  // Validate and normalize the configuration
5636
5967
  validateConfig(config);
5637
5968
  const hasSecretAuth = hasSecretConfig(config);
@@ -5667,9 +5998,11 @@ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_ini
5667
5998
  orgName: internalConfig.orgName,
5668
5999
  tenantName: internalConfig.tenantName
5669
6000
  };
5670
- // Initialize telemetry with SDK configuration
6001
+ // Initialize telemetry with SDK configuration.
5671
6002
  telemetryClient.initialize({
5672
6003
  baseUrl: config.baseUrl,
6004
+ orgId: __classPrivateFieldGet(this, _UiPath_metaOrgId, "f"),
6005
+ tenantId: __classPrivateFieldGet(this, _UiPath_metaTenantId, "f"),
5673
6006
  orgName: config.orgName,
5674
6007
  tenantName: config.tenantName,
5675
6008
  clientId: hasOAuthAuth ? config.clientId : undefined,
@@ -5677,10 +6010,12 @@ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_ini
5677
6010
  });
5678
6011
  // Track SDK initialization
5679
6012
  trackEvent('Sdk.Auth');
5680
- /** Auto-initialize for secret-based auth
5681
- * When viewed in Action Center, initialize tokenInfo with empty token. When an sdk call is made Action Center passes the token to sdk.
6013
+ /** Auto-initialize for secret-based auth, Action Center, and generic host-embedded apps.
6014
+ * When viewed in Action Center or embedded in a UiPath host frame via the UIP protocol,
6015
+ * initialize tokenInfo with an empty token so getValidToken() can bootstrap via postMessage.
6016
+ * When an sdk call is made, the host passes the token to the sdk.
5682
6017
  */
5683
- if (hasSecretAuth || isInActionCenter) {
6018
+ if (hasSecretAuth || isInActionCenter || trustedEmbeddingOrigin) {
5684
6019
  __classPrivateFieldGet(this, _UiPath_authService, "f").authenticateWithSecret(config.secret ?? '');
5685
6020
  __classPrivateFieldSet(this, _UiPath_initialized, true, "f");
5686
6021
  }
@@ -5688,6 +6023,8 @@ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_ini
5688
6023
  // Load from meta tags
5689
6024
  const metaConfig = loadFromMetaTags();
5690
6025
  __classPrivateFieldSet(this, _UiPath_metaFolderKey, metaConfig?.folderKey, "f");
6026
+ __classPrivateFieldSet(this, _UiPath_metaOrgId, metaConfig?.orgName, "f");
6027
+ __classPrivateFieldSet(this, _UiPath_metaTenantId, metaConfig?.tenantName, "f");
5691
6028
  // Merge with any partial config from constructor (constructor overrides meta tags)
5692
6029
  const merged = { ...metaConfig, ...__classPrivateFieldGet(this, _UiPath_partialConfig, "f") };
5693
6030
  if (!isCompleteConfig(merged)) {