@uipath/codedagent-tool 1.196.0 → 1.197.0-preview.59

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 (4) hide show
  1. package/dist/index.js +2 -0
  2. package/dist/init.js +821 -1866
  3. package/dist/tool.js +1509 -1928
  4. package/package.json +2 -2
package/dist/init.js CHANGED
@@ -13520,8 +13520,8 @@ var require_Subscription = __commonJS((exports) => {
13520
13520
  if (_parentOrParents instanceof Subscription2) {
13521
13521
  _parentOrParents.remove(this);
13522
13522
  } else if (_parentOrParents !== null) {
13523
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
13524
- var parent_1 = _parentOrParents[index2];
13523
+ for (var index = 0;index < _parentOrParents.length; ++index) {
13524
+ var parent_1 = _parentOrParents[index];
13525
13525
  parent_1.remove(this);
13526
13526
  }
13527
13527
  }
@@ -13536,10 +13536,10 @@ var require_Subscription = __commonJS((exports) => {
13536
13536
  }
13537
13537
  }
13538
13538
  if (isArray_1.isArray(_subscriptions)) {
13539
- var index2 = -1;
13539
+ var index = -1;
13540
13540
  var len = _subscriptions.length;
13541
- while (++index2 < len) {
13542
- var sub2 = _subscriptions[index2];
13541
+ while (++index < len) {
13542
+ var sub2 = _subscriptions[index];
13543
13543
  if (isObject_1.isObject(sub2)) {
13544
13544
  try {
13545
13545
  sub2.unsubscribe();
@@ -14969,13 +14969,13 @@ var require_AsyncAction = __commonJS((exports) => {
14969
14969
  var id = this.id;
14970
14970
  var scheduler = this.scheduler;
14971
14971
  var actions = scheduler.actions;
14972
- var index2 = actions.indexOf(this);
14972
+ var index = actions.indexOf(this);
14973
14973
  this.work = null;
14974
14974
  this.state = null;
14975
14975
  this.pending = false;
14976
14976
  this.scheduler = null;
14977
- if (index2 !== -1) {
14978
- actions.splice(index2, 1);
14977
+ if (index !== -1) {
14978
+ actions.splice(index, 1);
14979
14979
  }
14980
14980
  if (id != null) {
14981
14981
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -15819,17 +15819,17 @@ var require_AsapScheduler = __commonJS((exports) => {
15819
15819
  this.scheduled = undefined;
15820
15820
  var actions = this.actions;
15821
15821
  var error;
15822
- var index2 = -1;
15822
+ var index = -1;
15823
15823
  var count = actions.length;
15824
15824
  action = action || actions.shift();
15825
15825
  do {
15826
15826
  if (error = action.execute(action.state, action.delay)) {
15827
15827
  break;
15828
15828
  }
15829
- } while (++index2 < count && (action = actions.shift()));
15829
+ } while (++index < count && (action = actions.shift()));
15830
15830
  this.active = false;
15831
15831
  if (error) {
15832
- while (++index2 < count && (action = actions.shift())) {
15832
+ while (++index < count && (action = actions.shift())) {
15833
15833
  action.unsubscribe();
15834
15834
  }
15835
15835
  throw error;
@@ -15952,17 +15952,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
15952
15952
  this.scheduled = undefined;
15953
15953
  var actions = this.actions;
15954
15954
  var error;
15955
- var index2 = -1;
15955
+ var index = -1;
15956
15956
  var count = actions.length;
15957
15957
  action = action || actions.shift();
15958
15958
  do {
15959
15959
  if (error = action.execute(action.state, action.delay)) {
15960
15960
  break;
15961
15961
  }
15962
- } while (++index2 < count && (action = actions.shift()));
15962
+ } while (++index < count && (action = actions.shift()));
15963
15963
  this.active = false;
15964
15964
  if (error) {
15965
- while (++index2 < count && (action = actions.shift())) {
15965
+ while (++index < count && (action = actions.shift())) {
15966
15966
  action.unsubscribe();
15967
15967
  }
15968
15968
  throw error;
@@ -16046,16 +16046,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
16046
16046
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
16047
16047
  var VirtualAction = function(_super) {
16048
16048
  __extends(VirtualAction2, _super);
16049
- function VirtualAction2(scheduler, work, index2) {
16050
- if (index2 === undefined) {
16051
- index2 = scheduler.index += 1;
16049
+ function VirtualAction2(scheduler, work, index) {
16050
+ if (index === undefined) {
16051
+ index = scheduler.index += 1;
16052
16052
  }
16053
16053
  var _this = _super.call(this, scheduler, work) || this;
16054
16054
  _this.scheduler = scheduler;
16055
16055
  _this.work = work;
16056
- _this.index = index2;
16056
+ _this.index = index;
16057
16057
  _this.active = true;
16058
- _this.index = scheduler.index = index2;
16058
+ _this.index = scheduler.index = index;
16059
16059
  return _this;
16060
16060
  }
16061
16061
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -17202,9 +17202,9 @@ var require_mergeMap = __commonJS((exports) => {
17202
17202
  };
17203
17203
  MergeMapSubscriber2.prototype._tryNext = function(value) {
17204
17204
  var result;
17205
- var index2 = this.index++;
17205
+ var index = this.index++;
17206
17206
  try {
17207
- result = this.project(value, index2);
17207
+ result = this.project(value, index);
17208
17208
  } catch (err) {
17209
17209
  this.destination.error(err);
17210
17210
  return;
@@ -17784,12 +17784,12 @@ var require_pairs2 = __commonJS((exports) => {
17784
17784
  }
17785
17785
  exports.pairs = pairs;
17786
17786
  function dispatch(state) {
17787
- var { keys, index: index2, subscriber, subscription, obj } = state;
17787
+ var { keys, index, subscriber, subscription, obj } = state;
17788
17788
  if (!subscriber.closed) {
17789
- if (index2 < keys.length) {
17790
- var key = keys[index2];
17789
+ if (index < keys.length) {
17790
+ var key = keys[index];
17791
17791
  subscriber.next([key, obj[key]]);
17792
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
17792
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
17793
17793
  } else {
17794
17794
  subscriber.complete();
17795
17795
  }
@@ -18002,18 +18002,18 @@ var require_range = __commonJS((exports) => {
18002
18002
  count = start;
18003
18003
  start = 0;
18004
18004
  }
18005
- var index2 = 0;
18005
+ var index = 0;
18006
18006
  var current = start;
18007
18007
  if (scheduler) {
18008
18008
  return scheduler.schedule(dispatch, 0, {
18009
- index: index2,
18009
+ index,
18010
18010
  count,
18011
18011
  start,
18012
18012
  subscriber
18013
18013
  });
18014
18014
  } else {
18015
18015
  do {
18016
- if (index2++ >= count) {
18016
+ if (index++ >= count) {
18017
18017
  subscriber.complete();
18018
18018
  break;
18019
18019
  }
@@ -18028,8 +18028,8 @@ var require_range = __commonJS((exports) => {
18028
18028
  }
18029
18029
  exports.range = range;
18030
18030
  function dispatch(state) {
18031
- var { start, index: index2, count, subscriber } = state;
18032
- if (index2 >= count) {
18031
+ var { start, index, count, subscriber } = state;
18032
+ if (index >= count) {
18033
18033
  subscriber.complete();
18034
18034
  return;
18035
18035
  }
@@ -18037,7 +18037,7 @@ var require_range = __commonJS((exports) => {
18037
18037
  if (subscriber.closed) {
18038
18038
  return;
18039
18039
  }
18040
- state.index = index2 + 1;
18040
+ state.index = index + 1;
18041
18041
  state.start = start + 1;
18042
18042
  this.schedule(state);
18043
18043
  }
@@ -18075,14 +18075,14 @@ var require_timer = __commonJS((exports) => {
18075
18075
  }
18076
18076
  exports.timer = timer;
18077
18077
  function dispatch(state) {
18078
- var { index: index2, period, subscriber } = state;
18079
- subscriber.next(index2);
18078
+ var { index, period, subscriber } = state;
18079
+ subscriber.next(index);
18080
18080
  if (subscriber.closed) {
18081
18081
  return;
18082
18082
  } else if (period === -1) {
18083
18083
  return subscriber.complete();
18084
18084
  }
18085
- state.index = index2 + 1;
18085
+ state.index = index + 1;
18086
18086
  this.schedule(state, period);
18087
18087
  }
18088
18088
  });
@@ -21270,6 +21270,18 @@ var NETWORK_ERROR_CODES = new Set([
21270
21270
  "ENETUNREACH",
21271
21271
  "EAI_FAIL"
21272
21272
  ]);
21273
+ var TLS_ERROR_CODES = new Set([
21274
+ "SELF_SIGNED_CERT_IN_CHAIN",
21275
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
21276
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
21277
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21278
+ "UNABLE_TO_GET_ISSUER_CERT",
21279
+ "CERT_HAS_EXPIRED",
21280
+ "CERT_UNTRUSTED",
21281
+ "ERR_TLS_CERT_ALTNAME_INVALID"
21282
+ ]);
21283
+ var TLS_INSTRUCTIONS = "The server's TLS certificate could not be verified. Most often a " + "corporate proxy/firewall re-signs HTTPS with a root CA that Node does " + "not trust — set NODE_EXTRA_CA_CERTS to that CA's PEM file (and HTTPS_PROXY " + "if you connect through a proxy). If the certificate is instead expired or " + "its hostname does not match, fix the endpoint URL or the system clock. " + "Then retry.";
21284
+ var NETWORK_INSTRUCTIONS = "Could not reach the UiPath service. Check your network connection and " + "VPN, confirm any HTTP_PROXY/HTTPS_PROXY/NO_PROXY settings are correct, " + "then retry.";
21273
21285
  // ../../node_modules/commander/esm.mjs
21274
21286
  var import__ = __toESM(require_commander(), 1);
21275
21287
  var {
@@ -21344,6 +21356,7 @@ var CONSOLE_FALLBACK = {
21344
21356
  writeLog: (str) => process.stdout.write(str),
21345
21357
  capabilities: {
21346
21358
  isInteractive: false,
21359
+ canReadInput: false,
21347
21360
  supportsColor: false,
21348
21361
  outputWidth: 80
21349
21362
  }
@@ -26547,6 +26560,29 @@ function isPlainRecord(value) {
26547
26560
  const prototype = Object.getPrototypeOf(value);
26548
26561
  return prototype === Object.prototype || prototype === null;
26549
26562
  }
26563
+ function extractPagedRows(value) {
26564
+ if (Array.isArray(value) || !isPlainRecord(value))
26565
+ return null;
26566
+ const entries = Object.values(value);
26567
+ if (entries.length === 0)
26568
+ return null;
26569
+ let rows = null;
26570
+ let hasScalarSibling = false;
26571
+ for (const entry of entries) {
26572
+ if (Array.isArray(entry)) {
26573
+ if (rows !== null)
26574
+ return null;
26575
+ rows = entry;
26576
+ } else if (entry !== null && typeof entry === "object") {
26577
+ return null;
26578
+ } else {
26579
+ hasScalarSibling = true;
26580
+ }
26581
+ }
26582
+ if (rows === null || !hasScalarSibling)
26583
+ return null;
26584
+ return rows;
26585
+ }
26550
26586
  function toLowerCamelCaseKey(key) {
26551
26587
  if (!key)
26552
26588
  return key;
@@ -26611,7 +26647,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26611
26647
  break;
26612
26648
  case "plain": {
26613
26649
  if ("Data" in data && data.Data != null) {
26614
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
26650
+ const pagedRows = extractPagedRows(data.Data);
26651
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
26615
26652
  items.forEach((item) => {
26616
26653
  const values = Object.values(item).map((v) => v ?? "").join("\t");
26617
26654
  logFn(values);
@@ -26623,10 +26660,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26623
26660
  break;
26624
26661
  }
26625
26662
  default: {
26626
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
26663
+ const hasData = "Data" in data && data.Data != null;
26664
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
26665
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
26666
+ if (hasData && !(rows !== null && rows.length === 0)) {
26627
26667
  const logValue = data.Log;
26628
- if (Array.isArray(data.Data)) {
26629
- printResizableTable(data.Data, logFn, logValue);
26668
+ if (rows !== null) {
26669
+ printResizableTable(rows, logFn, logValue);
26630
26670
  } else {
26631
26671
  printVerticalTable(data.Data, logFn, logValue);
26632
26672
  }
@@ -26814,6 +26854,44 @@ function defaultErrorCodeForResult(result) {
26814
26854
  return "unknown_error";
26815
26855
  }
26816
26856
  }
26857
+ function parseHttpStatusFromMessage(message) {
26858
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
26859
+ if (!match)
26860
+ return;
26861
+ const status = Number(match[1]);
26862
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
26863
+ }
26864
+ function defaultErrorCodeForHttpStatus(status) {
26865
+ if (status === undefined)
26866
+ return;
26867
+ if (status === 400 || status === 409 || status === 422) {
26868
+ return "invalid_argument";
26869
+ }
26870
+ if (status === 401)
26871
+ return "authentication_required";
26872
+ if (status === 403)
26873
+ return "permission_denied";
26874
+ if (status === 404)
26875
+ return "not_found";
26876
+ if (status === 405)
26877
+ return "method_not_allowed";
26878
+ if (status === 408)
26879
+ return "timeout";
26880
+ if (status === 429)
26881
+ return "rate_limited";
26882
+ if (status >= 500 && status < 600)
26883
+ return "server_error";
26884
+ return;
26885
+ }
26886
+ function defaultErrorCodeForFailure(data) {
26887
+ if (data.Result === RESULTS.Failure) {
26888
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage(data.Message);
26889
+ const errorCode = defaultErrorCodeForHttpStatus(status);
26890
+ if (errorCode)
26891
+ return errorCode;
26892
+ }
26893
+ return defaultErrorCodeForResult(data.Result);
26894
+ }
26817
26895
  function defaultRetryForErrorCode(errorCode) {
26818
26896
  switch (errorCode) {
26819
26897
  case "network_error":
@@ -26843,16 +26921,19 @@ var OutputFormatter;
26843
26921
  OutputFormatter.success = success;
26844
26922
  function error(data) {
26845
26923
  data.Log ??= getLogFilePath() || undefined;
26846
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
26924
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
26847
26925
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
26848
26926
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
26849
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
26850
- result: data.Result,
26851
- errorCode: data.ErrorCode,
26852
- retry: data.Retry,
26853
- message: data.Message
26854
- });
26855
- logOutput(normalizeOutputKeys(data), getOutputFormat());
26927
+ const { SuppressTelemetry, ...envelope } = data;
26928
+ if (!SuppressTelemetry) {
26929
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
26930
+ result: data.Result,
26931
+ errorCode: data.ErrorCode,
26932
+ retry: data.Retry,
26933
+ message: data.Message
26934
+ });
26935
+ }
26936
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
26856
26937
  }
26857
26938
  OutputFormatter.error = error;
26858
26939
  function emitList(code, items, opts) {
@@ -27135,1631 +27216,315 @@ var UIPATH_HOME_DIR = ".uipath";
27135
27216
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
27136
27217
  // ../common/src/interactivity-context.ts
27137
27218
  var modeSlot = singleton("InteractivityMode");
27138
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
27139
- import vm from "vm";
27219
+ // ../common/src/polling/types.ts
27220
+ var PollOutcome = {
27221
+ Completed: "completed",
27222
+ Timeout: "timeout",
27223
+ Interrupted: "interrupted",
27224
+ Aborted: "aborted",
27225
+ Failed: "failed"
27226
+ };
27140
27227
 
27141
- class Hooks {
27142
- add(name, callback, first) {
27143
- if (typeof arguments[0] != "string") {
27144
- for (let name2 in arguments[0]) {
27145
- this.add(name2, arguments[0][name2], arguments[1]);
27146
- }
27147
- } else {
27148
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27149
- this[name2] = this[name2] || [];
27150
- if (callback) {
27151
- this[name2][first ? "unshift" : "push"](callback);
27152
- }
27153
- }, this);
27154
- }
27228
+ // ../common/src/polling/poll-failure-mapping.ts
27229
+ var REASON_BY_OUTCOME = {
27230
+ [PollOutcome.Timeout]: "poll_timeout",
27231
+ [PollOutcome.Failed]: "poll_failed",
27232
+ [PollOutcome.Interrupted]: "poll_failed",
27233
+ [PollOutcome.Aborted]: "poll_aborted"
27234
+ };
27235
+ // ../common/src/polling/terminal-statuses.ts
27236
+ var TERMINAL_STATUSES = new Set([
27237
+ "completed",
27238
+ "successful",
27239
+ "faulted",
27240
+ "failed",
27241
+ "cancelled",
27242
+ "canceled",
27243
+ "stopped",
27244
+ "finished"
27245
+ ]);
27246
+ var FAILURE_STATUSES = new Set([
27247
+ "faulted",
27248
+ "failed",
27249
+ "cancelled",
27250
+ "canceled",
27251
+ "stopped"
27252
+ ]);
27253
+ // ../common/src/preview.ts
27254
+ var previewSlot = singleton("PreviewBuild");
27255
+ function isPreviewBuild() {
27256
+ return previewSlot.get(false) ?? false;
27257
+ }
27258
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
27259
+ if (isPreviewBuild()) {
27260
+ return this.command(nameAndArgs, opts);
27155
27261
  }
27156
- run(name, env) {
27157
- this[name] = this[name] || [];
27158
- this[name].forEach(function(callback) {
27159
- callback.call(env && env.context ? env.context : env, env);
27160
- });
27262
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
27263
+ };
27264
+ // ../common/src/screen-logger.ts
27265
+ var ScreenLogger;
27266
+ ((ScreenLogger) => {
27267
+ function progress(message) {
27268
+ getOutputSink().writeErr(`${message}
27269
+ `);
27270
+ }
27271
+ ScreenLogger.progress = progress;
27272
+ })(ScreenLogger ||= {});
27273
+ // ../common/src/sdk-user-agent.ts
27274
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
27275
+ // ../common/src/tool-provider.ts
27276
+ var factorySlot = singleton("PackagerFactoryProvider");
27277
+ // ../uipath-python-bridge/src/cache.ts
27278
+ init_src();
27279
+ async function readCache(cacheFile) {
27280
+ const fs7 = getFileSystem();
27281
+ const [existsError, exists] = await catchError(fs7.exists(cacheFile));
27282
+ if (existsError || !exists)
27283
+ return null;
27284
+ const [readError, content] = await catchError(fs7.readFile(cacheFile, "utf-8"));
27285
+ if (readError) {
27286
+ logger.warn(`Failed to load cache: ${readError}`);
27287
+ return null;
27288
+ }
27289
+ const [parseError, cache] = catchError(() => JSON.parse(content));
27290
+ if (parseError) {
27291
+ logger.warn(`Failed to parse cache: ${parseError}`);
27292
+ return null;
27161
27293
  }
27294
+ return cache;
27162
27295
  }
27163
-
27164
- class Plugins {
27165
- constructor(jsep) {
27166
- this.jsep = jsep;
27167
- this.registered = {};
27296
+ // ../uipath-python-bridge/src/config.ts
27297
+ var DEFAULT_CONFIG = {
27298
+ allowedPythonVersions: ["3.14", "3.13", "3.12", "3.11"],
27299
+ packageName: "uipath",
27300
+ cacheFileName: ".uipath-python-cache.json"
27301
+ };
27302
+ function getCacheFileName() {
27303
+ return DEFAULT_CONFIG.cacheFileName;
27304
+ }
27305
+ function matchesPattern(args, pattern) {
27306
+ if (typeof pattern === "string") {
27307
+ return args.includes(pattern);
27168
27308
  }
27169
- register(...plugins) {
27170
- plugins.forEach((plugin) => {
27171
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27172
- throw new Error("Invalid JSEP plugin format");
27309
+ if (Array.isArray(pattern)) {
27310
+ for (let i = 0;i <= args.length - pattern.length; i++) {
27311
+ let match = true;
27312
+ for (let j = 0;j < pattern.length; j++) {
27313
+ if (args[i + j] !== pattern[j]) {
27314
+ match = false;
27315
+ break;
27316
+ }
27173
27317
  }
27174
- if (this.registered[plugin.name]) {
27175
- return;
27318
+ if (match) {
27319
+ return true;
27176
27320
  }
27177
- plugin.init(this.jsep);
27178
- this.registered[plugin.name] = plugin;
27179
- });
27321
+ }
27322
+ }
27323
+ return false;
27324
+ }
27325
+ function processCommandArgs(args, rules) {
27326
+ const hasForceFlag = args.includes("--force");
27327
+ const argsWithoutForce = args.filter((arg) => arg !== "--force");
27328
+ for (const rule of rules) {
27329
+ if (matchesPattern(argsWithoutForce, rule.pattern)) {
27330
+ switch (rule.action) {
27331
+ case "filter":
27332
+ if (hasForceFlag) {
27333
+ return {
27334
+ allowed: true,
27335
+ args: [...argsWithoutForce]
27336
+ };
27337
+ }
27338
+ return {
27339
+ allowed: false,
27340
+ args: [],
27341
+ errorMessage: rule.filterMessage || "This command is not allowed"
27342
+ };
27343
+ case "append":
27344
+ if (rule.appendArgs && rule.appendArgs.length > 0) {
27345
+ return {
27346
+ allowed: true,
27347
+ args: [...argsWithoutForce, ...rule.appendArgs]
27348
+ };
27349
+ }
27350
+ break;
27351
+ }
27352
+ }
27180
27353
  }
27354
+ return {
27355
+ allowed: true,
27356
+ args: [...argsWithoutForce]
27357
+ };
27181
27358
  }
27359
+ // ../uipath-python-bridge/src/execute.ts
27360
+ import { spawn } from "node:child_process";
27361
+
27362
+ // ../auth/src/config.ts
27363
+ init_constants();
27364
+ var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
27365
+ var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
27366
+ var globalSlot = globalThis;
27367
+ var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
27182
27368
 
27183
- class Jsep {
27184
- static get version() {
27185
- return "1.4.0";
27369
+ class InvalidBaseUrlError extends Error {
27370
+ url;
27371
+ reason;
27372
+ constructor(url, reason) {
27373
+ super(`Invalid base URL: "${url}"
27374
+ ` + `Reason: ${reason}
27375
+
27376
+ ` + `Expected format: an https:// URL, e.g. https://cloud.uipath.com (commercial), https://govcloud.uipath.us (Public Sector), or your Automation Suite host (https://<your-host>).
27377
+ ` + `You can specify the URL via:
27378
+ ` + ` • --authority flag
27379
+ ` + ` • UIPATH_URL environment variable
27380
+ ` + ` • auth.authority in config file`);
27381
+ this.url = url;
27382
+ this.reason = reason;
27383
+ this.name = "InvalidBaseUrlError";
27186
27384
  }
27187
- static toString() {
27188
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27385
+ }
27386
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
27387
+ var normalizeAndValidateBaseUrl = (rawUrl) => {
27388
+ let baseUrl = rawUrl;
27389
+ if (baseUrl.endsWith("/identity_/")) {
27390
+ baseUrl = baseUrl.slice(0, -11);
27391
+ } else if (baseUrl.endsWith("/identity_")) {
27392
+ baseUrl = baseUrl.slice(0, -10);
27189
27393
  }
27190
- static addUnaryOp(op_name) {
27191
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27192
- Jsep.unary_ops[op_name] = 1;
27193
- return Jsep;
27394
+ while (baseUrl.endsWith("/")) {
27395
+ baseUrl = baseUrl.slice(0, -1);
27194
27396
  }
27195
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27196
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27197
- Jsep.binary_ops[op_name] = precedence;
27198
- if (isRightAssociative) {
27199
- Jsep.right_associative.add(op_name);
27200
- } else {
27201
- Jsep.right_associative.delete(op_name);
27202
- }
27203
- return Jsep;
27397
+ const resolvedBaseUrl = baseUrl;
27398
+ const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
27399
+ if (urlError) {
27400
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
27204
27401
  }
27205
- static addIdentifierChar(char) {
27206
- Jsep.additional_identifier_chars.add(char);
27207
- return Jsep;
27402
+ if (url.protocol !== "https:") {
27403
+ throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
27208
27404
  }
27209
- static addLiteral(literal_name, literal_value) {
27210
- Jsep.literals[literal_name] = literal_value;
27211
- return Jsep;
27405
+ return url.pathname.length > 1 ? url.origin : baseUrl;
27406
+ };
27407
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
27408
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
27409
+ if (isExternalAppAuth)
27410
+ return requestedScopes;
27411
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
27412
+ };
27413
+ var resolveConfigAsync = async ({
27414
+ customAuthority,
27415
+ customClientId,
27416
+ customClientSecret,
27417
+ customScopes
27418
+ } = {}) => {
27419
+ const fileAuth = getAuthFileConfig();
27420
+ let baseUrl = customAuthority;
27421
+ if (!baseUrl) {
27422
+ baseUrl = process.env.UIPATH_URL;
27212
27423
  }
27213
- static removeUnaryOp(op_name) {
27214
- delete Jsep.unary_ops[op_name];
27215
- if (op_name.length === Jsep.max_unop_len) {
27216
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27217
- }
27218
- return Jsep;
27424
+ if (!baseUrl && fileAuth.authority) {
27425
+ baseUrl = fileAuth.authority;
27219
27426
  }
27220
- static removeAllUnaryOps() {
27221
- Jsep.unary_ops = {};
27222
- Jsep.max_unop_len = 0;
27223
- return Jsep;
27427
+ if (!baseUrl) {
27428
+ baseUrl = DEFAULT_BASE_URL;
27224
27429
  }
27225
- static removeIdentifierChar(char) {
27226
- Jsep.additional_identifier_chars.delete(char);
27227
- return Jsep;
27430
+ baseUrl = normalizeAndValidateBaseUrl(baseUrl);
27431
+ let clientId = customClientId;
27432
+ if (!clientId && fileAuth.clientId) {
27433
+ clientId = fileAuth.clientId;
27228
27434
  }
27229
- static removeBinaryOp(op_name) {
27230
- delete Jsep.binary_ops[op_name];
27231
- if (op_name.length === Jsep.max_binop_len) {
27232
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27233
- }
27234
- Jsep.right_associative.delete(op_name);
27235
- return Jsep;
27435
+ if (!clientId) {
27436
+ clientId = DEFAULT_CLIENT_ID;
27236
27437
  }
27237
- static removeAllBinaryOps() {
27238
- Jsep.binary_ops = {};
27239
- Jsep.max_binop_len = 0;
27240
- return Jsep;
27438
+ let clientSecret = customClientSecret;
27439
+ if (!clientSecret && fileAuth.clientSecret) {
27440
+ clientSecret = fileAuth.clientSecret;
27241
27441
  }
27242
- static removeLiteral(literal_name) {
27243
- delete Jsep.literals[literal_name];
27244
- return Jsep;
27442
+ const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
27443
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
27444
+ return {
27445
+ clientId,
27446
+ clientSecret,
27447
+ scopes,
27448
+ baseUrl,
27449
+ authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
27450
+ tokenEndpoint: `${baseUrl}/identity_/connect/token`
27451
+ };
27452
+ };
27453
+
27454
+ // ../auth/src/index.ts
27455
+ init_constants();
27456
+ // ../auth/src/loginStatus.ts
27457
+ init_src();
27458
+
27459
+ // ../auth/src/authProfile.ts
27460
+ init_src();
27461
+ init_constants();
27462
+ var DEFAULT_AUTH_PROFILE = "default";
27463
+ var PROFILE_DIR = "profiles";
27464
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
27465
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
27466
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
27467
+ var globalSlot2 = globalThis;
27468
+ function isAuthProfileStorage(value) {
27469
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
27470
+ }
27471
+ function createProfileStorage() {
27472
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
27473
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
27474
+ return {
27475
+ getStore: () => {
27476
+ return;
27477
+ },
27478
+ run: (_store, fn) => fn()
27479
+ };
27245
27480
  }
27246
- static removeAllLiterals() {
27247
- Jsep.literals = {};
27248
- return Jsep;
27481
+ return new mod2.AsyncLocalStorage;
27482
+ }
27483
+ function getProfileStorage() {
27484
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
27485
+ if (isAuthProfileStorage(existing)) {
27486
+ return existing;
27249
27487
  }
27250
- get char() {
27251
- return this.expr.charAt(this.index);
27488
+ const storage = createProfileStorage();
27489
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
27490
+ return storage;
27491
+ }
27492
+ var profileStorage = getProfileStorage();
27493
+
27494
+ class AuthProfileValidationError extends Error {
27495
+ constructor(message) {
27496
+ super(message);
27497
+ this.name = "AuthProfileValidationError";
27252
27498
  }
27253
- get code() {
27254
- return this.expr.charCodeAt(this.index);
27499
+ }
27500
+ function normalizeAuthProfileName(profile) {
27501
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
27502
+ return;
27255
27503
  }
27256
- constructor(expr) {
27257
- this.expr = expr;
27258
- this.index = 0;
27504
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
27505
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
27259
27506
  }
27260
- static parse(expr) {
27261
- return new Jsep(expr).parse();
27262
- }
27263
- static getMaxKeyLen(obj) {
27264
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27265
- }
27266
- static isDecimalDigit(ch) {
27267
- return ch >= 48 && ch <= 57;
27268
- }
27269
- static binaryPrecedence(op_val) {
27270
- return Jsep.binary_ops[op_val] || 0;
27271
- }
27272
- static isIdentifierStart(ch) {
27273
- return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] || Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
27274
- }
27275
- static isIdentifierPart(ch) {
27276
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27277
- }
27278
- throwError(message) {
27279
- const error = new Error(message + " at character " + this.index);
27280
- error.index = this.index;
27281
- error.description = message;
27282
- throw error;
27283
- }
27284
- runHook(name, node) {
27285
- if (Jsep.hooks[name]) {
27286
- const env = {
27287
- context: this,
27288
- node
27289
- };
27290
- Jsep.hooks.run(name, env);
27291
- return env.node;
27292
- }
27293
- return node;
27294
- }
27295
- searchHook(name) {
27296
- if (Jsep.hooks[name]) {
27297
- const env = {
27298
- context: this
27299
- };
27300
- Jsep.hooks[name].find(function(callback) {
27301
- callback.call(env.context, env);
27302
- return env.node;
27303
- });
27304
- return env.node;
27305
- }
27306
- }
27307
- gobbleSpaces() {
27308
- let ch = this.code;
27309
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27310
- ch = this.expr.charCodeAt(++this.index);
27311
- }
27312
- this.runHook("gobble-spaces");
27313
- }
27314
- parse() {
27315
- this.runHook("before-all");
27316
- const nodes = this.gobbleExpressions();
27317
- const node = nodes.length === 1 ? nodes[0] : {
27318
- type: Jsep.COMPOUND,
27319
- body: nodes
27320
- };
27321
- return this.runHook("after-all", node);
27322
- }
27323
- gobbleExpressions(untilICode) {
27324
- let nodes = [], ch_i, node;
27325
- while (this.index < this.expr.length) {
27326
- ch_i = this.code;
27327
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27328
- this.index++;
27329
- } else {
27330
- if (node = this.gobbleExpression()) {
27331
- nodes.push(node);
27332
- } else if (this.index < this.expr.length) {
27333
- if (ch_i === untilICode) {
27334
- break;
27335
- }
27336
- this.throwError('Unexpected "' + this.char + '"');
27337
- }
27338
- }
27339
- }
27340
- return nodes;
27341
- }
27342
- gobbleExpression() {
27343
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27344
- this.gobbleSpaces();
27345
- return this.runHook("after-expression", node);
27346
- }
27347
- gobbleBinaryOp() {
27348
- this.gobbleSpaces();
27349
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27350
- let tc_len = to_check.length;
27351
- while (tc_len > 0) {
27352
- if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
27353
- this.index += tc_len;
27354
- return to_check;
27355
- }
27356
- to_check = to_check.substr(0, --tc_len);
27357
- }
27358
- return false;
27359
- }
27360
- gobbleBinaryExpression() {
27361
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27362
- left = this.gobbleToken();
27363
- if (!left) {
27364
- return left;
27365
- }
27366
- biop = this.gobbleBinaryOp();
27367
- if (!biop) {
27368
- return left;
27369
- }
27370
- biop_info = {
27371
- value: biop,
27372
- prec: Jsep.binaryPrecedence(biop),
27373
- right_a: Jsep.right_associative.has(biop)
27374
- };
27375
- right = this.gobbleToken();
27376
- if (!right) {
27377
- this.throwError("Expected expression after " + biop);
27378
- }
27379
- stack = [left, biop_info, right];
27380
- while (biop = this.gobbleBinaryOp()) {
27381
- prec = Jsep.binaryPrecedence(biop);
27382
- if (prec === 0) {
27383
- this.index -= biop.length;
27384
- break;
27385
- }
27386
- biop_info = {
27387
- value: biop,
27388
- prec,
27389
- right_a: Jsep.right_associative.has(biop)
27390
- };
27391
- cur_biop = biop;
27392
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27393
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27394
- right = stack.pop();
27395
- biop = stack.pop().value;
27396
- left = stack.pop();
27397
- node = {
27398
- type: Jsep.BINARY_EXP,
27399
- operator: biop,
27400
- left,
27401
- right
27402
- };
27403
- stack.push(node);
27404
- }
27405
- node = this.gobbleToken();
27406
- if (!node) {
27407
- this.throwError("Expected expression after " + cur_biop);
27408
- }
27409
- stack.push(biop_info, node);
27410
- }
27411
- i = stack.length - 1;
27412
- node = stack[i];
27413
- while (i > 1) {
27414
- node = {
27415
- type: Jsep.BINARY_EXP,
27416
- operator: stack[i - 1].value,
27417
- left: stack[i - 2],
27418
- right: node
27419
- };
27420
- i -= 2;
27421
- }
27422
- return node;
27423
- }
27424
- gobbleToken() {
27425
- let ch, to_check, tc_len, node;
27426
- this.gobbleSpaces();
27427
- node = this.searchHook("gobble-token");
27428
- if (node) {
27429
- return this.runHook("after-token", node);
27430
- }
27431
- ch = this.code;
27432
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27433
- return this.gobbleNumericLiteral();
27434
- }
27435
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27436
- node = this.gobbleStringLiteral();
27437
- } else if (ch === Jsep.OBRACK_CODE) {
27438
- node = this.gobbleArray();
27439
- } else {
27440
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27441
- tc_len = to_check.length;
27442
- while (tc_len > 0) {
27443
- if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
27444
- this.index += tc_len;
27445
- const argument = this.gobbleToken();
27446
- if (!argument) {
27447
- this.throwError("missing unaryOp argument");
27448
- }
27449
- return this.runHook("after-token", {
27450
- type: Jsep.UNARY_EXP,
27451
- operator: to_check,
27452
- argument,
27453
- prefix: true
27454
- });
27455
- }
27456
- to_check = to_check.substr(0, --tc_len);
27457
- }
27458
- if (Jsep.isIdentifierStart(ch)) {
27459
- node = this.gobbleIdentifier();
27460
- if (Jsep.literals.hasOwnProperty(node.name)) {
27461
- node = {
27462
- type: Jsep.LITERAL,
27463
- value: Jsep.literals[node.name],
27464
- raw: node.name
27465
- };
27466
- } else if (node.name === Jsep.this_str) {
27467
- node = {
27468
- type: Jsep.THIS_EXP
27469
- };
27470
- }
27471
- } else if (ch === Jsep.OPAREN_CODE) {
27472
- node = this.gobbleGroup();
27473
- }
27474
- }
27475
- if (!node) {
27476
- return this.runHook("after-token", false);
27477
- }
27478
- node = this.gobbleTokenProperty(node);
27479
- return this.runHook("after-token", node);
27480
- }
27481
- gobbleTokenProperty(node) {
27482
- this.gobbleSpaces();
27483
- let ch = this.code;
27484
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27485
- let optional;
27486
- if (ch === Jsep.QUMARK_CODE) {
27487
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27488
- break;
27489
- }
27490
- optional = true;
27491
- this.index += 2;
27492
- this.gobbleSpaces();
27493
- ch = this.code;
27494
- }
27495
- this.index++;
27496
- if (ch === Jsep.OBRACK_CODE) {
27497
- node = {
27498
- type: Jsep.MEMBER_EXP,
27499
- computed: true,
27500
- object: node,
27501
- property: this.gobbleExpression()
27502
- };
27503
- if (!node.property) {
27504
- this.throwError('Unexpected "' + this.char + '"');
27505
- }
27506
- this.gobbleSpaces();
27507
- ch = this.code;
27508
- if (ch !== Jsep.CBRACK_CODE) {
27509
- this.throwError("Unclosed [");
27510
- }
27511
- this.index++;
27512
- } else if (ch === Jsep.OPAREN_CODE) {
27513
- node = {
27514
- type: Jsep.CALL_EXP,
27515
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27516
- callee: node
27517
- };
27518
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27519
- if (optional) {
27520
- this.index--;
27521
- }
27522
- this.gobbleSpaces();
27523
- node = {
27524
- type: Jsep.MEMBER_EXP,
27525
- computed: false,
27526
- object: node,
27527
- property: this.gobbleIdentifier()
27528
- };
27529
- }
27530
- if (optional) {
27531
- node.optional = true;
27532
- }
27533
- this.gobbleSpaces();
27534
- ch = this.code;
27535
- }
27536
- return node;
27537
- }
27538
- gobbleNumericLiteral() {
27539
- let number = "", ch, chCode;
27540
- while (Jsep.isDecimalDigit(this.code)) {
27541
- number += this.expr.charAt(this.index++);
27542
- }
27543
- if (this.code === Jsep.PERIOD_CODE) {
27544
- number += this.expr.charAt(this.index++);
27545
- while (Jsep.isDecimalDigit(this.code)) {
27546
- number += this.expr.charAt(this.index++);
27547
- }
27548
- }
27549
- ch = this.char;
27550
- if (ch === "e" || ch === "E") {
27551
- number += this.expr.charAt(this.index++);
27552
- ch = this.char;
27553
- if (ch === "+" || ch === "-") {
27554
- number += this.expr.charAt(this.index++);
27555
- }
27556
- while (Jsep.isDecimalDigit(this.code)) {
27557
- number += this.expr.charAt(this.index++);
27558
- }
27559
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27560
- this.throwError("Expected exponent (" + number + this.char + ")");
27561
- }
27562
- }
27563
- chCode = this.code;
27564
- if (Jsep.isIdentifierStart(chCode)) {
27565
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27566
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27567
- this.throwError("Unexpected period");
27568
- }
27569
- return {
27570
- type: Jsep.LITERAL,
27571
- value: parseFloat(number),
27572
- raw: number
27573
- };
27574
- }
27575
- gobbleStringLiteral() {
27576
- let str = "";
27577
- const startIndex = this.index;
27578
- const quote = this.expr.charAt(this.index++);
27579
- let closed = false;
27580
- while (this.index < this.expr.length) {
27581
- let ch = this.expr.charAt(this.index++);
27582
- if (ch === quote) {
27583
- closed = true;
27584
- break;
27585
- } else if (ch === "\\") {
27586
- ch = this.expr.charAt(this.index++);
27587
- switch (ch) {
27588
- case "n":
27589
- str += `
27590
- `;
27591
- break;
27592
- case "r":
27593
- str += "\r";
27594
- break;
27595
- case "t":
27596
- str += "\t";
27597
- break;
27598
- case "b":
27599
- str += "\b";
27600
- break;
27601
- case "f":
27602
- str += "\f";
27603
- break;
27604
- case "v":
27605
- str += "\v";
27606
- break;
27607
- default:
27608
- str += ch;
27609
- }
27610
- } else {
27611
- str += ch;
27612
- }
27613
- }
27614
- if (!closed) {
27615
- this.throwError('Unclosed quote after "' + str + '"');
27616
- }
27617
- return {
27618
- type: Jsep.LITERAL,
27619
- value: str,
27620
- raw: this.expr.substring(startIndex, this.index)
27621
- };
27622
- }
27623
- gobbleIdentifier() {
27624
- let ch = this.code, start = this.index;
27625
- if (Jsep.isIdentifierStart(ch)) {
27626
- this.index++;
27627
- } else {
27628
- this.throwError("Unexpected " + this.char);
27629
- }
27630
- while (this.index < this.expr.length) {
27631
- ch = this.code;
27632
- if (Jsep.isIdentifierPart(ch)) {
27633
- this.index++;
27634
- } else {
27635
- break;
27636
- }
27637
- }
27638
- return {
27639
- type: Jsep.IDENTIFIER,
27640
- name: this.expr.slice(start, this.index)
27641
- };
27642
- }
27643
- gobbleArguments(termination) {
27644
- const args = [];
27645
- let closed = false;
27646
- let separator_count = 0;
27647
- while (this.index < this.expr.length) {
27648
- this.gobbleSpaces();
27649
- let ch_i = this.code;
27650
- if (ch_i === termination) {
27651
- closed = true;
27652
- this.index++;
27653
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
27654
- this.throwError("Unexpected token " + String.fromCharCode(termination));
27655
- }
27656
- break;
27657
- } else if (ch_i === Jsep.COMMA_CODE) {
27658
- this.index++;
27659
- separator_count++;
27660
- if (separator_count !== args.length) {
27661
- if (termination === Jsep.CPAREN_CODE) {
27662
- this.throwError("Unexpected token ,");
27663
- } else if (termination === Jsep.CBRACK_CODE) {
27664
- for (let arg = args.length;arg < separator_count; arg++) {
27665
- args.push(null);
27666
- }
27667
- }
27668
- }
27669
- } else if (args.length !== separator_count && separator_count !== 0) {
27670
- this.throwError("Expected comma");
27671
- } else {
27672
- const node = this.gobbleExpression();
27673
- if (!node || node.type === Jsep.COMPOUND) {
27674
- this.throwError("Expected comma");
27675
- }
27676
- args.push(node);
27677
- }
27678
- }
27679
- if (!closed) {
27680
- this.throwError("Expected " + String.fromCharCode(termination));
27681
- }
27682
- return args;
27683
- }
27684
- gobbleGroup() {
27685
- this.index++;
27686
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
27687
- if (this.code === Jsep.CPAREN_CODE) {
27688
- this.index++;
27689
- if (nodes.length === 1) {
27690
- return nodes[0];
27691
- } else if (!nodes.length) {
27692
- return false;
27693
- } else {
27694
- return {
27695
- type: Jsep.SEQUENCE_EXP,
27696
- expressions: nodes
27697
- };
27698
- }
27699
- } else {
27700
- this.throwError("Unclosed (");
27701
- }
27702
- }
27703
- gobbleArray() {
27704
- this.index++;
27705
- return {
27706
- type: Jsep.ARRAY_EXP,
27707
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
27708
- };
27507
+ return profile;
27508
+ }
27509
+ function getActiveAuthProfile() {
27510
+ const scopedState = profileStorage.getStore();
27511
+ if (scopedState !== undefined) {
27512
+ return scopedState.profile;
27709
27513
  }
27514
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
27710
27515
  }
27711
- var hooks = new Hooks;
27712
- Object.assign(Jsep, {
27713
- hooks,
27714
- plugins: new Plugins(Jsep),
27715
- COMPOUND: "Compound",
27716
- SEQUENCE_EXP: "SequenceExpression",
27717
- IDENTIFIER: "Identifier",
27718
- MEMBER_EXP: "MemberExpression",
27719
- LITERAL: "Literal",
27720
- THIS_EXP: "ThisExpression",
27721
- CALL_EXP: "CallExpression",
27722
- UNARY_EXP: "UnaryExpression",
27723
- BINARY_EXP: "BinaryExpression",
27724
- ARRAY_EXP: "ArrayExpression",
27725
- TAB_CODE: 9,
27726
- LF_CODE: 10,
27727
- CR_CODE: 13,
27728
- SPACE_CODE: 32,
27729
- PERIOD_CODE: 46,
27730
- COMMA_CODE: 44,
27731
- SQUOTE_CODE: 39,
27732
- DQUOTE_CODE: 34,
27733
- OPAREN_CODE: 40,
27734
- CPAREN_CODE: 41,
27735
- OBRACK_CODE: 91,
27736
- CBRACK_CODE: 93,
27737
- QUMARK_CODE: 63,
27738
- SEMCOL_CODE: 59,
27739
- COLON_CODE: 58,
27740
- unary_ops: {
27741
- "-": 1,
27742
- "!": 1,
27743
- "~": 1,
27744
- "+": 1
27745
- },
27746
- binary_ops: {
27747
- "||": 1,
27748
- "??": 1,
27749
- "&&": 2,
27750
- "|": 3,
27751
- "^": 4,
27752
- "&": 5,
27753
- "==": 6,
27754
- "!=": 6,
27755
- "===": 6,
27756
- "!==": 6,
27757
- "<": 7,
27758
- ">": 7,
27759
- "<=": 7,
27760
- ">=": 7,
27761
- "<<": 8,
27762
- ">>": 8,
27763
- ">>>": 8,
27764
- "+": 9,
27765
- "-": 9,
27766
- "*": 10,
27767
- "/": 10,
27768
- "%": 10,
27769
- "**": 11
27770
- },
27771
- right_associative: new Set(["**"]),
27772
- additional_identifier_chars: new Set(["$", "_"]),
27773
- literals: {
27774
- true: true,
27775
- false: false,
27776
- null: null
27777
- },
27778
- this_str: "this"
27779
- });
27780
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27781
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27782
- var jsep = (expr) => new Jsep(expr).parse();
27783
- var stdClassProps = Object.getOwnPropertyNames(class Test {
27784
- });
27785
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
27786
- jsep[m] = Jsep[m];
27787
- });
27788
- jsep.Jsep = Jsep;
27789
- var CONDITIONAL_EXP = "ConditionalExpression";
27790
- var ternary = {
27791
- name: "ternary",
27792
- init(jsep2) {
27793
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
27794
- if (env.node && this.code === jsep2.QUMARK_CODE) {
27795
- this.index++;
27796
- const test = env.node;
27797
- const consequent = this.gobbleExpression();
27798
- if (!consequent) {
27799
- this.throwError("Expected expression");
27800
- }
27801
- this.gobbleSpaces();
27802
- if (this.code === jsep2.COLON_CODE) {
27803
- this.index++;
27804
- const alternate = this.gobbleExpression();
27805
- if (!alternate) {
27806
- this.throwError("Expected expression");
27807
- }
27808
- env.node = {
27809
- type: CONDITIONAL_EXP,
27810
- test,
27811
- consequent,
27812
- alternate
27813
- };
27814
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
27815
- let newTest = test;
27816
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
27817
- newTest = newTest.right;
27818
- }
27819
- env.node.test = newTest.right;
27820
- newTest.right = env.node;
27821
- env.node = test;
27822
- }
27823
- } else {
27824
- this.throwError("Expected :");
27825
- }
27826
- }
27827
- });
27828
- }
27829
- };
27830
- jsep.plugins.register(ternary);
27831
- var FSLASH_CODE = 47;
27832
- var BSLASH_CODE = 92;
27833
- var index = {
27834
- name: "regex",
27835
- init(jsep2) {
27836
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
27837
- if (this.code === FSLASH_CODE) {
27838
- const patternIndex = ++this.index;
27839
- let inCharSet = false;
27840
- while (this.index < this.expr.length) {
27841
- if (this.code === FSLASH_CODE && !inCharSet) {
27842
- const pattern = this.expr.slice(patternIndex, this.index);
27843
- let flags = "";
27844
- while (++this.index < this.expr.length) {
27845
- const code = this.code;
27846
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
27847
- flags += this.char;
27848
- } else {
27849
- break;
27850
- }
27851
- }
27852
- let value;
27853
- try {
27854
- value = new RegExp(pattern, flags);
27855
- } catch (e) {
27856
- this.throwError(e.message);
27857
- }
27858
- env.node = {
27859
- type: jsep2.LITERAL,
27860
- value,
27861
- raw: this.expr.slice(patternIndex - 1, this.index)
27862
- };
27863
- env.node = this.gobbleTokenProperty(env.node);
27864
- return env.node;
27865
- }
27866
- if (this.code === jsep2.OBRACK_CODE) {
27867
- inCharSet = true;
27868
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
27869
- inCharSet = false;
27870
- }
27871
- this.index += this.code === BSLASH_CODE ? 2 : 1;
27872
- }
27873
- this.throwError("Unclosed Regex");
27874
- }
27875
- });
27876
- }
27877
- };
27878
- var PLUS_CODE = 43;
27879
- var MINUS_CODE = 45;
27880
- var plugin = {
27881
- name: "assignment",
27882
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
27883
- updateOperators: [PLUS_CODE, MINUS_CODE],
27884
- assignmentPrecedence: 0.9,
27885
- init(jsep2) {
27886
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
27887
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
27888
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
27889
- const code = this.code;
27890
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
27891
- this.index += 2;
27892
- env.node = {
27893
- type: "UpdateExpression",
27894
- operator: code === PLUS_CODE ? "++" : "--",
27895
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
27896
- prefix: true
27897
- };
27898
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
27899
- this.throwError(`Unexpected ${env.node.operator}`);
27900
- }
27901
- }
27902
- });
27903
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
27904
- if (env.node) {
27905
- const code = this.code;
27906
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
27907
- if (!updateNodeTypes.includes(env.node.type)) {
27908
- this.throwError(`Unexpected ${env.node.operator}`);
27909
- }
27910
- this.index += 2;
27911
- env.node = {
27912
- type: "UpdateExpression",
27913
- operator: code === PLUS_CODE ? "++" : "--",
27914
- argument: env.node,
27915
- prefix: false
27916
- };
27917
- }
27918
- }
27919
- });
27920
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
27921
- if (env.node) {
27922
- updateBinariesToAssignments(env.node);
27923
- }
27924
- });
27925
- function updateBinariesToAssignments(node) {
27926
- if (plugin.assignmentOperators.has(node.operator)) {
27927
- node.type = "AssignmentExpression";
27928
- updateBinariesToAssignments(node.left);
27929
- updateBinariesToAssignments(node.right);
27930
- } else if (!node.operator) {
27931
- Object.values(node).forEach((val) => {
27932
- if (val && typeof val === "object") {
27933
- updateBinariesToAssignments(val);
27934
- }
27935
- });
27936
- }
27937
- }
27938
- }
27939
- };
27940
- jsep.plugins.register(index, plugin);
27941
- jsep.addUnaryOp("typeof");
27942
- jsep.addUnaryOp("void");
27943
- jsep.addLiteral("null", null);
27944
- jsep.addLiteral("undefined", undefined);
27945
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
27946
- var SafeEval = {
27947
- evalAst(ast, subs) {
27948
- switch (ast.type) {
27949
- case "BinaryExpression":
27950
- case "LogicalExpression":
27951
- return SafeEval.evalBinaryExpression(ast, subs);
27952
- case "Compound":
27953
- return SafeEval.evalCompound(ast, subs);
27954
- case "ConditionalExpression":
27955
- return SafeEval.evalConditionalExpression(ast, subs);
27956
- case "Identifier":
27957
- return SafeEval.evalIdentifier(ast, subs);
27958
- case "Literal":
27959
- return SafeEval.evalLiteral(ast, subs);
27960
- case "MemberExpression":
27961
- return SafeEval.evalMemberExpression(ast, subs);
27962
- case "UnaryExpression":
27963
- return SafeEval.evalUnaryExpression(ast, subs);
27964
- case "ArrayExpression":
27965
- return SafeEval.evalArrayExpression(ast, subs);
27966
- case "CallExpression":
27967
- return SafeEval.evalCallExpression(ast, subs);
27968
- case "AssignmentExpression":
27969
- return SafeEval.evalAssignmentExpression(ast, subs);
27970
- default:
27971
- throw SyntaxError("Unexpected expression", ast);
27972
- }
27973
- },
27974
- evalBinaryExpression(ast, subs) {
27975
- const result = {
27976
- "||": (a, b) => a || b(),
27977
- "&&": (a, b) => a && b(),
27978
- "|": (a, b) => a | b(),
27979
- "^": (a, b) => a ^ b(),
27980
- "&": (a, b) => a & b(),
27981
- "==": (a, b) => a == b(),
27982
- "!=": (a, b) => a != b(),
27983
- "===": (a, b) => a === b(),
27984
- "!==": (a, b) => a !== b(),
27985
- "<": (a, b) => a < b(),
27986
- ">": (a, b) => a > b(),
27987
- "<=": (a, b) => a <= b(),
27988
- ">=": (a, b) => a >= b(),
27989
- "<<": (a, b) => a << b(),
27990
- ">>": (a, b) => a >> b(),
27991
- ">>>": (a, b) => a >>> b(),
27992
- "+": (a, b) => a + b(),
27993
- "-": (a, b) => a - b(),
27994
- "*": (a, b) => a * b(),
27995
- "/": (a, b) => a / b(),
27996
- "%": (a, b) => a % b()
27997
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
27998
- return result;
27999
- },
28000
- evalCompound(ast, subs) {
28001
- let last;
28002
- for (let i = 0;i < ast.body.length; i++) {
28003
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28004
- i += 1;
28005
- }
28006
- const expr = ast.body[i];
28007
- last = SafeEval.evalAst(expr, subs);
28008
- }
28009
- return last;
28010
- },
28011
- evalConditionalExpression(ast, subs) {
28012
- if (SafeEval.evalAst(ast.test, subs)) {
28013
- return SafeEval.evalAst(ast.consequent, subs);
28014
- }
28015
- return SafeEval.evalAst(ast.alternate, subs);
28016
- },
28017
- evalIdentifier(ast, subs) {
28018
- if (Object.hasOwn(subs, ast.name)) {
28019
- return subs[ast.name];
28020
- }
28021
- throw ReferenceError(`${ast.name} is not defined`);
28022
- },
28023
- evalLiteral(ast) {
28024
- return ast.value;
28025
- },
28026
- evalMemberExpression(ast, subs) {
28027
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28028
- const obj = SafeEval.evalAst(ast.object, subs);
28029
- if (obj === undefined || obj === null) {
28030
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28031
- }
28032
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28033
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28034
- }
28035
- const result = obj[prop];
28036
- if (typeof result === "function") {
28037
- return result.bind(obj);
28038
- }
28039
- return result;
28040
- },
28041
- evalUnaryExpression(ast, subs) {
28042
- const result = {
28043
- "-": (a) => -SafeEval.evalAst(a, subs),
28044
- "!": (a) => !SafeEval.evalAst(a, subs),
28045
- "~": (a) => ~SafeEval.evalAst(a, subs),
28046
- "+": (a) => +SafeEval.evalAst(a, subs),
28047
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28048
- void: (a) => void SafeEval.evalAst(a, subs)
28049
- }[ast.operator](ast.argument);
28050
- return result;
28051
- },
28052
- evalArrayExpression(ast, subs) {
28053
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28054
- },
28055
- evalCallExpression(ast, subs) {
28056
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28057
- const func = SafeEval.evalAst(ast.callee, subs);
28058
- if (func === Function) {
28059
- throw new Error("Function constructor is disabled");
28060
- }
28061
- return func(...args);
28062
- },
28063
- evalAssignmentExpression(ast, subs) {
28064
- if (ast.left.type !== "Identifier") {
28065
- throw SyntaxError("Invalid left-hand side in assignment");
28066
- }
28067
- const id = ast.left.name;
28068
- const value = SafeEval.evalAst(ast.right, subs);
28069
- subs[id] = value;
28070
- return subs[id];
28071
- }
28072
- };
28073
-
28074
- class SafeScript {
28075
- constructor(expr) {
28076
- this.code = expr;
28077
- this.ast = jsep(this.code);
28078
- }
28079
- runInNewContext(context) {
28080
- const keyMap = Object.assign(Object.create(null), context);
28081
- return SafeEval.evalAst(this.ast, keyMap);
28082
- }
28083
- }
28084
- function push(arr, item) {
28085
- arr = arr.slice();
28086
- arr.push(item);
28087
- return arr;
28088
- }
28089
- function unshift(item, arr) {
28090
- arr = arr.slice();
28091
- arr.unshift(item);
28092
- return arr;
28093
- }
28094
-
28095
- class NewError extends Error {
28096
- constructor(value) {
28097
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28098
- this.avoidNew = true;
28099
- this.value = value;
28100
- this.name = "NewError";
28101
- }
28102
- }
28103
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28104
- if (!(this instanceof JSONPath)) {
28105
- try {
28106
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28107
- } catch (e) {
28108
- if (!e.avoidNew) {
28109
- throw e;
28110
- }
28111
- return e.value;
28112
- }
28113
- }
28114
- if (typeof opts === "string") {
28115
- otherTypeCallback = callback;
28116
- callback = obj;
28117
- obj = expr;
28118
- expr = opts;
28119
- opts = null;
28120
- }
28121
- const optObj = opts && typeof opts === "object";
28122
- opts = opts || {};
28123
- this.json = opts.json || obj;
28124
- this.path = opts.path || expr;
28125
- this.resultType = opts.resultType || "value";
28126
- this.flatten = opts.flatten || false;
28127
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28128
- this.sandbox = opts.sandbox || {};
28129
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28130
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28131
- this.parent = opts.parent || null;
28132
- this.parentProperty = opts.parentProperty || null;
28133
- this.callback = opts.callback || callback || null;
28134
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28135
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28136
- };
28137
- if (opts.autostart !== false) {
28138
- const args = {
28139
- path: optObj ? opts.path : expr
28140
- };
28141
- if (!optObj) {
28142
- args.json = obj;
28143
- } else if ("json" in opts) {
28144
- args.json = opts.json;
28145
- }
28146
- const ret = this.evaluate(args);
28147
- if (!ret || typeof ret !== "object") {
28148
- throw new NewError(ret);
28149
- }
28150
- return ret;
28151
- }
28152
- }
28153
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28154
- let currParent = this.parent, currParentProperty = this.parentProperty;
28155
- let {
28156
- flatten,
28157
- wrap
28158
- } = this;
28159
- this.currResultType = this.resultType;
28160
- this.currEval = this.eval;
28161
- this.currSandbox = this.sandbox;
28162
- callback = callback || this.callback;
28163
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28164
- json = json || this.json;
28165
- expr = expr || this.path;
28166
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28167
- if (!expr.path && expr.path !== "") {
28168
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28169
- }
28170
- if (!Object.hasOwn(expr, "json")) {
28171
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28172
- }
28173
- ({
28174
- json
28175
- } = expr);
28176
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28177
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28178
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28179
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28180
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28181
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28182
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28183
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28184
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28185
- expr = expr.path;
28186
- }
28187
- currParent = currParent || null;
28188
- currParentProperty = currParentProperty || null;
28189
- if (Array.isArray(expr)) {
28190
- expr = JSONPath.toPathString(expr);
28191
- }
28192
- if (!expr && expr !== "" || !json) {
28193
- return;
28194
- }
28195
- const exprList = JSONPath.toPathArray(expr);
28196
- if (exprList[0] === "$" && exprList.length > 1) {
28197
- exprList.shift();
28198
- }
28199
- this._hasParentSelector = null;
28200
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28201
- return ea && !ea.isParentSelector;
28202
- });
28203
- if (!result.length) {
28204
- return wrap ? [] : undefined;
28205
- }
28206
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28207
- return this._getPreferredOutput(result[0]);
28208
- }
28209
- return result.reduce((rslt, ea) => {
28210
- const valOrPath = this._getPreferredOutput(ea);
28211
- if (flatten && Array.isArray(valOrPath)) {
28212
- rslt = rslt.concat(valOrPath);
28213
- } else {
28214
- rslt.push(valOrPath);
28215
- }
28216
- return rslt;
28217
- }, []);
28218
- };
28219
- JSONPath.prototype._getPreferredOutput = function(ea) {
28220
- const resultType = this.currResultType;
28221
- switch (resultType) {
28222
- case "all": {
28223
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28224
- ea.pointer = JSONPath.toPointer(path3);
28225
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28226
- return ea;
28227
- }
28228
- case "value":
28229
- case "parent":
28230
- case "parentProperty":
28231
- return ea[resultType];
28232
- case "path":
28233
- return JSONPath.toPathString(ea[resultType]);
28234
- case "pointer":
28235
- return JSONPath.toPointer(ea.path);
28236
- default:
28237
- throw new TypeError("Unknown result type");
28238
- }
28239
- };
28240
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28241
- if (callback) {
28242
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28243
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28244
- callback(preferredOutput, type, fullRetObj);
28245
- }
28246
- };
28247
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28248
- let retObj;
28249
- if (!expr.length) {
28250
- retObj = {
28251
- path: path3,
28252
- value: val,
28253
- parent,
28254
- parentProperty: parentPropName,
28255
- hasArrExpr
28256
- };
28257
- this._handleCallback(retObj, callback, "value");
28258
- return retObj;
28259
- }
28260
- const loc = expr[0], x = expr.slice(1);
28261
- const ret = [];
28262
- function addRet(elems) {
28263
- if (Array.isArray(elems)) {
28264
- elems.forEach((t) => {
28265
- ret.push(t);
28266
- });
28267
- } else {
28268
- ret.push(elems);
28269
- }
28270
- }
28271
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28272
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28273
- } else if (loc === "*") {
28274
- this._walk(val, (m) => {
28275
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28276
- });
28277
- } else if (loc === "..") {
28278
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28279
- this._walk(val, (m) => {
28280
- if (typeof val[m] === "object") {
28281
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28282
- }
28283
- });
28284
- } else if (loc === "^") {
28285
- this._hasParentSelector = true;
28286
- return {
28287
- path: path3.slice(0, -1),
28288
- expr: x,
28289
- isParentSelector: true
28290
- };
28291
- } else if (loc === "~") {
28292
- retObj = {
28293
- path: push(path3, loc),
28294
- value: parentPropName,
28295
- parent,
28296
- parentProperty: null
28297
- };
28298
- this._handleCallback(retObj, callback, "property");
28299
- return retObj;
28300
- } else if (loc === "$") {
28301
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28302
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28303
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28304
- } else if (loc.indexOf("?(") === 0) {
28305
- if (this.currEval === false) {
28306
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28307
- }
28308
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28309
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28310
- if (nested) {
28311
- this._walk(val, (m) => {
28312
- const npath = [nested[2]];
28313
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28314
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28315
- if (filterResults.length > 0) {
28316
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28317
- }
28318
- });
28319
- } else {
28320
- this._walk(val, (m) => {
28321
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28322
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28323
- }
28324
- });
28325
- }
28326
- } else if (loc[0] === "(") {
28327
- if (this.currEval === false) {
28328
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
28329
- }
28330
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28331
- } else if (loc[0] === "@") {
28332
- let addType = false;
28333
- const valueType = loc.slice(1, -2);
28334
- switch (valueType) {
28335
- case "scalar":
28336
- if (!val || !["object", "function"].includes(typeof val)) {
28337
- addType = true;
28338
- }
28339
- break;
28340
- case "boolean":
28341
- case "string":
28342
- case "undefined":
28343
- case "function":
28344
- if (typeof val === valueType) {
28345
- addType = true;
28346
- }
28347
- break;
28348
- case "integer":
28349
- if (Number.isFinite(val) && !(val % 1)) {
28350
- addType = true;
28351
- }
28352
- break;
28353
- case "number":
28354
- if (Number.isFinite(val)) {
28355
- addType = true;
28356
- }
28357
- break;
28358
- case "nonFinite":
28359
- if (typeof val === "number" && !Number.isFinite(val)) {
28360
- addType = true;
28361
- }
28362
- break;
28363
- case "object":
28364
- if (val && typeof val === valueType) {
28365
- addType = true;
28366
- }
28367
- break;
28368
- case "array":
28369
- if (Array.isArray(val)) {
28370
- addType = true;
28371
- }
28372
- break;
28373
- case "other":
28374
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28375
- break;
28376
- case "null":
28377
- if (val === null) {
28378
- addType = true;
28379
- }
28380
- break;
28381
- default:
28382
- throw new TypeError("Unknown value type " + valueType);
28383
- }
28384
- if (addType) {
28385
- retObj = {
28386
- path: path3,
28387
- value: val,
28388
- parent,
28389
- parentProperty: parentPropName
28390
- };
28391
- this._handleCallback(retObj, callback, "value");
28392
- return retObj;
28393
- }
28394
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28395
- const locProp = loc.slice(1);
28396
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28397
- } else if (loc.includes(",")) {
28398
- const parts = loc.split(",");
28399
- for (const part of parts) {
28400
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28401
- }
28402
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28403
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28404
- }
28405
- if (this._hasParentSelector) {
28406
- for (let t = 0;t < ret.length; t++) {
28407
- const rett = ret[t];
28408
- if (rett && rett.isParentSelector) {
28409
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28410
- if (Array.isArray(tmp)) {
28411
- ret[t] = tmp[0];
28412
- const tl = tmp.length;
28413
- for (let tt = 1;tt < tl; tt++) {
28414
- t++;
28415
- ret.splice(t, 0, tmp[tt]);
28416
- }
28417
- } else {
28418
- ret[t] = tmp;
28419
- }
28420
- }
28421
- }
28422
- }
28423
- return ret;
28424
- };
28425
- JSONPath.prototype._walk = function(val, f) {
28426
- if (Array.isArray(val)) {
28427
- const n = val.length;
28428
- for (let i = 0;i < n; i++) {
28429
- f(i);
28430
- }
28431
- } else if (val && typeof val === "object") {
28432
- Object.keys(val).forEach((m) => {
28433
- f(m);
28434
- });
28435
- }
28436
- };
28437
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28438
- if (!Array.isArray(val)) {
28439
- return;
28440
- }
28441
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28442
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28443
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28444
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28445
- const ret = [];
28446
- for (let i = start;i < end; i += step) {
28447
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28448
- tmp.forEach((t) => {
28449
- ret.push(t);
28450
- });
28451
- }
28452
- return ret;
28453
- };
28454
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28455
- this.currSandbox._$_parentProperty = parentPropName;
28456
- this.currSandbox._$_parent = parent;
28457
- this.currSandbox._$_property = _vname;
28458
- this.currSandbox._$_root = this.json;
28459
- this.currSandbox._$_v = _v;
28460
- const containsPath = code.includes("@path");
28461
- if (containsPath) {
28462
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28463
- }
28464
- const scriptCacheKey = this.currEval + "Script:" + code;
28465
- if (!JSONPath.cache[scriptCacheKey]) {
28466
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28467
- if (containsPath) {
28468
- script = script.replaceAll("@path", "_$_path");
28469
- }
28470
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28471
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28472
- } else if (this.currEval === "native") {
28473
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28474
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28475
- const CurrEval = this.currEval;
28476
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28477
- } else if (typeof this.currEval === "function") {
28478
- JSONPath.cache[scriptCacheKey] = {
28479
- runInNewContext: (context) => this.currEval(script, context)
28480
- };
28481
- } else {
28482
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
28483
- }
28484
- }
28485
- try {
28486
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28487
- } catch (e) {
28488
- if (this.ignoreEvalErrors) {
28489
- return false;
28490
- }
28491
- throw new Error("jsonPath: " + e.message + ": " + code);
28492
- }
28493
- };
28494
- JSONPath.cache = {};
28495
- JSONPath.toPathString = function(pathArr) {
28496
- const x = pathArr, n = x.length;
28497
- let p = "$";
28498
- for (let i = 1;i < n; i++) {
28499
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28500
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28501
- }
28502
- }
28503
- return p;
28504
- };
28505
- JSONPath.toPointer = function(pointer) {
28506
- const x = pointer, n = x.length;
28507
- let p = "";
28508
- for (let i = 1;i < n; i++) {
28509
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28510
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
28511
- }
28512
- }
28513
- return p;
28514
- };
28515
- JSONPath.toPathArray = function(expr) {
28516
- const {
28517
- cache
28518
- } = JSONPath;
28519
- if (cache[expr]) {
28520
- return cache[expr].concat();
28521
- }
28522
- const subx = [];
28523
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28524
- return "[#" + (subx.push($1) - 1) + "]";
28525
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28526
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28527
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28528
- return ";" + ups.split("").join(";") + ";";
28529
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28530
- const exprList = normalized.split(";").map(function(exp) {
28531
- const match = exp.match(/#(\d+)/u);
28532
- return !match || !match[1] ? exp : subx[match[1]];
28533
- });
28534
- cache[expr] = exprList;
28535
- return cache[expr].concat();
28536
- };
28537
- JSONPath.prototype.safeVm = {
28538
- Script: SafeScript
28539
- };
28540
- JSONPath.prototype.vm = vm;
28541
- // ../common/src/polling/types.ts
28542
- var PollOutcome = {
28543
- Completed: "completed",
28544
- Timeout: "timeout",
28545
- Interrupted: "interrupted",
28546
- Aborted: "aborted",
28547
- Failed: "failed"
28548
- };
28549
-
28550
- // ../common/src/polling/poll-failure-mapping.ts
28551
- var REASON_BY_OUTCOME = {
28552
- [PollOutcome.Timeout]: "poll_timeout",
28553
- [PollOutcome.Failed]: "poll_failed",
28554
- [PollOutcome.Interrupted]: "poll_failed",
28555
- [PollOutcome.Aborted]: "poll_aborted"
28556
- };
28557
- // ../common/src/polling/terminal-statuses.ts
28558
- var TERMINAL_STATUSES = new Set([
28559
- "completed",
28560
- "successful",
28561
- "faulted",
28562
- "failed",
28563
- "cancelled",
28564
- "canceled",
28565
- "stopped",
28566
- "finished"
28567
- ]);
28568
- var FAILURE_STATUSES = new Set([
28569
- "faulted",
28570
- "failed",
28571
- "cancelled",
28572
- "canceled",
28573
- "stopped"
28574
- ]);
28575
- // ../common/src/screen-logger.ts
28576
- var ScreenLogger;
28577
- ((ScreenLogger) => {
28578
- function progress(message) {
28579
- getOutputSink().writeErr(`${message}
28580
- `);
27516
+ function resolveAuthProfileFilePath(profile) {
27517
+ const normalized = normalizeAuthProfileName(profile);
27518
+ if (normalized === undefined) {
27519
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
28581
27520
  }
28582
- ScreenLogger.progress = progress;
28583
- })(ScreenLogger ||= {});
28584
- // ../common/src/sdk-user-agent.ts
28585
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
28586
- // ../common/src/tool-provider.ts
28587
- var factorySlot = singleton("PackagerFactoryProvider");
28588
- // ../uipath-python-bridge/src/cache.ts
28589
- init_src();
28590
- async function readCache(cacheFile) {
28591
27521
  const fs7 = getFileSystem();
28592
- const [existsError, exists] = await catchError(fs7.exists(cacheFile));
28593
- if (existsError || !exists)
28594
- return null;
28595
- const [readError, content] = await catchError(fs7.readFile(cacheFile, "utf-8"));
28596
- if (readError) {
28597
- logger.warn(`Failed to load cache: ${readError}`);
28598
- return null;
28599
- }
28600
- const [parseError, cache] = catchError(() => JSON.parse(content));
28601
- if (parseError) {
28602
- logger.warn(`Failed to parse cache: ${parseError}`);
28603
- return null;
28604
- }
28605
- return cache;
27522
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR2, PROFILE_DIR, normalized, AUTH_FILENAME);
28606
27523
  }
28607
- // ../uipath-python-bridge/src/config.ts
28608
- var DEFAULT_CONFIG = {
28609
- allowedPythonVersions: ["3.13", "3.12", "3.11"],
28610
- packageName: "uipath",
28611
- cacheFileName: ".uipath-python-cache.json"
28612
- };
28613
- function getCacheFileName() {
28614
- return DEFAULT_CONFIG.cacheFileName;
27524
+ function getActiveAuthProfileFilePath() {
27525
+ const profile = getActiveAuthProfile();
27526
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
28615
27527
  }
28616
- function matchesPattern(args, pattern) {
28617
- if (typeof pattern === "string") {
28618
- return args.includes(pattern);
28619
- }
28620
- if (Array.isArray(pattern)) {
28621
- for (let i = 0;i <= args.length - pattern.length; i++) {
28622
- let match = true;
28623
- for (let j = 0;j < pattern.length; j++) {
28624
- if (args[i + j] !== pattern[j]) {
28625
- match = false;
28626
- break;
28627
- }
28628
- }
28629
- if (match) {
28630
- return true;
28631
- }
28632
- }
28633
- }
28634
- return false;
28635
- }
28636
- function processCommandArgs(args, rules) {
28637
- const hasForceFlag = args.includes("--force");
28638
- const argsWithoutForce = args.filter((arg) => arg !== "--force");
28639
- for (const rule of rules) {
28640
- if (matchesPattern(argsWithoutForce, rule.pattern)) {
28641
- switch (rule.action) {
28642
- case "filter":
28643
- if (hasForceFlag) {
28644
- return {
28645
- allowed: true,
28646
- args: [...argsWithoutForce]
28647
- };
28648
- }
28649
- return {
28650
- allowed: false,
28651
- args: [],
28652
- errorMessage: rule.filterMessage || "This command is not allowed"
28653
- };
28654
- case "append":
28655
- if (rule.appendArgs && rule.appendArgs.length > 0) {
28656
- return {
28657
- allowed: true,
28658
- args: [...argsWithoutForce, ...rule.appendArgs]
28659
- };
28660
- }
28661
- break;
28662
- }
28663
- }
28664
- }
28665
- return {
28666
- allowed: true,
28667
- args: [...argsWithoutForce]
28668
- };
28669
- }
28670
- // ../uipath-python-bridge/src/execute.ts
28671
- import { spawn } from "node:child_process";
28672
-
28673
- // ../auth/src/config.ts
28674
- init_constants();
28675
- var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
28676
- var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
28677
- var globalSlot = globalThis;
28678
- var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
28679
-
28680
- class InvalidBaseUrlError extends Error {
28681
- url;
28682
- reason;
28683
- constructor(url, reason) {
28684
- super(`Invalid base URL: "${url}"
28685
- ` + `Reason: ${reason}
28686
-
28687
- ` + `Expected format: an https:// URL, e.g. https://cloud.uipath.com (commercial), https://govcloud.uipath.us (Public Sector), or your Automation Suite host (https://<your-host>).
28688
- ` + `You can specify the URL via:
28689
- ` + ` • --authority flag
28690
- ` + ` • UIPATH_URL environment variable
28691
- ` + ` • auth.authority in config file`);
28692
- this.url = url;
28693
- this.reason = reason;
28694
- this.name = "InvalidBaseUrlError";
28695
- }
28696
- }
28697
- var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
28698
- var normalizeAndValidateBaseUrl = (rawUrl) => {
28699
- let baseUrl = rawUrl;
28700
- if (baseUrl.endsWith("/identity_/")) {
28701
- baseUrl = baseUrl.slice(0, -11);
28702
- } else if (baseUrl.endsWith("/identity_")) {
28703
- baseUrl = baseUrl.slice(0, -10);
28704
- }
28705
- while (baseUrl.endsWith("/")) {
28706
- baseUrl = baseUrl.slice(0, -1);
28707
- }
28708
- const resolvedBaseUrl = baseUrl;
28709
- const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
28710
- if (urlError) {
28711
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
28712
- }
28713
- if (url.protocol !== "https:") {
28714
- throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
28715
- }
28716
- return url.pathname.length > 1 ? url.origin : baseUrl;
28717
- };
28718
- var resolveConfigAsync = async ({
28719
- customAuthority,
28720
- customClientId,
28721
- customClientSecret,
28722
- customScopes
28723
- } = {}) => {
28724
- const fileAuth = getAuthFileConfig();
28725
- let baseUrl = customAuthority;
28726
- if (!baseUrl) {
28727
- baseUrl = process.env.UIPATH_URL;
28728
- }
28729
- if (!baseUrl && fileAuth.authority) {
28730
- baseUrl = fileAuth.authority;
28731
- }
28732
- if (!baseUrl) {
28733
- baseUrl = DEFAULT_BASE_URL;
28734
- }
28735
- baseUrl = normalizeAndValidateBaseUrl(baseUrl);
28736
- let clientId = customClientId;
28737
- if (!clientId && fileAuth.clientId) {
28738
- clientId = fileAuth.clientId;
28739
- }
28740
- if (!clientId) {
28741
- clientId = DEFAULT_CLIENT_ID;
28742
- }
28743
- let clientSecret = customClientSecret;
28744
- if (!clientSecret && fileAuth.clientSecret) {
28745
- clientSecret = fileAuth.clientSecret;
28746
- }
28747
- const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
28748
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
28749
- return {
28750
- clientId,
28751
- clientSecret,
28752
- scopes,
28753
- baseUrl,
28754
- authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
28755
- tokenEndpoint: `${baseUrl}/identity_/connect/token`
28756
- };
28757
- };
28758
-
28759
- // ../auth/src/index.ts
28760
- init_constants();
28761
- // ../auth/src/loginStatus.ts
28762
- init_src();
28763
27528
  // ../auth/src/utils/jwt.ts
28764
27529
  class InvalidIssuerError extends Error {
28765
27530
  expected;
@@ -28888,23 +27653,74 @@ var readAuthFromEnv = () => {
28888
27653
  organizationId,
28889
27654
  tenantName,
28890
27655
  tenantId,
28891
- expiration
27656
+ expiration,
27657
+ source: "env" /* Env */
28892
27658
  };
28893
27659
  };
28894
27660
 
27661
+ // ../auth/src/refreshCircuitBreaker.ts
27662
+ init_src();
27663
+ var BREAKER_SUFFIX = ".refresh-state";
27664
+ var BACKOFF_BASE_MS = 60000;
27665
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
27666
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
27667
+ async function refreshTokenFingerprint(refreshToken) {
27668
+ const bytes = new TextEncoder().encode(refreshToken);
27669
+ if (globalThis.crypto?.subtle) {
27670
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
27671
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
27672
+ }
27673
+ const { createHash } = await import("node:crypto");
27674
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
27675
+ }
27676
+ function breakerPathFor(authPath) {
27677
+ return `${authPath}${BREAKER_SUFFIX}`;
27678
+ }
27679
+ async function loadRefreshBreaker(authPath) {
27680
+ const fs7 = getFileSystem();
27681
+ try {
27682
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
27683
+ if (!content)
27684
+ return {};
27685
+ const parsed = JSON.parse(content);
27686
+ return parsed && typeof parsed === "object" ? parsed : {};
27687
+ } catch {
27688
+ return {};
27689
+ }
27690
+ }
27691
+ async function saveRefreshBreaker(authPath, state) {
27692
+ try {
27693
+ const fs7 = getFileSystem();
27694
+ const path3 = breakerPathFor(authPath);
27695
+ await fs7.mkdir(fs7.path.dirname(path3));
27696
+ const tempPath = `${path3}.tmp`;
27697
+ await fs7.writeFile(tempPath, JSON.stringify(state));
27698
+ await fs7.rename(tempPath, path3);
27699
+ } catch {}
27700
+ }
27701
+ async function clearRefreshBreaker(authPath) {
27702
+ const fs7 = getFileSystem();
27703
+ const path3 = breakerPathFor(authPath);
27704
+ try {
27705
+ if (await fs7.exists(path3)) {
27706
+ await fs7.rm(path3);
27707
+ }
27708
+ } catch {}
27709
+ }
27710
+ function nextBackoffMs(attempts) {
27711
+ const shift = Math.max(0, attempts - 1);
27712
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
27713
+ }
27714
+ function shouldSurface(state, nowMs) {
27715
+ if (state.lastSurfacedAtMs === undefined)
27716
+ return true;
27717
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
27718
+ }
27719
+
28895
27720
  // ../auth/src/robotClientFallback.ts
28896
27721
  init_src();
28897
27722
  var DEFAULT_TIMEOUT_MS = 1000;
28898
27723
  var CLOSE_TIMEOUT_MS = 500;
28899
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
28900
- var printNoticeOnce = () => {
28901
- const slot = globalThis;
28902
- if (slot[NOTICE_SENTINEL])
28903
- return;
28904
- slot[NOTICE_SENTINEL] = true;
28905
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
28906
- `));
28907
- };
28908
27724
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
28909
27725
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
28910
27726
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -29020,7 +27836,6 @@ var tryRobotClientFallback = async (options = {}) => {
29020
27836
  issuerFromToken = issClaim;
29021
27837
  }
29022
27838
  }
29023
- printNoticeOnce();
29024
27839
  return {
29025
27840
  accessToken,
29026
27841
  baseUrl: parsedUrl.baseUrl,
@@ -29245,18 +28060,327 @@ var saveEnvFileAsync = async ({
29245
28060
  };
29246
28061
 
29247
28062
  // ../auth/src/loginStatus.ts
29248
- function normalizeTokenRefreshFailure() {
29249
- return "stored refresh token is invalid or expired";
28063
+ var getLoginStatusAsync = async (options = {}) => {
28064
+ return getLoginStatusWithDeps(options);
28065
+ };
28066
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
28067
+ const {
28068
+ resolveEnvFilePath = resolveEnvFilePathAsync,
28069
+ loadEnvFile = loadEnvFileAsync,
28070
+ saveEnvFile = saveEnvFileAsync,
28071
+ getFs = getFileSystem,
28072
+ refreshToken: refreshTokenFn = refreshAccessToken,
28073
+ resolveConfig = resolveConfigAsync,
28074
+ robotFallback = tryRobotClientFallback,
28075
+ loadBreaker = loadRefreshBreaker,
28076
+ saveBreaker = saveRefreshBreaker,
28077
+ clearBreaker = clearRefreshBreaker
28078
+ } = deps;
28079
+ if (isRobotAuthEnforced()) {
28080
+ return resolveRobotEnforcedStatus(robotFallback);
28081
+ }
28082
+ if (isEnvAuthEnabled()) {
28083
+ return readAuthFromEnv();
28084
+ }
28085
+ const activeProfile = getActiveAuthProfile();
28086
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
28087
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
28088
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
28089
+ const { ensureTokenValidityMinutes } = options;
28090
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
28091
+ if (absolutePath === undefined) {
28092
+ if (usingActiveProfile) {
28093
+ return {
28094
+ loginStatus: "Not logged in",
28095
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
28096
+ };
28097
+ }
28098
+ return resolveBorrowedRobotStatus(robotFallback);
28099
+ }
28100
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
28101
+ if ("status" in loaded) {
28102
+ return loaded.status;
28103
+ }
28104
+ const { credentials } = loaded;
28105
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
28106
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
28107
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
28108
+ let tokens = {
28109
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
28110
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
28111
+ expiration,
28112
+ lockReleaseFailed: false
28113
+ };
28114
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
28115
+ if (expiration && expiration <= outerThreshold && refreshToken) {
28116
+ const refreshed = await attemptRefresh({
28117
+ absolutePath,
28118
+ credentials,
28119
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
28120
+ refreshToken,
28121
+ expiration,
28122
+ ensureTokenValidityMinutes,
28123
+ getFs,
28124
+ loadEnvFile,
28125
+ saveEnvFile,
28126
+ refreshFn: refreshTokenFn,
28127
+ resolveConfig,
28128
+ loadBreaker,
28129
+ saveBreaker,
28130
+ clearBreaker,
28131
+ globalHint
28132
+ });
28133
+ if (refreshed.kind === "terminal") {
28134
+ return refreshed.status;
28135
+ }
28136
+ tokens = refreshed.tokens;
28137
+ }
28138
+ return buildFileStatus(tokens, credentials, globalHint);
28139
+ };
28140
+ async function resolveRobotEnforcedStatus(robotFallback) {
28141
+ if (isEnvAuthEnabled()) {
28142
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
28143
+ }
28144
+ const robotCreds = await robotFallback({ force: true });
28145
+ if (!robotCreds) {
28146
+ return {
28147
+ loginStatus: "Not logged in",
28148
+ hint: `${ENFORCE_ROBOT_AUTH_VAR}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR} to fall back to file or ` + `env-var authentication.`
28149
+ };
28150
+ }
28151
+ return buildRobotStatus(robotCreds);
29250
28152
  }
29251
- function normalizeTokenRefreshUnavailableFailure() {
29252
- return "token refresh failed before authentication completed";
28153
+ async function resolveBorrowedRobotStatus(robotFallback) {
28154
+ const robotCreds = await robotFallback();
28155
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
29253
28156
  }
29254
- function errorMessage(error) {
29255
- return error instanceof Error ? error.message : String(error);
28157
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
28158
+ let credentials;
28159
+ try {
28160
+ credentials = await loadEnvFile({ envPath: absolutePath });
28161
+ } catch (error) {
28162
+ if (isFileNotFoundError(error)) {
28163
+ return { status: { loginStatus: "Not logged in" } };
28164
+ }
28165
+ throw error;
28166
+ }
28167
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
28168
+ return { status: { loginStatus: "Not logged in" } };
28169
+ }
28170
+ return { credentials };
28171
+ }
28172
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
28173
+ const fs7 = getFs();
28174
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
28175
+ if (absolutePath === globalPath)
28176
+ return;
28177
+ if (!await fs7.exists(globalPath))
28178
+ return;
28179
+ try {
28180
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
28181
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
28182
+ return;
28183
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
28184
+ if (globalExp && globalExp <= new Date)
28185
+ return;
28186
+ 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.`;
28187
+ } catch {
28188
+ return;
28189
+ }
29256
28190
  }
29257
28191
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
29258
28192
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
29259
28193
  }
28194
+ async function attemptRefresh(ctx) {
28195
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
28196
+ if (shortCircuit) {
28197
+ return { kind: "terminal", status: shortCircuit };
28198
+ }
28199
+ let release;
28200
+ try {
28201
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
28202
+ } catch (error) {
28203
+ return {
28204
+ kind: "terminal",
28205
+ status: await lockAcquireFailureStatus(ctx, error)
28206
+ };
28207
+ }
28208
+ let lockedFailure;
28209
+ let lockReleaseFailed = false;
28210
+ let success;
28211
+ try {
28212
+ const outcome = await runRefreshLocked({
28213
+ absolutePath: ctx.absolutePath,
28214
+ refreshToken: ctx.refreshToken,
28215
+ customAuthority: ctx.credentials.UIPATH_URL,
28216
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
28217
+ loadEnvFile: ctx.loadEnvFile,
28218
+ saveEnvFile: ctx.saveEnvFile,
28219
+ refreshFn: ctx.refreshFn,
28220
+ resolveConfig: ctx.resolveConfig,
28221
+ loadBreaker: ctx.loadBreaker,
28222
+ saveBreaker: ctx.saveBreaker,
28223
+ clearBreaker: ctx.clearBreaker
28224
+ });
28225
+ if (outcome.kind === "fail") {
28226
+ lockedFailure = outcome.status;
28227
+ } else {
28228
+ success = outcome;
28229
+ }
28230
+ } finally {
28231
+ try {
28232
+ await release();
28233
+ } catch {
28234
+ lockReleaseFailed = true;
28235
+ }
28236
+ }
28237
+ if (lockedFailure) {
28238
+ const globalHint = await ctx.globalHint();
28239
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
28240
+ return {
28241
+ kind: "terminal",
28242
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
28243
+ };
28244
+ }
28245
+ return {
28246
+ kind: "refreshed",
28247
+ tokens: {
28248
+ accessToken: success?.accessToken,
28249
+ refreshToken: success?.refreshToken,
28250
+ expiration: success?.expiration,
28251
+ tokenRefresh: success?.tokenRefresh,
28252
+ persistenceWarning: success?.persistenceWarning,
28253
+ lockReleaseFailed
28254
+ }
28255
+ };
28256
+ }
28257
+ async function buildFileStatus(tokens, credentials, globalHint) {
28258
+ const result = {
28259
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
28260
+ accessToken: tokens.accessToken,
28261
+ refreshToken: tokens.refreshToken,
28262
+ baseUrl: credentials.UIPATH_URL,
28263
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28264
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28265
+ tenantName: credentials.UIPATH_TENANT_NAME,
28266
+ tenantId: credentials.UIPATH_TENANT_ID,
28267
+ expiration: tokens.expiration,
28268
+ source: "file" /* File */,
28269
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
28270
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
28271
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
28272
+ };
28273
+ if (result.loginStatus === "Expired") {
28274
+ const hint = await globalHint();
28275
+ if (hint) {
28276
+ result.hint = hint;
28277
+ }
28278
+ }
28279
+ return result;
28280
+ }
28281
+ function buildRobotStatus(robotCreds) {
28282
+ return {
28283
+ loginStatus: "Logged in",
28284
+ accessToken: robotCreds.accessToken,
28285
+ baseUrl: robotCreds.baseUrl,
28286
+ organizationName: robotCreds.organizationName,
28287
+ organizationId: robotCreds.organizationId,
28288
+ tenantName: robotCreds.tenantName,
28289
+ tenantId: robotCreds.tenantId,
28290
+ issuer: robotCreds.issuer,
28291
+ expiration: getTokenExpiration(robotCreds.accessToken),
28292
+ source: "robot" /* Robot */
28293
+ };
28294
+ }
28295
+ var isFileNotFoundError = (error) => {
28296
+ if (!(error instanceof Object))
28297
+ return false;
28298
+ return error.code === "ENOENT";
28299
+ };
28300
+ async function circuitBreakerShortCircuit(ctx) {
28301
+ const {
28302
+ absolutePath,
28303
+ refreshToken,
28304
+ accessToken,
28305
+ credentials,
28306
+ expiration,
28307
+ loadBreaker,
28308
+ saveBreaker,
28309
+ clearBreaker
28310
+ } = ctx;
28311
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
28312
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
28313
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
28314
+ await clearBreaker(absolutePath);
28315
+ breaker.deadTokenFp = undefined;
28316
+ }
28317
+ const nowMs = Date.now();
28318
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
28319
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
28320
+ if (!tokenIsDead && !inBackoff)
28321
+ return;
28322
+ const globalHint = await ctx.globalHint();
28323
+ const suppressed = !shouldSurface(breaker, nowMs);
28324
+ if (!suppressed) {
28325
+ await saveBreaker(absolutePath, {
28326
+ ...breaker,
28327
+ lastSurfacedAtMs: nowMs
28328
+ });
28329
+ }
28330
+ const deadHint = "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>.";
28331
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
28332
+ return {
28333
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
28334
+ ...globalHint ? {
28335
+ accessToken,
28336
+ refreshToken,
28337
+ baseUrl: credentials.UIPATH_URL,
28338
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28339
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28340
+ tenantName: credentials.UIPATH_TENANT_NAME,
28341
+ tenantId: credentials.UIPATH_TENANT_ID,
28342
+ expiration,
28343
+ source: "file" /* File */
28344
+ } : {},
28345
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
28346
+ refreshCircuitOpen: true,
28347
+ refreshTelemetrySuppressed: suppressed,
28348
+ tokenRefresh: { attempted: false, success: false }
28349
+ };
28350
+ }
28351
+ async function lockAcquireFailureStatus(ctx, error) {
28352
+ const msg = errorMessage(error);
28353
+ const globalHint = await ctx.globalHint();
28354
+ if (globalHint) {
28355
+ return {
28356
+ loginStatus: "Expired",
28357
+ accessToken: ctx.accessToken,
28358
+ refreshToken: ctx.refreshToken,
28359
+ baseUrl: ctx.credentials.UIPATH_URL,
28360
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
28361
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
28362
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
28363
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
28364
+ expiration: ctx.expiration,
28365
+ source: "file" /* File */,
28366
+ hint: globalHint,
28367
+ tokenRefresh: {
28368
+ attempted: false,
28369
+ success: false,
28370
+ errorMessage: `lock acquisition failed: ${msg}`
28371
+ }
28372
+ };
28373
+ }
28374
+ return {
28375
+ loginStatus: "Refresh Failed",
28376
+ 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.",
28377
+ tokenRefresh: {
28378
+ attempted: false,
28379
+ success: false,
28380
+ errorMessage: `lock acquisition failed: ${msg}`
28381
+ }
28382
+ };
28383
+ }
29260
28384
  async function runRefreshLocked(inputs) {
29261
28385
  const {
29262
28386
  absolutePath,
@@ -29266,7 +28390,10 @@ async function runRefreshLocked(inputs) {
29266
28390
  loadEnvFile,
29267
28391
  saveEnvFile,
29268
28392
  refreshFn,
29269
- resolveConfig
28393
+ resolveConfig,
28394
+ loadBreaker,
28395
+ saveBreaker,
28396
+ clearBreaker
29270
28397
  } = inputs;
29271
28398
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29272
28399
  let fresh;
@@ -29289,6 +28416,7 @@ async function runRefreshLocked(inputs) {
29289
28416
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
29290
28417
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
29291
28418
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
28419
+ await clearBreaker(absolutePath);
29292
28420
  return {
29293
28421
  kind: "ok",
29294
28422
  accessToken: freshAccess,
@@ -29312,8 +28440,21 @@ async function runRefreshLocked(inputs) {
29312
28440
  refreshedRefresh = refreshed.refreshToken;
29313
28441
  } catch (error) {
29314
28442
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
29315
- 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.";
28443
+ const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired. In a non-interactive context, authenticate with: uip login --client-id <id> --client-secret <secret> -t <tenant>." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
29316
28444
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
28445
+ const fp = await refreshTokenFingerprint(tokenForIdP);
28446
+ if (isOAuthFailure) {
28447
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
28448
+ } else {
28449
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
28450
+ const attempts = (prior.attempts ?? 0) + 1;
28451
+ await saveBreaker(absolutePath, {
28452
+ ...prior,
28453
+ deadTokenFp: undefined,
28454
+ attempts,
28455
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
28456
+ });
28457
+ }
29317
28458
  return {
29318
28459
  kind: "fail",
29319
28460
  status: {
@@ -29342,6 +28483,7 @@ async function runRefreshLocked(inputs) {
29342
28483
  }
29343
28484
  };
29344
28485
  }
28486
+ await clearBreaker(absolutePath);
29345
28487
  try {
29346
28488
  await saveEnvFile({
29347
28489
  envPath: absolutePath,
@@ -29374,212 +28516,15 @@ async function runRefreshLocked(inputs) {
29374
28516
  };
29375
28517
  }
29376
28518
  }
29377
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
29378
- const {
29379
- resolveEnvFilePath = resolveEnvFilePathAsync,
29380
- loadEnvFile = loadEnvFileAsync,
29381
- saveEnvFile = saveEnvFileAsync,
29382
- getFs = getFileSystem,
29383
- refreshToken: refreshTokenFn = refreshAccessToken,
29384
- resolveConfig = resolveConfigAsync,
29385
- robotFallback = tryRobotClientFallback
29386
- } = deps;
29387
- if (isRobotAuthEnforced()) {
29388
- if (isEnvAuthEnabled()) {
29389
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
29390
- }
29391
- const robotCreds = await robotFallback({ force: true });
29392
- if (!robotCreds) {
29393
- return {
29394
- loginStatus: "Not logged in",
29395
- hint: `${ENFORCE_ROBOT_AUTH_VAR}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR} to fall back to file or ` + `env-var authentication.`
29396
- };
29397
- }
29398
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29399
- return {
29400
- loginStatus: "Logged in",
29401
- accessToken: robotCreds.accessToken,
29402
- baseUrl: robotCreds.baseUrl,
29403
- organizationName: robotCreds.organizationName,
29404
- organizationId: robotCreds.organizationId,
29405
- tenantName: robotCreds.tenantName,
29406
- tenantId: robotCreds.tenantId,
29407
- issuer: robotCreds.issuer,
29408
- expiration: expiration2,
29409
- source: "robot" /* Robot */
29410
- };
29411
- }
29412
- if (isEnvAuthEnabled()) {
29413
- return readAuthFromEnv();
29414
- }
29415
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
29416
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
29417
- if (absolutePath === undefined) {
29418
- const robotCreds = await robotFallback();
29419
- if (robotCreds) {
29420
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29421
- const status = {
29422
- loginStatus: "Logged in",
29423
- accessToken: robotCreds.accessToken,
29424
- baseUrl: robotCreds.baseUrl,
29425
- organizationName: robotCreds.organizationName,
29426
- organizationId: robotCreds.organizationId,
29427
- tenantName: robotCreds.tenantName,
29428
- tenantId: robotCreds.tenantId,
29429
- issuer: robotCreds.issuer,
29430
- expiration: expiration2,
29431
- source: "robot" /* Robot */
29432
- };
29433
- return status;
29434
- }
29435
- return { loginStatus: "Not logged in" };
29436
- }
29437
- let credentials;
29438
- try {
29439
- credentials = await loadEnvFile({ envPath: absolutePath });
29440
- } catch (error) {
29441
- if (isFileNotFoundError(error)) {
29442
- return { loginStatus: "Not logged in" };
29443
- }
29444
- throw error;
29445
- }
29446
- if (!credentials.UIPATH_ACCESS_TOKEN) {
29447
- return { loginStatus: "Not logged in" };
29448
- }
29449
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
29450
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
29451
- let expiration = getTokenExpiration(accessToken);
29452
- let persistenceWarning;
29453
- let lockReleaseFailed = false;
29454
- let tokenRefresh;
29455
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29456
- const tryGlobalCredsHint = async () => {
29457
- const fs7 = getFs();
29458
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
29459
- if (absolutePath === globalPath)
29460
- return;
29461
- if (!await fs7.exists(globalPath))
29462
- return;
29463
- try {
29464
- const globalCreds = await loadEnvFile({ envPath: globalPath });
29465
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
29466
- return;
29467
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
29468
- if (globalExp && globalExp <= new Date)
29469
- return;
29470
- 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.`;
29471
- } catch {
29472
- return;
29473
- }
29474
- };
29475
- if (expiration && expiration <= outerThreshold && refreshToken) {
29476
- let release;
29477
- try {
29478
- release = await getFs().acquireLock(absolutePath);
29479
- } catch (error) {
29480
- const msg = errorMessage(error);
29481
- const globalHint = await tryGlobalCredsHint();
29482
- if (globalHint) {
29483
- return {
29484
- loginStatus: "Expired",
29485
- accessToken,
29486
- refreshToken,
29487
- baseUrl: credentials.UIPATH_URL,
29488
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29489
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29490
- tenantName: credentials.UIPATH_TENANT_NAME,
29491
- tenantId: credentials.UIPATH_TENANT_ID,
29492
- expiration,
29493
- source: "file" /* File */,
29494
- hint: globalHint,
29495
- tokenRefresh: {
29496
- attempted: false,
29497
- success: false,
29498
- errorMessage: `lock acquisition failed: ${msg}`
29499
- }
29500
- };
29501
- }
29502
- return {
29503
- loginStatus: "Refresh Failed",
29504
- 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.",
29505
- tokenRefresh: {
29506
- attempted: false,
29507
- success: false,
29508
- errorMessage: `lock acquisition failed: ${msg}`
29509
- }
29510
- };
29511
- }
29512
- let lockedFailure;
29513
- try {
29514
- const outcome = await runRefreshLocked({
29515
- absolutePath,
29516
- refreshToken,
29517
- customAuthority: credentials.UIPATH_URL,
29518
- ensureTokenValidityMinutes,
29519
- loadEnvFile,
29520
- saveEnvFile,
29521
- refreshFn: refreshTokenFn,
29522
- resolveConfig
29523
- });
29524
- if (outcome.kind === "fail") {
29525
- lockedFailure = outcome.status;
29526
- } else {
29527
- accessToken = outcome.accessToken;
29528
- refreshToken = outcome.refreshToken;
29529
- expiration = outcome.expiration;
29530
- tokenRefresh = outcome.tokenRefresh;
29531
- if (outcome.persistenceWarning) {
29532
- persistenceWarning = outcome.persistenceWarning;
29533
- }
29534
- }
29535
- } finally {
29536
- try {
29537
- await release();
29538
- } catch {
29539
- lockReleaseFailed = true;
29540
- }
29541
- }
29542
- if (lockedFailure) {
29543
- const globalHint = await tryGlobalCredsHint();
29544
- const base = globalHint ? {
29545
- ...lockedFailure,
29546
- loginStatus: "Expired",
29547
- hint: globalHint
29548
- } : lockedFailure;
29549
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
29550
- }
29551
- }
29552
- const result = {
29553
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
29554
- accessToken,
29555
- refreshToken,
29556
- baseUrl: credentials.UIPATH_URL,
29557
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29558
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29559
- tenantName: credentials.UIPATH_TENANT_NAME,
29560
- tenantId: credentials.UIPATH_TENANT_ID,
29561
- expiration,
29562
- source: "file" /* File */,
29563
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
29564
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
29565
- ...tokenRefresh ? { tokenRefresh } : {}
29566
- };
29567
- if (result.loginStatus === "Expired") {
29568
- const globalHint = await tryGlobalCredsHint();
29569
- if (globalHint) {
29570
- result.hint = globalHint;
29571
- }
29572
- }
29573
- return result;
29574
- };
29575
- var isFileNotFoundError = (error) => {
29576
- if (!(error instanceof Object))
29577
- return false;
29578
- return error.code === "ENOENT";
29579
- };
29580
- var getLoginStatusAsync = async (options = {}) => {
29581
- return getLoginStatusWithDeps(options);
29582
- };
28519
+ function normalizeTokenRefreshFailure() {
28520
+ return "stored refresh token is invalid or expired";
28521
+ }
28522
+ function normalizeTokenRefreshUnavailableFailure() {
28523
+ return "token refresh failed before authentication completed";
28524
+ }
28525
+ function errorMessage(error) {
28526
+ return error instanceof Error ? error.message : String(error);
28527
+ }
29583
28528
 
29584
28529
  // ../auth/src/authContext.ts
29585
28530
  var getAuthEnv = async (options = {}) => {
@@ -29612,6 +28557,14 @@ var getAuthEnv = async (options = {}) => {
29612
28557
  };
29613
28558
  // ../auth/src/interactive.ts
29614
28559
  init_src();
28560
+
28561
+ // ../auth/src/selectTenant.ts
28562
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
28563
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
28564
+ var TENANT_SELECTION_CODES = new Set([
28565
+ TENANT_SELECTION_REQUIRED_CODE,
28566
+ INVALID_TENANT_CODE
28567
+ ]);
29615
28568
  // ../auth/src/logout.ts
29616
28569
  init_src();
29617
28570
 
@@ -29677,13 +28630,13 @@ var fail = (reason, message, instructions, extras = {}) => ({
29677
28630
  async function runUipathPythonCommand(args, options = {}) {
29678
28631
  const fs7 = getFileSystem();
29679
28632
  const cacheFile = fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, getCacheFileName());
29680
- const setupHint = options.commandPrefix ? `Run 'uip ${options.commandPrefix} setup' first to configure environment.` : "Run setup first to configure environment.";
28633
+ const setupHint = `Run 'uip ${options.commandPrefix ?? "codedagent"} setup' first to configure the environment. ` + "If you are using a virtual environment, activate it first.";
29681
28634
  const cache = await readCache(cacheFile);
29682
28635
  if (!cache?.uipathExePath) {
29683
28636
  return fail("python_not_configured", "Python not configured.", setupHint);
29684
28637
  }
29685
28638
  if (!await fs7.exists(cache.uipathExePath)) {
29686
- return fail("uipath_exe_missing", "uipath executable not found.", setupHint);
28639
+ return fail("uipath_exe_missing", "uipath executable not found. Please install it using 'pip install uipath' or 'uv add uipath'.", setupHint);
29687
28640
  }
29688
28641
  const processed = processCommandArgs(args, options.commandRules ?? []);
29689
28642
  if (!processed.allowed) {
@@ -29870,3 +28823,5 @@ async function codedagentInitAsync(options) {
29870
28823
  export {
29871
28824
  codedagentInitAsync
29872
28825
  };
28826
+
28827
+ //# debugId=63EA57CC79FD2F7B64756E2164756E21