@uipath/codedapp-tool 1.204.1-preview.254 → 1.205.0-preview.256

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.
@@ -182,6 +182,16 @@ class NodeFileSystem {
182
182
  async rename(oldPath, newPath) {
183
183
  await fs.rename(oldPath, newPath);
184
184
  }
185
+ async isSymbolicLink(filePath) {
186
+ try {
187
+ return (await fs.lstat(filePath)).isSymbolicLink();
188
+ } catch (error) {
189
+ if (this.isEnoent(error) || this.hasErrnoCode(error, "ENOTDIR")) {
190
+ return false;
191
+ }
192
+ throw error;
193
+ }
194
+ }
185
195
  async realpath(filePath) {
186
196
  try {
187
197
  return await fs.realpath(filePath);
@@ -234,4 +244,4 @@ var getFileSystem = () => fsInstance;
234
244
 
235
245
  export { getFileSystem };
236
246
 
237
- //# debugId=25EC9C9B4767723E64756E2164756E21
247
+ //# debugId=82E3494FD83B7EB464756E2164756E21
@@ -4,13 +4,66 @@ import {
4
4
  Path,
5
5
  ProjectTool,
6
6
  TemporaryStorageService,
7
- ToolResult,
7
+ ToolResult
8
+ } from "./packager-tool-d94wjncg.js";
9
+ import {
8
10
  catchError
9
- } from "./packager-tool-cfc7qtm7.js";
11
+ } from "./packager-tool-cmfktvbt.js";
10
12
  import {
11
13
  __export
12
14
  } from "./packager-tool-1yh8g550.js";
13
15
 
16
+ // ../packager/packager-tool-webapp/src/models/webapp-manifest.ts
17
+ var WebAppVariantType;
18
+ ((WebAppVariantType2) => {
19
+ WebAppVariantType2["Coded"] = "Coded";
20
+ WebAppVariantType2["JS"] = "JS";
21
+ })(WebAppVariantType ||= {});
22
+ var WEBAPP_MANIFEST_FILE_NAME = "webAppManifest.json";
23
+
24
+ // ../packager/packager-tool-webapp/src/utils/bundle-path.ts
25
+ function normalizeBundlePath(path) {
26
+ return path.replace(/\\/g, "/");
27
+ }
28
+ function isBundleRelativePath(path) {
29
+ const normalized = normalizeBundlePath(path);
30
+ const segments = normalized.split("/");
31
+ return !normalized.startsWith("/") && !/^[a-zA-Z]:/.test(normalized) && !segments.includes("..") && segments.some((segment) => segment !== "" && segment !== ".");
32
+ }
33
+ async function isCanonicalBundleChild(fileSystem, projectPath, bundlePath) {
34
+ const project = normalizeBundlePath(await fileSystem.realpath(projectPath)).replace(/\/+$/, "") || "/";
35
+ let bundle = project;
36
+ for (const segment of normalizeBundlePath(bundlePath).split("/")) {
37
+ if (!segment || segment === ".")
38
+ continue;
39
+ bundle = normalizeBundlePath(await fileSystem.realpath(Path.join(bundle, segment))).replace(/\/+$/, "") || "/";
40
+ }
41
+ return bundle !== project && bundle.startsWith(project === "/" ? "/" : `${project}/`);
42
+ }
43
+ function isHtmlEntryPointPath(path) {
44
+ return typeof path === "string" && isBundleRelativePath(path) && /\.html?$/i.test(path);
45
+ }
46
+ async function resolveHtmlEntryPoint(fileSystem, folder, declaredPath) {
47
+ if (!isHtmlEntryPointPath(declaredPath))
48
+ return null;
49
+ const segments = normalizeBundlePath(declaredPath).split("/").filter((part) => part !== "" && part !== ".");
50
+ if (!(await fileSystem.stat(Path.join(folder, ...segments)))?.isFile())
51
+ return null;
52
+ const actual = [];
53
+ for (const segment of segments) {
54
+ const entries = await fileSystem.readdir(Path.join(folder, ...actual));
55
+ if (entries.includes(segment)) {
56
+ actual.push(segment);
57
+ continue;
58
+ }
59
+ const matches = entries.filter((entry) => entry.toLowerCase() === segment.toLowerCase());
60
+ if (matches.length !== 1)
61
+ return null;
62
+ actual.push(matches[0]);
63
+ }
64
+ return actual.join("/");
65
+ }
66
+
14
67
  // ../packager/packager-tool-webapp/src/constants.ts
15
68
  var PROJECT_JSON_FILE = "project.json";
16
69
  var DEFAULT_BUNDLE_PATH = "source/dist";
@@ -19,12 +72,23 @@ var CONTENT_APP_FOLDER_NAME = "app";
19
72
  var TARGET_RUNTIME = "Coded";
20
73
  var TARGET_JS_RUNTIME = "JS";
21
74
  var DEFAULT_ENTRY_POINT_TYPE = "api";
75
+ var HTML_ENTRY_POINT_CANDIDATES = [
76
+ "index.html",
77
+ "main.html",
78
+ "app.html"
79
+ ];
22
80
  var ERROR_MESSAGES = {
23
81
  MANIFEST_NOT_FOUND: (file) => `WebApp manifest not found: ${file}. This file is required for WebApp projects.`,
24
82
  PROJECT_JSON_FOUND: "project.json found in WebApp project. The WebApp tool only supports Coded web apps without project.json.",
25
83
  MANIFEST_LOAD_FAILED: (file) => `Failed to load or parse ${file}`,
26
84
  BUNDLE_NOT_FOUND: (path) => `Compiled bundle not found at ${path}. Ensure the project is built before packing.`,
27
85
  BUNDLE_NOT_DIRECTORY: (path) => `Bundle path ${path} exists but is not a directory.`,
86
+ BUNDLE_OUTSIDE_PROJECT: (path) => `Bundle path ${path} resolves to the project root or outside the project. Use a child build output folder inside the project.`,
87
+ BUNDLE_NO_ENTRY_POINT: (path) => `Bundle at ${path} has no HTML entry point (${HTML_ENTRY_POINT_CANDIDATES.join(", ")}). Build the app before packing, or point config.bundlePath in webAppManifest.json at its build output.`,
88
+ MAIN_FILE_INVALID_TYPE: "Invalid webAppManifest.json: config.mainFile must be a string naming an HTML file, or be omitted.",
89
+ MAIN_FILE_NOT_IN_BUNDLE: (path, mainFile) => `${WEBAPP_MANIFEST_FILE_NAME} asks for "${mainFile}" as the app's main file, but the bundle at ${path} does not hold it. Name an HTML file inside the bundle in config.mainFile, or remove it to use the first of ${HTML_ENTRY_POINT_CANDIDATES.join(", ")} the bundle holds.`,
90
+ MAIN_FILE_LOST: (path, mainFile) => `Bundle at ${path} held "${mainFile}" when the pack started, but the copy taken for the package has not. Something changed the folder mid-pack — usually a build or watch process. Stop it and pack again.`,
91
+ BUNDLE_ENTRY_POINT_LOST: (path) => `Bundle at ${path} had an HTML entry point (${HTML_ENTRY_POINT_CANDIDATES.join(", ")}) when the pack started, but the copy taken for the package has none. Something changed the folder mid-pack — usually a build or watch process. Stop it and pack again.`,
28
92
  APP_FOLDER_NOT_FOUND: (path) => `.app folder not found at ${path}. Ensure the project contains a .app folder.`,
29
93
  APP_FOLDER_NOT_DIRECTORY: (path) => `.app path ${path} exists but is not a directory.`,
30
94
  BUILD_NOT_SUPPORTED: "Build execution (isCompiled=false) is not yet supported. Please build the project manually and set isCompiled=true.",
@@ -36,14 +100,6 @@ var ERROR_MESSAGES = {
36
100
  OUTPUT_PATH_REQUIRED: "Output path is required"
37
101
  };
38
102
 
39
- // ../packager/packager-tool-webapp/src/models/webapp-manifest.ts
40
- var WebAppVariantType;
41
- ((WebAppVariantType2) => {
42
- WebAppVariantType2["Coded"] = "Coded";
43
- WebAppVariantType2["JS"] = "JS";
44
- })(WebAppVariantType ||= {});
45
- var WEBAPP_MANIFEST_FILE_NAME = "webAppManifest.json";
46
-
47
103
  // ../packager/packager-tool-webapp/src/utils/fs-helpers.ts
48
104
  async function copyDirectoryAsync(fileSystem, sourcePath, destinationPath) {
49
105
  await fileSystem.mkdir(destinationPath);
@@ -113,9 +169,8 @@ class CodedAppStrategy {
113
169
  const isCompiled = typed.config?.isCompiled ?? true;
114
170
  if (isCompiled) {
115
171
  const fullBundlePath = Path.join(projectPath, bundlePath);
116
- const exists = await this.fileSystem.exists(fullBundlePath);
117
- if (!exists) {
118
- const message = ERROR_MESSAGES.BUNDLE_NOT_FOUND(fullBundlePath);
172
+ const message = await this.describeBundleProblemAsync(fullBundlePath, typed.config?.mainFile);
173
+ if (message) {
119
174
  const warnable = logger;
120
175
  if (warnable?.warn) {
121
176
  warnable.warn(message);
@@ -133,7 +188,11 @@ class CodedAppStrategy {
133
188
  bundlePath = DEFAULT_BUNDLE_PATH;
134
189
  }
135
190
  const isCompiled = manifest.config?.isCompiled ?? true;
191
+ const declaredMainFile = manifest.config?.mainFile;
136
192
  const fullBundlePath = Path.join(projectPath, bundlePath);
193
+ if (isBundleRelativePath(bundlePath) && !await isCanonicalBundleChild(this.fileSystem, projectPath, bundlePath)) {
194
+ throw new Error(ERROR_MESSAGES.BUNDLE_OUTSIDE_PROJECT(bundlePath));
195
+ }
137
196
  if (isCompiled) {
138
197
  logger?.progress("Validating compiled bundle...");
139
198
  const bundleExists = await this.fileSystem.exists(fullBundlePath);
@@ -144,18 +203,22 @@ class CodedAppStrategy {
144
203
  if (!bundleStat?.isDirectory()) {
145
204
  throw new Error(ERROR_MESSAGES.BUNDLE_NOT_DIRECTORY(fullBundlePath));
146
205
  }
206
+ const problem = await this.describeBundleEntryProblemAsync(fullBundlePath, declaredMainFile);
207
+ if (problem) {
208
+ throw new Error(problem);
209
+ }
147
210
  } else {
148
211
  logger?.info("Build mode (isCompiled=false) is not yet implemented in v1.");
149
212
  throw new Error(ERROR_MESSAGES.BUILD_NOT_SUPPORTED);
150
213
  }
151
- const localBuildFolder = Path.join(outputPath, NugetConstants.OutputFolderName);
214
+ const localBuildFolder = Path.join(outputPath, `${NugetConstants.OutputFolderName}-${crypto.randomUUID()}`);
152
215
  const contentFolder = Path.join(localBuildFolder, NugetConstants.ContentFolderName);
153
- await this.fileSystem.mkdir(contentFolder);
154
216
  try {
217
+ await this.fileSystem.mkdir(contentFolder);
155
218
  logger?.progress("Copying bundle to content folder...");
156
219
  await copyDirectoryAsync(this.fileSystem, fullBundlePath, contentFolder);
157
220
  logger?.progress("Preparing metadata files...");
158
- await this.prepareMetadataFiles(localBuildFolder, contentFolder, packageInfo, manifest, projectPath);
221
+ await this.prepareMetadataFiles(localBuildFolder, contentFolder, packageInfo, manifest, projectPath, fullBundlePath);
159
222
  logger?.progress("Creating NuGet package...");
160
223
  const nupkgFileName = `${packageInfo.id}.${packageInfo.version}.nupkg`;
161
224
  const nupkgPath = Path.join(outputPath, nupkgFileName);
@@ -171,19 +234,11 @@ class CodedAppStrategy {
171
234
  }
172
235
  }
173
236
  }
174
- async prepareMetadataFiles(_localBuildFolder, contentFolder, _packageInfo, _manifest, projectPath) {
175
- let mainFile = "index.html";
176
- const indexHtmlPath = Path.join(contentFolder, "index.html");
177
- const indexHtmlExists = await this.fileSystem.exists(indexHtmlPath);
178
- if (!indexHtmlExists) {
179
- const possibleEntries = ["index.html", "main.html", "app.html"];
180
- for (const entry of possibleEntries) {
181
- const entryPath = Path.join(contentFolder, entry);
182
- if (await this.fileSystem.exists(entryPath)) {
183
- mainFile = entry;
184
- break;
185
- }
186
- }
237
+ async prepareMetadataFiles(_localBuildFolder, contentFolder, _packageInfo, manifest, projectPath, sourceBundlePath) {
238
+ const declaredMainFile = manifest.config?.mainFile;
239
+ const mainFile = await this.resolveMainFileAsync(contentFolder, declaredMainFile);
240
+ if (!mainFile) {
241
+ throw new Error(declaredMainFile ? ERROR_MESSAGES.MAIN_FILE_LOST(sourceBundlePath, declaredMainFile) : ERROR_MESSAGES.BUNDLE_ENTRY_POINT_LOST(sourceBundlePath));
187
242
  }
188
243
  const operatePath = Path.join(contentFolder, NugetConstants.OperateFileName);
189
244
  const operateModel = {
@@ -199,15 +254,11 @@ class CodedAppStrategy {
199
254
  };
200
255
  const operateJson = JSON.stringify(operateModel, null, 2);
201
256
  await this.fileSystem.writeFile(operatePath, operateJson);
202
- const manifestSourcePath = Path.join(projectPath, WEBAPP_MANIFEST_FILE_NAME);
203
- const manifestDestPath = Path.join(contentFolder, WEBAPP_MANIFEST_FILE_NAME);
204
- const manifestExists = await this.fileSystem.exists(manifestSourcePath);
205
- if (manifestExists) {
206
- const manifestContent = await this.fileSystem.readFile(manifestSourcePath, "utf-8");
207
- if (manifestContent) {
208
- await this.fileSystem.writeFile(manifestDestPath, manifestContent);
209
- }
210
- }
257
+ await this.fileSystem.writeFile(Path.join(contentFolder, WEBAPP_MANIFEST_FILE_NAME), JSON.stringify({
258
+ ...manifest,
259
+ config: { ...manifest.config, mainFile },
260
+ projectId: operateModel.projectId
261
+ }, null, 2));
211
262
  const uipathJsonSourcePath = Path.join(projectPath, "uipath.json");
212
263
  const uipathJsonDestPath = Path.join(contentFolder, "uipath.json");
213
264
  const uipathJsonExists = await this.fileSystem.exists(uipathJsonSourcePath);
@@ -267,7 +318,7 @@ class CodedAppStrategy {
267
318
  if (projectEntryPointsExists) {
268
319
  const entryPointsData = await this.fileSystem.readFile(projectEntryPointsPath, "utf-8");
269
320
  if (entryPointsData) {
270
- entryPointsContent = entryPointsData;
321
+ entryPointsContent = this.alignEntryPoint(entryPointsData, mainFile);
271
322
  } else {
272
323
  entryPointsContent = this.createDefaultEntryPoints(mainFile);
273
324
  }
@@ -287,6 +338,56 @@ class CodedAppStrategy {
287
338
  const packageDescriptorJson = JSON.stringify(packageDescriptor, null, 2);
288
339
  await this.fileSystem.writeFile(packageDescriptorPath, packageDescriptorJson);
289
340
  }
341
+ async describeBundleProblemAsync(fullBundlePath, declaredMainFile) {
342
+ const bundleStat = await this.fileSystem.stat(fullBundlePath);
343
+ if (!bundleStat) {
344
+ return ERROR_MESSAGES.BUNDLE_NOT_FOUND(fullBundlePath);
345
+ }
346
+ if (!bundleStat.isDirectory()) {
347
+ return ERROR_MESSAGES.BUNDLE_NOT_DIRECTORY(fullBundlePath);
348
+ }
349
+ return this.describeBundleEntryProblemAsync(fullBundlePath, declaredMainFile);
350
+ }
351
+ async describeBundleEntryProblemAsync(fullBundlePath, declaredMainFile) {
352
+ if (declaredMainFile !== undefined && typeof declaredMainFile !== "string") {
353
+ return ERROR_MESSAGES.MAIN_FILE_INVALID_TYPE;
354
+ }
355
+ if (await this.resolveMainFileAsync(fullBundlePath, declaredMainFile)) {
356
+ return null;
357
+ }
358
+ return declaredMainFile !== undefined ? ERROR_MESSAGES.MAIN_FILE_NOT_IN_BUNDLE(fullBundlePath, declaredMainFile) : ERROR_MESSAGES.BUNDLE_NO_ENTRY_POINT(fullBundlePath);
359
+ }
360
+ async resolveMainFileAsync(folder, declaredMainFile) {
361
+ if (declaredMainFile === undefined) {
362
+ return this.findEntryPointAsync(folder);
363
+ }
364
+ return resolveHtmlEntryPoint(this.fileSystem, folder, declaredMainFile);
365
+ }
366
+ async findEntryPointAsync(folder) {
367
+ for (const candidate of HTML_ENTRY_POINT_CANDIDATES) {
368
+ const resolved = await resolveHtmlEntryPoint(this.fileSystem, folder, candidate);
369
+ if (resolved !== null)
370
+ return resolved;
371
+ }
372
+ return null;
373
+ }
374
+ alignEntryPoint(content, mainFile) {
375
+ const document = JSON.parse(content);
376
+ if (typeof document !== "object" || document === null || !("entryPoints" in document) || !Array.isArray(document.entryPoints)) {
377
+ throw new Error("Invalid entry-points.json: expected an entryPoints array.");
378
+ }
379
+ const primary = document.entryPoints[0];
380
+ if (typeof primary !== "object" || primary === null || Array.isArray(primary)) {
381
+ throw new Error("Invalid entry-points.json: expected a primary entry object.");
382
+ }
383
+ return JSON.stringify({
384
+ ...document,
385
+ entryPoints: [
386
+ { ...primary, filePath: mainFile },
387
+ ...document.entryPoints.slice(1)
388
+ ]
389
+ }, null, 2);
390
+ }
290
391
  createDefaultEntryPoints(mainFile) {
291
392
  const uniqueId = this.generateUniqueId();
292
393
  const entryPoints = {
@@ -592,7 +693,7 @@ class WebAppTool extends ProjectTool {
592
693
  let manifest;
593
694
  let strategy;
594
695
  try {
595
- const prepared = await this.getManifestAndStrategy(options.projectPath);
696
+ const prepared = await this.getManifestAndStrategy(options.projectPath, options.codedBundle);
596
697
  manifest = prepared.manifest;
597
698
  strategy = prepared.strategy;
598
699
  } catch (error) {
@@ -622,20 +723,33 @@ class WebAppTool extends ProjectTool {
622
723
  await this._temporaryStorage.cleanup();
623
724
  } catch {}
624
725
  }
625
- async getManifestAndStrategy(projectPath) {
726
+ async getManifestAndStrategy(projectPath, codedBundle) {
626
727
  const manifestPath = Path.join(projectPath, WEBAPP_MANIFEST_FILE_NAME);
627
728
  const manifestExists = await this.fileSystem.exists(manifestPath);
628
- if (!manifestExists) {
729
+ if (!manifestExists && !codedBundle) {
629
730
  throw new Error(ERROR_MESSAGES.MANIFEST_NOT_FOUND(WEBAPP_MANIFEST_FILE_NAME));
630
731
  }
631
732
  const projectJsonPath = Path.join(projectPath, PROJECT_JSON_FILE);
632
733
  if (await this.fileSystem.exists(projectJsonPath)) {
633
734
  throw new Error(ERROR_MESSAGES.PROJECT_JSON_FOUND);
634
735
  }
635
- const manifest = await loadWebAppManifest(this.fileSystem, projectPath);
736
+ let manifest = manifestExists ? await loadWebAppManifest(this.fileSystem, projectPath) : {
737
+ type: "Coded" /* Coded */,
738
+ solutionResourceSubType: "Coded" /* Coded */,
739
+ config: { isCompiled: true }
740
+ };
636
741
  if (!manifest) {
637
742
  throw new Error(ERROR_MESSAGES.MANIFEST_LOAD_FAILED(WEBAPP_MANIFEST_FILE_NAME));
638
743
  }
744
+ if (codedBundle) {
745
+ if (manifest.type !== "Coded" /* Coded */) {
746
+ throw new Error("A coded bundle requires a Coded webAppManifest.json.");
747
+ }
748
+ manifest = {
749
+ ...manifest,
750
+ config: { ...manifest.config, ...codedBundle }
751
+ };
752
+ }
639
753
  const strategy = VariantStrategyFactory.createStrategy(manifest, this.fileSystem);
640
754
  return { manifest, strategy };
641
755
  }
@@ -15276,6 +15390,6 @@ class WebAppContributingToolFactory extends WebAppToolFactory {
15276
15390
  return describeActionApp(projectDir, fs);
15277
15391
  }
15278
15392
  }
15279
- export { WEBAPP_MANIFEST_FILE_NAME, ACTION_SCHEMA_FILE_NAME, readProjectName, parseActionSchema, validateActionSchema, WebAppToolFactory, WebAppContributingToolFactory };
15393
+ export { WEBAPP_MANIFEST_FILE_NAME, ACTION_SCHEMA_FILE_NAME, isActionApp, readProjectName, parseActionSchema, validateActionSchema, normalizeBundlePath, isBundleRelativePath, isCanonicalBundleChild, isHtmlEntryPointPath, resolveHtmlEntryPoint, HTML_ENTRY_POINT_CANDIDATES, ERROR_MESSAGES, WebAppToolFactory, WebAppContributingToolFactory };
15280
15394
 
15281
- //# debugId=87A97AEB77F6A92664756E2164756E21
15395
+ //# debugId=100EE3599CDAD05364756E2164756E21
@@ -7,7 +7,7 @@ import {
7
7
  } from "./packager-tool-qa9gftnj.js";
8
8
  import {
9
9
  getFileSystem
10
- } from "./packager-tool-0v3s8r01.js";
10
+ } from "./packager-tool-je2re4j6.js";
11
11
  import {
12
12
  AUTH_FILENAME,
13
13
  DEFAULT_BASE_URL,
@@ -96,22 +96,12 @@ var resolveConfigAsync = async ({
96
96
  baseUrl = DEFAULT_BASE_URL;
97
97
  }
98
98
  baseUrl = normalizeAndValidateBaseUrl(baseUrl);
99
- let clientId = customClientId;
100
- if (!clientId && fileAuth.clientId) {
101
- clientId = fileAuth.clientId;
102
- }
103
- if (!clientId) {
104
- clientId = DEFAULT_CLIENT_ID;
105
- }
106
- let clientSecret = customClientSecret;
107
- if (!clientSecret && fileAuth.clientSecret) {
108
- clientSecret = fileAuth.clientSecret;
109
- }
110
- const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && (Boolean(clientSecret) || Boolean(customClientAssertion));
99
+ const clientId = customClientId || DEFAULT_CLIENT_ID;
100
+ const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && (Boolean(customClientSecret) || Boolean(customClientAssertion));
111
101
  const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
112
102
  return {
113
103
  clientId,
114
- clientSecret,
104
+ clientSecret: customClientSecret,
115
105
  scopes,
116
106
  baseUrl,
117
107
  authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
@@ -719,6 +709,16 @@ var resolveIdentityType = (claims, authFlow, email) => {
719
709
  }
720
710
  return;
721
711
  };
712
+ var resolveApplicationSubtype = (claims, authFlow) => {
713
+ switch (asString(claims?.sub_type)) {
714
+ case "service.external":
715
+ return "External";
716
+ case "service.internal":
717
+ return "Internal";
718
+ default:
719
+ return authFlow === "client_credentials" || authFlow === "federated_credentials" ? "External" : undefined;
720
+ }
721
+ };
722
722
  var looksLikeEmail = (value) => value?.includes("@") ?? false;
723
723
  var pickEmail = (claims) => {
724
724
  for (const candidate of [claims?.email, claims?.preferred_username]) {
@@ -760,6 +760,12 @@ var resolveSessionIdentity = (accessToken, authFlow) => {
760
760
  const clientId = asString(claims?.client_id);
761
761
  if (clientId)
762
762
  identity.clientId = clientId;
763
+ const subType = asString(claims?.sub_type);
764
+ if (subType)
765
+ identity.subType = subType;
766
+ const applicationSubtype = resolveApplicationSubtype(claims, authFlow);
767
+ if (applicationSubtype)
768
+ identity.applicationSubtype = applicationSubtype;
763
769
  return identity;
764
770
  };
765
771
  var readTokenScopes = (accessToken) => accessToken ? pickScopes(decodeClaims(accessToken)) : undefined;
@@ -1055,6 +1061,40 @@ var tryRobotClientFallback = async (options = {}) => {
1055
1061
  }
1056
1062
  };
1057
1063
 
1064
+ // ../auth/src/tenantSelection.ts
1065
+ var LOGIN_STATUS_HINT = "Run 'uip login status' to see the organization the CLI is signed in to.";
1066
+ var organizationHint = (organizationId) => `The request used '${organizationId}' as the organization. ${LOGIN_STATUS_HINT}`;
1067
+ var IDENTIFIER_STATUSES = new Set([400, 403, 404]);
1068
+ var describeNonJsonResponse = (organizationId, response, parseError) => {
1069
+ if (response.redirected) {
1070
+ return `Could not find organization '${organizationId}': the request was ` + `redirected to a sign-in page instead of the organization's tenant ` + `list. ${LOGIN_STATUS_HINT}`;
1071
+ }
1072
+ const contentType = response.headers.get("content-type") ?? "unknown";
1073
+ return `The organization service returned a '${contentType}' response instead ` + `of JSON: ${parseError.message}. ${organizationHint(organizationId)}`;
1074
+ };
1075
+ var fetchTenantsAndOrganizations = async (baseUrl, accessToken, organizationId, signal) => {
1076
+ const url = `${baseUrl}/${organizationId}/portal_/api/filtering/leftnav/tenantsAndOrganizationInfo`;
1077
+ const response = await fetch(url, {
1078
+ headers: {
1079
+ Authorization: `Bearer ${accessToken}`
1080
+ },
1081
+ ...signal ? { signal } : {}
1082
+ });
1083
+ if (!response.ok) {
1084
+ if (response.status === 401) {
1085
+ throw new Error(`Unauthorized: the access token was rejected, it was not ` + `issued for organization '${organizationId}', or ` + `'${organizationId}' was not accepted as an organization ` + `URL segment in this environment. ` + LOGIN_STATUS_HINT);
1086
+ }
1087
+ const errorText = await response.text();
1088
+ const message = `Failed to get tenants and organizations: ${response.status} ${errorText}`;
1089
+ throw new Error(IDENTIFIER_STATUSES.has(response.status) ? `${message}. ${organizationHint(organizationId)}` : message);
1090
+ }
1091
+ const [parseError, data] = await catchError(response.json());
1092
+ if (parseError) {
1093
+ throw new Error(describeNonJsonResponse(organizationId, response, parseError));
1094
+ }
1095
+ return data;
1096
+ };
1097
+
1058
1098
  // ../auth/src/tokenRefresh.ts
1059
1099
  var TOKEN_REFRESH_REAUTHENTICATE_MESSAGE = "Token refresh failed. Run 'uip login' to re-authenticate.";
1060
1100
 
@@ -1274,6 +1314,8 @@ var CredentialSource;
1274
1314
  CredentialSource2["Robot"] = "robot";
1275
1315
  CredentialSource2["EnvironmentVariables"] = "env-vars";
1276
1316
  })(CredentialSource ||= {});
1317
+ var defaultRobotTenantIdCache = new Map;
1318
+ var ROBOT_TENANT_LOOKUP_TIMEOUT_MS = 5000;
1277
1319
  var getLoginStatusAsync = async (options = {}) => {
1278
1320
  return getLoginStatusWithDeps(options);
1279
1321
  };
@@ -1286,12 +1328,20 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
1286
1328
  refreshToken: refreshTokenFn = refreshAccessToken,
1287
1329
  resolveConfig = resolveConfigAsync,
1288
1330
  robotFallback = tryRobotClientFallback,
1331
+ fetchTenantsAndOrgs = fetchTenantsAndOrganizations,
1332
+ robotTenantIdCache = defaultRobotTenantIdCache,
1333
+ robotTenantLookupTimeoutMs = ROBOT_TENANT_LOOKUP_TIMEOUT_MS,
1289
1334
  loadBreaker = loadRefreshBreaker,
1290
1335
  saveBreaker = saveRefreshBreaker,
1291
1336
  clearBreaker = clearRefreshBreaker
1292
1337
  } = deps;
1338
+ const robotDeps = {
1339
+ fetchTenantsAndOrgs,
1340
+ cache: robotTenantIdCache,
1341
+ lookupTimeoutMs: robotTenantLookupTimeoutMs
1342
+ };
1293
1343
  if (isRobotAuthEnforced()) {
1294
- return resolveRobotEnforcedStatus(robotFallback);
1344
+ return resolveRobotEnforcedStatus(robotFallback, robotDeps);
1295
1345
  }
1296
1346
  if (isEnvAuthEnabled()) {
1297
1347
  return readAuthFromEnv();
@@ -1309,7 +1359,7 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
1309
1359
  hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
1310
1360
  };
1311
1361
  }
1312
- return resolveBorrowedRobotStatus(robotFallback);
1362
+ return resolveBorrowedRobotStatus(robotFallback, robotDeps);
1313
1363
  }
1314
1364
  const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
1315
1365
  if ("status" in loaded) {
@@ -1351,7 +1401,7 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
1351
1401
  }
1352
1402
  return buildFileStatus(tokens, credentials, globalHint);
1353
1403
  };
1354
- async function resolveRobotEnforcedStatus(robotFallback) {
1404
+ async function resolveRobotEnforcedStatus(robotFallback, deps) {
1355
1405
  if (isEnvAuthEnabled()) {
1356
1406
  throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
1357
1407
  }
@@ -1362,11 +1412,11 @@ async function resolveRobotEnforcedStatus(robotFallback) {
1362
1412
  hint: `${ENFORCE_ROBOT_AUTH_VAR}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR} to fall back to file or ` + `env-var authentication.`
1363
1413
  };
1364
1414
  }
1365
- return buildRobotStatus(robotCreds);
1415
+ return buildRobotStatus(robotCreds, deps);
1366
1416
  }
1367
- async function resolveBorrowedRobotStatus(robotFallback) {
1417
+ async function resolveBorrowedRobotStatus(robotFallback, deps) {
1368
1418
  const robotCreds = await robotFallback();
1369
- return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
1419
+ return robotCreds ? buildRobotStatus(robotCreds, deps) : { loginStatus: "Not logged in" };
1370
1420
  }
1371
1421
  async function loadFileCredentials(loadEnvFile, absolutePath) {
1372
1422
  let credentials;
@@ -1501,9 +1551,10 @@ function identityFields(accessToken, credentials) {
1501
1551
  ...scopes ? { scopes } : {}
1502
1552
  };
1503
1553
  }
1504
- function buildRobotStatus(robotCreds) {
1554
+ async function buildRobotStatus(robotCreds, deps) {
1505
1555
  const identity = resolveSessionIdentity(robotCreds.accessToken);
1506
1556
  const scopes = readTokenScopes(robotCreds.accessToken);
1557
+ const tenant = robotCreds.tenantId ? { tenantId: robotCreds.tenantId } : await resolveRobotTenantId(robotCreds, deps);
1507
1558
  return {
1508
1559
  loginStatus: "Logged in",
1509
1560
  accessToken: robotCreds.accessToken,
@@ -1511,14 +1562,62 @@ function buildRobotStatus(robotCreds) {
1511
1562
  organizationName: robotCreds.organizationName,
1512
1563
  organizationId: robotCreds.organizationId,
1513
1564
  tenantName: robotCreds.tenantName,
1514
- tenantId: robotCreds.tenantId,
1565
+ tenantId: tenant.tenantId,
1515
1566
  issuer: robotCreds.issuer,
1516
1567
  expiration: getTokenExpiration(robotCreds.accessToken),
1517
1568
  source: "robot" /* Robot */,
1569
+ ...tenant.hint ? { hint: tenant.hint } : {},
1518
1570
  ...identity ? { identity } : {},
1519
1571
  ...scopes ? { scopes } : {}
1520
1572
  };
1521
1573
  }
1574
+ async function resolveRobotTenantId(robotCreds, deps) {
1575
+ const { baseUrl, accessToken, tenantName } = robotCreds;
1576
+ const organization = robotCreds.organizationName ?? robotCreds.organizationId;
1577
+ if (!tenantName || !organization) {
1578
+ return {};
1579
+ }
1580
+ const key = `${baseUrl}|${organization}|${tenantName}|${accessToken}`;
1581
+ let pending = deps.cache.get(key);
1582
+ if (!pending) {
1583
+ pending = catchError(lookupRobotTenantId({ baseUrl, accessToken, organization, tenantName }, deps)).then(([error, resolution]) => {
1584
+ const settled = error ? { hint: tenantLookupFailureHint(tenantName, error.message) } : resolution;
1585
+ if (!settled.tenantId) {
1586
+ deps.cache.delete(key);
1587
+ }
1588
+ return settled;
1589
+ });
1590
+ deps.cache.set(key, pending);
1591
+ }
1592
+ return pending;
1593
+ }
1594
+ async function lookupRobotTenantId(target, deps) {
1595
+ const { baseUrl, accessToken, organization, tenantName } = target;
1596
+ const [error, data] = await catchError(deps.fetchTenantsAndOrgs(baseUrl, accessToken, organization, AbortSignal.timeout(deps.lookupTimeoutMs)));
1597
+ if (error) {
1598
+ const reason = error.name === "TimeoutError" ? `the tenant list did not answer within ${deps.lookupTimeoutMs} ms.` : error.message;
1599
+ return { hint: tenantLookupFailureHint(tenantName, reason) };
1600
+ }
1601
+ const rows = data?.tenants;
1602
+ const tenants = Array.isArray(rows) ? rows.filter((tenant) => typeof tenant?.id === "string" && typeof tenant?.name === "string") : [];
1603
+ const wantedName = decodePathSegment(tenantName);
1604
+ const wanted = wantedName.toLowerCase();
1605
+ const match = tenants.find((tenant) => tenant.name === wantedName) ?? tenants.find((tenant) => tenant.name.toLowerCase() === wanted);
1606
+ if (!match) {
1607
+ const names = tenants.map((tenant) => tenant.name).join(", ");
1608
+ return {
1609
+ hint: `The Robot session targets tenant '${tenantName}', but ` + `organization '${organization}' lists no tenant of that name` + `${names ? ` (available: ${names})` : ""}. Commands that need ` + `the tenant id will fail until it can be resolved.`
1610
+ };
1611
+ }
1612
+ return { tenantId: match.id };
1613
+ }
1614
+ function tenantLookupFailureHint(tenantName, reason) {
1615
+ return `Could not resolve the id of tenant '${tenantName}' from the ` + `Robot session: ${reason} Commands that need the tenant id will ` + `fail until it can be resolved.`;
1616
+ }
1617
+ function decodePathSegment(segment) {
1618
+ const [error, decoded] = catchError(() => decodeURIComponent(segment));
1619
+ return error ? segment : decoded;
1620
+ }
1522
1621
  var isFileNotFoundError = (error) => {
1523
1622
  if (!(error instanceof Object))
1524
1623
  return false;
@@ -2040,39 +2139,6 @@ var federatedCredentialsLogin = async ({
2040
2139
  buildError: buildFederatedError
2041
2140
  });
2042
2141
  };
2043
- // ../auth/src/tenantSelection.ts
2044
- var LOGIN_STATUS_HINT = "Run 'uip login status' to see the organization the CLI is signed in to.";
2045
- var organizationHint = (organizationId) => `The request used '${organizationId}' as the organization. ${LOGIN_STATUS_HINT}`;
2046
- var IDENTIFIER_STATUSES = new Set([400, 403, 404]);
2047
- var describeNonJsonResponse = (organizationId, response, parseError) => {
2048
- if (response.redirected) {
2049
- return `Could not find organization '${organizationId}': the request was ` + `redirected to a sign-in page instead of the organization's tenant ` + `list. ${LOGIN_STATUS_HINT}`;
2050
- }
2051
- const contentType = response.headers.get("content-type") ?? "unknown";
2052
- return `The organization service returned a '${contentType}' response instead ` + `of JSON: ${parseError.message}. ${organizationHint(organizationId)}`;
2053
- };
2054
- var fetchTenantsAndOrganizations = async (baseUrl, accessToken, organizationId) => {
2055
- const url = `${baseUrl}/${organizationId}/portal_/api/filtering/leftnav/tenantsAndOrganizationInfo`;
2056
- const response = await fetch(url, {
2057
- headers: {
2058
- Authorization: `Bearer ${accessToken}`
2059
- }
2060
- });
2061
- if (!response.ok) {
2062
- if (response.status === 401) {
2063
- throw new Error(`Unauthorized: the access token was rejected, it was not ` + `issued for organization '${organizationId}', or ` + `'${organizationId}' was not accepted as an organization ` + `URL segment in this environment. ` + LOGIN_STATUS_HINT);
2064
- }
2065
- const errorText = await response.text();
2066
- const message = `Failed to get tenants and organizations: ${response.status} ${errorText}`;
2067
- throw new Error(IDENTIFIER_STATUSES.has(response.status) ? `${message}. ${organizationHint(organizationId)}` : message);
2068
- }
2069
- const [parseError, data] = await catchError(response.json());
2070
- if (parseError) {
2071
- throw new Error(describeNonJsonResponse(organizationId, response, parseError));
2072
- }
2073
- return data;
2074
- };
2075
-
2076
2142
  // ../auth/src/selectTenant.ts
2077
2143
  var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
2078
2144
  var INVALID_TENANT_CODE = "INVALID_TENANT";
@@ -2432,7 +2498,7 @@ var authenticate = async ({
2432
2498
  const { BrowserAuthStrategy } = await import("./browser-strategy-6atc7v8s.js");
2433
2499
  strategy = new BrowserAuthStrategy;
2434
2500
  } else {
2435
- const { NodeAuthStrategy } = await import("./node-strategy-0267x5e5.js");
2501
+ const { NodeAuthStrategy } = await import("./node-strategy-myagr1zp.js");
2436
2502
  strategy = new NodeAuthStrategy;
2437
2503
  }
2438
2504
  const code = await strategy.execute(authUrl, effectiveRedirectUriUrl, state, {
@@ -2452,6 +2518,6 @@ var authenticate = async ({
2452
2518
  });
2453
2519
  };
2454
2520
 
2455
- export { setAuthFileConfig, InvalidBaseUrlError, DEFAULT_AUTH_PROFILE, AuthProfileValidationError, normalizeAuthProfileName, setActiveAuthProfile, clearActiveAuthProfile, getActiveAuthProfile, runWithAuthProfile, resolveAuthProfileFilePath, getActiveAuthProfileFilePath, getAuthProfilesRootPath, resolveAuthProfileDirPath, listAuthProfileNamesAsync, authProfileExistsAsync, deleteAuthProfileAsync, parseJWT, parseAuthFlow, resolveSessionIdentity, readTokenScopes, ENV_AUTH_ENABLE_VAR, ENFORCE_ROBOT_AUTH_VAR, ENV_AUTH_VARS, EnvAuthConfigError, isEnvAuthEnabled, isRobotAuthEnforced, readAuthFromEnv, refreshTokenFingerprint, loadRefreshBreaker, saveRefreshBreaker, clearRefreshBreaker, registerRobotClientLoader, TokenRefreshOAuthError, isTokenRefreshOAuthFailure, refreshAccessToken, AUTH_FLOW_ENV_VAR, DEFAULT_AUTH_FILENAME, DEFAULT_ENV_FILENAME, resolveEnvFileLocationAsync, resolveEnvFilePathAsync, loadEnvFileAsync, saveEnvFileAsync, CredentialSource, getLoginStatusAsync, getLoginStatusWithDeps, getAuthContext, getAuthEnv, describeAuthProfilesAsync, ClientCredentialsAuthenticationError, clientCredentialsLogin, JWT_BEARER_ASSERTION_TYPE, FederatedCredentialsAuthenticationError, federatedCredentialsLogin, fetchTenantsAndOrganizations, TENANT_SELECTION_REQUIRED_CODE, INVALID_TENANT_CODE, TenantSelectionError, TenantSelectionRequiredError, InvalidTenantError, isTenantSelectionError, selectTenantWithDeps, interactiveLoginWithDeps, interactiveLogin, logoutWithDeps, logout, authenticate };
2521
+ export { setAuthFileConfig, InvalidBaseUrlError, DEFAULT_AUTH_PROFILE, AuthProfileValidationError, normalizeAuthProfileName, setActiveAuthProfile, clearActiveAuthProfile, getActiveAuthProfile, runWithAuthProfile, resolveAuthProfileFilePath, getActiveAuthProfileFilePath, getAuthProfilesRootPath, resolveAuthProfileDirPath, listAuthProfileNamesAsync, authProfileExistsAsync, deleteAuthProfileAsync, parseJWT, parseAuthFlow, resolveSessionIdentity, readTokenScopes, ENV_AUTH_ENABLE_VAR, ENFORCE_ROBOT_AUTH_VAR, ENV_AUTH_VARS, EnvAuthConfigError, isEnvAuthEnabled, isRobotAuthEnforced, readAuthFromEnv, refreshTokenFingerprint, loadRefreshBreaker, saveRefreshBreaker, clearRefreshBreaker, registerRobotClientLoader, fetchTenantsAndOrganizations, TokenRefreshOAuthError, isTokenRefreshOAuthFailure, refreshAccessToken, AUTH_FLOW_ENV_VAR, DEFAULT_AUTH_FILENAME, DEFAULT_ENV_FILENAME, resolveEnvFileLocationAsync, resolveEnvFilePathAsync, loadEnvFileAsync, saveEnvFileAsync, CredentialSource, getLoginStatusAsync, getLoginStatusWithDeps, getAuthContext, getAuthEnv, describeAuthProfilesAsync, ClientCredentialsAuthenticationError, clientCredentialsLogin, JWT_BEARER_ASSERTION_TYPE, FederatedCredentialsAuthenticationError, federatedCredentialsLogin, TENANT_SELECTION_REQUIRED_CODE, INVALID_TENANT_CODE, TenantSelectionError, TenantSelectionRequiredError, InvalidTenantError, isTenantSelectionError, selectTenantWithDeps, interactiveLoginWithDeps, interactiveLogin, logoutWithDeps, logout, authenticate };
2456
2522
 
2457
- //# debugId=C2A7396F2D34604964756E2164756E21
2523
+ //# debugId=40192C240CF134F264756E2164756E21