@uipath/insights-tool 1.1.0 → 1.195.0

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 (2) hide show
  1. package/dist/tool.js +652 -134
  2. package/package.json +28 -34
package/dist/tool.js CHANGED
@@ -2127,7 +2127,8 @@ var require_commander = __commonJS((exports) => {
2127
2127
  // package.json
2128
2128
  var package_default = {
2129
2129
  name: "@uipath/insights-tool",
2130
- version: "1.1.0",
2130
+ license: "MIT",
2131
+ version: "1.195.0",
2131
2132
  description: "Query UiPath Insights data — jobs, failures, and performance metrics.",
2132
2133
  private: false,
2133
2134
  repository: {
@@ -2169,6 +2170,7 @@ var package_default = {
2169
2170
  };
2170
2171
 
2171
2172
  // ../filesystem/src/node.ts
2173
+ import { randomUUID } from "node:crypto";
2172
2174
  import { existsSync } from "node:fs";
2173
2175
  import * as fs6 from "node:fs/promises";
2174
2176
  import * as os2 from "node:os";
@@ -2785,6 +2787,13 @@ defineLazyProperty(apps, "safari", () => detectPlatformBinary({
2785
2787
  var open_default = open;
2786
2788
 
2787
2789
  // ../filesystem/src/node.ts
2790
+ var LOCK_HEARTBEAT_MS = 5000;
2791
+ var LOCK_STALE_MS = 15000;
2792
+ var LOCK_MAX_WAIT_MS = 20000;
2793
+ var LOCK_MAX_HOLD_MS = 60000;
2794
+ var LOCK_RETRY_MIN_MS = 100;
2795
+ var LOCK_RETRY_JITTER_MS = 200;
2796
+
2788
2797
  class NodeFileSystem {
2789
2798
  path = {
2790
2799
  join: path2.join,
@@ -2861,6 +2870,90 @@ class NodeFileSystem {
2861
2870
  async mkdir(dirPath) {
2862
2871
  await fs6.mkdir(dirPath, { recursive: true });
2863
2872
  }
2873
+ async acquireLock(lockPath) {
2874
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
2875
+ const lockFile = `${canonicalPath}.lock`;
2876
+ const ownerId = randomUUID();
2877
+ const start = Date.now();
2878
+ while (true) {
2879
+ try {
2880
+ await fs6.writeFile(lockFile, ownerId, { flag: "wx" });
2881
+ return this.createLockRelease(lockFile, ownerId);
2882
+ } catch (error) {
2883
+ if (!this.hasErrnoCode(error, "EEXIST")) {
2884
+ throw error;
2885
+ }
2886
+ const stats = await fs6.stat(lockFile).catch(() => null);
2887
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
2888
+ const reclaimed = await fs6.rm(lockFile, { force: true }).then(() => true).catch(() => false);
2889
+ if (reclaimed)
2890
+ continue;
2891
+ }
2892
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
2893
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
2894
+ }
2895
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
2896
+ }
2897
+ }
2898
+ }
2899
+ async canonicalizeLockTarget(lockPath) {
2900
+ const absolute = path2.resolve(lockPath);
2901
+ const fullReal = await fs6.realpath(absolute).catch(() => null);
2902
+ if (fullReal)
2903
+ return fullReal;
2904
+ const parent = path2.dirname(absolute);
2905
+ const base = path2.basename(absolute);
2906
+ const canonicalParent = await fs6.realpath(parent).catch(() => parent);
2907
+ return path2.join(canonicalParent, base);
2908
+ }
2909
+ createLockRelease(lockFile, ownerId) {
2910
+ const heartbeatStart = Date.now();
2911
+ let heartbeatTimer;
2912
+ let stopped = false;
2913
+ const stopHeartbeat = () => {
2914
+ stopped = true;
2915
+ if (heartbeatTimer)
2916
+ clearTimeout(heartbeatTimer);
2917
+ };
2918
+ const scheduleNextHeartbeat = () => {
2919
+ if (stopped)
2920
+ return;
2921
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
2922
+ stopped = true;
2923
+ return;
2924
+ }
2925
+ heartbeatTimer = setTimeout(() => {
2926
+ runHeartbeat();
2927
+ }, LOCK_HEARTBEAT_MS);
2928
+ heartbeatTimer.unref?.();
2929
+ };
2930
+ const runHeartbeat = async () => {
2931
+ if (stopped)
2932
+ return;
2933
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
2934
+ if (stopped)
2935
+ return;
2936
+ if (current !== ownerId) {
2937
+ stopped = true;
2938
+ return;
2939
+ }
2940
+ const now = Date.now() / 1000;
2941
+ await fs6.utimes(lockFile, now, now).catch(() => {});
2942
+ scheduleNextHeartbeat();
2943
+ };
2944
+ scheduleNextHeartbeat();
2945
+ let released = false;
2946
+ return async () => {
2947
+ if (released)
2948
+ return;
2949
+ released = true;
2950
+ stopHeartbeat();
2951
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
2952
+ if (current === ownerId) {
2953
+ await fs6.rm(lockFile, { force: true });
2954
+ }
2955
+ };
2956
+ }
2864
2957
  async rm(filePath) {
2865
2958
  await fs6.rm(filePath, { recursive: true, force: true });
2866
2959
  }
@@ -2906,7 +2999,10 @@ class NodeFileSystem {
2906
2999
  }
2907
3000
  }
2908
3001
  isEnoent(error) {
2909
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
3002
+ return this.hasErrnoCode(error, "ENOENT");
3003
+ }
3004
+ hasErrnoCode(error, code) {
3005
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
2910
3006
  }
2911
3007
  }
2912
3008
 
@@ -8081,6 +8177,60 @@ function escapeNonAscii(jsonText) {
8081
8177
  function needsAsciiSafeJson(sink) {
8082
8178
  return process.platform === "win32" && !sink.capabilities.isInteractive;
8083
8179
  }
8180
+ function isPlainRecord(value) {
8181
+ if (value === null || typeof value !== "object")
8182
+ return false;
8183
+ const prototype = Object.getPrototypeOf(value);
8184
+ return prototype === Object.prototype || prototype === null;
8185
+ }
8186
+ function toLowerCamelCaseKey(key) {
8187
+ if (!key)
8188
+ return key;
8189
+ if (/[_\-\s]/.test(key)) {
8190
+ const [firstPart, ...restParts] = key.split(/[_\-\s]+/).filter(Boolean);
8191
+ if (!firstPart)
8192
+ return key;
8193
+ return [
8194
+ toLowerCamelCaseSimpleKey(firstPart),
8195
+ ...restParts.map((part) => {
8196
+ const normalized = toLowerCamelCaseSimpleKey(part);
8197
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
8198
+ })
8199
+ ].join("");
8200
+ }
8201
+ return toLowerCamelCaseSimpleKey(key);
8202
+ }
8203
+ function toLowerCamelCaseSimpleKey(key) {
8204
+ if (/^[A-Z0-9]+$/.test(key))
8205
+ return key.toLowerCase();
8206
+ return key.replace(/^[A-Z]+(?=[A-Z][a-z]|\d|$)|^[A-Z]/, (match) => match.toLowerCase());
8207
+ }
8208
+ function toPascalCaseKey(key) {
8209
+ const lowerCamelKey = toLowerCamelCaseKey(key);
8210
+ return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
8211
+ }
8212
+ function toPascalCaseData(value) {
8213
+ if (Array.isArray(value))
8214
+ return value.map(toPascalCaseData);
8215
+ if (!isPlainRecord(value))
8216
+ return value;
8217
+ const result = {};
8218
+ for (const [key, nestedValue] of Object.entries(value)) {
8219
+ result[toPascalCaseKey(key)] = toPascalCaseData(nestedValue);
8220
+ }
8221
+ return result;
8222
+ }
8223
+ function normalizeDataKeys(data) {
8224
+ return toPascalCaseData(data);
8225
+ }
8226
+ function normalizeOutputKeys(data) {
8227
+ const result = {};
8228
+ for (const [key, value] of Object.entries(data)) {
8229
+ const pascalKey = toPascalCaseKey(key);
8230
+ result[pascalKey] = pascalKey === "Data" ? value : toPascalCaseData(value);
8231
+ }
8232
+ return result;
8233
+ }
8084
8234
  function printOutput(data, format = "json", logFn, asciiSafe = false) {
8085
8235
  if (!data) {
8086
8236
  logFn("Empty response object. No data to display.");
@@ -8143,7 +8293,7 @@ function wrapText(text, width) {
8143
8293
  function printTable(data, logFn, externalLogValue) {
8144
8294
  if (data.length === 0)
8145
8295
  return;
8146
- const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
8296
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
8147
8297
  const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
8148
8298
  const header = keys.map((key, i2) => key.padEnd(maxWidths[i2])).join(" | ");
8149
8299
  logFn(header);
@@ -8158,7 +8308,7 @@ function printTable(data, logFn, externalLogValue) {
8158
8308
  }
8159
8309
  }
8160
8310
  function printVerticalTable(data, logFn = console.log, externalLogValue) {
8161
- const keys = Object.keys(data).filter((key) => key !== "Code" && key !== "Log");
8311
+ const keys = Object.keys(data).filter((key) => !["code", "log"].includes(key.toLowerCase()));
8162
8312
  if (keys.length === 0)
8163
8313
  return;
8164
8314
  const maxKeyWidth = Math.max(...keys.map((key) => key.length));
@@ -8174,7 +8324,7 @@ function printVerticalTable(data, logFn = console.log, externalLogValue) {
8174
8324
  function printResizableTable(data, logFn = console.log, externalLogValue) {
8175
8325
  if (data.length === 0)
8176
8326
  return;
8177
- const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
8327
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
8178
8328
  if (keys.length === 0)
8179
8329
  return;
8180
8330
  if (!process.stdout.isTTY) {
@@ -8250,8 +8400,26 @@ function printResizableTable(data, logFn = console.log, externalLogValue) {
8250
8400
  function toYaml(data) {
8251
8401
  return dump(data);
8252
8402
  }
8403
+ class FilterEvaluationError extends Error {
8404
+ __brand = "FilterEvaluationError";
8405
+ filter;
8406
+ instructions;
8407
+ result = RESULTS.ValidationError;
8408
+ constructor(filter, cause) {
8409
+ const underlying = cause instanceof Error ? cause.message : String(cause);
8410
+ super(`Filter '${filter}' failed to evaluate: ${underlying}`);
8411
+ this.name = "FilterEvaluationError";
8412
+ this.filter = filter;
8413
+ this.instructions = `The --output-filter expression '${filter}' failed at evaluation time. ` + "Note that --output-filter operates on the 'Data' field of the envelope, not the full object. " + "For example, on a list result use 'length(@)' instead of 'Data | length(@)'.";
8414
+ }
8415
+ }
8253
8416
  function applyFilter(data, filter) {
8254
- const result = search(data, filter);
8417
+ let result;
8418
+ try {
8419
+ result = search(data, filter);
8420
+ } catch (err) {
8421
+ throw new FilterEvaluationError(filter, err);
8422
+ }
8255
8423
  if (result == null)
8256
8424
  return [];
8257
8425
  if (Array.isArray(result)) {
@@ -8268,13 +8436,18 @@ function applyFilter(data, filter) {
8268
8436
  }
8269
8437
  var OutputFormatter;
8270
8438
  ((OutputFormatter) => {
8271
- function success(data) {
8439
+ function success(data, options) {
8272
8440
  data.Log ??= getLogFilePath() || undefined;
8441
+ const normalize = !options?.preserveDataKeys;
8442
+ if (normalize) {
8443
+ data.Data = normalizeDataKeys(data.Data);
8444
+ }
8273
8445
  const filter = getOutputFilter();
8274
8446
  if (filter) {
8275
- data.Data = applyFilter(data.Data, filter);
8447
+ const filtered = applyFilter(data.Data, filter);
8448
+ data.Data = normalize ? normalizeDataKeys(filtered) : filtered;
8276
8449
  }
8277
- logOutput(data, getOutputFormat());
8450
+ logOutput(normalizeOutputKeys(data), getOutputFormat());
8278
8451
  }
8279
8452
  OutputFormatter.success = success;
8280
8453
  function error(data) {
@@ -8284,7 +8457,7 @@ var OutputFormatter;
8284
8457
  result: data.Result,
8285
8458
  message: data.Message
8286
8459
  });
8287
- logOutput(data, getOutputFormat());
8460
+ logOutput(normalizeOutputKeys(data), getOutputFormat());
8288
8461
  }
8289
8462
  OutputFormatter.error = error;
8290
8463
  function emitList(code, items, opts) {
@@ -8305,13 +8478,14 @@ var OutputFormatter;
8305
8478
  function log(data) {
8306
8479
  const format = getOutputFormat();
8307
8480
  const sink = getOutputSink();
8481
+ const normalized = toPascalCaseData(data);
8308
8482
  if (format === "json") {
8309
- const json2 = JSON.stringify(data);
8483
+ const json2 = JSON.stringify(normalized);
8310
8484
  const safe = needsAsciiSafeJson(sink) ? escapeNonAscii(json2) : json2;
8311
8485
  sink.writeErr(`${safe}
8312
8486
  `);
8313
8487
  } else {
8314
- for (const [key, value] of Object.entries(data)) {
8488
+ for (const [key, value] of Object.entries(normalized)) {
8315
8489
  sink.writeErr(`${key}: ${value}
8316
8490
  `);
8317
8491
  }
@@ -8320,12 +8494,16 @@ var OutputFormatter;
8320
8494
  OutputFormatter.log = log;
8321
8495
  function formatToString(data) {
8322
8496
  const filter = getOutputFilter();
8323
- if (filter && "Data" in data && data.Data != null) {
8324
- data.Data = applyFilter(data.Data, filter);
8497
+ if ("Data" in data && data.Data != null) {
8498
+ data.Data = normalizeDataKeys(data.Data);
8499
+ if (filter) {
8500
+ data.Data = normalizeDataKeys(applyFilter(data.Data, filter));
8501
+ }
8325
8502
  }
8503
+ const output = normalizeOutputKeys(data);
8326
8504
  const lines = [];
8327
8505
  const sink = getOutputSink();
8328
- printOutput(data, getOutputFormat(), (msg) => {
8506
+ printOutput(output, getOutputFormat(), (msg) => {
8329
8507
  lines.push(msg);
8330
8508
  }, needsAsciiSafeJson(sink));
8331
8509
  return lines.join(`
@@ -9753,6 +9931,22 @@ function warnDeprecatedTenantOption(tenant) {
9753
9931
  return;
9754
9932
  warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
9755
9933
  }
9934
+ // ../common/src/polling/types.ts
9935
+ var PollOutcome = {
9936
+ Completed: "completed",
9937
+ Timeout: "timeout",
9938
+ Interrupted: "interrupted",
9939
+ Aborted: "aborted",
9940
+ Failed: "failed"
9941
+ };
9942
+
9943
+ // ../common/src/polling/poll-failure-mapping.ts
9944
+ var REASON_BY_OUTCOME = {
9945
+ [PollOutcome.Timeout]: "poll_timeout",
9946
+ [PollOutcome.Failed]: "poll_failed",
9947
+ [PollOutcome.Interrupted]: "poll_failed",
9948
+ [PollOutcome.Aborted]: "poll_aborted"
9949
+ };
9756
9950
  // ../common/src/polling/terminal-statuses.ts
9757
9951
  var TERMINAL_STATUSES = new Set([
9758
9952
  "completed",
@@ -9780,6 +9974,8 @@ var ScreenLogger;
9780
9974
  }
9781
9975
  ScreenLogger.progress = progress;
9782
9976
  })(ScreenLogger ||= {});
9977
+ // ../common/src/sdk-user-agent.ts
9978
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
9783
9979
  // ../common/src/tool-provider.ts
9784
9980
  var factorySlot = singleton("PackagerFactoryProvider");
9785
9981
  // ../common/src/telemetry/pii-redactor.ts
@@ -9962,13 +10158,17 @@ Command.prototype.trackedAction = function(context, fn, properties) {
9962
10158
  const [error] = await catchError(fn(...args));
9963
10159
  if (error) {
9964
10160
  errorMessage = error instanceof Error ? error.message : String(error);
9965
- logger.error(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
10161
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
10162
+ const typed = error;
10163
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
10164
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
10165
+ const finalResult = customResult ?? RESULTS.Failure;
9966
10166
  OutputFormatter.error({
9967
- Result: RESULTS.Failure,
10167
+ Result: finalResult,
9968
10168
  Message: errorMessage,
9969
- Instructions: "An unexpected error occurred. Run with --log-level debug for details."
10169
+ Instructions: customInstructions ?? "An unexpected error occurred. Run with --log-level debug for details."
9970
10170
  });
9971
- context.exit(1);
10171
+ context.exit(EXIT_CODES[finalResult]);
9972
10172
  }
9973
10173
  const durationMs = performance.now() - startTime;
9974
10174
  const success = !error && (process.exitCode === undefined || process.exitCode === 0);
@@ -10012,6 +10212,7 @@ import path3 from "node:path";
10012
10212
  import { fileURLToPath as fileURLToPath2 } from "node:url";
10013
10213
  import childProcess32 from "node:child_process";
10014
10214
  import fs52, { constants as fsConstants22 } from "node:fs/promises";
10215
+ import { randomUUID as randomUUID2 } from "node:crypto";
10015
10216
  import { existsSync as existsSync2 } from "node:fs";
10016
10217
  import * as fs62 from "node:fs/promises";
10017
10218
  import * as os22 from "node:os";
@@ -10730,6 +10931,90 @@ class NodeFileSystem2 {
10730
10931
  async mkdir(dirPath) {
10731
10932
  await fs62.mkdir(dirPath, { recursive: true });
10732
10933
  }
10934
+ async acquireLock(lockPath) {
10935
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
10936
+ const lockFile = `${canonicalPath}.lock`;
10937
+ const ownerId = randomUUID2();
10938
+ const start = Date.now();
10939
+ while (true) {
10940
+ try {
10941
+ await fs62.writeFile(lockFile, ownerId, { flag: "wx" });
10942
+ return this.createLockRelease(lockFile, ownerId);
10943
+ } catch (error) {
10944
+ if (!this.hasErrnoCode(error, "EEXIST")) {
10945
+ throw error;
10946
+ }
10947
+ const stats = await fs62.stat(lockFile).catch(() => null);
10948
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS2) {
10949
+ const reclaimed = await fs62.rm(lockFile, { force: true }).then(() => true).catch(() => false);
10950
+ if (reclaimed)
10951
+ continue;
10952
+ }
10953
+ if (Date.now() - start > LOCK_MAX_WAIT_MS2) {
10954
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
10955
+ }
10956
+ await new Promise((resolve22) => setTimeout(resolve22, LOCK_RETRY_MIN_MS2 + Math.random() * LOCK_RETRY_JITTER_MS2));
10957
+ }
10958
+ }
10959
+ }
10960
+ async canonicalizeLockTarget(lockPath) {
10961
+ const absolute = path22.resolve(lockPath);
10962
+ const fullReal = await fs62.realpath(absolute).catch(() => null);
10963
+ if (fullReal)
10964
+ return fullReal;
10965
+ const parent = path22.dirname(absolute);
10966
+ const base = path22.basename(absolute);
10967
+ const canonicalParent = await fs62.realpath(parent).catch(() => parent);
10968
+ return path22.join(canonicalParent, base);
10969
+ }
10970
+ createLockRelease(lockFile, ownerId) {
10971
+ const heartbeatStart = Date.now();
10972
+ let heartbeatTimer;
10973
+ let stopped = false;
10974
+ const stopHeartbeat = () => {
10975
+ stopped = true;
10976
+ if (heartbeatTimer)
10977
+ clearTimeout(heartbeatTimer);
10978
+ };
10979
+ const scheduleNextHeartbeat = () => {
10980
+ if (stopped)
10981
+ return;
10982
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS2) {
10983
+ stopped = true;
10984
+ return;
10985
+ }
10986
+ heartbeatTimer = setTimeout(() => {
10987
+ runHeartbeat();
10988
+ }, LOCK_HEARTBEAT_MS2);
10989
+ heartbeatTimer.unref?.();
10990
+ };
10991
+ const runHeartbeat = async () => {
10992
+ if (stopped)
10993
+ return;
10994
+ const current = await fs62.readFile(lockFile, "utf-8").catch(() => null);
10995
+ if (stopped)
10996
+ return;
10997
+ if (current !== ownerId) {
10998
+ stopped = true;
10999
+ return;
11000
+ }
11001
+ const now = Date.now() / 1000;
11002
+ await fs62.utimes(lockFile, now, now).catch(() => {});
11003
+ scheduleNextHeartbeat();
11004
+ };
11005
+ scheduleNextHeartbeat();
11006
+ let released = false;
11007
+ return async () => {
11008
+ if (released)
11009
+ return;
11010
+ released = true;
11011
+ stopHeartbeat();
11012
+ const current = await fs62.readFile(lockFile, "utf-8").catch(() => null);
11013
+ if (current === ownerId) {
11014
+ await fs62.rm(lockFile, { force: true });
11015
+ }
11016
+ };
11017
+ }
10733
11018
  async rm(filePath) {
10734
11019
  await fs62.rm(filePath, { recursive: true, force: true });
10735
11020
  }
@@ -10775,9 +11060,18 @@ class NodeFileSystem2 {
10775
11060
  }
10776
11061
  }
10777
11062
  isEnoent(error) {
10778
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
11063
+ return this.hasErrnoCode(error, "ENOENT");
11064
+ }
11065
+ hasErrnoCode(error, code) {
11066
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
10779
11067
  }
10780
11068
  }
11069
+ var LOCK_HEARTBEAT_MS2 = 5000;
11070
+ var LOCK_STALE_MS2 = 15000;
11071
+ var LOCK_MAX_WAIT_MS2 = 20000;
11072
+ var LOCK_MAX_HOLD_MS2 = 60000;
11073
+ var LOCK_RETRY_MIN_MS2 = 100;
11074
+ var LOCK_RETRY_JITTER_MS2 = 200;
10781
11075
  var init_node = __esm(() => {
10782
11076
  init_open();
10783
11077
  });
@@ -12905,7 +13199,7 @@ function isBrowser() {
12905
13199
  return typeof globalThis !== "undefined" && "window" in globalThis && "document" in globalThis;
12906
13200
  }
12907
13201
  var require_coreipc = __commonJS2((exports, module) => {
12908
- var __dirname3 = "/Users/alexandru.oltean/github/cli/node_modules/@uipath/coreipc";
13202
+ var __dirname3 = "/home/runner/work/cli/cli/node_modules/@uipath/coreipc";
12909
13203
  /*! For license information please see index.js.LICENSE.txt */
12910
13204
  (function(e, t) {
12911
13205
  typeof exports == "object" && typeof module == "object" ? module.exports = t() : typeof define == "function" && define.amd ? define([], t) : typeof exports == "object" ? exports.ipc = t() : e.ipc = t();
@@ -30705,6 +30999,9 @@ var require_dist = __commonJS2((exports) => {
30705
30999
  exports.RobotProxyConstructor = RobotProxyConstructor;
30706
31000
  __exportStar(require_agent(), exports);
30707
31001
  });
31002
+ var init_server = __esm(() => {
31003
+ init_constants();
31004
+ });
30708
31005
  init_src();
30709
31006
  function isPromiseLike3(value) {
30710
31007
  return value !== null && typeof value === "object" && typeof value.then === "function";
@@ -35845,6 +36142,60 @@ function escapeNonAscii2(jsonText) {
35845
36142
  function needsAsciiSafeJson2(sink) {
35846
36143
  return process.platform === "win32" && !sink.capabilities.isInteractive;
35847
36144
  }
36145
+ function isPlainRecord2(value) {
36146
+ if (value === null || typeof value !== "object")
36147
+ return false;
36148
+ const prototype = Object.getPrototypeOf(value);
36149
+ return prototype === Object.prototype || prototype === null;
36150
+ }
36151
+ function toLowerCamelCaseKey2(key) {
36152
+ if (!key)
36153
+ return key;
36154
+ if (/[_\-\s]/.test(key)) {
36155
+ const [firstPart, ...restParts] = key.split(/[_\-\s]+/).filter(Boolean);
36156
+ if (!firstPart)
36157
+ return key;
36158
+ return [
36159
+ toLowerCamelCaseSimpleKey2(firstPart),
36160
+ ...restParts.map((part) => {
36161
+ const normalized = toLowerCamelCaseSimpleKey2(part);
36162
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
36163
+ })
36164
+ ].join("");
36165
+ }
36166
+ return toLowerCamelCaseSimpleKey2(key);
36167
+ }
36168
+ function toLowerCamelCaseSimpleKey2(key) {
36169
+ if (/^[A-Z0-9]+$/.test(key))
36170
+ return key.toLowerCase();
36171
+ return key.replace(/^[A-Z]+(?=[A-Z][a-z]|\d|$)|^[A-Z]/, (match) => match.toLowerCase());
36172
+ }
36173
+ function toPascalCaseKey2(key) {
36174
+ const lowerCamelKey = toLowerCamelCaseKey2(key);
36175
+ return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
36176
+ }
36177
+ function toPascalCaseData2(value) {
36178
+ if (Array.isArray(value))
36179
+ return value.map(toPascalCaseData2);
36180
+ if (!isPlainRecord2(value))
36181
+ return value;
36182
+ const result = {};
36183
+ for (const [key, nestedValue] of Object.entries(value)) {
36184
+ result[toPascalCaseKey2(key)] = toPascalCaseData2(nestedValue);
36185
+ }
36186
+ return result;
36187
+ }
36188
+ function normalizeDataKeys2(data) {
36189
+ return toPascalCaseData2(data);
36190
+ }
36191
+ function normalizeOutputKeys2(data) {
36192
+ const result = {};
36193
+ for (const [key, value] of Object.entries(data)) {
36194
+ const pascalKey = toPascalCaseKey2(key);
36195
+ result[pascalKey] = pascalKey === "Data" ? value : toPascalCaseData2(value);
36196
+ }
36197
+ return result;
36198
+ }
35848
36199
  function printOutput2(data, format = "json", logFn, asciiSafe = false) {
35849
36200
  if (!data) {
35850
36201
  logFn("Empty response object. No data to display.");
@@ -35907,7 +36258,7 @@ function wrapText2(text, width) {
35907
36258
  function printTable2(data, logFn, externalLogValue) {
35908
36259
  if (data.length === 0)
35909
36260
  return;
35910
- const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
36261
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
35911
36262
  const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString2(item[key]).length)));
35912
36263
  const header = keys.map((key, i22) => key.padEnd(maxWidths[i22])).join(" | ");
35913
36264
  logFn(header);
@@ -35922,7 +36273,7 @@ function printTable2(data, logFn, externalLogValue) {
35922
36273
  }
35923
36274
  }
35924
36275
  function printVerticalTable2(data, logFn = console.log, externalLogValue) {
35925
- const keys = Object.keys(data).filter((key) => key !== "Code" && key !== "Log");
36276
+ const keys = Object.keys(data).filter((key) => !["code", "log"].includes(key.toLowerCase()));
35926
36277
  if (keys.length === 0)
35927
36278
  return;
35928
36279
  const maxKeyWidth = Math.max(...keys.map((key) => key.length));
@@ -35938,7 +36289,7 @@ function printVerticalTable2(data, logFn = console.log, externalLogValue) {
35938
36289
  function printResizableTable2(data, logFn = console.log, externalLogValue) {
35939
36290
  if (data.length === 0)
35940
36291
  return;
35941
- const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
36292
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
35942
36293
  if (keys.length === 0)
35943
36294
  return;
35944
36295
  if (!process.stdout.isTTY) {
@@ -36014,8 +36365,27 @@ function printResizableTable2(data, logFn = console.log, externalLogValue) {
36014
36365
  function toYaml2(data) {
36015
36366
  return dump2(data);
36016
36367
  }
36368
+
36369
+ class FilterEvaluationError2 extends Error {
36370
+ __brand = "FilterEvaluationError";
36371
+ filter;
36372
+ instructions;
36373
+ result = RESULTS2.ValidationError;
36374
+ constructor(filter, cause) {
36375
+ const underlying = cause instanceof Error ? cause.message : String(cause);
36376
+ super(`Filter '${filter}' failed to evaluate: ${underlying}`);
36377
+ this.name = "FilterEvaluationError";
36378
+ this.filter = filter;
36379
+ this.instructions = `The --output-filter expression '${filter}' failed at evaluation time. ` + "Note that --output-filter operates on the 'Data' field of the envelope, not the full object. " + "For example, on a list result use 'length(@)' instead of 'Data | length(@)'.";
36380
+ }
36381
+ }
36017
36382
  function applyFilter2(data, filter) {
36018
- const result = search2(data, filter);
36383
+ let result;
36384
+ try {
36385
+ result = search2(data, filter);
36386
+ } catch (err) {
36387
+ throw new FilterEvaluationError2(filter, err);
36388
+ }
36019
36389
  if (result == null)
36020
36390
  return [];
36021
36391
  if (Array.isArray(result)) {
@@ -36032,13 +36402,18 @@ function applyFilter2(data, filter) {
36032
36402
  }
36033
36403
  var OutputFormatter2;
36034
36404
  ((OutputFormatter3) => {
36035
- function success(data) {
36405
+ function success(data, options) {
36036
36406
  data.Log ??= getLogFilePath2() || undefined;
36407
+ const normalize = !options?.preserveDataKeys;
36408
+ if (normalize) {
36409
+ data.Data = normalizeDataKeys2(data.Data);
36410
+ }
36037
36411
  const filter = getOutputFilter2();
36038
36412
  if (filter) {
36039
- data.Data = applyFilter2(data.Data, filter);
36413
+ const filtered = applyFilter2(data.Data, filter);
36414
+ data.Data = normalize ? normalizeDataKeys2(filtered) : filtered;
36040
36415
  }
36041
- logOutput2(data, getOutputFormat2());
36416
+ logOutput2(normalizeOutputKeys2(data), getOutputFormat2());
36042
36417
  }
36043
36418
  OutputFormatter3.success = success;
36044
36419
  function error(data) {
@@ -36048,7 +36423,7 @@ var OutputFormatter2;
36048
36423
  result: data.Result,
36049
36424
  message: data.Message
36050
36425
  });
36051
- logOutput2(data, getOutputFormat2());
36426
+ logOutput2(normalizeOutputKeys2(data), getOutputFormat2());
36052
36427
  }
36053
36428
  OutputFormatter3.error = error;
36054
36429
  function emitList(code, items, opts) {
@@ -36069,13 +36444,14 @@ var OutputFormatter2;
36069
36444
  function log(data) {
36070
36445
  const format = getOutputFormat2();
36071
36446
  const sink = getOutputSink2();
36447
+ const normalized = toPascalCaseData2(data);
36072
36448
  if (format === "json") {
36073
- const json22 = JSON.stringify(data);
36449
+ const json22 = JSON.stringify(normalized);
36074
36450
  const safe = needsAsciiSafeJson2(sink) ? escapeNonAscii2(json22) : json22;
36075
36451
  sink.writeErr(`${safe}
36076
36452
  `);
36077
36453
  } else {
36078
- for (const [key, value] of Object.entries(data)) {
36454
+ for (const [key, value] of Object.entries(normalized)) {
36079
36455
  sink.writeErr(`${key}: ${value}
36080
36456
  `);
36081
36457
  }
@@ -36084,12 +36460,16 @@ var OutputFormatter2;
36084
36460
  OutputFormatter3.log = log;
36085
36461
  function formatToString(data) {
36086
36462
  const filter = getOutputFilter2();
36087
- if (filter && "Data" in data && data.Data != null) {
36088
- data.Data = applyFilter2(data.Data, filter);
36463
+ if ("Data" in data && data.Data != null) {
36464
+ data.Data = normalizeDataKeys2(data.Data);
36465
+ if (filter) {
36466
+ data.Data = normalizeDataKeys2(applyFilter2(data.Data, filter));
36467
+ }
36089
36468
  }
36469
+ const output = normalizeOutputKeys2(data);
36090
36470
  const lines = [];
36091
36471
  const sink = getOutputSink2();
36092
- printOutput2(data, getOutputFormat2(), (msg) => {
36472
+ printOutput2(output, getOutputFormat2(), (msg) => {
36093
36473
  lines.push(msg);
36094
36474
  }, needsAsciiSafeJson2(sink));
36095
36475
  return lines.join(`
@@ -37498,6 +37878,19 @@ JSONPath2.prototype.safeVm = {
37498
37878
  Script: SafeScript2
37499
37879
  };
37500
37880
  JSONPath2.prototype.vm = vm2;
37881
+ var PollOutcome2 = {
37882
+ Completed: "completed",
37883
+ Timeout: "timeout",
37884
+ Interrupted: "interrupted",
37885
+ Aborted: "aborted",
37886
+ Failed: "failed"
37887
+ };
37888
+ var REASON_BY_OUTCOME2 = {
37889
+ [PollOutcome2.Timeout]: "poll_timeout",
37890
+ [PollOutcome2.Failed]: "poll_failed",
37891
+ [PollOutcome2.Interrupted]: "poll_failed",
37892
+ [PollOutcome2.Aborted]: "poll_aborted"
37893
+ };
37501
37894
  var TERMINAL_STATUSES2 = new Set([
37502
37895
  "completed",
37503
37896
  "successful",
@@ -37523,6 +37916,7 @@ var ScreenLogger2;
37523
37916
  }
37524
37917
  ScreenLogger3.progress = progress;
37525
37918
  })(ScreenLogger2 ||= {});
37919
+ var sdkUserAgentHostToken2 = singleton3("SdkUserAgentHostToken");
37526
37920
  var factorySlot2 = singleton3("PackagerFactoryProvider");
37527
37921
  var REDACTED2 = "[REDACTED]";
37528
37922
  var MAX_VALUE_LENGTH2 = 200;
@@ -37693,13 +38087,17 @@ Command2.prototype.trackedAction = function(context, fn, properties) {
37693
38087
  const [error] = await catchError3(fn(...args));
37694
38088
  if (error) {
37695
38089
  errorMessage = error instanceof Error ? error.message : String(error);
37696
- logger3.error(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
38090
+ logger3.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
38091
+ const typed = error;
38092
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
38093
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS2.Success && Object.values(RESULTS2).includes(typed.result) ? typed.result : undefined;
38094
+ const finalResult = customResult ?? RESULTS2.Failure;
37697
38095
  OutputFormatter2.error({
37698
- Result: RESULTS2.Failure,
38096
+ Result: finalResult,
37699
38097
  Message: errorMessage,
37700
- Instructions: "An unexpected error occurred. Run with --log-level debug for details."
38098
+ Instructions: customInstructions ?? "An unexpected error occurred. Run with --log-level debug for details."
37701
38099
  });
37702
- context.exit(1);
38100
+ context.exit(EXIT_CODES2[finalResult]);
37703
38101
  }
37704
38102
  const durationMs = performance.now() - startTime;
37705
38103
  const success = !error && (process.exitCode === undefined || process.exitCode === 0);
@@ -37768,32 +38166,7 @@ class InvalidBaseUrlError extends Error {
37768
38166
  this.name = "InvalidBaseUrlError";
37769
38167
  }
37770
38168
  }
37771
- var DEFAULT_SCOPES = [
37772
- "offline_access",
37773
- "ProcessMining",
37774
- "OrchestratorApiUserAccess",
37775
- "StudioWebBackend",
37776
- "IdentityServerApi",
37777
- "ConnectionService",
37778
- "DataService",
37779
- "DataServiceApiUserAccess",
37780
- "DocumentUnderstanding",
37781
- "EnterpriseContextService",
37782
- "Directory",
37783
- "JamJamApi",
37784
- "LLMGateway",
37785
- "LLMOps",
37786
- "OMS",
37787
- "RCS.FolderAuthorization",
37788
- "RCS.TagsManagement",
37789
- "TestmanagerApiUserAccess",
37790
- "AutomationSolutions",
37791
- "StudioWebTypeCacheService",
37792
- "Docs.GPT.Search",
37793
- "Insights",
37794
- "ReferenceToken",
37795
- "Audit.Read"
37796
- ];
38169
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
37797
38170
  var normalizeAndValidateBaseUrl = (rawUrl) => {
37798
38171
  let baseUrl = rawUrl;
37799
38172
  if (baseUrl.endsWith("/identity_/")) {
@@ -37843,7 +38216,8 @@ var resolveConfigAsync = async ({
37843
38216
  if (!clientSecret && fileAuth.clientSecret) {
37844
38217
  clientSecret = fileAuth.clientSecret;
37845
38218
  }
37846
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : DEFAULT_SCOPES;
38219
+ const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
38220
+ const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
37847
38221
  return {
37848
38222
  clientId,
37849
38223
  clientSecret,
@@ -38330,6 +38704,129 @@ function normalizeTokenRefreshFailure() {
38330
38704
  function normalizeTokenRefreshUnavailableFailure() {
38331
38705
  return "token refresh failed before authentication completed";
38332
38706
  }
38707
+ function errorMessage(error) {
38708
+ return error instanceof Error ? error.message : String(error);
38709
+ }
38710
+ function computeExpirationThreshold(ensureTokenValidityMinutes) {
38711
+ return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
38712
+ }
38713
+ async function runRefreshLocked(inputs) {
38714
+ const {
38715
+ absolutePath,
38716
+ refreshToken: callerRefreshToken,
38717
+ customAuthority,
38718
+ ensureTokenValidityMinutes,
38719
+ loadEnvFile,
38720
+ saveEnvFile,
38721
+ refreshFn,
38722
+ resolveConfig
38723
+ } = inputs;
38724
+ const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
38725
+ let fresh;
38726
+ try {
38727
+ fresh = await loadEnvFile({ envPath: absolutePath });
38728
+ } catch (error) {
38729
+ return {
38730
+ kind: "fail",
38731
+ status: {
38732
+ loginStatus: "Refresh Failed",
38733
+ hint: "Could not read the auth file while refreshing. Retry, or run 'uip login' to re-authenticate.",
38734
+ tokenRefresh: {
38735
+ attempted: false,
38736
+ success: false,
38737
+ errorMessage: `auth file read failed: ${errorMessage(error)}`
38738
+ }
38739
+ }
38740
+ };
38741
+ }
38742
+ const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
38743
+ const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
38744
+ if (freshAccess && freshExp && freshExp > expirationThreshold) {
38745
+ return {
38746
+ kind: "ok",
38747
+ accessToken: freshAccess,
38748
+ refreshToken: fresh.UIPATH_REFRESH_TOKEN ?? callerRefreshToken,
38749
+ expiration: freshExp,
38750
+ tokenRefresh: { attempted: false, success: true }
38751
+ };
38752
+ }
38753
+ const tokenForIdP = fresh.UIPATH_REFRESH_TOKEN ?? callerRefreshToken;
38754
+ let refreshedAccess;
38755
+ let refreshedRefresh;
38756
+ try {
38757
+ const config = await resolveConfig({ customAuthority });
38758
+ const refreshed = await refreshFn({
38759
+ refreshToken: tokenForIdP,
38760
+ tokenEndpoint: config.tokenEndpoint,
38761
+ clientId: config.clientId,
38762
+ expectedAuthority: customAuthority
38763
+ });
38764
+ refreshedAccess = refreshed.accessToken;
38765
+ refreshedRefresh = refreshed.refreshToken;
38766
+ } catch (error) {
38767
+ const isOAuthFailure = isTokenRefreshOAuthFailure(error);
38768
+ const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
38769
+ const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
38770
+ return {
38771
+ kind: "fail",
38772
+ status: {
38773
+ loginStatus: "Refresh Failed",
38774
+ hint,
38775
+ tokenRefresh: {
38776
+ attempted: true,
38777
+ success: false,
38778
+ errorMessage: message
38779
+ }
38780
+ }
38781
+ };
38782
+ }
38783
+ const refreshedExp = getTokenExpiration(refreshedAccess);
38784
+ if (!refreshedExp || refreshedExp <= new Date) {
38785
+ return {
38786
+ kind: "fail",
38787
+ status: {
38788
+ loginStatus: "Refresh Failed",
38789
+ hint: "The identity server returned an unusable token. Run 'uip login' to re-authenticate.",
38790
+ tokenRefresh: {
38791
+ attempted: true,
38792
+ success: false,
38793
+ errorMessage: "refreshed token has no valid expiration claim"
38794
+ }
38795
+ }
38796
+ };
38797
+ }
38798
+ try {
38799
+ await saveEnvFile({
38800
+ envPath: absolutePath,
38801
+ data: {
38802
+ UIPATH_ACCESS_TOKEN: refreshedAccess,
38803
+ UIPATH_REFRESH_TOKEN: refreshedRefresh
38804
+ },
38805
+ merge: true
38806
+ });
38807
+ return {
38808
+ kind: "ok",
38809
+ accessToken: refreshedAccess,
38810
+ refreshToken: refreshedRefresh,
38811
+ expiration: refreshedExp,
38812
+ tokenRefresh: { attempted: true, success: true }
38813
+ };
38814
+ } catch (error) {
38815
+ const msg = errorMessage(error);
38816
+ return {
38817
+ kind: "ok",
38818
+ accessToken: refreshedAccess,
38819
+ refreshToken: refreshedRefresh,
38820
+ expiration: refreshedExp,
38821
+ persistenceWarning: `Access token refreshed in memory but could not be written to ${absolutePath}: ${msg}. The next CLI invocation will fail until the file can be updated — run 'uip login' to re-authenticate.`,
38822
+ tokenRefresh: {
38823
+ attempted: true,
38824
+ success: true,
38825
+ errorMessage: `persistence failed: ${msg}`
38826
+ }
38827
+ };
38828
+ }
38829
+ }
38333
38830
  var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
38334
38831
  const {
38335
38832
  resolveEnvFilePath = resolveEnvFilePathAsync,
@@ -38404,73 +38901,103 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
38404
38901
  let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
38405
38902
  let expiration = getTokenExpiration(accessToken);
38406
38903
  let persistenceWarning;
38904
+ let lockReleaseFailed = false;
38407
38905
  let tokenRefresh;
38408
- const expirationThreshold = new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
38409
- if (expiration && expiration <= expirationThreshold && refreshToken) {
38410
- let refreshedAccess;
38411
- let refreshedRefresh;
38906
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
38907
+ const tryGlobalCredsHint = async () => {
38908
+ const fs72 = getFs();
38909
+ const globalPath = fs72.path.join(fs72.env.homedir(), envFilePath);
38910
+ if (absolutePath === globalPath)
38911
+ return;
38912
+ if (!await fs72.exists(globalPath))
38913
+ return;
38412
38914
  try {
38413
- const config = await resolveConfig({
38414
- customAuthority: credentials.UIPATH_URL
38415
- });
38416
- const refreshed = await refreshTokenFn({
38417
- refreshToken,
38418
- tokenEndpoint: config.tokenEndpoint,
38419
- clientId: config.clientId,
38420
- expectedAuthority: credentials.UIPATH_URL
38421
- });
38422
- refreshedAccess = refreshed.accessToken;
38423
- refreshedRefresh = refreshed.refreshToken;
38424
- } catch (error) {
38425
- const isOAuthFailure = isTokenRefreshOAuthFailure(error);
38426
- const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
38427
- const errorMessage = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
38428
- return {
38429
- loginStatus: "Refresh Failed",
38430
- hint,
38431
- tokenRefresh: {
38432
- attempted: true,
38433
- success: false,
38434
- errorMessage
38435
- }
38436
- };
38915
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
38916
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
38917
+ return;
38918
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
38919
+ if (globalExp && globalExp <= new Date)
38920
+ return;
38921
+ return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
38922
+ } catch {
38923
+ return;
38437
38924
  }
38438
- const refreshedExp = getTokenExpiration(refreshedAccess);
38439
- if (!refreshedExp || refreshedExp <= new Date) {
38925
+ };
38926
+ if (expiration && expiration <= outerThreshold && refreshToken) {
38927
+ let release;
38928
+ try {
38929
+ release = await getFs().acquireLock(absolutePath);
38930
+ } catch (error) {
38931
+ const msg = errorMessage(error);
38932
+ const globalHint = await tryGlobalCredsHint();
38933
+ if (globalHint) {
38934
+ return {
38935
+ loginStatus: "Expired",
38936
+ accessToken,
38937
+ refreshToken,
38938
+ baseUrl: credentials.UIPATH_URL,
38939
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
38940
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
38941
+ tenantName: credentials.UIPATH_TENANT_NAME,
38942
+ tenantId: credentials.UIPATH_TENANT_ID,
38943
+ expiration,
38944
+ source: "file",
38945
+ hint: globalHint,
38946
+ tokenRefresh: {
38947
+ attempted: false,
38948
+ success: false,
38949
+ errorMessage: `lock acquisition failed: ${msg}`
38950
+ }
38951
+ };
38952
+ }
38440
38953
  return {
38441
38954
  loginStatus: "Refresh Failed",
38442
- hint: "The identity server returned an unusable token. Run 'uip login' to re-authenticate.",
38955
+ hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
38443
38956
  tokenRefresh: {
38444
- attempted: true,
38957
+ attempted: false,
38445
38958
  success: false,
38446
- errorMessage: "refreshed token has no valid expiration claim"
38959
+ errorMessage: `lock acquisition failed: ${msg}`
38447
38960
  }
38448
38961
  };
38449
38962
  }
38450
- accessToken = refreshedAccess;
38451
- refreshToken = refreshedRefresh;
38452
- expiration = refreshedExp;
38963
+ let lockedFailure;
38453
38964
  try {
38454
- await saveEnvFile({
38455
- envPath: absolutePath,
38456
- data: {
38457
- UIPATH_ACCESS_TOKEN: accessToken,
38458
- UIPATH_REFRESH_TOKEN: refreshToken
38459
- },
38460
- merge: true
38965
+ const outcome = await runRefreshLocked({
38966
+ absolutePath,
38967
+ refreshToken,
38968
+ customAuthority: credentials.UIPATH_URL,
38969
+ ensureTokenValidityMinutes,
38970
+ loadEnvFile,
38971
+ saveEnvFile,
38972
+ refreshFn: refreshTokenFn,
38973
+ resolveConfig
38461
38974
  });
38462
- tokenRefresh = {
38463
- attempted: true,
38464
- success: true
38465
- };
38466
- } catch (error) {
38467
- const msg = error instanceof Error ? error.message : String(error);
38468
- persistenceWarning = `Access token refreshed in memory but could not be written to ${absolutePath}: ${msg}. The next CLI invocation will fail until the file can be updated — run 'uip login' to re-authenticate.`;
38469
- tokenRefresh = {
38470
- attempted: true,
38471
- success: true,
38472
- errorMessage: `persistence failed: ${msg}`
38473
- };
38975
+ if (outcome.kind === "fail") {
38976
+ lockedFailure = outcome.status;
38977
+ } else {
38978
+ accessToken = outcome.accessToken;
38979
+ refreshToken = outcome.refreshToken;
38980
+ expiration = outcome.expiration;
38981
+ tokenRefresh = outcome.tokenRefresh;
38982
+ if (outcome.persistenceWarning) {
38983
+ persistenceWarning = outcome.persistenceWarning;
38984
+ }
38985
+ }
38986
+ } finally {
38987
+ try {
38988
+ await release();
38989
+ } catch {
38990
+ lockReleaseFailed = true;
38991
+ }
38992
+ }
38993
+ if (lockedFailure) {
38994
+ const globalHint = await tryGlobalCredsHint();
38995
+ const base = globalHint ? {
38996
+ ...lockedFailure,
38997
+ loginStatus: "Expired",
38998
+ hint: globalHint
38999
+ } : lockedFailure;
39000
+ return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
38474
39001
  }
38475
39002
  }
38476
39003
  const result = {
@@ -38485,23 +39012,13 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
38485
39012
  expiration,
38486
39013
  source: "file",
38487
39014
  ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
39015
+ ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
38488
39016
  ...tokenRefresh ? { tokenRefresh } : {}
38489
39017
  };
38490
39018
  if (result.loginStatus === "Expired") {
38491
- const fs72 = getFs();
38492
- const globalPath = fs72.path.join(fs72.env.homedir(), envFilePath);
38493
- if (absolutePath !== globalPath && await fs72.exists(globalPath)) {
38494
- try {
38495
- const globalCreds = await loadEnvFile({
38496
- envPath: globalPath
38497
- });
38498
- if (globalCreds.UIPATH_ACCESS_TOKEN) {
38499
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
38500
- if (!globalExp || globalExp > new Date) {
38501
- result.hint = `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
38502
- }
38503
- }
38504
- } catch {}
39019
+ const globalHint = await tryGlobalCredsHint();
39020
+ if (globalHint) {
39021
+ result.hint = globalHint;
38505
39022
  }
38506
39023
  }
38507
39024
  return result;
@@ -38545,6 +39062,7 @@ var getAuthContext = async (options = {}) => {
38545
39062
  };
38546
39063
  init_src();
38547
39064
  init_src();
39065
+ init_server();
38548
39066
  async function createInsightsConfig(tenantOverride) {
38549
39067
  const ctx = await getAuthContext({
38550
39068
  tenant: tenantOverride,
package/package.json CHANGED
@@ -1,36 +1,30 @@
1
1
  {
2
- "name": "@uipath/insights-tool",
3
- "version": "1.1.0",
4
- "description": "Query UiPath Insights data — jobs, failures, and performance metrics.",
5
- "private": false,
6
- "repository": {
7
- "type": "git",
8
- "url": "https://github.com/UiPath/cli.git",
9
- "directory": "packages/insights-tool"
10
- },
11
- "publishConfig": {
12
- "registry": "https://registry.npmjs.org/"
13
- },
14
- "keywords": [
15
- "cli-tool"
16
- ],
17
- "type": "module",
18
- "main": "./dist/tool.js",
19
- "exports": {
20
- ".": "./dist/tool.js"
21
- },
22
- "bin": {
23
- "insights-tool": "./dist/index.js"
24
- },
25
- "files": [
26
- "dist"
27
- ],
28
- "devDependencies": {
29
- "@uipath/common": "1.1.0",
30
- "@uipath/insights-sdk": "1.1.0",
31
- "@types/node": "^25.5.2",
32
- "commander": "^14.0.3",
33
- "typescript": "^6.0.2"
34
- },
35
- "gitHead": "06e8c8f566df4b87da4a008635483c62f64f33f0"
2
+ "name": "@uipath/insights-tool",
3
+ "license": "MIT",
4
+ "version": "1.195.0",
5
+ "description": "Query UiPath Insights data — jobs, failures, and performance metrics.",
6
+ "private": false,
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/UiPath/cli.git",
10
+ "directory": "packages/insights-tool"
11
+ },
12
+ "publishConfig": {
13
+ "registry": "https://registry.npmjs.org/"
14
+ },
15
+ "keywords": [
16
+ "cli-tool"
17
+ ],
18
+ "type": "module",
19
+ "main": "./dist/tool.js",
20
+ "exports": {
21
+ ".": "./dist/tool.js"
22
+ },
23
+ "bin": {
24
+ "insights-tool": "./dist/index.js"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "gitHead": "65fabb84552758b2710d8ca68470e70a9b1d19bc"
36
30
  }