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