@uipath/context-grounding-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 (3) hide show
  1. package/dist/index.js +2 -0
  2. package/dist/tool.js +826 -1871
  3. package/package.json +2 -2
package/dist/tool.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) {
@@ -27143,1627 +27224,241 @@ var UIPATH_HOME_DIR = ".uipath";
27143
27224
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
27144
27225
  // ../common/src/interactivity-context.ts
27145
27226
  var modeSlot = singleton("InteractivityMode");
27146
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
27147
- import vm from "vm";
27148
-
27149
- class Hooks {
27150
- add(name, callback, first) {
27151
- if (typeof arguments[0] != "string") {
27152
- for (let name2 in arguments[0]) {
27153
- this.add(name2, arguments[0][name2], arguments[1]);
27154
- }
27155
- } else {
27156
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27157
- this[name2] = this[name2] || [];
27158
- if (callback) {
27159
- this[name2][first ? "unshift" : "push"](callback);
27160
- }
27161
- }, this);
27162
- }
27163
- }
27164
- run(name, env) {
27165
- this[name] = this[name] || [];
27166
- this[name].forEach(function(callback) {
27167
- callback.call(env && env.context ? env.context : env, env);
27168
- });
27169
- }
27170
- }
27227
+ // ../common/src/polling/types.ts
27228
+ var PollOutcome = {
27229
+ Completed: "completed",
27230
+ Timeout: "timeout",
27231
+ Interrupted: "interrupted",
27232
+ Aborted: "aborted",
27233
+ Failed: "failed"
27234
+ };
27171
27235
 
27172
- class Plugins {
27173
- constructor(jsep) {
27174
- this.jsep = jsep;
27175
- this.registered = {};
27176
- }
27177
- register(...plugins) {
27178
- plugins.forEach((plugin) => {
27179
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27180
- throw new Error("Invalid JSEP plugin format");
27181
- }
27182
- if (this.registered[plugin.name]) {
27183
- return;
27184
- }
27185
- plugin.init(this.jsep);
27186
- this.registered[plugin.name] = plugin;
27187
- });
27188
- }
27236
+ // ../common/src/polling/poll-failure-mapping.ts
27237
+ var REASON_BY_OUTCOME = {
27238
+ [PollOutcome.Timeout]: "poll_timeout",
27239
+ [PollOutcome.Failed]: "poll_failed",
27240
+ [PollOutcome.Interrupted]: "poll_failed",
27241
+ [PollOutcome.Aborted]: "poll_aborted"
27242
+ };
27243
+ // ../common/src/polling/terminal-statuses.ts
27244
+ var TERMINAL_STATUSES = new Set([
27245
+ "completed",
27246
+ "successful",
27247
+ "faulted",
27248
+ "failed",
27249
+ "cancelled",
27250
+ "canceled",
27251
+ "stopped",
27252
+ "finished"
27253
+ ]);
27254
+ var FAILURE_STATUSES = new Set([
27255
+ "faulted",
27256
+ "failed",
27257
+ "cancelled",
27258
+ "canceled",
27259
+ "stopped"
27260
+ ]);
27261
+ // ../common/src/preview.ts
27262
+ var previewSlot = singleton("PreviewBuild");
27263
+ function isPreviewBuild() {
27264
+ return previewSlot.get(false) ?? false;
27189
27265
  }
27190
-
27191
- class Jsep {
27192
- static get version() {
27193
- return "1.4.0";
27266
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
27267
+ if (isPreviewBuild()) {
27268
+ return this.command(nameAndArgs, opts);
27194
27269
  }
27195
- static toString() {
27196
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27270
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
27271
+ };
27272
+ // ../common/src/screen-logger.ts
27273
+ var ScreenLogger;
27274
+ ((ScreenLogger) => {
27275
+ function progress(message) {
27276
+ getOutputSink().writeErr(`${message}
27277
+ `);
27197
27278
  }
27198
- static addUnaryOp(op_name) {
27199
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27200
- Jsep.unary_ops[op_name] = 1;
27201
- return Jsep;
27279
+ ScreenLogger.progress = progress;
27280
+ })(ScreenLogger ||= {});
27281
+ // ../common/src/sdk-user-agent.ts
27282
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
27283
+ // ../common/src/tool-provider.ts
27284
+ var factorySlot = singleton("PackagerFactoryProvider");
27285
+ // ../uipath-python-bridge/src/cache.ts
27286
+ init_src();
27287
+ async function readCache(cacheFile) {
27288
+ const fs7 = getFileSystem();
27289
+ const [existsError, exists] = await catchError(fs7.exists(cacheFile));
27290
+ if (existsError || !exists)
27291
+ return null;
27292
+ const [readError, content] = await catchError(fs7.readFile(cacheFile, "utf-8"));
27293
+ if (readError) {
27294
+ logger.warn(`Failed to load cache: ${readError}`);
27295
+ return null;
27202
27296
  }
27203
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27204
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27205
- Jsep.binary_ops[op_name] = precedence;
27206
- if (isRightAssociative) {
27207
- Jsep.right_associative.add(op_name);
27208
- } else {
27209
- Jsep.right_associative.delete(op_name);
27210
- }
27211
- return Jsep;
27297
+ const [parseError, cache] = catchError(() => JSON.parse(content));
27298
+ if (parseError) {
27299
+ logger.warn(`Failed to parse cache: ${parseError}`);
27300
+ return null;
27212
27301
  }
27213
- static addIdentifierChar(char) {
27214
- Jsep.additional_identifier_chars.add(char);
27215
- return Jsep;
27302
+ return cache;
27303
+ }
27304
+ // ../uipath-python-bridge/src/config.ts
27305
+ var DEFAULT_CONFIG = {
27306
+ allowedPythonVersions: ["3.14", "3.13", "3.12", "3.11"],
27307
+ packageName: "uipath",
27308
+ cacheFileName: ".uipath-python-cache.json"
27309
+ };
27310
+ function getAllowedPythonVersions() {
27311
+ const envVersions = process.env.PYTHON_TOOL_PYTHON_VERSIONS;
27312
+ if (envVersions) {
27313
+ return envVersions.split(",").map((v) => v.trim()).filter(Boolean);
27216
27314
  }
27217
- static addLiteral(literal_name, literal_value) {
27218
- Jsep.literals[literal_name] = literal_value;
27219
- return Jsep;
27315
+ return DEFAULT_CONFIG.allowedPythonVersions;
27316
+ }
27317
+ function getPackageName() {
27318
+ return DEFAULT_CONFIG.packageName;
27319
+ }
27320
+ function getCacheFileName() {
27321
+ return DEFAULT_CONFIG.cacheFileName;
27322
+ }
27323
+ function matchesPattern(args, pattern) {
27324
+ if (typeof pattern === "string") {
27325
+ return args.includes(pattern);
27220
27326
  }
27221
- static removeUnaryOp(op_name) {
27222
- delete Jsep.unary_ops[op_name];
27223
- if (op_name.length === Jsep.max_unop_len) {
27224
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27327
+ if (Array.isArray(pattern)) {
27328
+ for (let i = 0;i <= args.length - pattern.length; i++) {
27329
+ let match = true;
27330
+ for (let j = 0;j < pattern.length; j++) {
27331
+ if (args[i + j] !== pattern[j]) {
27332
+ match = false;
27333
+ break;
27334
+ }
27335
+ }
27336
+ if (match) {
27337
+ return true;
27338
+ }
27225
27339
  }
27226
- return Jsep;
27227
- }
27228
- static removeAllUnaryOps() {
27229
- Jsep.unary_ops = {};
27230
- Jsep.max_unop_len = 0;
27231
- return Jsep;
27232
- }
27233
- static removeIdentifierChar(char) {
27234
- Jsep.additional_identifier_chars.delete(char);
27235
- return Jsep;
27236
27340
  }
27237
- static removeBinaryOp(op_name) {
27238
- delete Jsep.binary_ops[op_name];
27239
- if (op_name.length === Jsep.max_binop_len) {
27240
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27341
+ return false;
27342
+ }
27343
+ function processCommandArgs(args, rules) {
27344
+ const hasForceFlag = args.includes("--force");
27345
+ const argsWithoutForce = args.filter((arg) => arg !== "--force");
27346
+ for (const rule of rules) {
27347
+ if (matchesPattern(argsWithoutForce, rule.pattern)) {
27348
+ switch (rule.action) {
27349
+ case "filter":
27350
+ if (hasForceFlag) {
27351
+ return {
27352
+ allowed: true,
27353
+ args: [...argsWithoutForce]
27354
+ };
27355
+ }
27356
+ return {
27357
+ allowed: false,
27358
+ args: [],
27359
+ errorMessage: rule.filterMessage || "This command is not allowed"
27360
+ };
27361
+ case "append":
27362
+ if (rule.appendArgs && rule.appendArgs.length > 0) {
27363
+ return {
27364
+ allowed: true,
27365
+ args: [...argsWithoutForce, ...rule.appendArgs]
27366
+ };
27367
+ }
27368
+ break;
27369
+ }
27241
27370
  }
27242
- Jsep.right_associative.delete(op_name);
27243
- return Jsep;
27244
- }
27245
- static removeAllBinaryOps() {
27246
- Jsep.binary_ops = {};
27247
- Jsep.max_binop_len = 0;
27248
- return Jsep;
27249
- }
27250
- static removeLiteral(literal_name) {
27251
- delete Jsep.literals[literal_name];
27252
- return Jsep;
27253
- }
27254
- static removeAllLiterals() {
27255
- Jsep.literals = {};
27256
- return Jsep;
27257
27371
  }
27258
- get char() {
27259
- return this.expr.charAt(this.index);
27260
- }
27261
- get code() {
27262
- return this.expr.charCodeAt(this.index);
27263
- }
27264
- constructor(expr) {
27265
- this.expr = expr;
27266
- this.index = 0;
27267
- }
27268
- static parse(expr) {
27269
- return new Jsep(expr).parse();
27372
+ return {
27373
+ allowed: true,
27374
+ args: [...argsWithoutForce]
27375
+ };
27376
+ }
27377
+ // ../uipath-python-bridge/src/execute.ts
27378
+ import { spawn } from "node:child_process";
27379
+
27380
+ // ../auth/src/config.ts
27381
+ init_constants();
27382
+ var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
27383
+ var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
27384
+ var globalSlot = globalThis;
27385
+ var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
27386
+
27387
+ class InvalidBaseUrlError extends Error {
27388
+ url;
27389
+ reason;
27390
+ constructor(url, reason) {
27391
+ super(`Invalid base URL: "${url}"
27392
+ ` + `Reason: ${reason}
27393
+
27394
+ ` + `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>).
27395
+ ` + `You can specify the URL via:
27396
+ ` + ` • --authority flag
27397
+ ` + ` • UIPATH_URL environment variable
27398
+ ` + ` • auth.authority in config file`);
27399
+ this.url = url;
27400
+ this.reason = reason;
27401
+ this.name = "InvalidBaseUrlError";
27270
27402
  }
27271
- static getMaxKeyLen(obj) {
27272
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27403
+ }
27404
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
27405
+ var normalizeAndValidateBaseUrl = (rawUrl) => {
27406
+ let baseUrl = rawUrl;
27407
+ if (baseUrl.endsWith("/identity_/")) {
27408
+ baseUrl = baseUrl.slice(0, -11);
27409
+ } else if (baseUrl.endsWith("/identity_")) {
27410
+ baseUrl = baseUrl.slice(0, -10);
27273
27411
  }
27274
- static isDecimalDigit(ch) {
27275
- return ch >= 48 && ch <= 57;
27412
+ while (baseUrl.endsWith("/")) {
27413
+ baseUrl = baseUrl.slice(0, -1);
27276
27414
  }
27277
- static binaryPrecedence(op_val) {
27278
- return Jsep.binary_ops[op_val] || 0;
27415
+ const resolvedBaseUrl = baseUrl;
27416
+ const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
27417
+ if (urlError) {
27418
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
27279
27419
  }
27280
- static isIdentifierStart(ch) {
27281
- 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));
27420
+ if (url.protocol !== "https:") {
27421
+ throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
27282
27422
  }
27283
- static isIdentifierPart(ch) {
27284
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27423
+ return url.pathname.length > 1 ? url.origin : baseUrl;
27424
+ };
27425
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
27426
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
27427
+ if (isExternalAppAuth)
27428
+ return requestedScopes;
27429
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
27430
+ };
27431
+ var resolveConfigAsync = async ({
27432
+ customAuthority,
27433
+ customClientId,
27434
+ customClientSecret,
27435
+ customScopes
27436
+ } = {}) => {
27437
+ const fileAuth = getAuthFileConfig();
27438
+ let baseUrl = customAuthority;
27439
+ if (!baseUrl) {
27440
+ baseUrl = process.env.UIPATH_URL;
27285
27441
  }
27286
- throwError(message) {
27287
- const error = new Error(message + " at character " + this.index);
27288
- error.index = this.index;
27289
- error.description = message;
27290
- throw error;
27442
+ if (!baseUrl && fileAuth.authority) {
27443
+ baseUrl = fileAuth.authority;
27291
27444
  }
27292
- runHook(name, node) {
27293
- if (Jsep.hooks[name]) {
27294
- const env = {
27295
- context: this,
27296
- node
27297
- };
27298
- Jsep.hooks.run(name, env);
27299
- return env.node;
27300
- }
27301
- return node;
27445
+ if (!baseUrl) {
27446
+ baseUrl = DEFAULT_BASE_URL;
27302
27447
  }
27303
- searchHook(name) {
27304
- if (Jsep.hooks[name]) {
27305
- const env = {
27306
- context: this
27307
- };
27308
- Jsep.hooks[name].find(function(callback) {
27309
- callback.call(env.context, env);
27310
- return env.node;
27311
- });
27312
- return env.node;
27313
- }
27448
+ baseUrl = normalizeAndValidateBaseUrl(baseUrl);
27449
+ let clientId = customClientId;
27450
+ if (!clientId && fileAuth.clientId) {
27451
+ clientId = fileAuth.clientId;
27314
27452
  }
27315
- gobbleSpaces() {
27316
- let ch = this.code;
27317
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27318
- ch = this.expr.charCodeAt(++this.index);
27319
- }
27320
- this.runHook("gobble-spaces");
27453
+ if (!clientId) {
27454
+ clientId = DEFAULT_CLIENT_ID;
27321
27455
  }
27322
- parse() {
27323
- this.runHook("before-all");
27324
- const nodes = this.gobbleExpressions();
27325
- const node = nodes.length === 1 ? nodes[0] : {
27326
- type: Jsep.COMPOUND,
27327
- body: nodes
27328
- };
27329
- return this.runHook("after-all", node);
27330
- }
27331
- gobbleExpressions(untilICode) {
27332
- let nodes = [], ch_i, node;
27333
- while (this.index < this.expr.length) {
27334
- ch_i = this.code;
27335
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27336
- this.index++;
27337
- } else {
27338
- if (node = this.gobbleExpression()) {
27339
- nodes.push(node);
27340
- } else if (this.index < this.expr.length) {
27341
- if (ch_i === untilICode) {
27342
- break;
27343
- }
27344
- this.throwError('Unexpected "' + this.char + '"');
27345
- }
27346
- }
27347
- }
27348
- return nodes;
27349
- }
27350
- gobbleExpression() {
27351
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27352
- this.gobbleSpaces();
27353
- return this.runHook("after-expression", node);
27354
- }
27355
- gobbleBinaryOp() {
27356
- this.gobbleSpaces();
27357
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27358
- let tc_len = to_check.length;
27359
- while (tc_len > 0) {
27360
- 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)))) {
27361
- this.index += tc_len;
27362
- return to_check;
27363
- }
27364
- to_check = to_check.substr(0, --tc_len);
27365
- }
27366
- return false;
27367
- }
27368
- gobbleBinaryExpression() {
27369
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27370
- left = this.gobbleToken();
27371
- if (!left) {
27372
- return left;
27373
- }
27374
- biop = this.gobbleBinaryOp();
27375
- if (!biop) {
27376
- return left;
27377
- }
27378
- biop_info = {
27379
- value: biop,
27380
- prec: Jsep.binaryPrecedence(biop),
27381
- right_a: Jsep.right_associative.has(biop)
27382
- };
27383
- right = this.gobbleToken();
27384
- if (!right) {
27385
- this.throwError("Expected expression after " + biop);
27386
- }
27387
- stack = [left, biop_info, right];
27388
- while (biop = this.gobbleBinaryOp()) {
27389
- prec = Jsep.binaryPrecedence(biop);
27390
- if (prec === 0) {
27391
- this.index -= biop.length;
27392
- break;
27393
- }
27394
- biop_info = {
27395
- value: biop,
27396
- prec,
27397
- right_a: Jsep.right_associative.has(biop)
27398
- };
27399
- cur_biop = biop;
27400
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27401
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27402
- right = stack.pop();
27403
- biop = stack.pop().value;
27404
- left = stack.pop();
27405
- node = {
27406
- type: Jsep.BINARY_EXP,
27407
- operator: biop,
27408
- left,
27409
- right
27410
- };
27411
- stack.push(node);
27412
- }
27413
- node = this.gobbleToken();
27414
- if (!node) {
27415
- this.throwError("Expected expression after " + cur_biop);
27416
- }
27417
- stack.push(biop_info, node);
27418
- }
27419
- i = stack.length - 1;
27420
- node = stack[i];
27421
- while (i > 1) {
27422
- node = {
27423
- type: Jsep.BINARY_EXP,
27424
- operator: stack[i - 1].value,
27425
- left: stack[i - 2],
27426
- right: node
27427
- };
27428
- i -= 2;
27429
- }
27430
- return node;
27431
- }
27432
- gobbleToken() {
27433
- let ch, to_check, tc_len, node;
27434
- this.gobbleSpaces();
27435
- node = this.searchHook("gobble-token");
27436
- if (node) {
27437
- return this.runHook("after-token", node);
27438
- }
27439
- ch = this.code;
27440
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27441
- return this.gobbleNumericLiteral();
27442
- }
27443
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27444
- node = this.gobbleStringLiteral();
27445
- } else if (ch === Jsep.OBRACK_CODE) {
27446
- node = this.gobbleArray();
27447
- } else {
27448
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27449
- tc_len = to_check.length;
27450
- while (tc_len > 0) {
27451
- 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)))) {
27452
- this.index += tc_len;
27453
- const argument = this.gobbleToken();
27454
- if (!argument) {
27455
- this.throwError("missing unaryOp argument");
27456
- }
27457
- return this.runHook("after-token", {
27458
- type: Jsep.UNARY_EXP,
27459
- operator: to_check,
27460
- argument,
27461
- prefix: true
27462
- });
27463
- }
27464
- to_check = to_check.substr(0, --tc_len);
27465
- }
27466
- if (Jsep.isIdentifierStart(ch)) {
27467
- node = this.gobbleIdentifier();
27468
- if (Jsep.literals.hasOwnProperty(node.name)) {
27469
- node = {
27470
- type: Jsep.LITERAL,
27471
- value: Jsep.literals[node.name],
27472
- raw: node.name
27473
- };
27474
- } else if (node.name === Jsep.this_str) {
27475
- node = {
27476
- type: Jsep.THIS_EXP
27477
- };
27478
- }
27479
- } else if (ch === Jsep.OPAREN_CODE) {
27480
- node = this.gobbleGroup();
27481
- }
27482
- }
27483
- if (!node) {
27484
- return this.runHook("after-token", false);
27485
- }
27486
- node = this.gobbleTokenProperty(node);
27487
- return this.runHook("after-token", node);
27488
- }
27489
- gobbleTokenProperty(node) {
27490
- this.gobbleSpaces();
27491
- let ch = this.code;
27492
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27493
- let optional;
27494
- if (ch === Jsep.QUMARK_CODE) {
27495
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27496
- break;
27497
- }
27498
- optional = true;
27499
- this.index += 2;
27500
- this.gobbleSpaces();
27501
- ch = this.code;
27502
- }
27503
- this.index++;
27504
- if (ch === Jsep.OBRACK_CODE) {
27505
- node = {
27506
- type: Jsep.MEMBER_EXP,
27507
- computed: true,
27508
- object: node,
27509
- property: this.gobbleExpression()
27510
- };
27511
- if (!node.property) {
27512
- this.throwError('Unexpected "' + this.char + '"');
27513
- }
27514
- this.gobbleSpaces();
27515
- ch = this.code;
27516
- if (ch !== Jsep.CBRACK_CODE) {
27517
- this.throwError("Unclosed [");
27518
- }
27519
- this.index++;
27520
- } else if (ch === Jsep.OPAREN_CODE) {
27521
- node = {
27522
- type: Jsep.CALL_EXP,
27523
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27524
- callee: node
27525
- };
27526
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27527
- if (optional) {
27528
- this.index--;
27529
- }
27530
- this.gobbleSpaces();
27531
- node = {
27532
- type: Jsep.MEMBER_EXP,
27533
- computed: false,
27534
- object: node,
27535
- property: this.gobbleIdentifier()
27536
- };
27537
- }
27538
- if (optional) {
27539
- node.optional = true;
27540
- }
27541
- this.gobbleSpaces();
27542
- ch = this.code;
27543
- }
27544
- return node;
27545
- }
27546
- gobbleNumericLiteral() {
27547
- let number = "", ch, chCode;
27548
- while (Jsep.isDecimalDigit(this.code)) {
27549
- number += this.expr.charAt(this.index++);
27550
- }
27551
- if (this.code === Jsep.PERIOD_CODE) {
27552
- number += this.expr.charAt(this.index++);
27553
- while (Jsep.isDecimalDigit(this.code)) {
27554
- number += this.expr.charAt(this.index++);
27555
- }
27556
- }
27557
- ch = this.char;
27558
- if (ch === "e" || ch === "E") {
27559
- number += this.expr.charAt(this.index++);
27560
- ch = this.char;
27561
- if (ch === "+" || ch === "-") {
27562
- number += this.expr.charAt(this.index++);
27563
- }
27564
- while (Jsep.isDecimalDigit(this.code)) {
27565
- number += this.expr.charAt(this.index++);
27566
- }
27567
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27568
- this.throwError("Expected exponent (" + number + this.char + ")");
27569
- }
27570
- }
27571
- chCode = this.code;
27572
- if (Jsep.isIdentifierStart(chCode)) {
27573
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27574
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27575
- this.throwError("Unexpected period");
27576
- }
27577
- return {
27578
- type: Jsep.LITERAL,
27579
- value: parseFloat(number),
27580
- raw: number
27581
- };
27582
- }
27583
- gobbleStringLiteral() {
27584
- let str = "";
27585
- const startIndex = this.index;
27586
- const quote = this.expr.charAt(this.index++);
27587
- let closed = false;
27588
- while (this.index < this.expr.length) {
27589
- let ch = this.expr.charAt(this.index++);
27590
- if (ch === quote) {
27591
- closed = true;
27592
- break;
27593
- } else if (ch === "\\") {
27594
- ch = this.expr.charAt(this.index++);
27595
- switch (ch) {
27596
- case "n":
27597
- str += `
27598
- `;
27599
- break;
27600
- case "r":
27601
- str += "\r";
27602
- break;
27603
- case "t":
27604
- str += "\t";
27605
- break;
27606
- case "b":
27607
- str += "\b";
27608
- break;
27609
- case "f":
27610
- str += "\f";
27611
- break;
27612
- case "v":
27613
- str += "\v";
27614
- break;
27615
- default:
27616
- str += ch;
27617
- }
27618
- } else {
27619
- str += ch;
27620
- }
27621
- }
27622
- if (!closed) {
27623
- this.throwError('Unclosed quote after "' + str + '"');
27624
- }
27625
- return {
27626
- type: Jsep.LITERAL,
27627
- value: str,
27628
- raw: this.expr.substring(startIndex, this.index)
27629
- };
27630
- }
27631
- gobbleIdentifier() {
27632
- let ch = this.code, start = this.index;
27633
- if (Jsep.isIdentifierStart(ch)) {
27634
- this.index++;
27635
- } else {
27636
- this.throwError("Unexpected " + this.char);
27637
- }
27638
- while (this.index < this.expr.length) {
27639
- ch = this.code;
27640
- if (Jsep.isIdentifierPart(ch)) {
27641
- this.index++;
27642
- } else {
27643
- break;
27644
- }
27645
- }
27646
- return {
27647
- type: Jsep.IDENTIFIER,
27648
- name: this.expr.slice(start, this.index)
27649
- };
27650
- }
27651
- gobbleArguments(termination) {
27652
- const args = [];
27653
- let closed = false;
27654
- let separator_count = 0;
27655
- while (this.index < this.expr.length) {
27656
- this.gobbleSpaces();
27657
- let ch_i = this.code;
27658
- if (ch_i === termination) {
27659
- closed = true;
27660
- this.index++;
27661
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
27662
- this.throwError("Unexpected token " + String.fromCharCode(termination));
27663
- }
27664
- break;
27665
- } else if (ch_i === Jsep.COMMA_CODE) {
27666
- this.index++;
27667
- separator_count++;
27668
- if (separator_count !== args.length) {
27669
- if (termination === Jsep.CPAREN_CODE) {
27670
- this.throwError("Unexpected token ,");
27671
- } else if (termination === Jsep.CBRACK_CODE) {
27672
- for (let arg = args.length;arg < separator_count; arg++) {
27673
- args.push(null);
27674
- }
27675
- }
27676
- }
27677
- } else if (args.length !== separator_count && separator_count !== 0) {
27678
- this.throwError("Expected comma");
27679
- } else {
27680
- const node = this.gobbleExpression();
27681
- if (!node || node.type === Jsep.COMPOUND) {
27682
- this.throwError("Expected comma");
27683
- }
27684
- args.push(node);
27685
- }
27686
- }
27687
- if (!closed) {
27688
- this.throwError("Expected " + String.fromCharCode(termination));
27689
- }
27690
- return args;
27691
- }
27692
- gobbleGroup() {
27693
- this.index++;
27694
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
27695
- if (this.code === Jsep.CPAREN_CODE) {
27696
- this.index++;
27697
- if (nodes.length === 1) {
27698
- return nodes[0];
27699
- } else if (!nodes.length) {
27700
- return false;
27701
- } else {
27702
- return {
27703
- type: Jsep.SEQUENCE_EXP,
27704
- expressions: nodes
27705
- };
27706
- }
27707
- } else {
27708
- this.throwError("Unclosed (");
27709
- }
27710
- }
27711
- gobbleArray() {
27712
- this.index++;
27713
- return {
27714
- type: Jsep.ARRAY_EXP,
27715
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
27716
- };
27717
- }
27718
- }
27719
- var hooks = new Hooks;
27720
- Object.assign(Jsep, {
27721
- hooks,
27722
- plugins: new Plugins(Jsep),
27723
- COMPOUND: "Compound",
27724
- SEQUENCE_EXP: "SequenceExpression",
27725
- IDENTIFIER: "Identifier",
27726
- MEMBER_EXP: "MemberExpression",
27727
- LITERAL: "Literal",
27728
- THIS_EXP: "ThisExpression",
27729
- CALL_EXP: "CallExpression",
27730
- UNARY_EXP: "UnaryExpression",
27731
- BINARY_EXP: "BinaryExpression",
27732
- ARRAY_EXP: "ArrayExpression",
27733
- TAB_CODE: 9,
27734
- LF_CODE: 10,
27735
- CR_CODE: 13,
27736
- SPACE_CODE: 32,
27737
- PERIOD_CODE: 46,
27738
- COMMA_CODE: 44,
27739
- SQUOTE_CODE: 39,
27740
- DQUOTE_CODE: 34,
27741
- OPAREN_CODE: 40,
27742
- CPAREN_CODE: 41,
27743
- OBRACK_CODE: 91,
27744
- CBRACK_CODE: 93,
27745
- QUMARK_CODE: 63,
27746
- SEMCOL_CODE: 59,
27747
- COLON_CODE: 58,
27748
- unary_ops: {
27749
- "-": 1,
27750
- "!": 1,
27751
- "~": 1,
27752
- "+": 1
27753
- },
27754
- binary_ops: {
27755
- "||": 1,
27756
- "??": 1,
27757
- "&&": 2,
27758
- "|": 3,
27759
- "^": 4,
27760
- "&": 5,
27761
- "==": 6,
27762
- "!=": 6,
27763
- "===": 6,
27764
- "!==": 6,
27765
- "<": 7,
27766
- ">": 7,
27767
- "<=": 7,
27768
- ">=": 7,
27769
- "<<": 8,
27770
- ">>": 8,
27771
- ">>>": 8,
27772
- "+": 9,
27773
- "-": 9,
27774
- "*": 10,
27775
- "/": 10,
27776
- "%": 10,
27777
- "**": 11
27778
- },
27779
- right_associative: new Set(["**"]),
27780
- additional_identifier_chars: new Set(["$", "_"]),
27781
- literals: {
27782
- true: true,
27783
- false: false,
27784
- null: null
27785
- },
27786
- this_str: "this"
27787
- });
27788
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27789
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27790
- var jsep = (expr) => new Jsep(expr).parse();
27791
- var stdClassProps = Object.getOwnPropertyNames(class Test {
27792
- });
27793
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
27794
- jsep[m] = Jsep[m];
27795
- });
27796
- jsep.Jsep = Jsep;
27797
- var CONDITIONAL_EXP = "ConditionalExpression";
27798
- var ternary = {
27799
- name: "ternary",
27800
- init(jsep2) {
27801
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
27802
- if (env.node && this.code === jsep2.QUMARK_CODE) {
27803
- this.index++;
27804
- const test = env.node;
27805
- const consequent = this.gobbleExpression();
27806
- if (!consequent) {
27807
- this.throwError("Expected expression");
27808
- }
27809
- this.gobbleSpaces();
27810
- if (this.code === jsep2.COLON_CODE) {
27811
- this.index++;
27812
- const alternate = this.gobbleExpression();
27813
- if (!alternate) {
27814
- this.throwError("Expected expression");
27815
- }
27816
- env.node = {
27817
- type: CONDITIONAL_EXP,
27818
- test,
27819
- consequent,
27820
- alternate
27821
- };
27822
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
27823
- let newTest = test;
27824
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
27825
- newTest = newTest.right;
27826
- }
27827
- env.node.test = newTest.right;
27828
- newTest.right = env.node;
27829
- env.node = test;
27830
- }
27831
- } else {
27832
- this.throwError("Expected :");
27833
- }
27834
- }
27835
- });
27836
- }
27837
- };
27838
- jsep.plugins.register(ternary);
27839
- var FSLASH_CODE = 47;
27840
- var BSLASH_CODE = 92;
27841
- var index = {
27842
- name: "regex",
27843
- init(jsep2) {
27844
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
27845
- if (this.code === FSLASH_CODE) {
27846
- const patternIndex = ++this.index;
27847
- let inCharSet = false;
27848
- while (this.index < this.expr.length) {
27849
- if (this.code === FSLASH_CODE && !inCharSet) {
27850
- const pattern = this.expr.slice(patternIndex, this.index);
27851
- let flags = "";
27852
- while (++this.index < this.expr.length) {
27853
- const code = this.code;
27854
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
27855
- flags += this.char;
27856
- } else {
27857
- break;
27858
- }
27859
- }
27860
- let value;
27861
- try {
27862
- value = new RegExp(pattern, flags);
27863
- } catch (e) {
27864
- this.throwError(e.message);
27865
- }
27866
- env.node = {
27867
- type: jsep2.LITERAL,
27868
- value,
27869
- raw: this.expr.slice(patternIndex - 1, this.index)
27870
- };
27871
- env.node = this.gobbleTokenProperty(env.node);
27872
- return env.node;
27873
- }
27874
- if (this.code === jsep2.OBRACK_CODE) {
27875
- inCharSet = true;
27876
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
27877
- inCharSet = false;
27878
- }
27879
- this.index += this.code === BSLASH_CODE ? 2 : 1;
27880
- }
27881
- this.throwError("Unclosed Regex");
27882
- }
27883
- });
27884
- }
27885
- };
27886
- var PLUS_CODE = 43;
27887
- var MINUS_CODE = 45;
27888
- var plugin = {
27889
- name: "assignment",
27890
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
27891
- updateOperators: [PLUS_CODE, MINUS_CODE],
27892
- assignmentPrecedence: 0.9,
27893
- init(jsep2) {
27894
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
27895
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
27896
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
27897
- const code = this.code;
27898
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
27899
- this.index += 2;
27900
- env.node = {
27901
- type: "UpdateExpression",
27902
- operator: code === PLUS_CODE ? "++" : "--",
27903
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
27904
- prefix: true
27905
- };
27906
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
27907
- this.throwError(`Unexpected ${env.node.operator}`);
27908
- }
27909
- }
27910
- });
27911
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
27912
- if (env.node) {
27913
- const code = this.code;
27914
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
27915
- if (!updateNodeTypes.includes(env.node.type)) {
27916
- this.throwError(`Unexpected ${env.node.operator}`);
27917
- }
27918
- this.index += 2;
27919
- env.node = {
27920
- type: "UpdateExpression",
27921
- operator: code === PLUS_CODE ? "++" : "--",
27922
- argument: env.node,
27923
- prefix: false
27924
- };
27925
- }
27926
- }
27927
- });
27928
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
27929
- if (env.node) {
27930
- updateBinariesToAssignments(env.node);
27931
- }
27932
- });
27933
- function updateBinariesToAssignments(node) {
27934
- if (plugin.assignmentOperators.has(node.operator)) {
27935
- node.type = "AssignmentExpression";
27936
- updateBinariesToAssignments(node.left);
27937
- updateBinariesToAssignments(node.right);
27938
- } else if (!node.operator) {
27939
- Object.values(node).forEach((val) => {
27940
- if (val && typeof val === "object") {
27941
- updateBinariesToAssignments(val);
27942
- }
27943
- });
27944
- }
27945
- }
27946
- }
27947
- };
27948
- jsep.plugins.register(index, plugin);
27949
- jsep.addUnaryOp("typeof");
27950
- jsep.addUnaryOp("void");
27951
- jsep.addLiteral("null", null);
27952
- jsep.addLiteral("undefined", undefined);
27953
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
27954
- var SafeEval = {
27955
- evalAst(ast, subs) {
27956
- switch (ast.type) {
27957
- case "BinaryExpression":
27958
- case "LogicalExpression":
27959
- return SafeEval.evalBinaryExpression(ast, subs);
27960
- case "Compound":
27961
- return SafeEval.evalCompound(ast, subs);
27962
- case "ConditionalExpression":
27963
- return SafeEval.evalConditionalExpression(ast, subs);
27964
- case "Identifier":
27965
- return SafeEval.evalIdentifier(ast, subs);
27966
- case "Literal":
27967
- return SafeEval.evalLiteral(ast, subs);
27968
- case "MemberExpression":
27969
- return SafeEval.evalMemberExpression(ast, subs);
27970
- case "UnaryExpression":
27971
- return SafeEval.evalUnaryExpression(ast, subs);
27972
- case "ArrayExpression":
27973
- return SafeEval.evalArrayExpression(ast, subs);
27974
- case "CallExpression":
27975
- return SafeEval.evalCallExpression(ast, subs);
27976
- case "AssignmentExpression":
27977
- return SafeEval.evalAssignmentExpression(ast, subs);
27978
- default:
27979
- throw SyntaxError("Unexpected expression", ast);
27980
- }
27981
- },
27982
- evalBinaryExpression(ast, subs) {
27983
- const result = {
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
- "<<": (a, b) => a << b(),
27998
- ">>": (a, b) => a >> b(),
27999
- ">>>": (a, b) => a >>> b(),
28000
- "+": (a, b) => a + b(),
28001
- "-": (a, b) => a - b(),
28002
- "*": (a, b) => a * b(),
28003
- "/": (a, b) => a / b(),
28004
- "%": (a, b) => a % b()
28005
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
28006
- return result;
28007
- },
28008
- evalCompound(ast, subs) {
28009
- let last;
28010
- for (let i = 0;i < ast.body.length; i++) {
28011
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28012
- i += 1;
28013
- }
28014
- const expr = ast.body[i];
28015
- last = SafeEval.evalAst(expr, subs);
28016
- }
28017
- return last;
28018
- },
28019
- evalConditionalExpression(ast, subs) {
28020
- if (SafeEval.evalAst(ast.test, subs)) {
28021
- return SafeEval.evalAst(ast.consequent, subs);
28022
- }
28023
- return SafeEval.evalAst(ast.alternate, subs);
28024
- },
28025
- evalIdentifier(ast, subs) {
28026
- if (Object.hasOwn(subs, ast.name)) {
28027
- return subs[ast.name];
28028
- }
28029
- throw ReferenceError(`${ast.name} is not defined`);
28030
- },
28031
- evalLiteral(ast) {
28032
- return ast.value;
28033
- },
28034
- evalMemberExpression(ast, subs) {
28035
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28036
- const obj = SafeEval.evalAst(ast.object, subs);
28037
- if (obj === undefined || obj === null) {
28038
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28039
- }
28040
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28041
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28042
- }
28043
- const result = obj[prop];
28044
- if (typeof result === "function") {
28045
- return result.bind(obj);
28046
- }
28047
- return result;
28048
- },
28049
- evalUnaryExpression(ast, subs) {
28050
- const result = {
28051
- "-": (a) => -SafeEval.evalAst(a, subs),
28052
- "!": (a) => !SafeEval.evalAst(a, subs),
28053
- "~": (a) => ~SafeEval.evalAst(a, subs),
28054
- "+": (a) => +SafeEval.evalAst(a, subs),
28055
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28056
- void: (a) => void SafeEval.evalAst(a, subs)
28057
- }[ast.operator](ast.argument);
28058
- return result;
28059
- },
28060
- evalArrayExpression(ast, subs) {
28061
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28062
- },
28063
- evalCallExpression(ast, subs) {
28064
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28065
- const func = SafeEval.evalAst(ast.callee, subs);
28066
- if (func === Function) {
28067
- throw new Error("Function constructor is disabled");
28068
- }
28069
- return func(...args);
28070
- },
28071
- evalAssignmentExpression(ast, subs) {
28072
- if (ast.left.type !== "Identifier") {
28073
- throw SyntaxError("Invalid left-hand side in assignment");
28074
- }
28075
- const id = ast.left.name;
28076
- const value = SafeEval.evalAst(ast.right, subs);
28077
- subs[id] = value;
28078
- return subs[id];
28079
- }
28080
- };
28081
-
28082
- class SafeScript {
28083
- constructor(expr) {
28084
- this.code = expr;
28085
- this.ast = jsep(this.code);
28086
- }
28087
- runInNewContext(context) {
28088
- const keyMap = Object.assign(Object.create(null), context);
28089
- return SafeEval.evalAst(this.ast, keyMap);
28090
- }
28091
- }
28092
- function push(arr, item) {
28093
- arr = arr.slice();
28094
- arr.push(item);
28095
- return arr;
28096
- }
28097
- function unshift(item, arr) {
28098
- arr = arr.slice();
28099
- arr.unshift(item);
28100
- return arr;
28101
- }
28102
-
28103
- class NewError extends Error {
28104
- constructor(value) {
28105
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28106
- this.avoidNew = true;
28107
- this.value = value;
28108
- this.name = "NewError";
28109
- }
28110
- }
28111
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28112
- if (!(this instanceof JSONPath)) {
28113
- try {
28114
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28115
- } catch (e) {
28116
- if (!e.avoidNew) {
28117
- throw e;
28118
- }
28119
- return e.value;
28120
- }
28121
- }
28122
- if (typeof opts === "string") {
28123
- otherTypeCallback = callback;
28124
- callback = obj;
28125
- obj = expr;
28126
- expr = opts;
28127
- opts = null;
28128
- }
28129
- const optObj = opts && typeof opts === "object";
28130
- opts = opts || {};
28131
- this.json = opts.json || obj;
28132
- this.path = opts.path || expr;
28133
- this.resultType = opts.resultType || "value";
28134
- this.flatten = opts.flatten || false;
28135
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28136
- this.sandbox = opts.sandbox || {};
28137
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28138
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28139
- this.parent = opts.parent || null;
28140
- this.parentProperty = opts.parentProperty || null;
28141
- this.callback = opts.callback || callback || null;
28142
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28143
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28144
- };
28145
- if (opts.autostart !== false) {
28146
- const args = {
28147
- path: optObj ? opts.path : expr
28148
- };
28149
- if (!optObj) {
28150
- args.json = obj;
28151
- } else if ("json" in opts) {
28152
- args.json = opts.json;
28153
- }
28154
- const ret = this.evaluate(args);
28155
- if (!ret || typeof ret !== "object") {
28156
- throw new NewError(ret);
28157
- }
28158
- return ret;
28159
- }
28160
- }
28161
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28162
- let currParent = this.parent, currParentProperty = this.parentProperty;
28163
- let {
28164
- flatten,
28165
- wrap
28166
- } = this;
28167
- this.currResultType = this.resultType;
28168
- this.currEval = this.eval;
28169
- this.currSandbox = this.sandbox;
28170
- callback = callback || this.callback;
28171
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28172
- json = json || this.json;
28173
- expr = expr || this.path;
28174
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28175
- if (!expr.path && expr.path !== "") {
28176
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28177
- }
28178
- if (!Object.hasOwn(expr, "json")) {
28179
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28180
- }
28181
- ({
28182
- json
28183
- } = expr);
28184
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28185
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28186
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28187
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28188
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28189
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28190
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28191
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28192
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28193
- expr = expr.path;
28194
- }
28195
- currParent = currParent || null;
28196
- currParentProperty = currParentProperty || null;
28197
- if (Array.isArray(expr)) {
28198
- expr = JSONPath.toPathString(expr);
28199
- }
28200
- if (!expr && expr !== "" || !json) {
28201
- return;
28202
- }
28203
- const exprList = JSONPath.toPathArray(expr);
28204
- if (exprList[0] === "$" && exprList.length > 1) {
28205
- exprList.shift();
28206
- }
28207
- this._hasParentSelector = null;
28208
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28209
- return ea && !ea.isParentSelector;
28210
- });
28211
- if (!result.length) {
28212
- return wrap ? [] : undefined;
28213
- }
28214
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28215
- return this._getPreferredOutput(result[0]);
28216
- }
28217
- return result.reduce((rslt, ea) => {
28218
- const valOrPath = this._getPreferredOutput(ea);
28219
- if (flatten && Array.isArray(valOrPath)) {
28220
- rslt = rslt.concat(valOrPath);
28221
- } else {
28222
- rslt.push(valOrPath);
28223
- }
28224
- return rslt;
28225
- }, []);
28226
- };
28227
- JSONPath.prototype._getPreferredOutput = function(ea) {
28228
- const resultType = this.currResultType;
28229
- switch (resultType) {
28230
- case "all": {
28231
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28232
- ea.pointer = JSONPath.toPointer(path3);
28233
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28234
- return ea;
28235
- }
28236
- case "value":
28237
- case "parent":
28238
- case "parentProperty":
28239
- return ea[resultType];
28240
- case "path":
28241
- return JSONPath.toPathString(ea[resultType]);
28242
- case "pointer":
28243
- return JSONPath.toPointer(ea.path);
28244
- default:
28245
- throw new TypeError("Unknown result type");
28246
- }
28247
- };
28248
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28249
- if (callback) {
28250
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28251
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28252
- callback(preferredOutput, type, fullRetObj);
28253
- }
28254
- };
28255
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28256
- let retObj;
28257
- if (!expr.length) {
28258
- retObj = {
28259
- path: path3,
28260
- value: val,
28261
- parent,
28262
- parentProperty: parentPropName,
28263
- hasArrExpr
28264
- };
28265
- this._handleCallback(retObj, callback, "value");
28266
- return retObj;
28267
- }
28268
- const loc = expr[0], x = expr.slice(1);
28269
- const ret = [];
28270
- function addRet(elems) {
28271
- if (Array.isArray(elems)) {
28272
- elems.forEach((t) => {
28273
- ret.push(t);
28274
- });
28275
- } else {
28276
- ret.push(elems);
28277
- }
28278
- }
28279
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28280
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28281
- } else if (loc === "*") {
28282
- this._walk(val, (m) => {
28283
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28284
- });
28285
- } else if (loc === "..") {
28286
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28287
- this._walk(val, (m) => {
28288
- if (typeof val[m] === "object") {
28289
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28290
- }
28291
- });
28292
- } else if (loc === "^") {
28293
- this._hasParentSelector = true;
28294
- return {
28295
- path: path3.slice(0, -1),
28296
- expr: x,
28297
- isParentSelector: true
28298
- };
28299
- } else if (loc === "~") {
28300
- retObj = {
28301
- path: push(path3, loc),
28302
- value: parentPropName,
28303
- parent,
28304
- parentProperty: null
28305
- };
28306
- this._handleCallback(retObj, callback, "property");
28307
- return retObj;
28308
- } else if (loc === "$") {
28309
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28310
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28311
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28312
- } else if (loc.indexOf("?(") === 0) {
28313
- if (this.currEval === false) {
28314
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28315
- }
28316
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28317
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28318
- if (nested) {
28319
- this._walk(val, (m) => {
28320
- const npath = [nested[2]];
28321
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28322
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28323
- if (filterResults.length > 0) {
28324
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28325
- }
28326
- });
28327
- } else {
28328
- this._walk(val, (m) => {
28329
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28330
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28331
- }
28332
- });
28333
- }
28334
- } else if (loc[0] === "(") {
28335
- if (this.currEval === false) {
28336
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
28337
- }
28338
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28339
- } else if (loc[0] === "@") {
28340
- let addType = false;
28341
- const valueType = loc.slice(1, -2);
28342
- switch (valueType) {
28343
- case "scalar":
28344
- if (!val || !["object", "function"].includes(typeof val)) {
28345
- addType = true;
28346
- }
28347
- break;
28348
- case "boolean":
28349
- case "string":
28350
- case "undefined":
28351
- case "function":
28352
- if (typeof val === valueType) {
28353
- addType = true;
28354
- }
28355
- break;
28356
- case "integer":
28357
- if (Number.isFinite(val) && !(val % 1)) {
28358
- addType = true;
28359
- }
28360
- break;
28361
- case "number":
28362
- if (Number.isFinite(val)) {
28363
- addType = true;
28364
- }
28365
- break;
28366
- case "nonFinite":
28367
- if (typeof val === "number" && !Number.isFinite(val)) {
28368
- addType = true;
28369
- }
28370
- break;
28371
- case "object":
28372
- if (val && typeof val === valueType) {
28373
- addType = true;
28374
- }
28375
- break;
28376
- case "array":
28377
- if (Array.isArray(val)) {
28378
- addType = true;
28379
- }
28380
- break;
28381
- case "other":
28382
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28383
- break;
28384
- case "null":
28385
- if (val === null) {
28386
- addType = true;
28387
- }
28388
- break;
28389
- default:
28390
- throw new TypeError("Unknown value type " + valueType);
28391
- }
28392
- if (addType) {
28393
- retObj = {
28394
- path: path3,
28395
- value: val,
28396
- parent,
28397
- parentProperty: parentPropName
28398
- };
28399
- this._handleCallback(retObj, callback, "value");
28400
- return retObj;
28401
- }
28402
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28403
- const locProp = loc.slice(1);
28404
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28405
- } else if (loc.includes(",")) {
28406
- const parts = loc.split(",");
28407
- for (const part of parts) {
28408
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28409
- }
28410
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28411
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28412
- }
28413
- if (this._hasParentSelector) {
28414
- for (let t = 0;t < ret.length; t++) {
28415
- const rett = ret[t];
28416
- if (rett && rett.isParentSelector) {
28417
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28418
- if (Array.isArray(tmp)) {
28419
- ret[t] = tmp[0];
28420
- const tl = tmp.length;
28421
- for (let tt = 1;tt < tl; tt++) {
28422
- t++;
28423
- ret.splice(t, 0, tmp[tt]);
28424
- }
28425
- } else {
28426
- ret[t] = tmp;
28427
- }
28428
- }
28429
- }
28430
- }
28431
- return ret;
28432
- };
28433
- JSONPath.prototype._walk = function(val, f) {
28434
- if (Array.isArray(val)) {
28435
- const n = val.length;
28436
- for (let i = 0;i < n; i++) {
28437
- f(i);
28438
- }
28439
- } else if (val && typeof val === "object") {
28440
- Object.keys(val).forEach((m) => {
28441
- f(m);
28442
- });
28443
- }
28444
- };
28445
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28446
- if (!Array.isArray(val)) {
28447
- return;
28448
- }
28449
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28450
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28451
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28452
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28453
- const ret = [];
28454
- for (let i = start;i < end; i += step) {
28455
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28456
- tmp.forEach((t) => {
28457
- ret.push(t);
28458
- });
28459
- }
28460
- return ret;
28461
- };
28462
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28463
- this.currSandbox._$_parentProperty = parentPropName;
28464
- this.currSandbox._$_parent = parent;
28465
- this.currSandbox._$_property = _vname;
28466
- this.currSandbox._$_root = this.json;
28467
- this.currSandbox._$_v = _v;
28468
- const containsPath = code.includes("@path");
28469
- if (containsPath) {
28470
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28471
- }
28472
- const scriptCacheKey = this.currEval + "Script:" + code;
28473
- if (!JSONPath.cache[scriptCacheKey]) {
28474
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28475
- if (containsPath) {
28476
- script = script.replaceAll("@path", "_$_path");
28477
- }
28478
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28479
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28480
- } else if (this.currEval === "native") {
28481
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28482
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28483
- const CurrEval = this.currEval;
28484
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28485
- } else if (typeof this.currEval === "function") {
28486
- JSONPath.cache[scriptCacheKey] = {
28487
- runInNewContext: (context) => this.currEval(script, context)
28488
- };
28489
- } else {
28490
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
28491
- }
28492
- }
28493
- try {
28494
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28495
- } catch (e) {
28496
- if (this.ignoreEvalErrors) {
28497
- return false;
28498
- }
28499
- throw new Error("jsonPath: " + e.message + ": " + code);
28500
- }
28501
- };
28502
- JSONPath.cache = {};
28503
- JSONPath.toPathString = function(pathArr) {
28504
- const x = pathArr, n = x.length;
28505
- let p = "$";
28506
- for (let i = 1;i < n; i++) {
28507
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28508
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28509
- }
28510
- }
28511
- return p;
28512
- };
28513
- JSONPath.toPointer = function(pointer) {
28514
- const x = pointer, n = x.length;
28515
- let p = "";
28516
- for (let i = 1;i < n; i++) {
28517
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28518
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
28519
- }
28520
- }
28521
- return p;
28522
- };
28523
- JSONPath.toPathArray = function(expr) {
28524
- const {
28525
- cache
28526
- } = JSONPath;
28527
- if (cache[expr]) {
28528
- return cache[expr].concat();
28529
- }
28530
- const subx = [];
28531
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28532
- return "[#" + (subx.push($1) - 1) + "]";
28533
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28534
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28535
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28536
- return ";" + ups.split("").join(";") + ";";
28537
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28538
- const exprList = normalized.split(";").map(function(exp) {
28539
- const match = exp.match(/#(\d+)/u);
28540
- return !match || !match[1] ? exp : subx[match[1]];
28541
- });
28542
- cache[expr] = exprList;
28543
- return cache[expr].concat();
28544
- };
28545
- JSONPath.prototype.safeVm = {
28546
- Script: SafeScript
28547
- };
28548
- JSONPath.prototype.vm = vm;
28549
- // ../common/src/polling/types.ts
28550
- var PollOutcome = {
28551
- Completed: "completed",
28552
- Timeout: "timeout",
28553
- Interrupted: "interrupted",
28554
- Aborted: "aborted",
28555
- Failed: "failed"
28556
- };
28557
-
28558
- // ../common/src/polling/poll-failure-mapping.ts
28559
- var REASON_BY_OUTCOME = {
28560
- [PollOutcome.Timeout]: "poll_timeout",
28561
- [PollOutcome.Failed]: "poll_failed",
28562
- [PollOutcome.Interrupted]: "poll_failed",
28563
- [PollOutcome.Aborted]: "poll_aborted"
28564
- };
28565
- // ../common/src/polling/terminal-statuses.ts
28566
- var TERMINAL_STATUSES = new Set([
28567
- "completed",
28568
- "successful",
28569
- "faulted",
28570
- "failed",
28571
- "cancelled",
28572
- "canceled",
28573
- "stopped",
28574
- "finished"
28575
- ]);
28576
- var FAILURE_STATUSES = new Set([
28577
- "faulted",
28578
- "failed",
28579
- "cancelled",
28580
- "canceled",
28581
- "stopped"
28582
- ]);
28583
- // ../common/src/screen-logger.ts
28584
- var ScreenLogger;
28585
- ((ScreenLogger) => {
28586
- function progress(message) {
28587
- getOutputSink().writeErr(`${message}
28588
- `);
28589
- }
28590
- ScreenLogger.progress = progress;
28591
- })(ScreenLogger ||= {});
28592
- // ../common/src/sdk-user-agent.ts
28593
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
28594
- // ../common/src/tool-provider.ts
28595
- var factorySlot = singleton("PackagerFactoryProvider");
28596
- // ../uipath-python-bridge/src/cache.ts
28597
- init_src();
28598
- async function readCache(cacheFile) {
28599
- const fs7 = getFileSystem();
28600
- const [existsError, exists] = await catchError(fs7.exists(cacheFile));
28601
- if (existsError || !exists)
28602
- return null;
28603
- const [readError, content] = await catchError(fs7.readFile(cacheFile, "utf-8"));
28604
- if (readError) {
28605
- logger.warn(`Failed to load cache: ${readError}`);
28606
- return null;
28607
- }
28608
- const [parseError, cache] = catchError(() => JSON.parse(content));
28609
- if (parseError) {
28610
- logger.warn(`Failed to parse cache: ${parseError}`);
28611
- return null;
28612
- }
28613
- return cache;
28614
- }
28615
- // ../uipath-python-bridge/src/config.ts
28616
- var DEFAULT_CONFIG = {
28617
- allowedPythonVersions: ["3.13", "3.12", "3.11"],
28618
- packageName: "uipath",
28619
- cacheFileName: ".uipath-python-cache.json"
28620
- };
28621
- function getAllowedPythonVersions() {
28622
- const envVersions = process.env.PYTHON_TOOL_PYTHON_VERSIONS;
28623
- if (envVersions) {
28624
- return envVersions.split(",").map((v) => v.trim()).filter(Boolean);
28625
- }
28626
- return DEFAULT_CONFIG.allowedPythonVersions;
28627
- }
28628
- function getPackageName() {
28629
- return DEFAULT_CONFIG.packageName;
28630
- }
28631
- function getCacheFileName() {
28632
- return DEFAULT_CONFIG.cacheFileName;
28633
- }
28634
- function matchesPattern(args, pattern) {
28635
- if (typeof pattern === "string") {
28636
- return args.includes(pattern);
28637
- }
28638
- if (Array.isArray(pattern)) {
28639
- for (let i = 0;i <= args.length - pattern.length; i++) {
28640
- let match = true;
28641
- for (let j = 0;j < pattern.length; j++) {
28642
- if (args[i + j] !== pattern[j]) {
28643
- match = false;
28644
- break;
28645
- }
28646
- }
28647
- if (match) {
28648
- return true;
28649
- }
28650
- }
28651
- }
28652
- return false;
28653
- }
28654
- function processCommandArgs(args, rules) {
28655
- const hasForceFlag = args.includes("--force");
28656
- const argsWithoutForce = args.filter((arg) => arg !== "--force");
28657
- for (const rule of rules) {
28658
- if (matchesPattern(argsWithoutForce, rule.pattern)) {
28659
- switch (rule.action) {
28660
- case "filter":
28661
- if (hasForceFlag) {
28662
- return {
28663
- allowed: true,
28664
- args: [...argsWithoutForce]
28665
- };
28666
- }
28667
- return {
28668
- allowed: false,
28669
- args: [],
28670
- errorMessage: rule.filterMessage || "This command is not allowed"
28671
- };
28672
- case "append":
28673
- if (rule.appendArgs && rule.appendArgs.length > 0) {
28674
- return {
28675
- allowed: true,
28676
- args: [...argsWithoutForce, ...rule.appendArgs]
28677
- };
28678
- }
28679
- break;
28680
- }
28681
- }
28682
- }
28683
- return {
28684
- allowed: true,
28685
- args: [...argsWithoutForce]
28686
- };
28687
- }
28688
- // ../uipath-python-bridge/src/execute.ts
28689
- import { spawn } from "node:child_process";
28690
-
28691
- // ../auth/src/config.ts
28692
- init_constants();
28693
- var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
28694
- var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
28695
- var globalSlot = globalThis;
28696
- var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
28697
-
28698
- class InvalidBaseUrlError extends Error {
28699
- url;
28700
- reason;
28701
- constructor(url, reason) {
28702
- super(`Invalid base URL: "${url}"
28703
- ` + `Reason: ${reason}
28704
-
28705
- ` + `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>).
28706
- ` + `You can specify the URL via:
28707
- ` + ` • --authority flag
28708
- ` + ` • UIPATH_URL environment variable
28709
- ` + ` • auth.authority in config file`);
28710
- this.url = url;
28711
- this.reason = reason;
28712
- this.name = "InvalidBaseUrlError";
28713
- }
28714
- }
28715
- var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
28716
- var normalizeAndValidateBaseUrl = (rawUrl) => {
28717
- let baseUrl = rawUrl;
28718
- if (baseUrl.endsWith("/identity_/")) {
28719
- baseUrl = baseUrl.slice(0, -11);
28720
- } else if (baseUrl.endsWith("/identity_")) {
28721
- baseUrl = baseUrl.slice(0, -10);
28722
- }
28723
- while (baseUrl.endsWith("/")) {
28724
- baseUrl = baseUrl.slice(0, -1);
28725
- }
28726
- const resolvedBaseUrl = baseUrl;
28727
- const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
28728
- if (urlError) {
28729
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
28730
- }
28731
- if (url.protocol !== "https:") {
28732
- throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
28733
- }
28734
- return url.pathname.length > 1 ? url.origin : baseUrl;
28735
- };
28736
- var resolveConfigAsync = async ({
28737
- customAuthority,
28738
- customClientId,
28739
- customClientSecret,
28740
- customScopes
28741
- } = {}) => {
28742
- const fileAuth = getAuthFileConfig();
28743
- let baseUrl = customAuthority;
28744
- if (!baseUrl) {
28745
- baseUrl = process.env.UIPATH_URL;
28746
- }
28747
- if (!baseUrl && fileAuth.authority) {
28748
- baseUrl = fileAuth.authority;
28749
- }
28750
- if (!baseUrl) {
28751
- baseUrl = DEFAULT_BASE_URL;
28752
- }
28753
- baseUrl = normalizeAndValidateBaseUrl(baseUrl);
28754
- let clientId = customClientId;
28755
- if (!clientId && fileAuth.clientId) {
28756
- clientId = fileAuth.clientId;
28757
- }
28758
- if (!clientId) {
28759
- clientId = DEFAULT_CLIENT_ID;
28760
- }
28761
- let clientSecret = customClientSecret;
28762
- if (!clientSecret && fileAuth.clientSecret) {
28763
- clientSecret = fileAuth.clientSecret;
27456
+ let clientSecret = customClientSecret;
27457
+ if (!clientSecret && fileAuth.clientSecret) {
27458
+ clientSecret = fileAuth.clientSecret;
28764
27459
  }
28765
27460
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
28766
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
27461
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
28767
27462
  return {
28768
27463
  clientId,
28769
27464
  clientSecret,
@@ -28778,6 +27473,76 @@ var resolveConfigAsync = async ({
28778
27473
  init_constants();
28779
27474
  // ../auth/src/loginStatus.ts
28780
27475
  init_src();
27476
+
27477
+ // ../auth/src/authProfile.ts
27478
+ init_src();
27479
+ init_constants();
27480
+ var DEFAULT_AUTH_PROFILE = "default";
27481
+ var PROFILE_DIR = "profiles";
27482
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
27483
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
27484
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
27485
+ var globalSlot2 = globalThis;
27486
+ function isAuthProfileStorage(value) {
27487
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
27488
+ }
27489
+ function createProfileStorage() {
27490
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
27491
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
27492
+ return {
27493
+ getStore: () => {
27494
+ return;
27495
+ },
27496
+ run: (_store, fn) => fn()
27497
+ };
27498
+ }
27499
+ return new mod2.AsyncLocalStorage;
27500
+ }
27501
+ function getProfileStorage() {
27502
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
27503
+ if (isAuthProfileStorage(existing)) {
27504
+ return existing;
27505
+ }
27506
+ const storage = createProfileStorage();
27507
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
27508
+ return storage;
27509
+ }
27510
+ var profileStorage = getProfileStorage();
27511
+
27512
+ class AuthProfileValidationError extends Error {
27513
+ constructor(message) {
27514
+ super(message);
27515
+ this.name = "AuthProfileValidationError";
27516
+ }
27517
+ }
27518
+ function normalizeAuthProfileName(profile) {
27519
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
27520
+ return;
27521
+ }
27522
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
27523
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
27524
+ }
27525
+ return profile;
27526
+ }
27527
+ function getActiveAuthProfile() {
27528
+ const scopedState = profileStorage.getStore();
27529
+ if (scopedState !== undefined) {
27530
+ return scopedState.profile;
27531
+ }
27532
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
27533
+ }
27534
+ function resolveAuthProfileFilePath(profile) {
27535
+ const normalized = normalizeAuthProfileName(profile);
27536
+ if (normalized === undefined) {
27537
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
27538
+ }
27539
+ const fs7 = getFileSystem();
27540
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR2, PROFILE_DIR, normalized, AUTH_FILENAME);
27541
+ }
27542
+ function getActiveAuthProfileFilePath() {
27543
+ const profile = getActiveAuthProfile();
27544
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
27545
+ }
28781
27546
  // ../auth/src/utils/jwt.ts
28782
27547
  class InvalidIssuerError extends Error {
28783
27548
  expected;
@@ -28906,23 +27671,74 @@ var readAuthFromEnv = () => {
28906
27671
  organizationId,
28907
27672
  tenantName,
28908
27673
  tenantId,
28909
- expiration
27674
+ expiration,
27675
+ source: "env" /* Env */
28910
27676
  };
28911
27677
  };
28912
27678
 
27679
+ // ../auth/src/refreshCircuitBreaker.ts
27680
+ init_src();
27681
+ var BREAKER_SUFFIX = ".refresh-state";
27682
+ var BACKOFF_BASE_MS = 60000;
27683
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
27684
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
27685
+ async function refreshTokenFingerprint(refreshToken) {
27686
+ const bytes = new TextEncoder().encode(refreshToken);
27687
+ if (globalThis.crypto?.subtle) {
27688
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
27689
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
27690
+ }
27691
+ const { createHash } = await import("node:crypto");
27692
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
27693
+ }
27694
+ function breakerPathFor(authPath) {
27695
+ return `${authPath}${BREAKER_SUFFIX}`;
27696
+ }
27697
+ async function loadRefreshBreaker(authPath) {
27698
+ const fs7 = getFileSystem();
27699
+ try {
27700
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
27701
+ if (!content)
27702
+ return {};
27703
+ const parsed = JSON.parse(content);
27704
+ return parsed && typeof parsed === "object" ? parsed : {};
27705
+ } catch {
27706
+ return {};
27707
+ }
27708
+ }
27709
+ async function saveRefreshBreaker(authPath, state) {
27710
+ try {
27711
+ const fs7 = getFileSystem();
27712
+ const path3 = breakerPathFor(authPath);
27713
+ await fs7.mkdir(fs7.path.dirname(path3));
27714
+ const tempPath = `${path3}.tmp`;
27715
+ await fs7.writeFile(tempPath, JSON.stringify(state));
27716
+ await fs7.rename(tempPath, path3);
27717
+ } catch {}
27718
+ }
27719
+ async function clearRefreshBreaker(authPath) {
27720
+ const fs7 = getFileSystem();
27721
+ const path3 = breakerPathFor(authPath);
27722
+ try {
27723
+ if (await fs7.exists(path3)) {
27724
+ await fs7.rm(path3);
27725
+ }
27726
+ } catch {}
27727
+ }
27728
+ function nextBackoffMs(attempts) {
27729
+ const shift = Math.max(0, attempts - 1);
27730
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
27731
+ }
27732
+ function shouldSurface(state, nowMs) {
27733
+ if (state.lastSurfacedAtMs === undefined)
27734
+ return true;
27735
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
27736
+ }
27737
+
28913
27738
  // ../auth/src/robotClientFallback.ts
28914
27739
  init_src();
28915
27740
  var DEFAULT_TIMEOUT_MS = 1000;
28916
27741
  var CLOSE_TIMEOUT_MS = 500;
28917
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
28918
- var printNoticeOnce = () => {
28919
- const slot = globalThis;
28920
- if (slot[NOTICE_SENTINEL])
28921
- return;
28922
- slot[NOTICE_SENTINEL] = true;
28923
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
28924
- `));
28925
- };
28926
27742
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
28927
27743
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
28928
27744
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -29038,7 +27854,6 @@ var tryRobotClientFallback = async (options = {}) => {
29038
27854
  issuerFromToken = issClaim;
29039
27855
  }
29040
27856
  }
29041
- printNoticeOnce();
29042
27857
  return {
29043
27858
  accessToken,
29044
27859
  baseUrl: parsedUrl.baseUrl,
@@ -29263,18 +28078,327 @@ var saveEnvFileAsync = async ({
29263
28078
  };
29264
28079
 
29265
28080
  // ../auth/src/loginStatus.ts
29266
- function normalizeTokenRefreshFailure() {
29267
- return "stored refresh token is invalid or expired";
28081
+ var getLoginStatusAsync = async (options = {}) => {
28082
+ return getLoginStatusWithDeps(options);
28083
+ };
28084
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
28085
+ const {
28086
+ resolveEnvFilePath = resolveEnvFilePathAsync,
28087
+ loadEnvFile = loadEnvFileAsync,
28088
+ saveEnvFile = saveEnvFileAsync,
28089
+ getFs = getFileSystem,
28090
+ refreshToken: refreshTokenFn = refreshAccessToken,
28091
+ resolveConfig = resolveConfigAsync,
28092
+ robotFallback = tryRobotClientFallback,
28093
+ loadBreaker = loadRefreshBreaker,
28094
+ saveBreaker = saveRefreshBreaker,
28095
+ clearBreaker = clearRefreshBreaker
28096
+ } = deps;
28097
+ if (isRobotAuthEnforced()) {
28098
+ return resolveRobotEnforcedStatus(robotFallback);
28099
+ }
28100
+ if (isEnvAuthEnabled()) {
28101
+ return readAuthFromEnv();
28102
+ }
28103
+ const activeProfile = getActiveAuthProfile();
28104
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
28105
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
28106
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
28107
+ const { ensureTokenValidityMinutes } = options;
28108
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
28109
+ if (absolutePath === undefined) {
28110
+ if (usingActiveProfile) {
28111
+ return {
28112
+ loginStatus: "Not logged in",
28113
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
28114
+ };
28115
+ }
28116
+ return resolveBorrowedRobotStatus(robotFallback);
28117
+ }
28118
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
28119
+ if ("status" in loaded) {
28120
+ return loaded.status;
28121
+ }
28122
+ const { credentials } = loaded;
28123
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
28124
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
28125
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
28126
+ let tokens = {
28127
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
28128
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
28129
+ expiration,
28130
+ lockReleaseFailed: false
28131
+ };
28132
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
28133
+ if (expiration && expiration <= outerThreshold && refreshToken) {
28134
+ const refreshed = await attemptRefresh({
28135
+ absolutePath,
28136
+ credentials,
28137
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
28138
+ refreshToken,
28139
+ expiration,
28140
+ ensureTokenValidityMinutes,
28141
+ getFs,
28142
+ loadEnvFile,
28143
+ saveEnvFile,
28144
+ refreshFn: refreshTokenFn,
28145
+ resolveConfig,
28146
+ loadBreaker,
28147
+ saveBreaker,
28148
+ clearBreaker,
28149
+ globalHint
28150
+ });
28151
+ if (refreshed.kind === "terminal") {
28152
+ return refreshed.status;
28153
+ }
28154
+ tokens = refreshed.tokens;
28155
+ }
28156
+ return buildFileStatus(tokens, credentials, globalHint);
28157
+ };
28158
+ async function resolveRobotEnforcedStatus(robotFallback) {
28159
+ if (isEnvAuthEnabled()) {
28160
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
28161
+ }
28162
+ const robotCreds = await robotFallback({ force: true });
28163
+ if (!robotCreds) {
28164
+ return {
28165
+ loginStatus: "Not logged in",
28166
+ 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.`
28167
+ };
28168
+ }
28169
+ return buildRobotStatus(robotCreds);
29268
28170
  }
29269
- function normalizeTokenRefreshUnavailableFailure() {
29270
- return "token refresh failed before authentication completed";
28171
+ async function resolveBorrowedRobotStatus(robotFallback) {
28172
+ const robotCreds = await robotFallback();
28173
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
29271
28174
  }
29272
- function errorMessage(error) {
29273
- return error instanceof Error ? error.message : String(error);
28175
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
28176
+ let credentials;
28177
+ try {
28178
+ credentials = await loadEnvFile({ envPath: absolutePath });
28179
+ } catch (error) {
28180
+ if (isFileNotFoundError(error)) {
28181
+ return { status: { loginStatus: "Not logged in" } };
28182
+ }
28183
+ throw error;
28184
+ }
28185
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
28186
+ return { status: { loginStatus: "Not logged in" } };
28187
+ }
28188
+ return { credentials };
28189
+ }
28190
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
28191
+ const fs7 = getFs();
28192
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
28193
+ if (absolutePath === globalPath)
28194
+ return;
28195
+ if (!await fs7.exists(globalPath))
28196
+ return;
28197
+ try {
28198
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
28199
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
28200
+ return;
28201
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
28202
+ if (globalExp && globalExp <= new Date)
28203
+ return;
28204
+ 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.`;
28205
+ } catch {
28206
+ return;
28207
+ }
29274
28208
  }
29275
28209
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
29276
28210
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
29277
28211
  }
28212
+ async function attemptRefresh(ctx) {
28213
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
28214
+ if (shortCircuit) {
28215
+ return { kind: "terminal", status: shortCircuit };
28216
+ }
28217
+ let release;
28218
+ try {
28219
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
28220
+ } catch (error) {
28221
+ return {
28222
+ kind: "terminal",
28223
+ status: await lockAcquireFailureStatus(ctx, error)
28224
+ };
28225
+ }
28226
+ let lockedFailure;
28227
+ let lockReleaseFailed = false;
28228
+ let success;
28229
+ try {
28230
+ const outcome = await runRefreshLocked({
28231
+ absolutePath: ctx.absolutePath,
28232
+ refreshToken: ctx.refreshToken,
28233
+ customAuthority: ctx.credentials.UIPATH_URL,
28234
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
28235
+ loadEnvFile: ctx.loadEnvFile,
28236
+ saveEnvFile: ctx.saveEnvFile,
28237
+ refreshFn: ctx.refreshFn,
28238
+ resolveConfig: ctx.resolveConfig,
28239
+ loadBreaker: ctx.loadBreaker,
28240
+ saveBreaker: ctx.saveBreaker,
28241
+ clearBreaker: ctx.clearBreaker
28242
+ });
28243
+ if (outcome.kind === "fail") {
28244
+ lockedFailure = outcome.status;
28245
+ } else {
28246
+ success = outcome;
28247
+ }
28248
+ } finally {
28249
+ try {
28250
+ await release();
28251
+ } catch {
28252
+ lockReleaseFailed = true;
28253
+ }
28254
+ }
28255
+ if (lockedFailure) {
28256
+ const globalHint = await ctx.globalHint();
28257
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
28258
+ return {
28259
+ kind: "terminal",
28260
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
28261
+ };
28262
+ }
28263
+ return {
28264
+ kind: "refreshed",
28265
+ tokens: {
28266
+ accessToken: success?.accessToken,
28267
+ refreshToken: success?.refreshToken,
28268
+ expiration: success?.expiration,
28269
+ tokenRefresh: success?.tokenRefresh,
28270
+ persistenceWarning: success?.persistenceWarning,
28271
+ lockReleaseFailed
28272
+ }
28273
+ };
28274
+ }
28275
+ async function buildFileStatus(tokens, credentials, globalHint) {
28276
+ const result = {
28277
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
28278
+ accessToken: tokens.accessToken,
28279
+ refreshToken: tokens.refreshToken,
28280
+ baseUrl: credentials.UIPATH_URL,
28281
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28282
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28283
+ tenantName: credentials.UIPATH_TENANT_NAME,
28284
+ tenantId: credentials.UIPATH_TENANT_ID,
28285
+ expiration: tokens.expiration,
28286
+ source: "file" /* File */,
28287
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
28288
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
28289
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
28290
+ };
28291
+ if (result.loginStatus === "Expired") {
28292
+ const hint = await globalHint();
28293
+ if (hint) {
28294
+ result.hint = hint;
28295
+ }
28296
+ }
28297
+ return result;
28298
+ }
28299
+ function buildRobotStatus(robotCreds) {
28300
+ return {
28301
+ loginStatus: "Logged in",
28302
+ accessToken: robotCreds.accessToken,
28303
+ baseUrl: robotCreds.baseUrl,
28304
+ organizationName: robotCreds.organizationName,
28305
+ organizationId: robotCreds.organizationId,
28306
+ tenantName: robotCreds.tenantName,
28307
+ tenantId: robotCreds.tenantId,
28308
+ issuer: robotCreds.issuer,
28309
+ expiration: getTokenExpiration(robotCreds.accessToken),
28310
+ source: "robot" /* Robot */
28311
+ };
28312
+ }
28313
+ var isFileNotFoundError = (error) => {
28314
+ if (!(error instanceof Object))
28315
+ return false;
28316
+ return error.code === "ENOENT";
28317
+ };
28318
+ async function circuitBreakerShortCircuit(ctx) {
28319
+ const {
28320
+ absolutePath,
28321
+ refreshToken,
28322
+ accessToken,
28323
+ credentials,
28324
+ expiration,
28325
+ loadBreaker,
28326
+ saveBreaker,
28327
+ clearBreaker
28328
+ } = ctx;
28329
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
28330
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
28331
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
28332
+ await clearBreaker(absolutePath);
28333
+ breaker.deadTokenFp = undefined;
28334
+ }
28335
+ const nowMs = Date.now();
28336
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
28337
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
28338
+ if (!tokenIsDead && !inBackoff)
28339
+ return;
28340
+ const globalHint = await ctx.globalHint();
28341
+ const suppressed = !shouldSurface(breaker, nowMs);
28342
+ if (!suppressed) {
28343
+ await saveBreaker(absolutePath, {
28344
+ ...breaker,
28345
+ lastSurfacedAtMs: nowMs
28346
+ });
28347
+ }
28348
+ 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>.";
28349
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
28350
+ return {
28351
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
28352
+ ...globalHint ? {
28353
+ accessToken,
28354
+ refreshToken,
28355
+ baseUrl: credentials.UIPATH_URL,
28356
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
28357
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
28358
+ tenantName: credentials.UIPATH_TENANT_NAME,
28359
+ tenantId: credentials.UIPATH_TENANT_ID,
28360
+ expiration,
28361
+ source: "file" /* File */
28362
+ } : {},
28363
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
28364
+ refreshCircuitOpen: true,
28365
+ refreshTelemetrySuppressed: suppressed,
28366
+ tokenRefresh: { attempted: false, success: false }
28367
+ };
28368
+ }
28369
+ async function lockAcquireFailureStatus(ctx, error) {
28370
+ const msg = errorMessage(error);
28371
+ const globalHint = await ctx.globalHint();
28372
+ if (globalHint) {
28373
+ return {
28374
+ loginStatus: "Expired",
28375
+ accessToken: ctx.accessToken,
28376
+ refreshToken: ctx.refreshToken,
28377
+ baseUrl: ctx.credentials.UIPATH_URL,
28378
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
28379
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
28380
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
28381
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
28382
+ expiration: ctx.expiration,
28383
+ source: "file" /* File */,
28384
+ hint: globalHint,
28385
+ tokenRefresh: {
28386
+ attempted: false,
28387
+ success: false,
28388
+ errorMessage: `lock acquisition failed: ${msg}`
28389
+ }
28390
+ };
28391
+ }
28392
+ return {
28393
+ loginStatus: "Refresh Failed",
28394
+ 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.",
28395
+ tokenRefresh: {
28396
+ attempted: false,
28397
+ success: false,
28398
+ errorMessage: `lock acquisition failed: ${msg}`
28399
+ }
28400
+ };
28401
+ }
29278
28402
  async function runRefreshLocked(inputs) {
29279
28403
  const {
29280
28404
  absolutePath,
@@ -29284,7 +28408,10 @@ async function runRefreshLocked(inputs) {
29284
28408
  loadEnvFile,
29285
28409
  saveEnvFile,
29286
28410
  refreshFn,
29287
- resolveConfig
28411
+ resolveConfig,
28412
+ loadBreaker,
28413
+ saveBreaker,
28414
+ clearBreaker
29288
28415
  } = inputs;
29289
28416
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29290
28417
  let fresh;
@@ -29307,6 +28434,7 @@ async function runRefreshLocked(inputs) {
29307
28434
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
29308
28435
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
29309
28436
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
28437
+ await clearBreaker(absolutePath);
29310
28438
  return {
29311
28439
  kind: "ok",
29312
28440
  accessToken: freshAccess,
@@ -29330,8 +28458,21 @@ async function runRefreshLocked(inputs) {
29330
28458
  refreshedRefresh = refreshed.refreshToken;
29331
28459
  } catch (error) {
29332
28460
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
29333
- 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.";
28461
+ 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.";
29334
28462
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
28463
+ const fp = await refreshTokenFingerprint(tokenForIdP);
28464
+ if (isOAuthFailure) {
28465
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
28466
+ } else {
28467
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
28468
+ const attempts = (prior.attempts ?? 0) + 1;
28469
+ await saveBreaker(absolutePath, {
28470
+ ...prior,
28471
+ deadTokenFp: undefined,
28472
+ attempts,
28473
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
28474
+ });
28475
+ }
29335
28476
  return {
29336
28477
  kind: "fail",
29337
28478
  status: {
@@ -29360,6 +28501,7 @@ async function runRefreshLocked(inputs) {
29360
28501
  }
29361
28502
  };
29362
28503
  }
28504
+ await clearBreaker(absolutePath);
29363
28505
  try {
29364
28506
  await saveEnvFile({
29365
28507
  envPath: absolutePath,
@@ -29392,212 +28534,15 @@ async function runRefreshLocked(inputs) {
29392
28534
  };
29393
28535
  }
29394
28536
  }
29395
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
29396
- const {
29397
- resolveEnvFilePath = resolveEnvFilePathAsync,
29398
- loadEnvFile = loadEnvFileAsync,
29399
- saveEnvFile = saveEnvFileAsync,
29400
- getFs = getFileSystem,
29401
- refreshToken: refreshTokenFn = refreshAccessToken,
29402
- resolveConfig = resolveConfigAsync,
29403
- robotFallback = tryRobotClientFallback
29404
- } = deps;
29405
- if (isRobotAuthEnforced()) {
29406
- if (isEnvAuthEnabled()) {
29407
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
29408
- }
29409
- const robotCreds = await robotFallback({ force: true });
29410
- if (!robotCreds) {
29411
- return {
29412
- loginStatus: "Not logged in",
29413
- 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.`
29414
- };
29415
- }
29416
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29417
- return {
29418
- loginStatus: "Logged in",
29419
- accessToken: robotCreds.accessToken,
29420
- baseUrl: robotCreds.baseUrl,
29421
- organizationName: robotCreds.organizationName,
29422
- organizationId: robotCreds.organizationId,
29423
- tenantName: robotCreds.tenantName,
29424
- tenantId: robotCreds.tenantId,
29425
- issuer: robotCreds.issuer,
29426
- expiration: expiration2,
29427
- source: "robot" /* Robot */
29428
- };
29429
- }
29430
- if (isEnvAuthEnabled()) {
29431
- return readAuthFromEnv();
29432
- }
29433
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
29434
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
29435
- if (absolutePath === undefined) {
29436
- const robotCreds = await robotFallback();
29437
- if (robotCreds) {
29438
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
29439
- const status = {
29440
- loginStatus: "Logged in",
29441
- accessToken: robotCreds.accessToken,
29442
- baseUrl: robotCreds.baseUrl,
29443
- organizationName: robotCreds.organizationName,
29444
- organizationId: robotCreds.organizationId,
29445
- tenantName: robotCreds.tenantName,
29446
- tenantId: robotCreds.tenantId,
29447
- issuer: robotCreds.issuer,
29448
- expiration: expiration2,
29449
- source: "robot" /* Robot */
29450
- };
29451
- return status;
29452
- }
29453
- return { loginStatus: "Not logged in" };
29454
- }
29455
- let credentials;
29456
- try {
29457
- credentials = await loadEnvFile({ envPath: absolutePath });
29458
- } catch (error) {
29459
- if (isFileNotFoundError(error)) {
29460
- return { loginStatus: "Not logged in" };
29461
- }
29462
- throw error;
29463
- }
29464
- if (!credentials.UIPATH_ACCESS_TOKEN) {
29465
- return { loginStatus: "Not logged in" };
29466
- }
29467
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
29468
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
29469
- let expiration = getTokenExpiration(accessToken);
29470
- let persistenceWarning;
29471
- let lockReleaseFailed = false;
29472
- let tokenRefresh;
29473
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
29474
- const tryGlobalCredsHint = async () => {
29475
- const fs7 = getFs();
29476
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
29477
- if (absolutePath === globalPath)
29478
- return;
29479
- if (!await fs7.exists(globalPath))
29480
- return;
29481
- try {
29482
- const globalCreds = await loadEnvFile({ envPath: globalPath });
29483
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
29484
- return;
29485
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
29486
- if (globalExp && globalExp <= new Date)
29487
- return;
29488
- 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.`;
29489
- } catch {
29490
- return;
29491
- }
29492
- };
29493
- if (expiration && expiration <= outerThreshold && refreshToken) {
29494
- let release;
29495
- try {
29496
- release = await getFs().acquireLock(absolutePath);
29497
- } catch (error) {
29498
- const msg = errorMessage(error);
29499
- const globalHint = await tryGlobalCredsHint();
29500
- if (globalHint) {
29501
- return {
29502
- loginStatus: "Expired",
29503
- accessToken,
29504
- refreshToken,
29505
- baseUrl: credentials.UIPATH_URL,
29506
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29507
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29508
- tenantName: credentials.UIPATH_TENANT_NAME,
29509
- tenantId: credentials.UIPATH_TENANT_ID,
29510
- expiration,
29511
- source: "file" /* File */,
29512
- hint: globalHint,
29513
- tokenRefresh: {
29514
- attempted: false,
29515
- success: false,
29516
- errorMessage: `lock acquisition failed: ${msg}`
29517
- }
29518
- };
29519
- }
29520
- return {
29521
- loginStatus: "Refresh Failed",
29522
- 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.",
29523
- tokenRefresh: {
29524
- attempted: false,
29525
- success: false,
29526
- errorMessage: `lock acquisition failed: ${msg}`
29527
- }
29528
- };
29529
- }
29530
- let lockedFailure;
29531
- try {
29532
- const outcome = await runRefreshLocked({
29533
- absolutePath,
29534
- refreshToken,
29535
- customAuthority: credentials.UIPATH_URL,
29536
- ensureTokenValidityMinutes,
29537
- loadEnvFile,
29538
- saveEnvFile,
29539
- refreshFn: refreshTokenFn,
29540
- resolveConfig
29541
- });
29542
- if (outcome.kind === "fail") {
29543
- lockedFailure = outcome.status;
29544
- } else {
29545
- accessToken = outcome.accessToken;
29546
- refreshToken = outcome.refreshToken;
29547
- expiration = outcome.expiration;
29548
- tokenRefresh = outcome.tokenRefresh;
29549
- if (outcome.persistenceWarning) {
29550
- persistenceWarning = outcome.persistenceWarning;
29551
- }
29552
- }
29553
- } finally {
29554
- try {
29555
- await release();
29556
- } catch {
29557
- lockReleaseFailed = true;
29558
- }
29559
- }
29560
- if (lockedFailure) {
29561
- const globalHint = await tryGlobalCredsHint();
29562
- const base = globalHint ? {
29563
- ...lockedFailure,
29564
- loginStatus: "Expired",
29565
- hint: globalHint
29566
- } : lockedFailure;
29567
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
29568
- }
29569
- }
29570
- const result = {
29571
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
29572
- accessToken,
29573
- refreshToken,
29574
- baseUrl: credentials.UIPATH_URL,
29575
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
29576
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
29577
- tenantName: credentials.UIPATH_TENANT_NAME,
29578
- tenantId: credentials.UIPATH_TENANT_ID,
29579
- expiration,
29580
- source: "file" /* File */,
29581
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
29582
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
29583
- ...tokenRefresh ? { tokenRefresh } : {}
29584
- };
29585
- if (result.loginStatus === "Expired") {
29586
- const globalHint = await tryGlobalCredsHint();
29587
- if (globalHint) {
29588
- result.hint = globalHint;
29589
- }
29590
- }
29591
- return result;
29592
- };
29593
- var isFileNotFoundError = (error) => {
29594
- if (!(error instanceof Object))
29595
- return false;
29596
- return error.code === "ENOENT";
29597
- };
29598
- var getLoginStatusAsync = async (options = {}) => {
29599
- return getLoginStatusWithDeps(options);
29600
- };
28537
+ function normalizeTokenRefreshFailure() {
28538
+ return "stored refresh token is invalid or expired";
28539
+ }
28540
+ function normalizeTokenRefreshUnavailableFailure() {
28541
+ return "token refresh failed before authentication completed";
28542
+ }
28543
+ function errorMessage(error) {
28544
+ return error instanceof Error ? error.message : String(error);
28545
+ }
29601
28546
 
29602
28547
  // ../auth/src/authContext.ts
29603
28548
  var getAuthEnv = async (options = {}) => {
@@ -29630,6 +28575,14 @@ var getAuthEnv = async (options = {}) => {
29630
28575
  };
29631
28576
  // ../auth/src/interactive.ts
29632
28577
  init_src();
28578
+
28579
+ // ../auth/src/selectTenant.ts
28580
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
28581
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
28582
+ var TENANT_SELECTION_CODES = new Set([
28583
+ TENANT_SELECTION_REQUIRED_CODE,
28584
+ INVALID_TENANT_CODE
28585
+ ]);
29633
28586
  // ../auth/src/logout.ts
29634
28587
  init_src();
29635
28588
 
@@ -29695,13 +28648,13 @@ var fail = (reason, message, instructions, extras = {}) => ({
29695
28648
  async function runUipathPythonCommand(args, options = {}) {
29696
28649
  const fs7 = getFileSystem();
29697
28650
  const cacheFile = fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, getCacheFileName());
29698
- const setupHint = options.commandPrefix ? `Run 'uip ${options.commandPrefix} setup' first to configure environment.` : "Run setup first to configure environment.";
28651
+ const setupHint = `Run 'uip ${options.commandPrefix ?? "codedagent"} setup' first to configure the environment. ` + "If you are using a virtual environment, activate it first.";
29699
28652
  const cache = await readCache(cacheFile);
29700
28653
  if (!cache?.uipathExePath) {
29701
28654
  return fail("python_not_configured", "Python not configured.", setupHint);
29702
28655
  }
29703
28656
  if (!await fs7.exists(cache.uipathExePath)) {
29704
- return fail("uipath_exe_missing", "uipath executable not found.", setupHint);
28657
+ return fail("uipath_exe_missing", "uipath executable not found. Please install it using 'pip install uipath' or 'uv add uipath'.", setupHint);
29705
28658
  }
29706
28659
  const processed = processCommandArgs(args, options.commandRules ?? []);
29707
28660
  if (!processed.allowed) {
@@ -30314,7 +29267,7 @@ function createCommandForwarder(executeCommand) {
30314
29267
  var package_default = {
30315
29268
  name: "@uipath/context-grounding-tool",
30316
29269
  license: "MIT",
30317
- version: "1.196.0",
29270
+ version: "1.197.0-preview.59",
30318
29271
  description: "Tool for context grounding operations via the UiPath Python SDK",
30319
29272
  keywords: [
30320
29273
  "uipcli-tool",
@@ -30416,3 +29369,5 @@ export {
30416
29369
  registerCommands,
30417
29370
  metadata
30418
29371
  };
29372
+
29373
+ //# debugId=BAF9336AFB4BFE5264756E2164756E21