@uipath/cli 1.205.0-preview.281 → 1.206.0-preview.282

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 (76) hide show
  1. package/dist/{applicationinsights-s28k1t0d.js → applicationinsights-pwe8sf3y.js} +1269 -1269
  2. package/dist/{browser-strategy-6atc7v8s.js → browser-strategy-p5fhwxqj.js} +6 -7
  3. package/dist/cli-s27j1n5p.js +23 -0
  4. package/dist/contentStore-m1z06vbp.js +41 -0
  5. package/dist/environmentInfo-687282b3.js +71 -0
  6. package/dist/feedbackPrompts-t1enxv1x.js +144 -0
  7. package/dist/handlers-93z27zrr.js +805 -0
  8. package/dist/index-090cbg51.js +72 -0
  9. package/dist/index-16d4evd1.js +1051 -0
  10. package/dist/index-1vyte4ma.js +14 -0
  11. package/dist/index-1z45q8dr.js +365 -0
  12. package/dist/index-21kns9qg.js +10 -0
  13. package/dist/{index-30618bjs.js → index-2mm750yx.js} +174 -234
  14. package/dist/{index-622x1qb5.js → index-3fvbddpw.js} +7092 -7092
  15. package/dist/{index-d3w0wn6k.js → index-5gce5wfd.js} +16 -16
  16. package/dist/index-5j0bfd3e.js +4744 -0
  17. package/dist/index-5r4q8h0q.js +30 -0
  18. package/dist/index-68xmrb9x.js +237 -0
  19. package/dist/index-6wj58qka.js +59 -0
  20. package/dist/index-99emfvtm.js +13 -0
  21. package/dist/{index-pj3g8ftz.js → index-9db5vwx9.js} +2429 -1693
  22. package/dist/index-ayg25v46.js +151 -0
  23. package/dist/index-bf0e4evz.js +6180 -0
  24. package/dist/index-bpqx6f8h.js +92 -0
  25. package/dist/index-bpxh3fqv.js +392 -0
  26. package/dist/index-c6fsnn8s.js +200 -0
  27. package/dist/{index-m5nwse9v.js → index-cj4v0jct.js} +21 -69
  28. package/dist/index-ckafghar.js +274 -0
  29. package/dist/{index-469jgr1w.js → index-dsj3jrm0.js} +105 -106
  30. package/dist/{index-1yh8g550.js → index-epsr41wx.js} +8 -12
  31. package/dist/index-gbdz3pb5.js +668 -0
  32. package/dist/{index-yb4er9vd.js → index-jjejkkg4.js} +474 -528
  33. package/dist/index-jmz7bmca.js +1327 -0
  34. package/dist/{index-wwyf05nx.js → index-k9t8g78x.js} +331 -2595
  35. package/dist/index-kg1xrq51.js +171 -0
  36. package/dist/index-m8vqyv3g.js +72 -0
  37. package/dist/index-nht90rae.js +45 -0
  38. package/dist/index-nsrrst23.js +44 -0
  39. package/dist/{index-h8cph72k.js → index-nzr4mx5p.js} +2 -22
  40. package/dist/index-qadhm1gn.js +271 -0
  41. package/dist/index-qwbyt2q5.js +95 -0
  42. package/dist/index-rr5hdtcy.js +95 -0
  43. package/dist/{index-qa9gftnj.js → index-xd2w5pct.js} +3 -3
  44. package/dist/{index-925304r7.js → index-y085rpen.js} +29 -25
  45. package/dist/index-y5ncb93a.js +240 -0
  46. package/dist/index-y7d0cth0.js +93 -0
  47. package/dist/{index-hdxtgckw.js → index-z070caqq.js} +56 -12
  48. package/dist/index-zdqbp34f.js +14 -0
  49. package/dist/index.js +38 -36
  50. package/dist/install-3gw33jcf.js +558 -0
  51. package/dist/{jmespath-e4a59c8w.js → jmespath-ab6tdc42.js} +1 -1
  52. package/dist/js-yaml-0c4svjwq.js +36 -0
  53. package/dist/{mcp-jssaz3wr.js → mcp-s50h6d56.js} +236 -472
  54. package/dist/{node-strategy-ggx3nmyj.js → node-strategy-p1n8wr5s.js} +16 -19
  55. package/dist/project-context-285hydnd.js +94 -0
  56. package/dist/prompt-yxpm7mfr.js +13 -0
  57. package/dist/{server-7jza1fyx.js → server-900wc6vc.js} +28 -43
  58. package/dist/skillCatalog-d1t2qec8.js +22 -0
  59. package/dist/skillsService-tpvbx5g8.js +29 -0
  60. package/dist/{stdio-tmngemcz.js → stdio-kpsab5bz.js} +2 -4
  61. package/dist/{telemetry-drain-r92f0e4r.js → telemetry-drain-bw59e8f5.js} +8 -9
  62. package/dist/tree-j4w7p0pg.js +17 -0
  63. package/dist/updateService-mt6d51p1.js +522 -0
  64. package/dist/updateService.skills-491vfgt8.js +22 -0
  65. package/dist/updateService.tools-f7tr6kc6.js +16 -0
  66. package/package.json +2 -2
  67. package/dist/cli-kyp49kdm.js +0 -19
  68. package/dist/index-0gctz400.js +0 -17
  69. package/dist/index-4cq44eth.js +0 -19427
  70. package/dist/index-7tshyfxx.js +0 -157
  71. package/dist/index-g8ck9tv6.js +0 -2
  72. package/dist/index-ngs0a2he.js +0 -15
  73. package/dist/index-pr8kzdte.js +0 -9867
  74. package/dist/index-yc4kw997.js +0 -13
  75. package/dist/js-yaml-69tsdrrf.js +0 -37
  76. package/dist/updateService-t3yq8936.js +0 -14
@@ -0,0 +1,1051 @@
1
+ import {
2
+ getFileSystem2
3
+ } from "./index-z070caqq.js";
4
+ import {
5
+ catchError,
6
+ extractErrorMessageSync,
7
+ logger
8
+ } from "./index-9db5vwx9.js";
9
+ import {
10
+ withSystemCaEnv,
11
+ mergeEnvCaseInsensitive,
12
+ REGISTRY_TLS_INSTRUCTIONS,
13
+ NPM_FETCH_RETRY_ENV,
14
+ RegistryTlsError,
15
+ isRegistryTlsError,
16
+ npmTlsErrorCode
17
+ } from "./index-qwbyt2q5.js";
18
+
19
+ // src/utils/globalNpmRoot.ts
20
+ var NPM_ROOT_TIMEOUT_MS = 5000;
21
+ var cachedLookup = null;
22
+ async function getGlobalNpmUipathDir() {
23
+ if (cachedLookup)
24
+ return cachedLookup;
25
+ cachedLookup = resolveGlobalNpmUipathDir();
26
+ return cachedLookup;
27
+ }
28
+ async function refreshGlobalNpmUipathDir() {
29
+ cachedLookup = resolveGlobalNpmUipathDir();
30
+ return cachedLookup;
31
+ }
32
+ async function resolveGlobalNpmUipathDir() {
33
+ const root = await runNpmRootGlobal();
34
+ if (!root) {
35
+ logger.debug("npm root -g lookup failed; skipping global plugin fallback");
36
+ return null;
37
+ }
38
+ const fs = getFileSystem2();
39
+ const candidate = fs.path.join(root, "@uipath");
40
+ const [existsError, exists] = await catchError(fs.exists(candidate));
41
+ if (existsError) {
42
+ logger.debug(`fs.exists check failed for ${candidate}: ${String(existsError)}`);
43
+ return null;
44
+ }
45
+ if (!exists) {
46
+ logger.debug(`Global @uipath not present at ${candidate}`);
47
+ return null;
48
+ }
49
+ logger.debug(`Global @uipath resolved via npm root -g: ${candidate}`);
50
+ return candidate;
51
+ }
52
+ async function runNpmRootGlobal() {
53
+ const { spawn } = await import("node:child_process");
54
+ const isWindows = process.platform === "win32";
55
+ return new Promise((resolve) => {
56
+ const proc = isWindows ? spawn("npm root -g", [], {
57
+ shell: true,
58
+ stdio: ["ignore", "pipe", "pipe"],
59
+ windowsHide: true
60
+ }) : spawn("npm", ["root", "-g"], {
61
+ stdio: ["ignore", "pipe", "pipe"]
62
+ });
63
+ let stdout = "";
64
+ proc.stdout?.on("data", (d) => {
65
+ stdout += d.toString();
66
+ });
67
+ proc.stderr?.on("data", () => {});
68
+ const timer = setTimeout(() => {
69
+ proc.kill("SIGTERM");
70
+ resolve(null);
71
+ }, NPM_ROOT_TIMEOUT_MS);
72
+ proc.on("error", () => {
73
+ clearTimeout(timer);
74
+ resolve(null);
75
+ });
76
+ proc.on("close", (code) => {
77
+ clearTimeout(timer);
78
+ const trimmed = stdout.trim();
79
+ resolve(code === 0 && trimmed ? trimmed : null);
80
+ });
81
+ });
82
+ }
83
+
84
+ // src/utils/toolsDirsEnv.ts
85
+ var TOOLS_DIRS_ENV_VAR = "UIPATH_CLI_TOOLS_DIRS";
86
+ var UNSAFE_PATH_CHARS = /["%\p{Cc}]/u;
87
+ function hasUnsafePathChars(value) {
88
+ return UNSAFE_PATH_CHARS.test(value);
89
+ }
90
+ var cachedDeclaration = null;
91
+ async function getEnvToolsDirsDeclaration() {
92
+ if (cachedDeclaration)
93
+ return cachedDeclaration;
94
+ cachedDeclaration = resolveDeclaration();
95
+ return cachedDeclaration;
96
+ }
97
+ async function resolveDeclaration() {
98
+ const fs = getFileSystem2();
99
+ const raw = fs.env.getenv(TOOLS_DIRS_ENV_VAR);
100
+ if (raw === undefined || raw.trim() === "")
101
+ return null;
102
+ const delimiter = process.platform === "win32" ? ";" : ":";
103
+ const dirs = [];
104
+ const seen = new Set;
105
+ let installTarget = null;
106
+ let declared = false;
107
+ for (const entry of raw.split(delimiter)) {
108
+ const candidate = entry.trim();
109
+ if (candidate === "")
110
+ continue;
111
+ if (hasUnsafePathChars(candidate)) {
112
+ logger.warn(`${TOOLS_DIRS_ENV_VAR} entry rejected — unsupported characters in path: ${JSON.stringify(candidate)}`);
113
+ continue;
114
+ }
115
+ if (!fs.path.isAbsolute(candidate)) {
116
+ logger.warn(`${TOOLS_DIRS_ENV_VAR} entry rejected — path is not absolute: ${JSON.stringify(candidate)}`);
117
+ continue;
118
+ }
119
+ const resolved = fs.path.resolve(candidate);
120
+ const key = process.platform === "win32" ? resolved.toLowerCase() : resolved;
121
+ if (seen.has(key))
122
+ continue;
123
+ seen.add(key);
124
+ const isFirst = !declared;
125
+ declared = true;
126
+ const [error, stats] = await catchError(fs.stat(resolved));
127
+ if (error) {
128
+ logger.debug(`${TOOLS_DIRS_ENV_VAR} entry skipped — cannot stat ${resolved}: ${String(error)}`);
129
+ continue;
130
+ }
131
+ if (stats && !stats.isDirectory()) {
132
+ logger.warn(`${TOOLS_DIRS_ENV_VAR} entry skipped — not a directory: ${resolved}`);
133
+ continue;
134
+ }
135
+ if (stats) {
136
+ const [readError] = await catchError(fs.readdir(resolved));
137
+ if (readError) {
138
+ logger.warn(`${TOOLS_DIRS_ENV_VAR} entry skipped — directory is not readable: ${resolved}`);
139
+ continue;
140
+ }
141
+ }
142
+ if (isFirst) {
143
+ installTarget = resolved;
144
+ dirs.push(resolved);
145
+ continue;
146
+ }
147
+ if (!stats) {
148
+ logger.debug(`${TOOLS_DIRS_ENV_VAR} entry skipped — directory does not exist: ${resolved}`);
149
+ continue;
150
+ }
151
+ dirs.push(resolved);
152
+ }
153
+ if (!declared)
154
+ return null;
155
+ logger.debug(`${TOOLS_DIRS_ENV_VAR} declared tool directories: [${dirs.join(", ")}] (install target: ${installTarget ?? "none"})`);
156
+ return { installTarget, dirs };
157
+ }
158
+ function resolveNpmPrefixForToolsDir(toolsDir, platform = process.platform) {
159
+ const fs = getFileSystem2();
160
+ const { basename, dirname } = fs.path;
161
+ const is = (path, name) => platform === "win32" ? basename(path).toLowerCase() === name : basename(path) === name;
162
+ if (!is(toolsDir, "@uipath"))
163
+ return null;
164
+ const nodeModules = dirname(toolsDir);
165
+ if (!is(nodeModules, "node_modules"))
166
+ return null;
167
+ const parent = dirname(nodeModules);
168
+ if (platform === "win32")
169
+ return parent;
170
+ return is(parent, "lib") ? dirname(parent) : null;
171
+ }
172
+ function npmGlobalRootParent(prefix, platform = process.platform) {
173
+ return platform === "win32" ? prefix : getFileSystem2().path.join(prefix, "lib");
174
+ }
175
+
176
+ // src/services/bundleDistribution.ts
177
+ var BUNDLE_PACKAGE_NAME = "uipath-cli-bundle";
178
+
179
+ class InstallRefusedError extends Error {
180
+ instructions;
181
+ __brand = "InstallRefusedError";
182
+ errorCode;
183
+ retry;
184
+ constructor(message, instructions, classification) {
185
+ super(message);
186
+ this.instructions = instructions;
187
+ this.name = "InstallRefusedError";
188
+ this.errorCode = classification?.errorCode;
189
+ this.retry = classification?.retry;
190
+ }
191
+ }
192
+ var detectionCache = new Map;
193
+ function isBundledDistribution(prefixPath) {
194
+ let cached = detectionCache.get(prefixPath);
195
+ if (!cached) {
196
+ cached = detectBundleManifest(prefixPath);
197
+ detectionCache.set(prefixPath, cached);
198
+ }
199
+ return cached;
200
+ }
201
+ async function detectBundleManifest(prefixPath) {
202
+ const fs = getFileSystem2();
203
+ const manifestPath = fs.path.join(prefixPath, "package.json");
204
+ const [, raw] = await catchError(fs.readFile(manifestPath, "utf-8"));
205
+ if (!raw)
206
+ return false;
207
+ const [, manifest] = catchError(() => JSON.parse(raw));
208
+ const isBundle = manifest?.name === BUNDLE_PACKAGE_NAME;
209
+ if (isBundle) {
210
+ logger.debug(`Bundled CLI distribution detected at ${prefixPath} (manifest name '${BUNDLE_PACKAGE_NAME}')`);
211
+ }
212
+ return isBundle;
213
+ }
214
+
215
+ // src/services/installArch.ts
216
+ function archPinEnv(host) {
217
+ return {
218
+ npm_config_cpu: host?.arch ?? process.arch,
219
+ npm_config_os: host?.platform ?? process.platform
220
+ };
221
+ }
222
+ async function detectTranslatedNodeAsync(host, readCpuModel) {
223
+ const platform = host?.platform ?? process.platform;
224
+ const arch = host?.arch ?? process.arch;
225
+ if (platform !== "darwin" || arch !== "x64") {
226
+ return;
227
+ }
228
+ const model = await (readCpuModel ?? readDarwinCpuModelAsync)();
229
+ if (!model.includes("Apple")) {
230
+ return;
231
+ }
232
+ return { nodeArch: "x64", hostArch: "arm64" };
233
+ }
234
+ async function readDarwinCpuModelAsync() {
235
+ const { cpus } = await import("node:os");
236
+ return cpus()[0]?.model ?? "";
237
+ }
238
+ var TRANSLATED_NODE_HINT = "Which node runs `uip` is decided by PATH order, not by this install. Run `command -v -a node` to see the candidates, put an arm64 node ahead " + "of the x64 one on PATH, and re-run — the next update then installs arm64 " + "builds on its own.";
239
+ function describeTranslatedNode(detected) {
240
+ return `This CLI is running under an ${detected.nodeArch} node on an ${detected.hostArch} Mac (Rosetta), so tools are being installed as ${detected.nodeArch}. Native components on this machine — the .NET ` + `runtime included — are ${detected.hostArch}, and tools that load native payloads (for example \`uip rpa pack\`) will fail to start. ` + TRANSLATED_NODE_HINT;
241
+ }
242
+ var translatedNodeWarned = false;
243
+ async function warnIfTranslatedNodeAsync(host, readCpuModel) {
244
+ if (translatedNodeWarned) {
245
+ return;
246
+ }
247
+ const detected = await detectTranslatedNodeAsync(host, readCpuModel).catch(() => {
248
+ return;
249
+ });
250
+ if (!detected) {
251
+ return;
252
+ }
253
+ translatedNodeWarned = true;
254
+ logger.warn(describeTranslatedNode(detected));
255
+ }
256
+
257
+ // src/services/tools-whitelist.ts
258
+ var TOOLS_WHITELIST = new Map([
259
+ ["@uipath/solution-tool", "solution"],
260
+ ["@uipath/agent-tool", "agent"],
261
+ ["@uipath/agenthub-tool", "agenthub"],
262
+ ["@uipath/conversational-tool", "conversational"],
263
+ ["@uipath/codedagent-tool", "codedagent"],
264
+ ["@uipath/context-grounding-tool", "context-grounding"],
265
+ ["@uipath/function-tool", "function"],
266
+ ["@uipath/codedapp-tool", "codedapp"],
267
+ ["@uipath/integrationservice-tool", "is"],
268
+ ["@uipath/eval-tool", "eval"],
269
+ ["@uipath/orchestrator-tool", "or"],
270
+ ["@uipath/rpa-tool", "rpa"],
271
+ ["@uipath/test-manager-tool", "tm"],
272
+ ["@uipath/api-workflow-tool", "api-workflow"],
273
+ ["@uipath/maestro-tool", "maestro"],
274
+ ["@uipath/rules-tool", "rules"],
275
+ ["@uipath/docsai-tool", "docsai"],
276
+ ["@uipath/vertical-solutions-tool", "vss"],
277
+ ["@uipath/rpa-legacy-tool", "rpa-legacy"],
278
+ ["@uipath/traces-tool", "traces"],
279
+ ["@uipath/gov-tool", "gov"],
280
+ ["@uipath/admin-tool", "admin"],
281
+ ["@uipath/data-fabric-tool", "df"],
282
+ ["@uipath/insights-tool", "insights"],
283
+ ["@uipath/tasks-tool", "tasks"],
284
+ ["@uipath/aops-tool", "aops"],
285
+ ["@uipath/llmgw-tool", "llm-configuration"],
286
+ ["@uipath/llm-gateway-tool", "llm-gateway"],
287
+ ["@uipath/guardrails-tool", "guardrails"],
288
+ ["@uipath/model-hub-tool", "model-hub"],
289
+ ["@uipath/platform-tool", "platform"],
290
+ ["@uipath/ixp-tool", "ixp"],
291
+ ["@uipath/pm-tool", "pm"],
292
+ ["@uipath/coder-tool", "coder"],
293
+ ["@uipath/automation-hub-tool", "ah"]
294
+ ]);
295
+ var COMMAND_ALIASES = new Map([
296
+ ["orchestrator", "or"],
297
+ ["functions", "function"]
298
+ ]);
299
+ var ALIASES_BY_COMMAND = (() => {
300
+ const map = new Map;
301
+ for (const [alias, canonical] of COMMAND_ALIASES) {
302
+ const list = map.get(canonical) ?? [];
303
+ list.push(alias);
304
+ map.set(canonical, list);
305
+ }
306
+ return map;
307
+ })();
308
+ var WHITELIST_BY_COMMAND = (() => {
309
+ const map = new Map([...TOOLS_WHITELIST.entries()].map(([pkg, cmd]) => [cmd, pkg]));
310
+ for (const [alias, canonical] of COMMAND_ALIASES) {
311
+ const pkg = [...TOOLS_WHITELIST.entries()].find(([, cmd]) => cmd === canonical)?.[0];
312
+ if (pkg)
313
+ map.set(alias, pkg);
314
+ }
315
+ return map;
316
+ })();
317
+ var WHITELIST_BY_SHORT_NAME = new Map([...TOOLS_WHITELIST.keys()].map((pkg) => [
318
+ pkg.replace(/^@uipath\//, ""),
319
+ pkg
320
+ ]));
321
+
322
+ // src/services/toolService.ts
323
+ var SEMVER_RE = /^\d+\.\d+\.\d+(-[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*)?(\+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*)?$/;
324
+ function isValidSemver(v) {
325
+ return SEMVER_RE.test(v);
326
+ }
327
+ function compareSemver(a, b) {
328
+ const parseVersion = (v) => {
329
+ const stripped = v.replace(/\+.*$/, "");
330
+ const dashIdx = stripped.indexOf("-");
331
+ const core = dashIdx === -1 ? stripped : stripped.slice(0, dashIdx);
332
+ const prerelease = dashIdx === -1 ? undefined : stripped.slice(dashIdx + 1);
333
+ const [major, minor, patch] = core.split(".").map(Number);
334
+ return { major, minor, patch, prerelease };
335
+ };
336
+ const pa = parseVersion(a);
337
+ const pb = parseVersion(b);
338
+ const diff = pa.major - pb.major || pa.minor - pb.minor || pa.patch - pb.patch;
339
+ if (diff !== 0)
340
+ return diff;
341
+ if (!pa.prerelease && !pb.prerelease)
342
+ return 0;
343
+ if (!pa.prerelease)
344
+ return 1;
345
+ if (!pb.prerelease)
346
+ return -1;
347
+ const aParts = pa.prerelease.split(".");
348
+ const bParts = pb.prerelease.split(".");
349
+ const len = Math.max(aParts.length, bParts.length);
350
+ for (let i = 0;i < len; i++) {
351
+ if (i >= aParts.length)
352
+ return -1;
353
+ if (i >= bParts.length)
354
+ return 1;
355
+ const aNum = aParts[i].length > 0 ? Number(aParts[i]) : NaN;
356
+ const bNum = bParts[i].length > 0 ? Number(bParts[i]) : NaN;
357
+ const aIsNum = !Number.isNaN(aNum);
358
+ const bIsNum = !Number.isNaN(bNum);
359
+ if (aIsNum && bIsNum) {
360
+ if (aNum !== bNum)
361
+ return aNum - bNum;
362
+ } else if (aIsNum) {
363
+ return -1;
364
+ } else if (bIsNum) {
365
+ return 1;
366
+ } else {
367
+ if (aParts[i] < bParts[i])
368
+ return -1;
369
+ if (aParts[i] > bParts[i])
370
+ return 1;
371
+ }
372
+ }
373
+ return 0;
374
+ }
375
+ var SAFE_PACKAGE_SPEC = /^@?[a-zA-Z0-9._/-]+(@[a-zA-Z0-9._+:~^<>=| -]+)?$/;
376
+ var SHELL_SAFE_ARG = /^[a-zA-Z0-9@/._-]+$/;
377
+ var SHELL_SAFE_COMMAND_LINE = /^[a-zA-Z0-9@/._\- ]+$/;
378
+ var NPM_TIMEOUT_MS = 180000;
379
+ var NPM_VIEW_TIMEOUT_MS = 30000;
380
+ var NPM_MAX_RETRIES = 2;
381
+ var TRANSIENT_NPM_ERRORS = ["ENOTEMPTY", "EBUSY"];
382
+ var UNSUPPORTED_PROTOCOL_MARKER = "EUNSUPPORTEDPROTOCOL";
383
+ var cachedBunOnPath;
384
+ var childProcessModulePromise;
385
+ function loadChildProcess() {
386
+ childProcessModulePromise ??= import("node:child_process");
387
+ return childProcessModulePromise;
388
+ }
389
+ async function isBunOnPath() {
390
+ if (cachedBunOnPath !== undefined)
391
+ return cachedBunOnPath;
392
+ const [error, result] = await catchError((async () => {
393
+ const { spawn } = await loadChildProcess();
394
+ const isWindows = process.platform === "win32";
395
+ const cmd = isWindows ? "where" : "which";
396
+ return await new Promise((resolve) => {
397
+ const proc = spawn(cmd, ["bun"], { stdio: "ignore" });
398
+ proc.on("error", () => resolve(false));
399
+ proc.on("close", (code) => resolve(code === 0));
400
+ });
401
+ })());
402
+ cachedBunOnPath = !error && result === true;
403
+ return cachedBunOnPath;
404
+ }
405
+ function validatePackageSpec(spec) {
406
+ if (!SAFE_PACKAGE_SPEC.test(spec)) {
407
+ throw new Error(`Invalid package specifier: '${spec}'. Only alphanumeric characters, dots, hyphens, underscores, slashes, and @ are allowed.`);
408
+ }
409
+ }
410
+ class NpmViewMetadataError extends Error {
411
+ constructor(message) {
412
+ super(message);
413
+ this.name = "NpmViewMetadataError";
414
+ }
415
+ }
416
+ function isNpmViewMetadataError(error) {
417
+ return error instanceof NpmViewMetadataError || error.name === "NpmViewMetadataError";
418
+ }
419
+ function resolveToolPackageName(arg) {
420
+ return WHITELIST_BY_COMMAND.get(arg) ?? WHITELIST_BY_SHORT_NAME.get(arg) ?? arg;
421
+ }
422
+ function asNpmViewMetadata(value) {
423
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
424
+ return;
425
+ }
426
+ return value;
427
+ }
428
+ function pickHighestNpmViewMetadata(values) {
429
+ const candidates = values.map(asNpmViewMetadata).filter((candidate) => typeof candidate?.version === "string" && isValidSemver(candidate.version));
430
+ if (candidates.length === 0)
431
+ return;
432
+ candidates.sort((a, b) => compareSemver(b.version ?? "", a.version ?? ""));
433
+ const selected = candidates[0];
434
+ const selectedVersion = selected?.version;
435
+ if (!selected || !selectedVersion)
436
+ return;
437
+ const availableVersions = collectNpmViewMetadataVersions(candidates);
438
+ return {
439
+ ...selected,
440
+ "dist-tags": {
441
+ ...selected["dist-tags"],
442
+ latest: selectedVersion
443
+ },
444
+ versions: availableVersions
445
+ };
446
+ }
447
+ function collectNpmViewMetadataVersions(values) {
448
+ const versions = new Set;
449
+ for (const value of values) {
450
+ const rawVersions = Array.isArray(value.versions) ? value.versions : typeof value.versions === "string" ? [value.versions] : [];
451
+ for (const version of rawVersions) {
452
+ if (isValidSemver(version))
453
+ versions.add(version);
454
+ }
455
+ if (value.version && isValidSemver(value.version)) {
456
+ versions.add(value.version);
457
+ }
458
+ }
459
+ return [...versions].sort((a, b) => compareSemver(b, a));
460
+ }
461
+ function normalizeNpmViewMetadata(parsed, packageName) {
462
+ let unwrapped = parsed;
463
+ while (Array.isArray(unwrapped) && unwrapped.length === 1) {
464
+ unwrapped = unwrapped[0];
465
+ }
466
+ if (Array.isArray(unwrapped)) {
467
+ const selected = pickHighestNpmViewMetadata(unwrapped);
468
+ if (selected)
469
+ return selected;
470
+ throw new NpmViewMetadataError(`npm view ${packageName} returned no versioned package metadata`);
471
+ }
472
+ const metadata = asNpmViewMetadata(unwrapped);
473
+ if (!metadata) {
474
+ throw new NpmViewMetadataError(`npm view ${packageName} returned unsupported metadata shape`);
475
+ }
476
+ return metadata;
477
+ }
478
+ function parsePackageSpec(spec) {
479
+ const versionSeparator = spec.startsWith("@") ? spec.indexOf("@", 1) : spec.indexOf("@");
480
+ if (versionSeparator === -1) {
481
+ return { name: spec, version: undefined };
482
+ }
483
+ return {
484
+ name: spec.slice(0, versionSeparator),
485
+ version: spec.slice(versionSeparator + 1) || undefined
486
+ };
487
+ }
488
+ function classifyRegistryFailure(message) {
489
+ if (/^Authentication required for /.test(message)) {
490
+ return "authentication";
491
+ }
492
+ if (/ not found in the registry$/.test(message)) {
493
+ return "not-found";
494
+ }
495
+ return "other";
496
+ }
497
+ function describeCandidateFailure(packageName, versionPrefix, failure, registry) {
498
+ const where = registry ? ` on ${registry}` : "";
499
+ if (failure?.kind === "authentication") {
500
+ return {
501
+ message: `Authentication failed for '${packageName}'${where}, so no version could be resolved.`,
502
+ instructions: `Fix that registry's credentials in .npmrc, then re-run — for GitHub Packages that means a token with read:packages. 'uip tools search ${packageName}' reports the same auth failure directly.`,
503
+ errorCode: "authentication_required",
504
+ retry: "RetryWillNotFix"
505
+ };
506
+ }
507
+ if (failure?.kind === "unusable-metadata") {
508
+ return {
509
+ message: `The registry answered for '${packageName}'${where} with metadata the CLI could not read (${failure.message}).`,
510
+ instructions: `Re-run to fetch it again. If it persists, check whether a proxy or mirror is rewriting the response: 'npm view ${packageName} --json' shows what the registry actually sent.`,
511
+ errorCode: "server_error",
512
+ retry: "RetryLater"
513
+ };
514
+ }
515
+ if (failure?.kind === "tls") {
516
+ return {
517
+ message: `Could not look up '${packageName}'${where}: ${failure.message}.`,
518
+ instructions: REGISTRY_TLS_INSTRUCTIONS,
519
+ errorCode: "network_error",
520
+ retry: "RetryWillNotFix"
521
+ };
522
+ }
523
+ if (failure?.kind === "other") {
524
+ return {
525
+ message: `The registry could not be reached for '${packageName}'${where} (${failure.message}).`,
526
+ instructions: "Check network access and any proxy or registry configuration in .npmrc, then re-run.",
527
+ errorCode: "network_error",
528
+ retry: "RetryLater"
529
+ };
530
+ }
531
+ return {
532
+ message: `No compatible version of '${packageName}' found for the CLI's ${versionPrefix}x line${where}.`,
533
+ instructions: `Install a build for this line with 'uip tools install ${packageName}@<version>', or run 'uip update' to move the CLI onto a line that publishes it. If the tool is published elsewhere, point the @uipath scope at that registry in .npmrc.`,
534
+ errorCode: "not_found",
535
+ retry: "RetryWillNotFix"
536
+ };
537
+ }
538
+ var effectiveNpmConfigPromise = null;
539
+ function readEffectiveNpmConfig() {
540
+ effectiveNpmConfigPromise ??= (async () => {
541
+ const args = ["config", "list", "--json"];
542
+ const { spawn } = await loadChildProcess();
543
+ const isWindows = process.platform === "win32";
544
+ const stdout = await new Promise((resolve, reject) => {
545
+ let proc;
546
+ if (isWindows) {
547
+ for (const token of ["npm", ...args]) {
548
+ if (!SHELL_SAFE_ARG.test(token)) {
549
+ reject(new Error(`Unsafe argument: '${token}'`));
550
+ return;
551
+ }
552
+ }
553
+ const commandLine = ["npm", ...args].join(" ");
554
+ if (!SHELL_SAFE_COMMAND_LINE.test(commandLine)) {
555
+ reject(new Error(`Unsafe command line: '${commandLine}'`));
556
+ return;
557
+ }
558
+ proc = spawn(commandLine, [], { shell: true });
559
+ } else {
560
+ proc = spawn("npm", args);
561
+ }
562
+ let out = "";
563
+ proc.stdout?.on("data", (d) => {
564
+ out += d.toString();
565
+ });
566
+ const timer = setTimeout(() => {
567
+ proc.kill("SIGTERM");
568
+ reject(new Error("npm config list timed out"));
569
+ }, NPM_VIEW_TIMEOUT_MS);
570
+ proc.on("error", (err) => {
571
+ clearTimeout(timer);
572
+ reject(err);
573
+ });
574
+ proc.on("close", (code) => {
575
+ clearTimeout(timer);
576
+ code === 0 ? resolve(out) : reject(new Error(`npm config list failed with code ${code}`));
577
+ });
578
+ });
579
+ return JSON.parse(stdout);
580
+ })();
581
+ return effectiveNpmConfigPromise;
582
+ }
583
+ async function getEffectiveRegistry(packageName) {
584
+ const scope = packageName.split("/")[0];
585
+ const [err, cfg] = await catchError(readEffectiveNpmConfig());
586
+ if (err || !cfg) {
587
+ logger.debug(`Could not read the effective npm config: ${err?.message ?? "empty output"}`);
588
+ return null;
589
+ }
590
+ const scoped = cfg[`${scope}:registry`];
591
+ if (typeof scoped === "string" && scoped.length > 0) {
592
+ return sanitizeRegistryForDisplay(scoped);
593
+ }
594
+ const global = cfg.registry;
595
+ return typeof global === "string" && global.length > 0 ? sanitizeRegistryForDisplay(global) : null;
596
+ }
597
+ function sanitizeRegistryForDisplay(raw) {
598
+ const [err, url] = catchError(() => new URL(raw));
599
+ if (err || !url)
600
+ return null;
601
+ return `${url.protocol}//${url.host}${url.pathname}`;
602
+ }
603
+ function pickForChannel(versions, channel) {
604
+ if (channel === "stable") {
605
+ return versions.find((v) => !v.includes("-")) ?? null;
606
+ }
607
+ const tag = `-${channel}.`;
608
+ return versions.find((v) => v.includes(tag)) ?? null;
609
+ }
610
+ async function isDevMode() {
611
+ const [error, result] = await catchError((async () => {
612
+ const fs = getFileSystem2();
613
+ let dir = fs.env.cwd();
614
+ for (let i = 0;i < 10; i++) {
615
+ const pkgPath = fs.path.join(dir, "package.json");
616
+ if (await fs.exists(pkgPath)) {
617
+ const raw = await fs.readFile(pkgPath, "utf-8");
618
+ if (raw) {
619
+ const pkg = JSON.parse(raw);
620
+ if (pkg.workspaces && pkg.private) {
621
+ const bunLockPath = fs.path.join(dir, "bun.lock");
622
+ if (await fs.exists(bunLockPath)) {
623
+ logger.debug(`Dev mode detected — found monorepo root at ${dir}`);
624
+ return true;
625
+ }
626
+ }
627
+ }
628
+ }
629
+ const parent = fs.path.dirname(dir);
630
+ if (parent === dir)
631
+ break;
632
+ dir = parent;
633
+ }
634
+ return false;
635
+ })());
636
+ if (error) {
637
+ logger.debug("Dev mode not detected — using npm");
638
+ return false;
639
+ }
640
+ if (result)
641
+ return true;
642
+ logger.debug("Dev mode not detected — using npm");
643
+ return false;
644
+ }
645
+ var PERMISSION_ERROR_MARKERS = [
646
+ "EACCES",
647
+ "EPERM",
648
+ "permission denied",
649
+ "operation not permitted"
650
+ ];
651
+ function isPermissionError(err) {
652
+ const code = err.code;
653
+ const text = `${String(code ?? "")} ${err.name} ${err.message}`.toLowerCase();
654
+ return PERMISSION_ERROR_MARKERS.some((m) => text.includes(m.toLowerCase()));
655
+ }
656
+ async function spawnPackageManager(executable, args, cwd, label, extraEnv) {
657
+ if (!SHELL_SAFE_ARG.test(executable)) {
658
+ throw new Error(`Unsafe executable: '${executable}'`);
659
+ }
660
+ for (const arg of args) {
661
+ if (!SHELL_SAFE_ARG.test(arg)) {
662
+ throw new Error(`Unsafe argument: '${arg}'`);
663
+ }
664
+ }
665
+ const { spawn } = await loadChildProcess();
666
+ const isWindows = process.platform === "win32";
667
+ const envOpt = {
668
+ env: withSystemCaEnv(extraEnv ? mergeEnvCaseInsensitive(process.env, extraEnv) : process.env)
669
+ };
670
+ return new Promise((resolve, reject) => {
671
+ let proc;
672
+ if (isWindows) {
673
+ const commandLine = [executable, ...args].join(" ");
674
+ if (!SHELL_SAFE_COMMAND_LINE.test(commandLine)) {
675
+ throw new Error(`Unsafe command line: '${commandLine}'`);
676
+ }
677
+ proc = spawn(commandLine, [], {
678
+ stdio: ["inherit", "pipe", "pipe"],
679
+ shell: true,
680
+ cwd,
681
+ ...envOpt
682
+ });
683
+ } else {
684
+ proc = spawn(executable, args, {
685
+ stdio: ["inherit", "pipe", "pipe"],
686
+ cwd,
687
+ ...envOpt
688
+ });
689
+ }
690
+ let stderr = "";
691
+ const MAX_STDERR = 65536;
692
+ proc.stdout?.on("data", (d) => {
693
+ logger.info(d.toString().trimEnd());
694
+ });
695
+ proc.stderr?.on("data", (d) => {
696
+ if (stderr.length < MAX_STDERR) {
697
+ stderr += d.toString();
698
+ }
699
+ });
700
+ const timer = setTimeout(() => {
701
+ proc.kill("SIGTERM");
702
+ reject(new Error(`${label} timed out after ${NPM_TIMEOUT_MS / 1000}s`));
703
+ }, NPM_TIMEOUT_MS);
704
+ proc.on("error", (err) => {
705
+ clearTimeout(timer);
706
+ reject(err);
707
+ });
708
+ proc.on("close", (code) => {
709
+ clearTimeout(timer);
710
+ code === 0 ? resolve() : reject(new Error(stderr.trim() || `${label} failed with code ${code}`));
711
+ });
712
+ });
713
+ }
714
+ function prefixEnv(prefix) {
715
+ if (prefix === undefined || prefix.trim() === "")
716
+ return {};
717
+ if (!/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(prefix)) {
718
+ throw new Error(`npm prefix must be an absolute path: ${prefix}`);
719
+ }
720
+ if (hasUnsafePathChars(prefix)) {
721
+ throw new Error(`npm prefix contains unsupported characters: ${JSON.stringify(prefix)}`);
722
+ }
723
+ return { npm_config_prefix: prefix };
724
+ }
725
+ async function bunCwdFor(args, cwd, extraEnv) {
726
+ const prefix = extraEnv?.npm_config_prefix;
727
+ if (!prefix || !args.includes("-g"))
728
+ return cwd;
729
+ const root = npmGlobalRootParent(prefix);
730
+ if (root !== cwd)
731
+ await getFileSystem2().mkdir(root);
732
+ return root;
733
+ }
734
+ async function runPackageManager(args, cwd, extraEnv) {
735
+ for (const arg of args) {
736
+ if (arg !== "-g" && !arg.startsWith("--")) {
737
+ validatePackageSpec(arg);
738
+ }
739
+ }
740
+ const useBun = await isDevMode();
741
+ const pm = useBun ? "bun" : "npm";
742
+ const runCwd = useBun ? await bunCwdFor(args, cwd, extraEnv) : cwd;
743
+ logger.debug(`Running package manager: ${pm} ${args.join(" ")}${runCwd ? ` (cwd: ${runCwd})` : ""}`);
744
+ const pmArgs = useBun ? args.filter((a) => a !== "-g").map((a) => a === "uninstall" ? "remove" : a) : args;
745
+ await spawnPackageManager(pm, pmArgs, runCwd, `${pm} ${pmArgs[0]}`, extraEnv);
746
+ }
747
+ async function runPackageManagerWithBun(args, cwd, extraEnv) {
748
+ for (const arg of args) {
749
+ if (arg !== "-g" && !arg.startsWith("--")) {
750
+ validatePackageSpec(arg);
751
+ }
752
+ }
753
+ const pmArgs = args.filter((a) => a !== "-g").map((a) => a === "uninstall" ? "remove" : a);
754
+ const bunCwd = await bunCwdFor(args, cwd, extraEnv);
755
+ logger.debug(`Running package manager: bun ${pmArgs.join(" ")}${bunCwd ? ` (cwd: ${bunCwd})` : ""}`);
756
+ await spawnPackageManager("bun", pmArgs, bunCwd, `bun ${pmArgs[0]}`, extraEnv);
757
+ }
758
+
759
+ class HostOwnedToolError extends InstallRefusedError {
760
+ constructor(packageName, dir) {
761
+ super(`Refusing to uninstall '${packageName}': it ships with the host application at ${dir}, which the CLI does not manage.`, "Only tools installed with 'uip tools install' can be uninstalled here.");
762
+ this.name = "HostOwnedToolError";
763
+ }
764
+ }
765
+
766
+ class NodeToolService {
767
+ async npmView(packageName, timeoutMs = NPM_VIEW_TIMEOUT_MS) {
768
+ validatePackageSpec(packageName);
769
+ const args = ["view", packageName, "--json"];
770
+ const { spawn } = await loadChildProcess();
771
+ const isWindows = process.platform === "win32";
772
+ const spawnOpts = {
773
+ env: withSystemCaEnv(mergeEnvCaseInsensitive(process.env, NPM_FETCH_RETRY_ENV))
774
+ };
775
+ const { stdout } = await new Promise((resolve, reject) => {
776
+ let proc;
777
+ if (isWindows) {
778
+ if (!SHELL_SAFE_ARG.test("npm")) {
779
+ reject(new Error("Unsafe executable: 'npm'"));
780
+ return;
781
+ }
782
+ for (const arg of args) {
783
+ if (!SHELL_SAFE_ARG.test(arg)) {
784
+ reject(new Error(`Unsafe argument: '${arg}'`));
785
+ return;
786
+ }
787
+ }
788
+ const commandLine = ["npm", ...args].join(" ");
789
+ if (!SHELL_SAFE_COMMAND_LINE.test(commandLine)) {
790
+ reject(new Error(`Unsafe command line: '${commandLine}'`));
791
+ return;
792
+ }
793
+ proc = spawn(commandLine, [], {
794
+ shell: true,
795
+ ...spawnOpts
796
+ });
797
+ } else {
798
+ proc = spawn("npm", args, spawnOpts);
799
+ }
800
+ let out = "";
801
+ let err = "";
802
+ const MAX_STDERR = 65536;
803
+ proc.stdout?.on("data", (d) => {
804
+ out += d.toString();
805
+ });
806
+ proc.stderr?.on("data", (d) => {
807
+ if (err.length < MAX_STDERR) {
808
+ err += d.toString();
809
+ }
810
+ });
811
+ const timer = setTimeout(() => {
812
+ proc.kill("SIGTERM");
813
+ reject(new Error(`npm view ${packageName} timed out after ${timeoutMs / 1000}s`));
814
+ }, timeoutMs);
815
+ proc.on("error", (spawnErr) => {
816
+ clearTimeout(timer);
817
+ reject(this.mapNpmViewError(packageName, err, out, spawnErr));
818
+ });
819
+ proc.on("close", (code) => {
820
+ clearTimeout(timer);
821
+ if (code === 0) {
822
+ resolve({ stdout: out });
823
+ } else {
824
+ reject(this.mapNpmViewError(packageName, err, out, code));
825
+ }
826
+ });
827
+ });
828
+ const [parseError, parsed] = catchError(() => JSON.parse(stdout));
829
+ if (parseError) {
830
+ throw new NpmViewMetadataError(`npm view ${packageName} returned invalid JSON`);
831
+ }
832
+ const data = normalizeNpmViewMetadata(parsed, packageName);
833
+ const latestVersion = data["dist-tags"]?.latest ?? data.version;
834
+ const rawVersions = Array.isArray(data.versions) ? data.versions : data.versions ? [data.versions] : [];
835
+ const availableVersions = rawVersions.filter(isValidSemver).sort((a, b) => compareSemver(b, a));
836
+ let registryLabel;
837
+ if (data.dist?.tarball) {
838
+ const tarball = data.dist.tarball;
839
+ const [urlError, parsedUrl] = catchError(() => new URL(tarball));
840
+ registryLabel = urlError ? undefined : parsedUrl.host;
841
+ }
842
+ logger.debug(`Package '${packageName}': latest=${latestVersion ?? "unknown"}, ${availableVersions.length} versions available`);
843
+ return {
844
+ name: data.name ?? packageName,
845
+ version: latestVersion || "latest",
846
+ description: data.description || "",
847
+ availableVersions,
848
+ registry: registryLabel
849
+ };
850
+ }
851
+ mapNpmViewError(packageName, stderr, stdout, codeOrError) {
852
+ const tlsCode = npmTlsErrorCode(stderr, stdout);
853
+ if (tlsCode) {
854
+ return new RegistryTlsError(`npm view ${packageName} failed`, tlsCode);
855
+ }
856
+ if (/\bE404\b|\b404\b/.test(stderr)) {
857
+ return new Error(`Package ${packageName} not found in the registry`);
858
+ }
859
+ if (/E401|E403|ENEEDAUTH|need(s)? auth|authentication/i.test(stderr)) {
860
+ return new Error(`Authentication required for ${packageName} (configure a token in .npmrc)`);
861
+ }
862
+ const detail = stderr.trim() || (codeOrError instanceof Error ? codeOrError.message : `exit ${codeOrError}`);
863
+ return new Error(`npm view ${packageName} failed: ${detail}`);
864
+ }
865
+ async search(query) {
866
+ const packages = [...TOOLS_WHITELIST.keys()];
867
+ const settled = await Promise.allSettled(packages.map((name) => this.npmView(name)));
868
+ const results = [];
869
+ const errors = [];
870
+ for (const r of settled) {
871
+ if (r.status === "fulfilled") {
872
+ results.push(r.value);
873
+ } else {
874
+ errors.push(r.reason instanceof Error ? r.reason.message : String(r.reason));
875
+ }
876
+ }
877
+ if (results.length === 0) {
878
+ const reasons = settled.map((r) => r.status === "rejected" ? r.reason : undefined);
879
+ if (reasons.every(isRegistryTlsError)) {
880
+ throw reasons[0];
881
+ }
882
+ throw new Error(`All ${packages.length} package lookups failed:
883
+ ${errors.map((e) => ` - ${e}`).join(`
884
+ `)}`);
885
+ }
886
+ if (query && query.trim() !== "") {
887
+ const q = query.toLowerCase();
888
+ return results.filter((r) => r.name.toLowerCase().includes(q) || r.description.toLowerCase().includes(q));
889
+ }
890
+ return results;
891
+ }
892
+ async searchLatestVersion(packageName, versionPrefix, options) {
893
+ const channel = options?.channel ?? "stable";
894
+ logger.debug(`Searching latest version of '${packageName}'${versionPrefix ? ` with prefix '${versionPrefix}'` : ""} (channel: ${channel})`);
895
+ const info = await this.npmView(packageName, options?.timeoutMs);
896
+ if (options?.exact !== undefined && info.availableVersions?.includes(options.exact)) {
897
+ logger.debug(`Resolved version: ${options.exact} (exact pin match)`);
898
+ return options.exact;
899
+ }
900
+ if (versionPrefix && info.availableVersions) {
901
+ const matching = info.availableVersions.filter((v) => v.startsWith(versionPrefix));
902
+ const picked = pickForChannel(matching, channel);
903
+ if (picked) {
904
+ logger.debug(`Resolved version: ${picked} (${channel}, prefix match)`);
905
+ return picked;
906
+ }
907
+ logger.debug(`No ${channel} version found matching prefix '${versionPrefix}'`);
908
+ return null;
909
+ }
910
+ if (channel !== "stable" && info.availableVersions) {
911
+ const picked = pickForChannel(info.availableVersions, channel);
912
+ logger.debug(`Resolved version: ${picked ?? "null"} (${channel}, no prefix)`);
913
+ return picked;
914
+ }
915
+ logger.debug(`Resolved version: ${info.version ?? "null"} (latest)`);
916
+ return info.version ?? null;
917
+ }
918
+ async resolveInstallCandidate(packageName, versionPrefix, channel = "stable", onRegistryError) {
919
+ const [err, info] = await catchError(this.npmView(packageName));
920
+ if (err) {
921
+ const message = extractErrorMessageSync(err);
922
+ logger.debug(`Lookup failed for '${packageName}': ${message}`);
923
+ onRegistryError?.({
924
+ message,
925
+ kind: isNpmViewMetadataError(err) ? "unusable-metadata" : isRegistryTlsError(err) ? "tls" : classifyRegistryFailure(message)
926
+ });
927
+ return null;
928
+ }
929
+ const onLine = (info.availableVersions ?? []).filter((v) => v.startsWith(versionPrefix));
930
+ const version = pickForChannel(onLine, channel);
931
+ if (!version) {
932
+ return null;
933
+ }
934
+ logger.debug(`Resolved '${packageName}@${version}' from ${info.registry ?? "the configured registry"} (${channel})`);
935
+ return { version, registry: info.registry };
936
+ }
937
+ async install(packageName, destination, options) {
938
+ validatePackageSpec(packageName);
939
+ await refuseIfBundledDistribution(destination, "install", packageName);
940
+ const baseArgs = options?.global ? ["install", "-g", packageName] : ["install", packageName];
941
+ const extraEnv = {
942
+ ...archPinEnv(),
943
+ ...options?.global ? prefixEnv(options.prefix) : {}
944
+ };
945
+ await warnIfTranslatedNodeAsync();
946
+ for (let attempt = 0;attempt <= NPM_MAX_RETRIES; attempt++) {
947
+ const [err] = await catchError(runPackageManager(baseArgs, destination, extraEnv));
948
+ if (!err) {
949
+ return;
950
+ }
951
+ const msg = extractErrorMessageSync(err);
952
+ if (msg.includes(UNSUPPORTED_PROTOCOL_MARKER)) {
953
+ if (await isBunOnPath()) {
954
+ logger.warn(`npm install failed with ${UNSUPPORTED_PROTOCOL_MARKER} — ` + `the published package contains 'workspace:' deps that npm cannot resolve. Retrying with bun. Note that bun ignores the npm_config_cpu/npm_config_os pin and picks optional dependencies for the bun binary's own architecture, so a bun that does not match ${process.arch} can land native payloads this process cannot use.`);
955
+ await runPackageManagerWithBun(baseArgs, destination, extraEnv);
956
+ return;
957
+ }
958
+ throw new Error(`Installation of '${packageName}' failed with ${UNSUPPORTED_PROTOCOL_MARKER}: the published package contains 'workspace:' deps that npm cannot resolve. Install bun (https://bun.sh) and rerun to enable automatic fallback, or use a pre-bundled CLI distribution. Original error: ${msg}`);
959
+ }
960
+ if (msg.includes("EPERM")) {
961
+ throw new InstallRefusedError(`npm cannot write to '${destination}' (EPERM: operation not permitted). This uip installation directory is not writable by the current user.`, "Use a CLI installed in a user-writable location (e.g. 'npm install -g @uipath/cli' with a user-scoped npm prefix), or re-run from an elevated shell if this installation is intentionally system-wide.");
962
+ }
963
+ const isTransient = TRANSIENT_NPM_ERRORS.some((code) => msg.includes(code));
964
+ if (!isTransient || attempt === NPM_MAX_RETRIES) {
965
+ throw err;
966
+ }
967
+ const delayMs = 1000 * (attempt + 1);
968
+ logger.warn(`npm install failed with transient error (attempt ${attempt + 1}/${NPM_MAX_RETRIES + 1}), retrying in ${delayMs}ms: ${msg}`);
969
+ await new Promise((r) => setTimeout(r, delayMs));
970
+ }
971
+ }
972
+ async uninstall(packageName, destination, options) {
973
+ await refuseIfBundledDistribution(destination, "uninstall", packageName);
974
+ const fs = getFileSystem2();
975
+ let containerDir;
976
+ let relativeName;
977
+ if (options?.global) {
978
+ const declaration = options.prefix ? await getEnvToolsDirsDeclaration() : null;
979
+ const globalUipathDir = declaration ? declaration.installTarget : await getGlobalNpmUipathDir();
980
+ if (!globalUipathDir) {
981
+ throw new Error(`Cannot locate '${packageName}': npm root -g unavailable`);
982
+ }
983
+ containerDir = globalUipathDir;
984
+ relativeName = packageName.replace(/^@uipath\//, "");
985
+ } else {
986
+ containerDir = fs.path.resolve(destination, "node_modules");
987
+ relativeName = packageName;
988
+ }
989
+ const packageDir = fs.path.resolve(fs.path.join(containerDir, relativeName));
990
+ if (!packageDir.startsWith(`${containerDir}/`) && !packageDir.startsWith(`${containerDir}\\`)) {
991
+ throw new Error(`Refusing to uninstall '${packageName}': resolved path escapes ${containerDir}`);
992
+ }
993
+ if (!await fs.exists(packageDir)) {
994
+ const declaration = options?.prefix ? await getEnvToolsDirsDeclaration() : null;
995
+ for (const dir of declaration?.dirs.slice(1) ?? []) {
996
+ if (await fs.exists(fs.path.join(dir, relativeName))) {
997
+ throw new HostOwnedToolError(packageName, dir);
998
+ }
999
+ }
1000
+ throw new Error(`Package '${packageName}' is not installed at ${packageDir}`);
1001
+ }
1002
+ const [statError, stat] = await catchError(fs.stat(packageDir));
1003
+ if (!statError && !stat) {
1004
+ await fs.rm(packageDir);
1005
+ logger.info(`Removed workspace-linked package '${packageName}'`);
1006
+ return;
1007
+ }
1008
+ if (options?.global) {
1009
+ await runPackageManager(["uninstall", "-g", packageName], destination, options.prefix ? prefixEnv(options.prefix) : undefined);
1010
+ } else {
1011
+ await runPackageManager(["uninstall", packageName], destination);
1012
+ }
1013
+ if (await fs.exists(packageDir)) {
1014
+ await fs.rm(packageDir);
1015
+ logger.info(`Package directory for '${packageName}' still existed after uninstall — removed manually`);
1016
+ }
1017
+ }
1018
+ }
1019
+ async function refuseIfBundledDistribution(destination, operation, packageName) {
1020
+ if (!await isBundledDistribution(destination))
1021
+ return;
1022
+ throw new InstallRefusedError(`Refusing to ${operation} '${packageName}' in the Studio-bundled CLI at '${destination}': the bundle is a fixed set of tools managed by Studio setup, and modifying it would rewrite its packages.`, "Use a globally installed CLI instead: 'npm install -g @uipath/cli', then re-run the command with that 'uip'.");
1023
+ }
1024
+ function truncateVersionsForDisplay(versions) {
1025
+ const maxStable = 10;
1026
+ const maxPrerelease = 10;
1027
+ let stableCount = 0;
1028
+ let prereleaseCount = 0;
1029
+ const result = [];
1030
+ for (const v of versions) {
1031
+ if (v.includes("-")) {
1032
+ if (prereleaseCount < maxPrerelease) {
1033
+ result.push(v);
1034
+ prereleaseCount++;
1035
+ }
1036
+ } else {
1037
+ if (stableCount < maxStable) {
1038
+ result.push(v);
1039
+ stableCount++;
1040
+ }
1041
+ }
1042
+ if (stableCount >= maxStable && prereleaseCount >= maxPrerelease)
1043
+ break;
1044
+ }
1045
+ return result;
1046
+ }
1047
+ var toolService = new NodeToolService;
1048
+
1049
+ export { getGlobalNpmUipathDir, refreshGlobalNpmUipathDir, TOOLS_DIRS_ENV_VAR, getEnvToolsDirsDeclaration, resolveNpmPrefixForToolsDir, InstallRefusedError, isBundledDistribution, TOOLS_WHITELIST, COMMAND_ALIASES, ALIASES_BY_COMMAND, WHITELIST_BY_COMMAND, WHITELIST_BY_SHORT_NAME, isValidSemver, compareSemver, validatePackageSpec, isNpmViewMetadataError, resolveToolPackageName, parsePackageSpec, describeCandidateFailure, getEffectiveRegistry, isDevMode, isPermissionError, HostOwnedToolError, truncateVersionsForDisplay, toolService };
1050
+
1051
+ //# debugId=9245966C327ABCAE64756E2164756E21