@uipath/docsai-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 +858 -1873
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -13533,8 +13533,8 @@ var require_Subscription = __commonJS((exports) => {
13533
13533
  if (_parentOrParents instanceof Subscription2) {
13534
13534
  _parentOrParents.remove(this);
13535
13535
  } else if (_parentOrParents !== null) {
13536
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
13537
- var parent_1 = _parentOrParents[index2];
13536
+ for (var index = 0;index < _parentOrParents.length; ++index) {
13537
+ var parent_1 = _parentOrParents[index];
13538
13538
  parent_1.remove(this);
13539
13539
  }
13540
13540
  }
@@ -13549,10 +13549,10 @@ var require_Subscription = __commonJS((exports) => {
13549
13549
  }
13550
13550
  }
13551
13551
  if (isArray_1.isArray(_subscriptions)) {
13552
- var index2 = -1;
13552
+ var index = -1;
13553
13553
  var len = _subscriptions.length;
13554
- while (++index2 < len) {
13555
- var sub2 = _subscriptions[index2];
13554
+ while (++index < len) {
13555
+ var sub2 = _subscriptions[index];
13556
13556
  if (isObject_1.isObject(sub2)) {
13557
13557
  try {
13558
13558
  sub2.unsubscribe();
@@ -14982,13 +14982,13 @@ var require_AsyncAction = __commonJS((exports) => {
14982
14982
  var id = this.id;
14983
14983
  var scheduler = this.scheduler;
14984
14984
  var actions = scheduler.actions;
14985
- var index2 = actions.indexOf(this);
14985
+ var index = actions.indexOf(this);
14986
14986
  this.work = null;
14987
14987
  this.state = null;
14988
14988
  this.pending = false;
14989
14989
  this.scheduler = null;
14990
- if (index2 !== -1) {
14991
- actions.splice(index2, 1);
14990
+ if (index !== -1) {
14991
+ actions.splice(index, 1);
14992
14992
  }
14993
14993
  if (id != null) {
14994
14994
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -15832,17 +15832,17 @@ var require_AsapScheduler = __commonJS((exports) => {
15832
15832
  this.scheduled = undefined;
15833
15833
  var actions = this.actions;
15834
15834
  var error;
15835
- var index2 = -1;
15835
+ var index = -1;
15836
15836
  var count = actions.length;
15837
15837
  action = action || actions.shift();
15838
15838
  do {
15839
15839
  if (error = action.execute(action.state, action.delay)) {
15840
15840
  break;
15841
15841
  }
15842
- } while (++index2 < count && (action = actions.shift()));
15842
+ } while (++index < count && (action = actions.shift()));
15843
15843
  this.active = false;
15844
15844
  if (error) {
15845
- while (++index2 < count && (action = actions.shift())) {
15845
+ while (++index < count && (action = actions.shift())) {
15846
15846
  action.unsubscribe();
15847
15847
  }
15848
15848
  throw error;
@@ -15965,17 +15965,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
15965
15965
  this.scheduled = undefined;
15966
15966
  var actions = this.actions;
15967
15967
  var error;
15968
- var index2 = -1;
15968
+ var index = -1;
15969
15969
  var count = actions.length;
15970
15970
  action = action || actions.shift();
15971
15971
  do {
15972
15972
  if (error = action.execute(action.state, action.delay)) {
15973
15973
  break;
15974
15974
  }
15975
- } while (++index2 < count && (action = actions.shift()));
15975
+ } while (++index < count && (action = actions.shift()));
15976
15976
  this.active = false;
15977
15977
  if (error) {
15978
- while (++index2 < count && (action = actions.shift())) {
15978
+ while (++index < count && (action = actions.shift())) {
15979
15979
  action.unsubscribe();
15980
15980
  }
15981
15981
  throw error;
@@ -16059,16 +16059,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
16059
16059
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
16060
16060
  var VirtualAction = function(_super) {
16061
16061
  __extends(VirtualAction2, _super);
16062
- function VirtualAction2(scheduler, work, index2) {
16063
- if (index2 === undefined) {
16064
- index2 = scheduler.index += 1;
16062
+ function VirtualAction2(scheduler, work, index) {
16063
+ if (index === undefined) {
16064
+ index = scheduler.index += 1;
16065
16065
  }
16066
16066
  var _this = _super.call(this, scheduler, work) || this;
16067
16067
  _this.scheduler = scheduler;
16068
16068
  _this.work = work;
16069
- _this.index = index2;
16069
+ _this.index = index;
16070
16070
  _this.active = true;
16071
- _this.index = scheduler.index = index2;
16071
+ _this.index = scheduler.index = index;
16072
16072
  return _this;
16073
16073
  }
16074
16074
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -17215,9 +17215,9 @@ var require_mergeMap = __commonJS((exports) => {
17215
17215
  };
17216
17216
  MergeMapSubscriber2.prototype._tryNext = function(value) {
17217
17217
  var result;
17218
- var index2 = this.index++;
17218
+ var index = this.index++;
17219
17219
  try {
17220
- result = this.project(value, index2);
17220
+ result = this.project(value, index);
17221
17221
  } catch (err) {
17222
17222
  this.destination.error(err);
17223
17223
  return;
@@ -17797,12 +17797,12 @@ var require_pairs2 = __commonJS((exports) => {
17797
17797
  }
17798
17798
  exports.pairs = pairs;
17799
17799
  function dispatch(state) {
17800
- var { keys, index: index2, subscriber, subscription, obj } = state;
17800
+ var { keys, index, subscriber, subscription, obj } = state;
17801
17801
  if (!subscriber.closed) {
17802
- if (index2 < keys.length) {
17803
- var key = keys[index2];
17802
+ if (index < keys.length) {
17803
+ var key = keys[index];
17804
17804
  subscriber.next([key, obj[key]]);
17805
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
17805
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
17806
17806
  } else {
17807
17807
  subscriber.complete();
17808
17808
  }
@@ -18015,18 +18015,18 @@ var require_range = __commonJS((exports) => {
18015
18015
  count = start;
18016
18016
  start = 0;
18017
18017
  }
18018
- var index2 = 0;
18018
+ var index = 0;
18019
18019
  var current = start;
18020
18020
  if (scheduler) {
18021
18021
  return scheduler.schedule(dispatch, 0, {
18022
- index: index2,
18022
+ index,
18023
18023
  count,
18024
18024
  start,
18025
18025
  subscriber
18026
18026
  });
18027
18027
  } else {
18028
18028
  do {
18029
- if (index2++ >= count) {
18029
+ if (index++ >= count) {
18030
18030
  subscriber.complete();
18031
18031
  break;
18032
18032
  }
@@ -18041,8 +18041,8 @@ var require_range = __commonJS((exports) => {
18041
18041
  }
18042
18042
  exports.range = range;
18043
18043
  function dispatch(state) {
18044
- var { start, index: index2, count, subscriber } = state;
18045
- if (index2 >= count) {
18044
+ var { start, index, count, subscriber } = state;
18045
+ if (index >= count) {
18046
18046
  subscriber.complete();
18047
18047
  return;
18048
18048
  }
@@ -18050,7 +18050,7 @@ var require_range = __commonJS((exports) => {
18050
18050
  if (subscriber.closed) {
18051
18051
  return;
18052
18052
  }
18053
- state.index = index2 + 1;
18053
+ state.index = index + 1;
18054
18054
  state.start = start + 1;
18055
18055
  this.schedule(state);
18056
18056
  }
@@ -18088,14 +18088,14 @@ var require_timer = __commonJS((exports) => {
18088
18088
  }
18089
18089
  exports.timer = timer;
18090
18090
  function dispatch(state) {
18091
- var { index: index2, period, subscriber } = state;
18092
- subscriber.next(index2);
18091
+ var { index, period, subscriber } = state;
18092
+ subscriber.next(index);
18093
18093
  if (subscriber.closed) {
18094
18094
  return;
18095
18095
  } else if (period === -1) {
18096
18096
  return subscriber.complete();
18097
18097
  }
18098
- state.index = index2 + 1;
18098
+ state.index = index + 1;
18099
18099
  this.schedule(state, period);
18100
18100
  }
18101
18101
  });
@@ -27802,7 +27802,7 @@ var require_dist2 = __commonJS((exports, module) => {
27802
27802
  var package_default = {
27803
27803
  name: "@uipath/docsai-tool",
27804
27804
  license: "MIT",
27805
- version: "1.196.0",
27805
+ version: "1.197.0-preview.59",
27806
27806
  description: "Search UiPath documentation with AI-powered answers.",
27807
27807
  private: false,
27808
27808
  repository: {
@@ -27889,6 +27889,18 @@ var NETWORK_ERROR_CODES = new Set([
27889
27889
  "ENETUNREACH",
27890
27890
  "EAI_FAIL"
27891
27891
  ]);
27892
+ var TLS_ERROR_CODES = new Set([
27893
+ "SELF_SIGNED_CERT_IN_CHAIN",
27894
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
27895
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
27896
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
27897
+ "UNABLE_TO_GET_ISSUER_CERT",
27898
+ "CERT_HAS_EXPIRED",
27899
+ "CERT_UNTRUSTED",
27900
+ "ERR_TLS_CERT_ALTNAME_INVALID"
27901
+ ]);
27902
+ 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.";
27903
+ 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.";
27892
27904
  function extractErrorMessageSync(error) {
27893
27905
  if (error instanceof Error) {
27894
27906
  return error.message;
@@ -27977,6 +27989,7 @@ var CONSOLE_FALLBACK = {
27977
27989
  writeLog: (str) => process.stdout.write(str),
27978
27990
  capabilities: {
27979
27991
  isInteractive: false,
27992
+ canReadInput: false,
27980
27993
  supportsColor: false,
27981
27994
  outputWidth: 80
27982
27995
  }
@@ -33177,6 +33190,29 @@ function isPlainRecord(value) {
33177
33190
  const prototype = Object.getPrototypeOf(value);
33178
33191
  return prototype === Object.prototype || prototype === null;
33179
33192
  }
33193
+ function extractPagedRows(value) {
33194
+ if (Array.isArray(value) || !isPlainRecord(value))
33195
+ return null;
33196
+ const entries = Object.values(value);
33197
+ if (entries.length === 0)
33198
+ return null;
33199
+ let rows = null;
33200
+ let hasScalarSibling = false;
33201
+ for (const entry of entries) {
33202
+ if (Array.isArray(entry)) {
33203
+ if (rows !== null)
33204
+ return null;
33205
+ rows = entry;
33206
+ } else if (entry !== null && typeof entry === "object") {
33207
+ return null;
33208
+ } else {
33209
+ hasScalarSibling = true;
33210
+ }
33211
+ }
33212
+ if (rows === null || !hasScalarSibling)
33213
+ return null;
33214
+ return rows;
33215
+ }
33180
33216
  function toLowerCamelCaseKey(key) {
33181
33217
  if (!key)
33182
33218
  return key;
@@ -33241,7 +33277,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
33241
33277
  break;
33242
33278
  case "plain": {
33243
33279
  if ("Data" in data && data.Data != null) {
33244
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
33280
+ const pagedRows = extractPagedRows(data.Data);
33281
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
33245
33282
  items.forEach((item) => {
33246
33283
  const values = Object.values(item).map((v) => v ?? "").join("\t");
33247
33284
  logFn(values);
@@ -33253,10 +33290,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
33253
33290
  break;
33254
33291
  }
33255
33292
  default: {
33256
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
33293
+ const hasData = "Data" in data && data.Data != null;
33294
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
33295
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
33296
+ if (hasData && !(rows !== null && rows.length === 0)) {
33257
33297
  const logValue = data.Log;
33258
- if (Array.isArray(data.Data)) {
33259
- printResizableTable(data.Data, logFn, logValue);
33298
+ if (rows !== null) {
33299
+ printResizableTable(rows, logFn, logValue);
33260
33300
  } else {
33261
33301
  printVerticalTable(data.Data, logFn, logValue);
33262
33302
  }
@@ -33444,6 +33484,44 @@ function defaultErrorCodeForResult(result) {
33444
33484
  return "unknown_error";
33445
33485
  }
33446
33486
  }
33487
+ function parseHttpStatusFromMessage(message) {
33488
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
33489
+ if (!match)
33490
+ return;
33491
+ const status = Number(match[1]);
33492
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
33493
+ }
33494
+ function defaultErrorCodeForHttpStatus(status) {
33495
+ if (status === undefined)
33496
+ return;
33497
+ if (status === 400 || status === 409 || status === 422) {
33498
+ return "invalid_argument";
33499
+ }
33500
+ if (status === 401)
33501
+ return "authentication_required";
33502
+ if (status === 403)
33503
+ return "permission_denied";
33504
+ if (status === 404)
33505
+ return "not_found";
33506
+ if (status === 405)
33507
+ return "method_not_allowed";
33508
+ if (status === 408)
33509
+ return "timeout";
33510
+ if (status === 429)
33511
+ return "rate_limited";
33512
+ if (status >= 500 && status < 600)
33513
+ return "server_error";
33514
+ return;
33515
+ }
33516
+ function defaultErrorCodeForFailure(data) {
33517
+ if (data.Result === RESULTS.Failure) {
33518
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage(data.Message);
33519
+ const errorCode = defaultErrorCodeForHttpStatus(status);
33520
+ if (errorCode)
33521
+ return errorCode;
33522
+ }
33523
+ return defaultErrorCodeForResult(data.Result);
33524
+ }
33447
33525
  function defaultRetryForErrorCode(errorCode) {
33448
33526
  switch (errorCode) {
33449
33527
  case "network_error":
@@ -33473,16 +33551,19 @@ var OutputFormatter;
33473
33551
  OutputFormatter.success = success;
33474
33552
  function error(data) {
33475
33553
  data.Log ??= getLogFilePath() || undefined;
33476
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
33554
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
33477
33555
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
33478
33556
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
33479
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
33480
- result: data.Result,
33481
- errorCode: data.ErrorCode,
33482
- retry: data.Retry,
33483
- message: data.Message
33484
- });
33485
- logOutput(normalizeOutputKeys(data), getOutputFormat());
33557
+ const { SuppressTelemetry, ...envelope } = data;
33558
+ if (!SuppressTelemetry) {
33559
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
33560
+ result: data.Result,
33561
+ errorCode: data.ErrorCode,
33562
+ retry: data.Retry,
33563
+ message: data.Message
33564
+ });
33565
+ }
33566
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
33486
33567
  }
33487
33568
  OutputFormatter.error = error;
33488
33569
  function emitList(code, items, opts) {
@@ -33772,1606 +33853,290 @@ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
33772
33853
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
33773
33854
  // ../common/src/interactivity-context.ts
33774
33855
  var modeSlot = singleton("InteractivityMode");
33775
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
33776
- import vm from "vm";
33777
-
33778
- class Hooks {
33779
- add(name, callback, first) {
33780
- if (typeof arguments[0] != "string") {
33781
- for (let name2 in arguments[0]) {
33782
- this.add(name2, arguments[0][name2], arguments[1]);
33783
- }
33784
- } else {
33785
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
33786
- this[name2] = this[name2] || [];
33787
- if (callback) {
33788
- this[name2][first ? "unshift" : "push"](callback);
33789
- }
33790
- }, this);
33791
- }
33792
- }
33793
- run(name, env) {
33794
- this[name] = this[name] || [];
33795
- this[name].forEach(function(callback) {
33796
- callback.call(env && env.context ? env.context : env, env);
33797
- });
33798
- }
33856
+ // ../common/src/option-aliases.ts
33857
+ function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
33858
+ getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
33859
+ `);
33799
33860
  }
33800
-
33801
- class Plugins {
33802
- constructor(jsep) {
33803
- this.jsep = jsep;
33804
- this.registered = {};
33805
- }
33806
- register(...plugins) {
33807
- plugins.forEach((plugin) => {
33808
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
33809
- throw new Error("Invalid JSEP plugin format");
33810
- }
33811
- if (this.registered[plugin.name]) {
33812
- return;
33813
- }
33814
- plugin.init(this.jsep);
33815
- this.registered[plugin.name] = plugin;
33816
- });
33817
- }
33861
+ var TENANT_SWITCH_COMMAND = "uip login tenant set <tenant>";
33862
+ function createHiddenDeprecatedTenantOption(flags = "-t, --tenant <tenant-name>") {
33863
+ return new Option(flags, `Tenant name. Deprecated; use ${TENANT_SWITCH_COMMAND} to switch active tenants.`).hideHelp().argParser((tenant) => {
33864
+ warnDeprecatedTenantOption(tenant);
33865
+ return tenant;
33866
+ });
33867
+ }
33868
+ function warnDeprecatedTenantOption(tenant) {
33869
+ if (tenant === undefined)
33870
+ return;
33871
+ warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
33818
33872
  }
33873
+ // ../common/src/polling/types.ts
33874
+ var PollOutcome = {
33875
+ Completed: "completed",
33876
+ Timeout: "timeout",
33877
+ Interrupted: "interrupted",
33878
+ Aborted: "aborted",
33879
+ Failed: "failed"
33880
+ };
33819
33881
 
33820
- class Jsep {
33821
- static get version() {
33822
- return "1.4.0";
33823
- }
33824
- static toString() {
33825
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
33826
- }
33827
- static addUnaryOp(op_name) {
33828
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
33829
- Jsep.unary_ops[op_name] = 1;
33830
- return Jsep;
33831
- }
33832
- static addBinaryOp(op_name, precedence, isRightAssociative) {
33833
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
33834
- Jsep.binary_ops[op_name] = precedence;
33835
- if (isRightAssociative) {
33836
- Jsep.right_associative.add(op_name);
33837
- } else {
33838
- Jsep.right_associative.delete(op_name);
33839
- }
33840
- return Jsep;
33882
+ // ../common/src/polling/poll-failure-mapping.ts
33883
+ var REASON_BY_OUTCOME = {
33884
+ [PollOutcome.Timeout]: "poll_timeout",
33885
+ [PollOutcome.Failed]: "poll_failed",
33886
+ [PollOutcome.Interrupted]: "poll_failed",
33887
+ [PollOutcome.Aborted]: "poll_aborted"
33888
+ };
33889
+ // ../common/src/polling/terminal-statuses.ts
33890
+ var TERMINAL_STATUSES = new Set([
33891
+ "completed",
33892
+ "successful",
33893
+ "faulted",
33894
+ "failed",
33895
+ "cancelled",
33896
+ "canceled",
33897
+ "stopped",
33898
+ "finished"
33899
+ ]);
33900
+ var FAILURE_STATUSES = new Set([
33901
+ "faulted",
33902
+ "failed",
33903
+ "cancelled",
33904
+ "canceled",
33905
+ "stopped"
33906
+ ]);
33907
+ // ../common/src/preview.ts
33908
+ var previewSlot = singleton("PreviewBuild");
33909
+ function isPreviewBuild() {
33910
+ return previewSlot.get(false) ?? false;
33911
+ }
33912
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
33913
+ if (isPreviewBuild()) {
33914
+ return this.command(nameAndArgs, opts);
33841
33915
  }
33842
- static addIdentifierChar(char) {
33843
- Jsep.additional_identifier_chars.add(char);
33844
- return Jsep;
33916
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
33917
+ };
33918
+ // ../common/src/screen-logger.ts
33919
+ var ScreenLogger;
33920
+ ((ScreenLogger) => {
33921
+ function progress(message) {
33922
+ getOutputSink().writeErr(`${message}
33923
+ `);
33845
33924
  }
33846
- static addLiteral(literal_name, literal_value) {
33847
- Jsep.literals[literal_name] = literal_value;
33848
- return Jsep;
33925
+ ScreenLogger.progress = progress;
33926
+ })(ScreenLogger ||= {});
33927
+ // ../common/src/sdk-user-agent.ts
33928
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
33929
+ // ../common/src/tool-provider.ts
33930
+ var factorySlot = singleton("PackagerFactoryProvider");
33931
+ // ../auth/src/config.ts
33932
+ init_constants();
33933
+ var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
33934
+ var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
33935
+ var globalSlot = globalThis;
33936
+ var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
33937
+
33938
+ class InvalidBaseUrlError extends Error {
33939
+ url;
33940
+ reason;
33941
+ constructor(url, reason) {
33942
+ super(`Invalid base URL: "${url}"
33943
+ ` + `Reason: ${reason}
33944
+
33945
+ ` + `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>).
33946
+ ` + `You can specify the URL via:
33947
+ ` + ` • --authority flag
33948
+ ` + ` • UIPATH_URL environment variable
33949
+ ` + ` • auth.authority in config file`);
33950
+ this.url = url;
33951
+ this.reason = reason;
33952
+ this.name = "InvalidBaseUrlError";
33849
33953
  }
33850
- static removeUnaryOp(op_name) {
33851
- delete Jsep.unary_ops[op_name];
33852
- if (op_name.length === Jsep.max_unop_len) {
33853
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
33854
- }
33855
- return Jsep;
33954
+ }
33955
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
33956
+ var normalizeAndValidateBaseUrl = (rawUrl) => {
33957
+ let baseUrl = rawUrl;
33958
+ if (baseUrl.endsWith("/identity_/")) {
33959
+ baseUrl = baseUrl.slice(0, -11);
33960
+ } else if (baseUrl.endsWith("/identity_")) {
33961
+ baseUrl = baseUrl.slice(0, -10);
33856
33962
  }
33857
- static removeAllUnaryOps() {
33858
- Jsep.unary_ops = {};
33859
- Jsep.max_unop_len = 0;
33860
- return Jsep;
33963
+ while (baseUrl.endsWith("/")) {
33964
+ baseUrl = baseUrl.slice(0, -1);
33861
33965
  }
33862
- static removeIdentifierChar(char) {
33863
- Jsep.additional_identifier_chars.delete(char);
33864
- return Jsep;
33966
+ const resolvedBaseUrl = baseUrl;
33967
+ const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
33968
+ if (urlError) {
33969
+ throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
33865
33970
  }
33866
- static removeBinaryOp(op_name) {
33867
- delete Jsep.binary_ops[op_name];
33868
- if (op_name.length === Jsep.max_binop_len) {
33869
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
33870
- }
33871
- Jsep.right_associative.delete(op_name);
33872
- return Jsep;
33971
+ if (url.protocol !== "https:") {
33972
+ throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
33873
33973
  }
33874
- static removeAllBinaryOps() {
33875
- Jsep.binary_ops = {};
33876
- Jsep.max_binop_len = 0;
33877
- return Jsep;
33974
+ return url.pathname.length > 1 ? url.origin : baseUrl;
33975
+ };
33976
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
33977
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
33978
+ if (isExternalAppAuth)
33979
+ return requestedScopes;
33980
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
33981
+ };
33982
+ var resolveConfigAsync = async ({
33983
+ customAuthority,
33984
+ customClientId,
33985
+ customClientSecret,
33986
+ customScopes
33987
+ } = {}) => {
33988
+ const fileAuth = getAuthFileConfig();
33989
+ let baseUrl = customAuthority;
33990
+ if (!baseUrl) {
33991
+ baseUrl = process.env.UIPATH_URL;
33878
33992
  }
33879
- static removeLiteral(literal_name) {
33880
- delete Jsep.literals[literal_name];
33881
- return Jsep;
33993
+ if (!baseUrl && fileAuth.authority) {
33994
+ baseUrl = fileAuth.authority;
33882
33995
  }
33883
- static removeAllLiterals() {
33884
- Jsep.literals = {};
33885
- return Jsep;
33996
+ if (!baseUrl) {
33997
+ baseUrl = DEFAULT_BASE_URL;
33886
33998
  }
33887
- get char() {
33888
- return this.expr.charAt(this.index);
33999
+ baseUrl = normalizeAndValidateBaseUrl(baseUrl);
34000
+ let clientId = customClientId;
34001
+ if (!clientId && fileAuth.clientId) {
34002
+ clientId = fileAuth.clientId;
33889
34003
  }
33890
- get code() {
33891
- return this.expr.charCodeAt(this.index);
34004
+ if (!clientId) {
34005
+ clientId = DEFAULT_CLIENT_ID;
33892
34006
  }
33893
- constructor(expr) {
33894
- this.expr = expr;
33895
- this.index = 0;
34007
+ let clientSecret = customClientSecret;
34008
+ if (!clientSecret && fileAuth.clientSecret) {
34009
+ clientSecret = fileAuth.clientSecret;
33896
34010
  }
33897
- static parse(expr) {
33898
- return new Jsep(expr).parse();
34011
+ const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
34012
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
34013
+ return {
34014
+ clientId,
34015
+ clientSecret,
34016
+ scopes,
34017
+ baseUrl,
34018
+ authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
34019
+ tokenEndpoint: `${baseUrl}/identity_/connect/token`
34020
+ };
34021
+ };
34022
+
34023
+ // ../auth/src/index.ts
34024
+ init_constants();
34025
+ // ../auth/src/loginStatus.ts
34026
+ init_src();
34027
+
34028
+ // ../auth/src/authProfile.ts
34029
+ init_src();
34030
+ init_constants();
34031
+ var DEFAULT_AUTH_PROFILE = "default";
34032
+ var PROFILE_DIR = "profiles";
34033
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
34034
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
34035
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
34036
+ var globalSlot2 = globalThis;
34037
+ function isAuthProfileStorage(value) {
34038
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
34039
+ }
34040
+ function createProfileStorage() {
34041
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
34042
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
34043
+ return {
34044
+ getStore: () => {
34045
+ return;
34046
+ },
34047
+ run: (_store, fn) => fn()
34048
+ };
33899
34049
  }
33900
- static getMaxKeyLen(obj) {
33901
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
34050
+ return new mod2.AsyncLocalStorage;
34051
+ }
34052
+ function getProfileStorage() {
34053
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
34054
+ if (isAuthProfileStorage(existing)) {
34055
+ return existing;
33902
34056
  }
33903
- static isDecimalDigit(ch) {
33904
- return ch >= 48 && ch <= 57;
34057
+ const storage = createProfileStorage();
34058
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
34059
+ return storage;
34060
+ }
34061
+ var profileStorage = getProfileStorage();
34062
+
34063
+ class AuthProfileValidationError extends Error {
34064
+ constructor(message) {
34065
+ super(message);
34066
+ this.name = "AuthProfileValidationError";
33905
34067
  }
33906
- static binaryPrecedence(op_val) {
33907
- return Jsep.binary_ops[op_val] || 0;
34068
+ }
34069
+ function normalizeAuthProfileName(profile) {
34070
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
34071
+ return;
33908
34072
  }
33909
- static isIdentifierStart(ch) {
33910
- 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));
34073
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
34074
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
33911
34075
  }
33912
- static isIdentifierPart(ch) {
33913
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
34076
+ return profile;
34077
+ }
34078
+ function getActiveAuthProfile() {
34079
+ const scopedState = profileStorage.getStore();
34080
+ if (scopedState !== undefined) {
34081
+ return scopedState.profile;
33914
34082
  }
33915
- throwError(message) {
33916
- const error = new Error(message + " at character " + this.index);
33917
- error.index = this.index;
33918
- error.description = message;
33919
- throw error;
34083
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
34084
+ }
34085
+ function resolveAuthProfileFilePath(profile) {
34086
+ const normalized = normalizeAuthProfileName(profile);
34087
+ if (normalized === undefined) {
34088
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
33920
34089
  }
33921
- runHook(name, node) {
33922
- if (Jsep.hooks[name]) {
33923
- const env = {
33924
- context: this,
33925
- node
33926
- };
33927
- Jsep.hooks.run(name, env);
33928
- return env.node;
33929
- }
33930
- return node;
34090
+ const fs7 = getFileSystem();
34091
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
34092
+ }
34093
+ function getActiveAuthProfileFilePath() {
34094
+ const profile = getActiveAuthProfile();
34095
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
34096
+ }
34097
+ // ../auth/src/utils/jwt.ts
34098
+ class InvalidIssuerError extends Error {
34099
+ expected;
34100
+ actual;
34101
+ constructor(expected, actual) {
34102
+ const actualText = actual ?? "<missing>";
34103
+ super(`Token issuer does not match the authority used to log in.
34104
+ ` + `Expected: ${expected}
34105
+ ` + `Actual: ${actualText}
34106
+
34107
+ ` + `The identity server that issued this token is not the one ` + `you pointed --authority at. Refusing to save credentials.`);
34108
+ this.expected = expected;
34109
+ this.actual = actual;
34110
+ this.name = "InvalidIssuerError";
33931
34111
  }
33932
- searchHook(name) {
33933
- if (Jsep.hooks[name]) {
33934
- const env = {
33935
- context: this
33936
- };
33937
- Jsep.hooks[name].find(function(callback) {
33938
- callback.call(env.context, env);
33939
- return env.node;
33940
- });
33941
- return env.node;
34112
+ }
34113
+ var parseJWT = (token) => {
34114
+ try {
34115
+ const parts = token.split(".");
34116
+ const base64Url = parts[1];
34117
+ if (!base64Url) {
34118
+ throw new Error("Invalid JWT token format - missing payload section");
33942
34119
  }
33943
- }
33944
- gobbleSpaces() {
33945
- let ch = this.code;
33946
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
33947
- ch = this.expr.charCodeAt(++this.index);
34120
+ const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
34121
+ let decodedString;
34122
+ if (isBrowser() && typeof atob !== "undefined") {
34123
+ decodedString = atob(base64);
34124
+ } else {
34125
+ decodedString = Buffer.from(base64, "base64").toString();
33948
34126
  }
33949
- this.runHook("gobble-spaces");
34127
+ const jsonPayload = decodeURIComponent(decodedString.split("").map((c) => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""));
34128
+ const parsed = JSON.parse(jsonPayload);
34129
+ return parsed;
34130
+ } catch (error) {
34131
+ throw new Error(`Failed to parse JWT: ${error instanceof Error ? error.message : "Unknown error"}`);
33950
34132
  }
33951
- parse() {
33952
- this.runHook("before-all");
33953
- const nodes = this.gobbleExpressions();
33954
- const node = nodes.length === 1 ? nodes[0] : {
33955
- type: Jsep.COMPOUND,
33956
- body: nodes
33957
- };
33958
- return this.runHook("after-all", node);
33959
- }
33960
- gobbleExpressions(untilICode) {
33961
- let nodes = [], ch_i, node;
33962
- while (this.index < this.expr.length) {
33963
- ch_i = this.code;
33964
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
33965
- this.index++;
33966
- } else {
33967
- if (node = this.gobbleExpression()) {
33968
- nodes.push(node);
33969
- } else if (this.index < this.expr.length) {
33970
- if (ch_i === untilICode) {
33971
- break;
33972
- }
33973
- this.throwError('Unexpected "' + this.char + '"');
33974
- }
33975
- }
33976
- }
33977
- return nodes;
33978
- }
33979
- gobbleExpression() {
33980
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
33981
- this.gobbleSpaces();
33982
- return this.runHook("after-expression", node);
33983
- }
33984
- gobbleBinaryOp() {
33985
- this.gobbleSpaces();
33986
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
33987
- let tc_len = to_check.length;
33988
- while (tc_len > 0) {
33989
- 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)))) {
33990
- this.index += tc_len;
33991
- return to_check;
33992
- }
33993
- to_check = to_check.substr(0, --tc_len);
33994
- }
33995
- return false;
33996
- }
33997
- gobbleBinaryExpression() {
33998
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
33999
- left = this.gobbleToken();
34000
- if (!left) {
34001
- return left;
34002
- }
34003
- biop = this.gobbleBinaryOp();
34004
- if (!biop) {
34005
- return left;
34006
- }
34007
- biop_info = {
34008
- value: biop,
34009
- prec: Jsep.binaryPrecedence(biop),
34010
- right_a: Jsep.right_associative.has(biop)
34011
- };
34012
- right = this.gobbleToken();
34013
- if (!right) {
34014
- this.throwError("Expected expression after " + biop);
34015
- }
34016
- stack = [left, biop_info, right];
34017
- while (biop = this.gobbleBinaryOp()) {
34018
- prec = Jsep.binaryPrecedence(biop);
34019
- if (prec === 0) {
34020
- this.index -= biop.length;
34021
- break;
34022
- }
34023
- biop_info = {
34024
- value: biop,
34025
- prec,
34026
- right_a: Jsep.right_associative.has(biop)
34027
- };
34028
- cur_biop = biop;
34029
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
34030
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
34031
- right = stack.pop();
34032
- biop = stack.pop().value;
34033
- left = stack.pop();
34034
- node = {
34035
- type: Jsep.BINARY_EXP,
34036
- operator: biop,
34037
- left,
34038
- right
34039
- };
34040
- stack.push(node);
34041
- }
34042
- node = this.gobbleToken();
34043
- if (!node) {
34044
- this.throwError("Expected expression after " + cur_biop);
34045
- }
34046
- stack.push(biop_info, node);
34047
- }
34048
- i = stack.length - 1;
34049
- node = stack[i];
34050
- while (i > 1) {
34051
- node = {
34052
- type: Jsep.BINARY_EXP,
34053
- operator: stack[i - 1].value,
34054
- left: stack[i - 2],
34055
- right: node
34056
- };
34057
- i -= 2;
34058
- }
34059
- return node;
34060
- }
34061
- gobbleToken() {
34062
- let ch, to_check, tc_len, node;
34063
- this.gobbleSpaces();
34064
- node = this.searchHook("gobble-token");
34065
- if (node) {
34066
- return this.runHook("after-token", node);
34067
- }
34068
- ch = this.code;
34069
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
34070
- return this.gobbleNumericLiteral();
34071
- }
34072
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
34073
- node = this.gobbleStringLiteral();
34074
- } else if (ch === Jsep.OBRACK_CODE) {
34075
- node = this.gobbleArray();
34076
- } else {
34077
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
34078
- tc_len = to_check.length;
34079
- while (tc_len > 0) {
34080
- 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)))) {
34081
- this.index += tc_len;
34082
- const argument = this.gobbleToken();
34083
- if (!argument) {
34084
- this.throwError("missing unaryOp argument");
34085
- }
34086
- return this.runHook("after-token", {
34087
- type: Jsep.UNARY_EXP,
34088
- operator: to_check,
34089
- argument,
34090
- prefix: true
34091
- });
34092
- }
34093
- to_check = to_check.substr(0, --tc_len);
34094
- }
34095
- if (Jsep.isIdentifierStart(ch)) {
34096
- node = this.gobbleIdentifier();
34097
- if (Jsep.literals.hasOwnProperty(node.name)) {
34098
- node = {
34099
- type: Jsep.LITERAL,
34100
- value: Jsep.literals[node.name],
34101
- raw: node.name
34102
- };
34103
- } else if (node.name === Jsep.this_str) {
34104
- node = {
34105
- type: Jsep.THIS_EXP
34106
- };
34107
- }
34108
- } else if (ch === Jsep.OPAREN_CODE) {
34109
- node = this.gobbleGroup();
34110
- }
34111
- }
34112
- if (!node) {
34113
- return this.runHook("after-token", false);
34114
- }
34115
- node = this.gobbleTokenProperty(node);
34116
- return this.runHook("after-token", node);
34117
- }
34118
- gobbleTokenProperty(node) {
34119
- this.gobbleSpaces();
34120
- let ch = this.code;
34121
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
34122
- let optional;
34123
- if (ch === Jsep.QUMARK_CODE) {
34124
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
34125
- break;
34126
- }
34127
- optional = true;
34128
- this.index += 2;
34129
- this.gobbleSpaces();
34130
- ch = this.code;
34131
- }
34132
- this.index++;
34133
- if (ch === Jsep.OBRACK_CODE) {
34134
- node = {
34135
- type: Jsep.MEMBER_EXP,
34136
- computed: true,
34137
- object: node,
34138
- property: this.gobbleExpression()
34139
- };
34140
- if (!node.property) {
34141
- this.throwError('Unexpected "' + this.char + '"');
34142
- }
34143
- this.gobbleSpaces();
34144
- ch = this.code;
34145
- if (ch !== Jsep.CBRACK_CODE) {
34146
- this.throwError("Unclosed [");
34147
- }
34148
- this.index++;
34149
- } else if (ch === Jsep.OPAREN_CODE) {
34150
- node = {
34151
- type: Jsep.CALL_EXP,
34152
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
34153
- callee: node
34154
- };
34155
- } else if (ch === Jsep.PERIOD_CODE || optional) {
34156
- if (optional) {
34157
- this.index--;
34158
- }
34159
- this.gobbleSpaces();
34160
- node = {
34161
- type: Jsep.MEMBER_EXP,
34162
- computed: false,
34163
- object: node,
34164
- property: this.gobbleIdentifier()
34165
- };
34166
- }
34167
- if (optional) {
34168
- node.optional = true;
34169
- }
34170
- this.gobbleSpaces();
34171
- ch = this.code;
34172
- }
34173
- return node;
34174
- }
34175
- gobbleNumericLiteral() {
34176
- let number = "", ch, chCode;
34177
- while (Jsep.isDecimalDigit(this.code)) {
34178
- number += this.expr.charAt(this.index++);
34179
- }
34180
- if (this.code === Jsep.PERIOD_CODE) {
34181
- number += this.expr.charAt(this.index++);
34182
- while (Jsep.isDecimalDigit(this.code)) {
34183
- number += this.expr.charAt(this.index++);
34184
- }
34185
- }
34186
- ch = this.char;
34187
- if (ch === "e" || ch === "E") {
34188
- number += this.expr.charAt(this.index++);
34189
- ch = this.char;
34190
- if (ch === "+" || ch === "-") {
34191
- number += this.expr.charAt(this.index++);
34192
- }
34193
- while (Jsep.isDecimalDigit(this.code)) {
34194
- number += this.expr.charAt(this.index++);
34195
- }
34196
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
34197
- this.throwError("Expected exponent (" + number + this.char + ")");
34198
- }
34199
- }
34200
- chCode = this.code;
34201
- if (Jsep.isIdentifierStart(chCode)) {
34202
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
34203
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
34204
- this.throwError("Unexpected period");
34205
- }
34206
- return {
34207
- type: Jsep.LITERAL,
34208
- value: parseFloat(number),
34209
- raw: number
34210
- };
34211
- }
34212
- gobbleStringLiteral() {
34213
- let str = "";
34214
- const startIndex = this.index;
34215
- const quote = this.expr.charAt(this.index++);
34216
- let closed = false;
34217
- while (this.index < this.expr.length) {
34218
- let ch = this.expr.charAt(this.index++);
34219
- if (ch === quote) {
34220
- closed = true;
34221
- break;
34222
- } else if (ch === "\\") {
34223
- ch = this.expr.charAt(this.index++);
34224
- switch (ch) {
34225
- case "n":
34226
- str += `
34227
- `;
34228
- break;
34229
- case "r":
34230
- str += "\r";
34231
- break;
34232
- case "t":
34233
- str += "\t";
34234
- break;
34235
- case "b":
34236
- str += "\b";
34237
- break;
34238
- case "f":
34239
- str += "\f";
34240
- break;
34241
- case "v":
34242
- str += "\v";
34243
- break;
34244
- default:
34245
- str += ch;
34246
- }
34247
- } else {
34248
- str += ch;
34249
- }
34250
- }
34251
- if (!closed) {
34252
- this.throwError('Unclosed quote after "' + str + '"');
34253
- }
34254
- return {
34255
- type: Jsep.LITERAL,
34256
- value: str,
34257
- raw: this.expr.substring(startIndex, this.index)
34258
- };
34259
- }
34260
- gobbleIdentifier() {
34261
- let ch = this.code, start = this.index;
34262
- if (Jsep.isIdentifierStart(ch)) {
34263
- this.index++;
34264
- } else {
34265
- this.throwError("Unexpected " + this.char);
34266
- }
34267
- while (this.index < this.expr.length) {
34268
- ch = this.code;
34269
- if (Jsep.isIdentifierPart(ch)) {
34270
- this.index++;
34271
- } else {
34272
- break;
34273
- }
34274
- }
34275
- return {
34276
- type: Jsep.IDENTIFIER,
34277
- name: this.expr.slice(start, this.index)
34278
- };
34279
- }
34280
- gobbleArguments(termination) {
34281
- const args = [];
34282
- let closed = false;
34283
- let separator_count = 0;
34284
- while (this.index < this.expr.length) {
34285
- this.gobbleSpaces();
34286
- let ch_i = this.code;
34287
- if (ch_i === termination) {
34288
- closed = true;
34289
- this.index++;
34290
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
34291
- this.throwError("Unexpected token " + String.fromCharCode(termination));
34292
- }
34293
- break;
34294
- } else if (ch_i === Jsep.COMMA_CODE) {
34295
- this.index++;
34296
- separator_count++;
34297
- if (separator_count !== args.length) {
34298
- if (termination === Jsep.CPAREN_CODE) {
34299
- this.throwError("Unexpected token ,");
34300
- } else if (termination === Jsep.CBRACK_CODE) {
34301
- for (let arg = args.length;arg < separator_count; arg++) {
34302
- args.push(null);
34303
- }
34304
- }
34305
- }
34306
- } else if (args.length !== separator_count && separator_count !== 0) {
34307
- this.throwError("Expected comma");
34308
- } else {
34309
- const node = this.gobbleExpression();
34310
- if (!node || node.type === Jsep.COMPOUND) {
34311
- this.throwError("Expected comma");
34312
- }
34313
- args.push(node);
34314
- }
34315
- }
34316
- if (!closed) {
34317
- this.throwError("Expected " + String.fromCharCode(termination));
34318
- }
34319
- return args;
34320
- }
34321
- gobbleGroup() {
34322
- this.index++;
34323
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
34324
- if (this.code === Jsep.CPAREN_CODE) {
34325
- this.index++;
34326
- if (nodes.length === 1) {
34327
- return nodes[0];
34328
- } else if (!nodes.length) {
34329
- return false;
34330
- } else {
34331
- return {
34332
- type: Jsep.SEQUENCE_EXP,
34333
- expressions: nodes
34334
- };
34335
- }
34336
- } else {
34337
- this.throwError("Unclosed (");
34338
- }
34339
- }
34340
- gobbleArray() {
34341
- this.index++;
34342
- return {
34343
- type: Jsep.ARRAY_EXP,
34344
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
34345
- };
34346
- }
34347
- }
34348
- var hooks = new Hooks;
34349
- Object.assign(Jsep, {
34350
- hooks,
34351
- plugins: new Plugins(Jsep),
34352
- COMPOUND: "Compound",
34353
- SEQUENCE_EXP: "SequenceExpression",
34354
- IDENTIFIER: "Identifier",
34355
- MEMBER_EXP: "MemberExpression",
34356
- LITERAL: "Literal",
34357
- THIS_EXP: "ThisExpression",
34358
- CALL_EXP: "CallExpression",
34359
- UNARY_EXP: "UnaryExpression",
34360
- BINARY_EXP: "BinaryExpression",
34361
- ARRAY_EXP: "ArrayExpression",
34362
- TAB_CODE: 9,
34363
- LF_CODE: 10,
34364
- CR_CODE: 13,
34365
- SPACE_CODE: 32,
34366
- PERIOD_CODE: 46,
34367
- COMMA_CODE: 44,
34368
- SQUOTE_CODE: 39,
34369
- DQUOTE_CODE: 34,
34370
- OPAREN_CODE: 40,
34371
- CPAREN_CODE: 41,
34372
- OBRACK_CODE: 91,
34373
- CBRACK_CODE: 93,
34374
- QUMARK_CODE: 63,
34375
- SEMCOL_CODE: 59,
34376
- COLON_CODE: 58,
34377
- unary_ops: {
34378
- "-": 1,
34379
- "!": 1,
34380
- "~": 1,
34381
- "+": 1
34382
- },
34383
- binary_ops: {
34384
- "||": 1,
34385
- "??": 1,
34386
- "&&": 2,
34387
- "|": 3,
34388
- "^": 4,
34389
- "&": 5,
34390
- "==": 6,
34391
- "!=": 6,
34392
- "===": 6,
34393
- "!==": 6,
34394
- "<": 7,
34395
- ">": 7,
34396
- "<=": 7,
34397
- ">=": 7,
34398
- "<<": 8,
34399
- ">>": 8,
34400
- ">>>": 8,
34401
- "+": 9,
34402
- "-": 9,
34403
- "*": 10,
34404
- "/": 10,
34405
- "%": 10,
34406
- "**": 11
34407
- },
34408
- right_associative: new Set(["**"]),
34409
- additional_identifier_chars: new Set(["$", "_"]),
34410
- literals: {
34411
- true: true,
34412
- false: false,
34413
- null: null
34414
- },
34415
- this_str: "this"
34416
- });
34417
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
34418
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
34419
- var jsep = (expr) => new Jsep(expr).parse();
34420
- var stdClassProps = Object.getOwnPropertyNames(class Test {
34421
- });
34422
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
34423
- jsep[m] = Jsep[m];
34424
- });
34425
- jsep.Jsep = Jsep;
34426
- var CONDITIONAL_EXP = "ConditionalExpression";
34427
- var ternary = {
34428
- name: "ternary",
34429
- init(jsep2) {
34430
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
34431
- if (env.node && this.code === jsep2.QUMARK_CODE) {
34432
- this.index++;
34433
- const test = env.node;
34434
- const consequent = this.gobbleExpression();
34435
- if (!consequent) {
34436
- this.throwError("Expected expression");
34437
- }
34438
- this.gobbleSpaces();
34439
- if (this.code === jsep2.COLON_CODE) {
34440
- this.index++;
34441
- const alternate = this.gobbleExpression();
34442
- if (!alternate) {
34443
- this.throwError("Expected expression");
34444
- }
34445
- env.node = {
34446
- type: CONDITIONAL_EXP,
34447
- test,
34448
- consequent,
34449
- alternate
34450
- };
34451
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
34452
- let newTest = test;
34453
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
34454
- newTest = newTest.right;
34455
- }
34456
- env.node.test = newTest.right;
34457
- newTest.right = env.node;
34458
- env.node = test;
34459
- }
34460
- } else {
34461
- this.throwError("Expected :");
34462
- }
34463
- }
34464
- });
34465
- }
34466
- };
34467
- jsep.plugins.register(ternary);
34468
- var FSLASH_CODE = 47;
34469
- var BSLASH_CODE = 92;
34470
- var index = {
34471
- name: "regex",
34472
- init(jsep2) {
34473
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
34474
- if (this.code === FSLASH_CODE) {
34475
- const patternIndex = ++this.index;
34476
- let inCharSet = false;
34477
- while (this.index < this.expr.length) {
34478
- if (this.code === FSLASH_CODE && !inCharSet) {
34479
- const pattern = this.expr.slice(patternIndex, this.index);
34480
- let flags = "";
34481
- while (++this.index < this.expr.length) {
34482
- const code = this.code;
34483
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
34484
- flags += this.char;
34485
- } else {
34486
- break;
34487
- }
34488
- }
34489
- let value;
34490
- try {
34491
- value = new RegExp(pattern, flags);
34492
- } catch (e) {
34493
- this.throwError(e.message);
34494
- }
34495
- env.node = {
34496
- type: jsep2.LITERAL,
34497
- value,
34498
- raw: this.expr.slice(patternIndex - 1, this.index)
34499
- };
34500
- env.node = this.gobbleTokenProperty(env.node);
34501
- return env.node;
34502
- }
34503
- if (this.code === jsep2.OBRACK_CODE) {
34504
- inCharSet = true;
34505
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
34506
- inCharSet = false;
34507
- }
34508
- this.index += this.code === BSLASH_CODE ? 2 : 1;
34509
- }
34510
- this.throwError("Unclosed Regex");
34511
- }
34512
- });
34513
- }
34514
- };
34515
- var PLUS_CODE = 43;
34516
- var MINUS_CODE = 45;
34517
- var plugin = {
34518
- name: "assignment",
34519
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
34520
- updateOperators: [PLUS_CODE, MINUS_CODE],
34521
- assignmentPrecedence: 0.9,
34522
- init(jsep2) {
34523
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
34524
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
34525
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
34526
- const code = this.code;
34527
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
34528
- this.index += 2;
34529
- env.node = {
34530
- type: "UpdateExpression",
34531
- operator: code === PLUS_CODE ? "++" : "--",
34532
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
34533
- prefix: true
34534
- };
34535
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
34536
- this.throwError(`Unexpected ${env.node.operator}`);
34537
- }
34538
- }
34539
- });
34540
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
34541
- if (env.node) {
34542
- const code = this.code;
34543
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
34544
- if (!updateNodeTypes.includes(env.node.type)) {
34545
- this.throwError(`Unexpected ${env.node.operator}`);
34546
- }
34547
- this.index += 2;
34548
- env.node = {
34549
- type: "UpdateExpression",
34550
- operator: code === PLUS_CODE ? "++" : "--",
34551
- argument: env.node,
34552
- prefix: false
34553
- };
34554
- }
34555
- }
34556
- });
34557
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
34558
- if (env.node) {
34559
- updateBinariesToAssignments(env.node);
34560
- }
34561
- });
34562
- function updateBinariesToAssignments(node) {
34563
- if (plugin.assignmentOperators.has(node.operator)) {
34564
- node.type = "AssignmentExpression";
34565
- updateBinariesToAssignments(node.left);
34566
- updateBinariesToAssignments(node.right);
34567
- } else if (!node.operator) {
34568
- Object.values(node).forEach((val) => {
34569
- if (val && typeof val === "object") {
34570
- updateBinariesToAssignments(val);
34571
- }
34572
- });
34573
- }
34574
- }
34575
- }
34576
- };
34577
- jsep.plugins.register(index, plugin);
34578
- jsep.addUnaryOp("typeof");
34579
- jsep.addUnaryOp("void");
34580
- jsep.addLiteral("null", null);
34581
- jsep.addLiteral("undefined", undefined);
34582
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
34583
- var SafeEval = {
34584
- evalAst(ast, subs) {
34585
- switch (ast.type) {
34586
- case "BinaryExpression":
34587
- case "LogicalExpression":
34588
- return SafeEval.evalBinaryExpression(ast, subs);
34589
- case "Compound":
34590
- return SafeEval.evalCompound(ast, subs);
34591
- case "ConditionalExpression":
34592
- return SafeEval.evalConditionalExpression(ast, subs);
34593
- case "Identifier":
34594
- return SafeEval.evalIdentifier(ast, subs);
34595
- case "Literal":
34596
- return SafeEval.evalLiteral(ast, subs);
34597
- case "MemberExpression":
34598
- return SafeEval.evalMemberExpression(ast, subs);
34599
- case "UnaryExpression":
34600
- return SafeEval.evalUnaryExpression(ast, subs);
34601
- case "ArrayExpression":
34602
- return SafeEval.evalArrayExpression(ast, subs);
34603
- case "CallExpression":
34604
- return SafeEval.evalCallExpression(ast, subs);
34605
- case "AssignmentExpression":
34606
- return SafeEval.evalAssignmentExpression(ast, subs);
34607
- default:
34608
- throw SyntaxError("Unexpected expression", ast);
34609
- }
34610
- },
34611
- evalBinaryExpression(ast, subs) {
34612
- const result = {
34613
- "||": (a, b) => a || b(),
34614
- "&&": (a, b) => a && b(),
34615
- "|": (a, b) => a | b(),
34616
- "^": (a, b) => a ^ b(),
34617
- "&": (a, b) => a & b(),
34618
- "==": (a, b) => a == b(),
34619
- "!=": (a, b) => a != b(),
34620
- "===": (a, b) => a === b(),
34621
- "!==": (a, b) => a !== b(),
34622
- "<": (a, b) => a < b(),
34623
- ">": (a, b) => a > b(),
34624
- "<=": (a, b) => a <= b(),
34625
- ">=": (a, b) => a >= b(),
34626
- "<<": (a, b) => a << b(),
34627
- ">>": (a, b) => a >> b(),
34628
- ">>>": (a, b) => a >>> b(),
34629
- "+": (a, b) => a + b(),
34630
- "-": (a, b) => a - b(),
34631
- "*": (a, b) => a * b(),
34632
- "/": (a, b) => a / b(),
34633
- "%": (a, b) => a % b()
34634
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
34635
- return result;
34636
- },
34637
- evalCompound(ast, subs) {
34638
- let last;
34639
- for (let i = 0;i < ast.body.length; i++) {
34640
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
34641
- i += 1;
34642
- }
34643
- const expr = ast.body[i];
34644
- last = SafeEval.evalAst(expr, subs);
34645
- }
34646
- return last;
34647
- },
34648
- evalConditionalExpression(ast, subs) {
34649
- if (SafeEval.evalAst(ast.test, subs)) {
34650
- return SafeEval.evalAst(ast.consequent, subs);
34651
- }
34652
- return SafeEval.evalAst(ast.alternate, subs);
34653
- },
34654
- evalIdentifier(ast, subs) {
34655
- if (Object.hasOwn(subs, ast.name)) {
34656
- return subs[ast.name];
34657
- }
34658
- throw ReferenceError(`${ast.name} is not defined`);
34659
- },
34660
- evalLiteral(ast) {
34661
- return ast.value;
34662
- },
34663
- evalMemberExpression(ast, subs) {
34664
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
34665
- const obj = SafeEval.evalAst(ast.object, subs);
34666
- if (obj === undefined || obj === null) {
34667
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
34668
- }
34669
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
34670
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
34671
- }
34672
- const result = obj[prop];
34673
- if (typeof result === "function") {
34674
- return result.bind(obj);
34675
- }
34676
- return result;
34677
- },
34678
- evalUnaryExpression(ast, subs) {
34679
- const result = {
34680
- "-": (a) => -SafeEval.evalAst(a, subs),
34681
- "!": (a) => !SafeEval.evalAst(a, subs),
34682
- "~": (a) => ~SafeEval.evalAst(a, subs),
34683
- "+": (a) => +SafeEval.evalAst(a, subs),
34684
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
34685
- void: (a) => void SafeEval.evalAst(a, subs)
34686
- }[ast.operator](ast.argument);
34687
- return result;
34688
- },
34689
- evalArrayExpression(ast, subs) {
34690
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
34691
- },
34692
- evalCallExpression(ast, subs) {
34693
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
34694
- const func = SafeEval.evalAst(ast.callee, subs);
34695
- if (func === Function) {
34696
- throw new Error("Function constructor is disabled");
34697
- }
34698
- return func(...args);
34699
- },
34700
- evalAssignmentExpression(ast, subs) {
34701
- if (ast.left.type !== "Identifier") {
34702
- throw SyntaxError("Invalid left-hand side in assignment");
34703
- }
34704
- const id = ast.left.name;
34705
- const value = SafeEval.evalAst(ast.right, subs);
34706
- subs[id] = value;
34707
- return subs[id];
34708
- }
34709
- };
34710
-
34711
- class SafeScript {
34712
- constructor(expr) {
34713
- this.code = expr;
34714
- this.ast = jsep(this.code);
34715
- }
34716
- runInNewContext(context) {
34717
- const keyMap = Object.assign(Object.create(null), context);
34718
- return SafeEval.evalAst(this.ast, keyMap);
34719
- }
34720
- }
34721
- function push(arr, item) {
34722
- arr = arr.slice();
34723
- arr.push(item);
34724
- return arr;
34725
- }
34726
- function unshift(item, arr) {
34727
- arr = arr.slice();
34728
- arr.unshift(item);
34729
- return arr;
34730
- }
34731
-
34732
- class NewError extends Error {
34733
- constructor(value) {
34734
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
34735
- this.avoidNew = true;
34736
- this.value = value;
34737
- this.name = "NewError";
34738
- }
34739
- }
34740
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
34741
- if (!(this instanceof JSONPath)) {
34742
- try {
34743
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
34744
- } catch (e) {
34745
- if (!e.avoidNew) {
34746
- throw e;
34747
- }
34748
- return e.value;
34749
- }
34750
- }
34751
- if (typeof opts === "string") {
34752
- otherTypeCallback = callback;
34753
- callback = obj;
34754
- obj = expr;
34755
- expr = opts;
34756
- opts = null;
34757
- }
34758
- const optObj = opts && typeof opts === "object";
34759
- opts = opts || {};
34760
- this.json = opts.json || obj;
34761
- this.path = opts.path || expr;
34762
- this.resultType = opts.resultType || "value";
34763
- this.flatten = opts.flatten || false;
34764
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
34765
- this.sandbox = opts.sandbox || {};
34766
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
34767
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
34768
- this.parent = opts.parent || null;
34769
- this.parentProperty = opts.parentProperty || null;
34770
- this.callback = opts.callback || callback || null;
34771
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
34772
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
34773
- };
34774
- if (opts.autostart !== false) {
34775
- const args = {
34776
- path: optObj ? opts.path : expr
34777
- };
34778
- if (!optObj) {
34779
- args.json = obj;
34780
- } else if ("json" in opts) {
34781
- args.json = opts.json;
34782
- }
34783
- const ret = this.evaluate(args);
34784
- if (!ret || typeof ret !== "object") {
34785
- throw new NewError(ret);
34786
- }
34787
- return ret;
34788
- }
34789
- }
34790
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
34791
- let currParent = this.parent, currParentProperty = this.parentProperty;
34792
- let {
34793
- flatten,
34794
- wrap
34795
- } = this;
34796
- this.currResultType = this.resultType;
34797
- this.currEval = this.eval;
34798
- this.currSandbox = this.sandbox;
34799
- callback = callback || this.callback;
34800
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
34801
- json = json || this.json;
34802
- expr = expr || this.path;
34803
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
34804
- if (!expr.path && expr.path !== "") {
34805
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
34806
- }
34807
- if (!Object.hasOwn(expr, "json")) {
34808
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
34809
- }
34810
- ({
34811
- json
34812
- } = expr);
34813
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
34814
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
34815
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
34816
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
34817
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
34818
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
34819
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
34820
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
34821
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
34822
- expr = expr.path;
34823
- }
34824
- currParent = currParent || null;
34825
- currParentProperty = currParentProperty || null;
34826
- if (Array.isArray(expr)) {
34827
- expr = JSONPath.toPathString(expr);
34828
- }
34829
- if (!expr && expr !== "" || !json) {
34830
- return;
34831
- }
34832
- const exprList = JSONPath.toPathArray(expr);
34833
- if (exprList[0] === "$" && exprList.length > 1) {
34834
- exprList.shift();
34835
- }
34836
- this._hasParentSelector = null;
34837
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
34838
- return ea && !ea.isParentSelector;
34839
- });
34840
- if (!result.length) {
34841
- return wrap ? [] : undefined;
34842
- }
34843
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
34844
- return this._getPreferredOutput(result[0]);
34845
- }
34846
- return result.reduce((rslt, ea) => {
34847
- const valOrPath = this._getPreferredOutput(ea);
34848
- if (flatten && Array.isArray(valOrPath)) {
34849
- rslt = rslt.concat(valOrPath);
34850
- } else {
34851
- rslt.push(valOrPath);
34852
- }
34853
- return rslt;
34854
- }, []);
34855
- };
34856
- JSONPath.prototype._getPreferredOutput = function(ea) {
34857
- const resultType = this.currResultType;
34858
- switch (resultType) {
34859
- case "all": {
34860
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
34861
- ea.pointer = JSONPath.toPointer(path3);
34862
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
34863
- return ea;
34864
- }
34865
- case "value":
34866
- case "parent":
34867
- case "parentProperty":
34868
- return ea[resultType];
34869
- case "path":
34870
- return JSONPath.toPathString(ea[resultType]);
34871
- case "pointer":
34872
- return JSONPath.toPointer(ea.path);
34873
- default:
34874
- throw new TypeError("Unknown result type");
34875
- }
34876
- };
34877
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
34878
- if (callback) {
34879
- const preferredOutput = this._getPreferredOutput(fullRetObj);
34880
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
34881
- callback(preferredOutput, type, fullRetObj);
34882
- }
34883
- };
34884
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
34885
- let retObj;
34886
- if (!expr.length) {
34887
- retObj = {
34888
- path: path3,
34889
- value: val,
34890
- parent,
34891
- parentProperty: parentPropName,
34892
- hasArrExpr
34893
- };
34894
- this._handleCallback(retObj, callback, "value");
34895
- return retObj;
34896
- }
34897
- const loc = expr[0], x = expr.slice(1);
34898
- const ret = [];
34899
- function addRet(elems) {
34900
- if (Array.isArray(elems)) {
34901
- elems.forEach((t) => {
34902
- ret.push(t);
34903
- });
34904
- } else {
34905
- ret.push(elems);
34906
- }
34907
- }
34908
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
34909
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
34910
- } else if (loc === "*") {
34911
- this._walk(val, (m) => {
34912
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
34913
- });
34914
- } else if (loc === "..") {
34915
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
34916
- this._walk(val, (m) => {
34917
- if (typeof val[m] === "object") {
34918
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
34919
- }
34920
- });
34921
- } else if (loc === "^") {
34922
- this._hasParentSelector = true;
34923
- return {
34924
- path: path3.slice(0, -1),
34925
- expr: x,
34926
- isParentSelector: true
34927
- };
34928
- } else if (loc === "~") {
34929
- retObj = {
34930
- path: push(path3, loc),
34931
- value: parentPropName,
34932
- parent,
34933
- parentProperty: null
34934
- };
34935
- this._handleCallback(retObj, callback, "property");
34936
- return retObj;
34937
- } else if (loc === "$") {
34938
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
34939
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
34940
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
34941
- } else if (loc.indexOf("?(") === 0) {
34942
- if (this.currEval === false) {
34943
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
34944
- }
34945
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
34946
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
34947
- if (nested) {
34948
- this._walk(val, (m) => {
34949
- const npath = [nested[2]];
34950
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
34951
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
34952
- if (filterResults.length > 0) {
34953
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
34954
- }
34955
- });
34956
- } else {
34957
- this._walk(val, (m) => {
34958
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
34959
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
34960
- }
34961
- });
34962
- }
34963
- } else if (loc[0] === "(") {
34964
- if (this.currEval === false) {
34965
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
34966
- }
34967
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
34968
- } else if (loc[0] === "@") {
34969
- let addType = false;
34970
- const valueType = loc.slice(1, -2);
34971
- switch (valueType) {
34972
- case "scalar":
34973
- if (!val || !["object", "function"].includes(typeof val)) {
34974
- addType = true;
34975
- }
34976
- break;
34977
- case "boolean":
34978
- case "string":
34979
- case "undefined":
34980
- case "function":
34981
- if (typeof val === valueType) {
34982
- addType = true;
34983
- }
34984
- break;
34985
- case "integer":
34986
- if (Number.isFinite(val) && !(val % 1)) {
34987
- addType = true;
34988
- }
34989
- break;
34990
- case "number":
34991
- if (Number.isFinite(val)) {
34992
- addType = true;
34993
- }
34994
- break;
34995
- case "nonFinite":
34996
- if (typeof val === "number" && !Number.isFinite(val)) {
34997
- addType = true;
34998
- }
34999
- break;
35000
- case "object":
35001
- if (val && typeof val === valueType) {
35002
- addType = true;
35003
- }
35004
- break;
35005
- case "array":
35006
- if (Array.isArray(val)) {
35007
- addType = true;
35008
- }
35009
- break;
35010
- case "other":
35011
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
35012
- break;
35013
- case "null":
35014
- if (val === null) {
35015
- addType = true;
35016
- }
35017
- break;
35018
- default:
35019
- throw new TypeError("Unknown value type " + valueType);
35020
- }
35021
- if (addType) {
35022
- retObj = {
35023
- path: path3,
35024
- value: val,
35025
- parent,
35026
- parentProperty: parentPropName
35027
- };
35028
- this._handleCallback(retObj, callback, "value");
35029
- return retObj;
35030
- }
35031
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
35032
- const locProp = loc.slice(1);
35033
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
35034
- } else if (loc.includes(",")) {
35035
- const parts = loc.split(",");
35036
- for (const part of parts) {
35037
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
35038
- }
35039
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
35040
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
35041
- }
35042
- if (this._hasParentSelector) {
35043
- for (let t = 0;t < ret.length; t++) {
35044
- const rett = ret[t];
35045
- if (rett && rett.isParentSelector) {
35046
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
35047
- if (Array.isArray(tmp)) {
35048
- ret[t] = tmp[0];
35049
- const tl = tmp.length;
35050
- for (let tt = 1;tt < tl; tt++) {
35051
- t++;
35052
- ret.splice(t, 0, tmp[tt]);
35053
- }
35054
- } else {
35055
- ret[t] = tmp;
35056
- }
35057
- }
35058
- }
35059
- }
35060
- return ret;
35061
- };
35062
- JSONPath.prototype._walk = function(val, f) {
35063
- if (Array.isArray(val)) {
35064
- const n = val.length;
35065
- for (let i = 0;i < n; i++) {
35066
- f(i);
35067
- }
35068
- } else if (val && typeof val === "object") {
35069
- Object.keys(val).forEach((m) => {
35070
- f(m);
35071
- });
35072
- }
35073
- };
35074
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
35075
- if (!Array.isArray(val)) {
35076
- return;
35077
- }
35078
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
35079
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
35080
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
35081
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
35082
- const ret = [];
35083
- for (let i = start;i < end; i += step) {
35084
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
35085
- tmp.forEach((t) => {
35086
- ret.push(t);
35087
- });
35088
- }
35089
- return ret;
35090
- };
35091
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
35092
- this.currSandbox._$_parentProperty = parentPropName;
35093
- this.currSandbox._$_parent = parent;
35094
- this.currSandbox._$_property = _vname;
35095
- this.currSandbox._$_root = this.json;
35096
- this.currSandbox._$_v = _v;
35097
- const containsPath = code.includes("@path");
35098
- if (containsPath) {
35099
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
35100
- }
35101
- const scriptCacheKey = this.currEval + "Script:" + code;
35102
- if (!JSONPath.cache[scriptCacheKey]) {
35103
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
35104
- if (containsPath) {
35105
- script = script.replaceAll("@path", "_$_path");
35106
- }
35107
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
35108
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
35109
- } else if (this.currEval === "native") {
35110
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
35111
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
35112
- const CurrEval = this.currEval;
35113
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
35114
- } else if (typeof this.currEval === "function") {
35115
- JSONPath.cache[scriptCacheKey] = {
35116
- runInNewContext: (context) => this.currEval(script, context)
35117
- };
35118
- } else {
35119
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
35120
- }
35121
- }
35122
- try {
35123
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
35124
- } catch (e) {
35125
- if (this.ignoreEvalErrors) {
35126
- return false;
35127
- }
35128
- throw new Error("jsonPath: " + e.message + ": " + code);
35129
- }
35130
- };
35131
- JSONPath.cache = {};
35132
- JSONPath.toPathString = function(pathArr) {
35133
- const x = pathArr, n = x.length;
35134
- let p = "$";
35135
- for (let i = 1;i < n; i++) {
35136
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
35137
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
35138
- }
35139
- }
35140
- return p;
35141
- };
35142
- JSONPath.toPointer = function(pointer) {
35143
- const x = pointer, n = x.length;
35144
- let p = "";
35145
- for (let i = 1;i < n; i++) {
35146
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
35147
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
35148
- }
35149
- }
35150
- return p;
35151
- };
35152
- JSONPath.toPathArray = function(expr) {
35153
- const {
35154
- cache
35155
- } = JSONPath;
35156
- if (cache[expr]) {
35157
- return cache[expr].concat();
35158
- }
35159
- const subx = [];
35160
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
35161
- return "[#" + (subx.push($1) - 1) + "]";
35162
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
35163
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
35164
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
35165
- return ";" + ups.split("").join(";") + ";";
35166
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
35167
- const exprList = normalized.split(";").map(function(exp) {
35168
- const match = exp.match(/#(\d+)/u);
35169
- return !match || !match[1] ? exp : subx[match[1]];
35170
- });
35171
- cache[expr] = exprList;
35172
- return cache[expr].concat();
35173
- };
35174
- JSONPath.prototype.safeVm = {
35175
- Script: SafeScript
35176
- };
35177
- JSONPath.prototype.vm = vm;
35178
- // ../common/src/option-aliases.ts
35179
- function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
35180
- getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
35181
- `);
35182
- }
35183
- var TENANT_SWITCH_COMMAND = "uip login tenant set <tenant>";
35184
- function createHiddenDeprecatedTenantOption(flags = "-t, --tenant <tenant-name>") {
35185
- return new Option(flags, `Tenant name. Deprecated; use ${TENANT_SWITCH_COMMAND} to switch active tenants.`).hideHelp().argParser((tenant) => {
35186
- warnDeprecatedTenantOption(tenant);
35187
- return tenant;
35188
- });
35189
- }
35190
- function warnDeprecatedTenantOption(tenant) {
35191
- if (tenant === undefined)
35192
- return;
35193
- warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
35194
- }
35195
- // ../common/src/polling/types.ts
35196
- var PollOutcome = {
35197
- Completed: "completed",
35198
- Timeout: "timeout",
35199
- Interrupted: "interrupted",
35200
- Aborted: "aborted",
35201
- Failed: "failed"
35202
- };
35203
-
35204
- // ../common/src/polling/poll-failure-mapping.ts
35205
- var REASON_BY_OUTCOME = {
35206
- [PollOutcome.Timeout]: "poll_timeout",
35207
- [PollOutcome.Failed]: "poll_failed",
35208
- [PollOutcome.Interrupted]: "poll_failed",
35209
- [PollOutcome.Aborted]: "poll_aborted"
35210
- };
35211
- // ../common/src/polling/terminal-statuses.ts
35212
- var TERMINAL_STATUSES = new Set([
35213
- "completed",
35214
- "successful",
35215
- "faulted",
35216
- "failed",
35217
- "cancelled",
35218
- "canceled",
35219
- "stopped",
35220
- "finished"
35221
- ]);
35222
- var FAILURE_STATUSES = new Set([
35223
- "faulted",
35224
- "failed",
35225
- "cancelled",
35226
- "canceled",
35227
- "stopped"
35228
- ]);
35229
- // ../common/src/screen-logger.ts
35230
- var ScreenLogger;
35231
- ((ScreenLogger) => {
35232
- function progress(message) {
35233
- getOutputSink().writeErr(`${message}
35234
- `);
35235
- }
35236
- ScreenLogger.progress = progress;
35237
- })(ScreenLogger ||= {});
35238
- // ../common/src/sdk-user-agent.ts
35239
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
35240
- // ../common/src/tool-provider.ts
35241
- var factorySlot = singleton("PackagerFactoryProvider");
35242
- // ../auth/src/config.ts
35243
- init_constants();
35244
- var DEFAULT_CLIENT_ID = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00";
35245
- var AUTH_FILE_CONFIG_KEY = Symbol.for("@uipath/auth/AuthFileConfig");
35246
- var globalSlot = globalThis;
35247
- var getAuthFileConfig = () => globalSlot[AUTH_FILE_CONFIG_KEY] ?? {};
35248
-
35249
- class InvalidBaseUrlError extends Error {
35250
- url;
35251
- reason;
35252
- constructor(url, reason) {
35253
- super(`Invalid base URL: "${url}"
35254
- ` + `Reason: ${reason}
35255
-
35256
- ` + `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>).
35257
- ` + `You can specify the URL via:
35258
- ` + ` • --authority flag
35259
- ` + ` • UIPATH_URL environment variable
35260
- ` + ` • auth.authority in config file`);
35261
- this.url = url;
35262
- this.reason = reason;
35263
- this.name = "InvalidBaseUrlError";
35264
- }
35265
- }
35266
- var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
35267
- var normalizeAndValidateBaseUrl = (rawUrl) => {
35268
- let baseUrl = rawUrl;
35269
- if (baseUrl.endsWith("/identity_/")) {
35270
- baseUrl = baseUrl.slice(0, -11);
35271
- } else if (baseUrl.endsWith("/identity_")) {
35272
- baseUrl = baseUrl.slice(0, -10);
35273
- }
35274
- while (baseUrl.endsWith("/")) {
35275
- baseUrl = baseUrl.slice(0, -1);
35276
- }
35277
- const resolvedBaseUrl = baseUrl;
35278
- const [urlError, url] = catchError2(() => new URL(resolvedBaseUrl));
35279
- if (urlError) {
35280
- throw new InvalidBaseUrlError(baseUrl, `Malformed URL. ${urlError instanceof Error ? urlError.message : "Unknown error"}`);
35281
- }
35282
- if (url.protocol !== "https:") {
35283
- throw new InvalidBaseUrlError(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
35284
- }
35285
- return url.pathname.length > 1 ? url.origin : baseUrl;
35286
- };
35287
- var resolveConfigAsync = async ({
35288
- customAuthority,
35289
- customClientId,
35290
- customClientSecret,
35291
- customScopes
35292
- } = {}) => {
35293
- const fileAuth = getAuthFileConfig();
35294
- let baseUrl = customAuthority;
35295
- if (!baseUrl) {
35296
- baseUrl = process.env.UIPATH_URL;
35297
- }
35298
- if (!baseUrl && fileAuth.authority) {
35299
- baseUrl = fileAuth.authority;
35300
- }
35301
- if (!baseUrl) {
35302
- baseUrl = DEFAULT_BASE_URL;
35303
- }
35304
- baseUrl = normalizeAndValidateBaseUrl(baseUrl);
35305
- let clientId = customClientId;
35306
- if (!clientId && fileAuth.clientId) {
35307
- clientId = fileAuth.clientId;
35308
- }
35309
- if (!clientId) {
35310
- clientId = DEFAULT_CLIENT_ID;
35311
- }
35312
- let clientSecret = customClientSecret;
35313
- if (!clientSecret && fileAuth.clientSecret) {
35314
- clientSecret = fileAuth.clientSecret;
35315
- }
35316
- const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
35317
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
35318
- return {
35319
- clientId,
35320
- clientSecret,
35321
- scopes,
35322
- baseUrl,
35323
- authorizationEndpoint: `${baseUrl}/identity_/connect/authorize`,
35324
- tokenEndpoint: `${baseUrl}/identity_/connect/token`
35325
- };
35326
- };
35327
-
35328
- // ../auth/src/index.ts
35329
- init_constants();
35330
- // ../auth/src/loginStatus.ts
35331
- init_src();
35332
- // ../auth/src/utils/jwt.ts
35333
- class InvalidIssuerError extends Error {
35334
- expected;
35335
- actual;
35336
- constructor(expected, actual) {
35337
- const actualText = actual ?? "<missing>";
35338
- super(`Token issuer does not match the authority used to log in.
35339
- ` + `Expected: ${expected}
35340
- ` + `Actual: ${actualText}
35341
-
35342
- ` + `The identity server that issued this token is not the one ` + `you pointed --authority at. Refusing to save credentials.`);
35343
- this.expected = expected;
35344
- this.actual = actual;
35345
- this.name = "InvalidIssuerError";
35346
- }
35347
- }
35348
- var parseJWT = (token) => {
35349
- try {
35350
- const parts = token.split(".");
35351
- const base64Url = parts[1];
35352
- if (!base64Url) {
35353
- throw new Error("Invalid JWT token format - missing payload section");
35354
- }
35355
- const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
35356
- let decodedString;
35357
- if (isBrowser() && typeof atob !== "undefined") {
35358
- decodedString = atob(base64);
35359
- } else {
35360
- decodedString = Buffer.from(base64, "base64").toString();
35361
- }
35362
- const jsonPayload = decodeURIComponent(decodedString.split("").map((c) => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""));
35363
- const parsed = JSON.parse(jsonPayload);
35364
- return parsed;
35365
- } catch (error) {
35366
- throw new Error(`Failed to parse JWT: ${error instanceof Error ? error.message : "Unknown error"}`);
35367
- }
35368
- };
35369
- var assertIssuerMatchesAuthority = (token, authority) => {
35370
- let payload;
35371
- try {
35372
- payload = parseJWT(token);
35373
- } catch (error) {
35374
- throw new InvalidIssuerError(`${authority.replace(/\/+$/, "")}/identity_`, `<unparseable: ${error instanceof Error ? error.message : "unknown error"}>`);
34133
+ };
34134
+ var assertIssuerMatchesAuthority = (token, authority) => {
34135
+ let payload;
34136
+ try {
34137
+ payload = parseJWT(token);
34138
+ } catch (error) {
34139
+ throw new InvalidIssuerError(`${authority.replace(/\/+$/, "")}/identity_`, `<unparseable: ${error instanceof Error ? error.message : "unknown error"}>`);
35375
34140
  }
35376
34141
  const stripTrailingSlash = (s) => s.replace(/\/+$/, "");
35377
34142
  const expected = `${stripTrailingSlash(authority)}/identity_`;
@@ -35457,23 +34222,74 @@ var readAuthFromEnv = () => {
35457
34222
  organizationId,
35458
34223
  tenantName,
35459
34224
  tenantId,
35460
- expiration
34225
+ expiration,
34226
+ source: "env" /* Env */
35461
34227
  };
35462
34228
  };
35463
34229
 
34230
+ // ../auth/src/refreshCircuitBreaker.ts
34231
+ init_src();
34232
+ var BREAKER_SUFFIX = ".refresh-state";
34233
+ var BACKOFF_BASE_MS = 60000;
34234
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
34235
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
34236
+ async function refreshTokenFingerprint(refreshToken) {
34237
+ const bytes = new TextEncoder().encode(refreshToken);
34238
+ if (globalThis.crypto?.subtle) {
34239
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
34240
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
34241
+ }
34242
+ const { createHash } = await import("node:crypto");
34243
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
34244
+ }
34245
+ function breakerPathFor(authPath) {
34246
+ return `${authPath}${BREAKER_SUFFIX}`;
34247
+ }
34248
+ async function loadRefreshBreaker(authPath) {
34249
+ const fs7 = getFileSystem();
34250
+ try {
34251
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
34252
+ if (!content)
34253
+ return {};
34254
+ const parsed = JSON.parse(content);
34255
+ return parsed && typeof parsed === "object" ? parsed : {};
34256
+ } catch {
34257
+ return {};
34258
+ }
34259
+ }
34260
+ async function saveRefreshBreaker(authPath, state) {
34261
+ try {
34262
+ const fs7 = getFileSystem();
34263
+ const path3 = breakerPathFor(authPath);
34264
+ await fs7.mkdir(fs7.path.dirname(path3));
34265
+ const tempPath = `${path3}.tmp`;
34266
+ await fs7.writeFile(tempPath, JSON.stringify(state));
34267
+ await fs7.rename(tempPath, path3);
34268
+ } catch {}
34269
+ }
34270
+ async function clearRefreshBreaker(authPath) {
34271
+ const fs7 = getFileSystem();
34272
+ const path3 = breakerPathFor(authPath);
34273
+ try {
34274
+ if (await fs7.exists(path3)) {
34275
+ await fs7.rm(path3);
34276
+ }
34277
+ } catch {}
34278
+ }
34279
+ function nextBackoffMs(attempts) {
34280
+ const shift = Math.max(0, attempts - 1);
34281
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
34282
+ }
34283
+ function shouldSurface(state, nowMs) {
34284
+ if (state.lastSurfacedAtMs === undefined)
34285
+ return true;
34286
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
34287
+ }
34288
+
35464
34289
  // ../auth/src/robotClientFallback.ts
35465
34290
  init_src();
35466
34291
  var DEFAULT_TIMEOUT_MS = 1000;
35467
34292
  var CLOSE_TIMEOUT_MS = 500;
35468
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
35469
- var printNoticeOnce = () => {
35470
- const slot = globalThis;
35471
- if (slot[NOTICE_SENTINEL])
35472
- return;
35473
- slot[NOTICE_SENTINEL] = true;
35474
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
35475
- `));
35476
- };
35477
34293
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
35478
34294
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
35479
34295
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -35589,7 +34405,6 @@ var tryRobotClientFallback = async (options = {}) => {
35589
34405
  issuerFromToken = issClaim;
35590
34406
  }
35591
34407
  }
35592
- printNoticeOnce();
35593
34408
  return {
35594
34409
  accessToken,
35595
34410
  baseUrl: parsedUrl.baseUrl,
@@ -35814,18 +34629,327 @@ var saveEnvFileAsync = async ({
35814
34629
  };
35815
34630
 
35816
34631
  // ../auth/src/loginStatus.ts
35817
- function normalizeTokenRefreshFailure() {
35818
- return "stored refresh token is invalid or expired";
34632
+ var getLoginStatusAsync = async (options = {}) => {
34633
+ return getLoginStatusWithDeps(options);
34634
+ };
34635
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
34636
+ const {
34637
+ resolveEnvFilePath = resolveEnvFilePathAsync,
34638
+ loadEnvFile = loadEnvFileAsync,
34639
+ saveEnvFile = saveEnvFileAsync,
34640
+ getFs = getFileSystem,
34641
+ refreshToken: refreshTokenFn = refreshAccessToken,
34642
+ resolveConfig = resolveConfigAsync,
34643
+ robotFallback = tryRobotClientFallback,
34644
+ loadBreaker = loadRefreshBreaker,
34645
+ saveBreaker = saveRefreshBreaker,
34646
+ clearBreaker = clearRefreshBreaker
34647
+ } = deps;
34648
+ if (isRobotAuthEnforced()) {
34649
+ return resolveRobotEnforcedStatus(robotFallback);
34650
+ }
34651
+ if (isEnvAuthEnabled()) {
34652
+ return readAuthFromEnv();
34653
+ }
34654
+ const activeProfile = getActiveAuthProfile();
34655
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
34656
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
34657
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
34658
+ const { ensureTokenValidityMinutes } = options;
34659
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
34660
+ if (absolutePath === undefined) {
34661
+ if (usingActiveProfile) {
34662
+ return {
34663
+ loginStatus: "Not logged in",
34664
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
34665
+ };
34666
+ }
34667
+ return resolveBorrowedRobotStatus(robotFallback);
34668
+ }
34669
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
34670
+ if ("status" in loaded) {
34671
+ return loaded.status;
34672
+ }
34673
+ const { credentials } = loaded;
34674
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
34675
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
34676
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
34677
+ let tokens = {
34678
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
34679
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
34680
+ expiration,
34681
+ lockReleaseFailed: false
34682
+ };
34683
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
34684
+ if (expiration && expiration <= outerThreshold && refreshToken) {
34685
+ const refreshed = await attemptRefresh({
34686
+ absolutePath,
34687
+ credentials,
34688
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
34689
+ refreshToken,
34690
+ expiration,
34691
+ ensureTokenValidityMinutes,
34692
+ getFs,
34693
+ loadEnvFile,
34694
+ saveEnvFile,
34695
+ refreshFn: refreshTokenFn,
34696
+ resolveConfig,
34697
+ loadBreaker,
34698
+ saveBreaker,
34699
+ clearBreaker,
34700
+ globalHint
34701
+ });
34702
+ if (refreshed.kind === "terminal") {
34703
+ return refreshed.status;
34704
+ }
34705
+ tokens = refreshed.tokens;
34706
+ }
34707
+ return buildFileStatus(tokens, credentials, globalHint);
34708
+ };
34709
+ async function resolveRobotEnforcedStatus(robotFallback) {
34710
+ if (isEnvAuthEnabled()) {
34711
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
34712
+ }
34713
+ const robotCreds = await robotFallback({ force: true });
34714
+ if (!robotCreds) {
34715
+ return {
34716
+ loginStatus: "Not logged in",
34717
+ 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.`
34718
+ };
34719
+ }
34720
+ return buildRobotStatus(robotCreds);
35819
34721
  }
35820
- function normalizeTokenRefreshUnavailableFailure() {
35821
- return "token refresh failed before authentication completed";
34722
+ async function resolveBorrowedRobotStatus(robotFallback) {
34723
+ const robotCreds = await robotFallback();
34724
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
35822
34725
  }
35823
- function errorMessage(error) {
35824
- return error instanceof Error ? error.message : String(error);
34726
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
34727
+ let credentials;
34728
+ try {
34729
+ credentials = await loadEnvFile({ envPath: absolutePath });
34730
+ } catch (error) {
34731
+ if (isFileNotFoundError(error)) {
34732
+ return { status: { loginStatus: "Not logged in" } };
34733
+ }
34734
+ throw error;
34735
+ }
34736
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
34737
+ return { status: { loginStatus: "Not logged in" } };
34738
+ }
34739
+ return { credentials };
34740
+ }
34741
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
34742
+ const fs7 = getFs();
34743
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
34744
+ if (absolutePath === globalPath)
34745
+ return;
34746
+ if (!await fs7.exists(globalPath))
34747
+ return;
34748
+ try {
34749
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
34750
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
34751
+ return;
34752
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
34753
+ if (globalExp && globalExp <= new Date)
34754
+ return;
34755
+ 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.`;
34756
+ } catch {
34757
+ return;
34758
+ }
35825
34759
  }
35826
34760
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
35827
34761
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
35828
34762
  }
34763
+ async function attemptRefresh(ctx) {
34764
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
34765
+ if (shortCircuit) {
34766
+ return { kind: "terminal", status: shortCircuit };
34767
+ }
34768
+ let release;
34769
+ try {
34770
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
34771
+ } catch (error) {
34772
+ return {
34773
+ kind: "terminal",
34774
+ status: await lockAcquireFailureStatus(ctx, error)
34775
+ };
34776
+ }
34777
+ let lockedFailure;
34778
+ let lockReleaseFailed = false;
34779
+ let success;
34780
+ try {
34781
+ const outcome = await runRefreshLocked({
34782
+ absolutePath: ctx.absolutePath,
34783
+ refreshToken: ctx.refreshToken,
34784
+ customAuthority: ctx.credentials.UIPATH_URL,
34785
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
34786
+ loadEnvFile: ctx.loadEnvFile,
34787
+ saveEnvFile: ctx.saveEnvFile,
34788
+ refreshFn: ctx.refreshFn,
34789
+ resolveConfig: ctx.resolveConfig,
34790
+ loadBreaker: ctx.loadBreaker,
34791
+ saveBreaker: ctx.saveBreaker,
34792
+ clearBreaker: ctx.clearBreaker
34793
+ });
34794
+ if (outcome.kind === "fail") {
34795
+ lockedFailure = outcome.status;
34796
+ } else {
34797
+ success = outcome;
34798
+ }
34799
+ } finally {
34800
+ try {
34801
+ await release();
34802
+ } catch {
34803
+ lockReleaseFailed = true;
34804
+ }
34805
+ }
34806
+ if (lockedFailure) {
34807
+ const globalHint = await ctx.globalHint();
34808
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
34809
+ return {
34810
+ kind: "terminal",
34811
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
34812
+ };
34813
+ }
34814
+ return {
34815
+ kind: "refreshed",
34816
+ tokens: {
34817
+ accessToken: success?.accessToken,
34818
+ refreshToken: success?.refreshToken,
34819
+ expiration: success?.expiration,
34820
+ tokenRefresh: success?.tokenRefresh,
34821
+ persistenceWarning: success?.persistenceWarning,
34822
+ lockReleaseFailed
34823
+ }
34824
+ };
34825
+ }
34826
+ async function buildFileStatus(tokens, credentials, globalHint) {
34827
+ const result = {
34828
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
34829
+ accessToken: tokens.accessToken,
34830
+ refreshToken: tokens.refreshToken,
34831
+ baseUrl: credentials.UIPATH_URL,
34832
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
34833
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
34834
+ tenantName: credentials.UIPATH_TENANT_NAME,
34835
+ tenantId: credentials.UIPATH_TENANT_ID,
34836
+ expiration: tokens.expiration,
34837
+ source: "file" /* File */,
34838
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
34839
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
34840
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
34841
+ };
34842
+ if (result.loginStatus === "Expired") {
34843
+ const hint = await globalHint();
34844
+ if (hint) {
34845
+ result.hint = hint;
34846
+ }
34847
+ }
34848
+ return result;
34849
+ }
34850
+ function buildRobotStatus(robotCreds) {
34851
+ return {
34852
+ loginStatus: "Logged in",
34853
+ accessToken: robotCreds.accessToken,
34854
+ baseUrl: robotCreds.baseUrl,
34855
+ organizationName: robotCreds.organizationName,
34856
+ organizationId: robotCreds.organizationId,
34857
+ tenantName: robotCreds.tenantName,
34858
+ tenantId: robotCreds.tenantId,
34859
+ issuer: robotCreds.issuer,
34860
+ expiration: getTokenExpiration(robotCreds.accessToken),
34861
+ source: "robot" /* Robot */
34862
+ };
34863
+ }
34864
+ var isFileNotFoundError = (error) => {
34865
+ if (!(error instanceof Object))
34866
+ return false;
34867
+ return error.code === "ENOENT";
34868
+ };
34869
+ async function circuitBreakerShortCircuit(ctx) {
34870
+ const {
34871
+ absolutePath,
34872
+ refreshToken,
34873
+ accessToken,
34874
+ credentials,
34875
+ expiration,
34876
+ loadBreaker,
34877
+ saveBreaker,
34878
+ clearBreaker
34879
+ } = ctx;
34880
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
34881
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
34882
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
34883
+ await clearBreaker(absolutePath);
34884
+ breaker.deadTokenFp = undefined;
34885
+ }
34886
+ const nowMs = Date.now();
34887
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
34888
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
34889
+ if (!tokenIsDead && !inBackoff)
34890
+ return;
34891
+ const globalHint = await ctx.globalHint();
34892
+ const suppressed = !shouldSurface(breaker, nowMs);
34893
+ if (!suppressed) {
34894
+ await saveBreaker(absolutePath, {
34895
+ ...breaker,
34896
+ lastSurfacedAtMs: nowMs
34897
+ });
34898
+ }
34899
+ 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>.";
34900
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
34901
+ return {
34902
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
34903
+ ...globalHint ? {
34904
+ accessToken,
34905
+ refreshToken,
34906
+ baseUrl: credentials.UIPATH_URL,
34907
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
34908
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
34909
+ tenantName: credentials.UIPATH_TENANT_NAME,
34910
+ tenantId: credentials.UIPATH_TENANT_ID,
34911
+ expiration,
34912
+ source: "file" /* File */
34913
+ } : {},
34914
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
34915
+ refreshCircuitOpen: true,
34916
+ refreshTelemetrySuppressed: suppressed,
34917
+ tokenRefresh: { attempted: false, success: false }
34918
+ };
34919
+ }
34920
+ async function lockAcquireFailureStatus(ctx, error) {
34921
+ const msg = errorMessage(error);
34922
+ const globalHint = await ctx.globalHint();
34923
+ if (globalHint) {
34924
+ return {
34925
+ loginStatus: "Expired",
34926
+ accessToken: ctx.accessToken,
34927
+ refreshToken: ctx.refreshToken,
34928
+ baseUrl: ctx.credentials.UIPATH_URL,
34929
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
34930
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
34931
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
34932
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
34933
+ expiration: ctx.expiration,
34934
+ source: "file" /* File */,
34935
+ hint: globalHint,
34936
+ tokenRefresh: {
34937
+ attempted: false,
34938
+ success: false,
34939
+ errorMessage: `lock acquisition failed: ${msg}`
34940
+ }
34941
+ };
34942
+ }
34943
+ return {
34944
+ loginStatus: "Refresh Failed",
34945
+ 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.",
34946
+ tokenRefresh: {
34947
+ attempted: false,
34948
+ success: false,
34949
+ errorMessage: `lock acquisition failed: ${msg}`
34950
+ }
34951
+ };
34952
+ }
35829
34953
  async function runRefreshLocked(inputs) {
35830
34954
  const {
35831
34955
  absolutePath,
@@ -35835,7 +34959,10 @@ async function runRefreshLocked(inputs) {
35835
34959
  loadEnvFile,
35836
34960
  saveEnvFile,
35837
34961
  refreshFn,
35838
- resolveConfig
34962
+ resolveConfig,
34963
+ loadBreaker,
34964
+ saveBreaker,
34965
+ clearBreaker
35839
34966
  } = inputs;
35840
34967
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
35841
34968
  let fresh;
@@ -35858,6 +34985,7 @@ async function runRefreshLocked(inputs) {
35858
34985
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
35859
34986
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
35860
34987
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
34988
+ await clearBreaker(absolutePath);
35861
34989
  return {
35862
34990
  kind: "ok",
35863
34991
  accessToken: freshAccess,
@@ -35881,8 +35009,21 @@ async function runRefreshLocked(inputs) {
35881
35009
  refreshedRefresh = refreshed.refreshToken;
35882
35010
  } catch (error) {
35883
35011
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
35884
- 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.";
35012
+ 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.";
35885
35013
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
35014
+ const fp = await refreshTokenFingerprint(tokenForIdP);
35015
+ if (isOAuthFailure) {
35016
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
35017
+ } else {
35018
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
35019
+ const attempts = (prior.attempts ?? 0) + 1;
35020
+ await saveBreaker(absolutePath, {
35021
+ ...prior,
35022
+ deadTokenFp: undefined,
35023
+ attempts,
35024
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
35025
+ });
35026
+ }
35886
35027
  return {
35887
35028
  kind: "fail",
35888
35029
  status: {
@@ -35911,6 +35052,7 @@ async function runRefreshLocked(inputs) {
35911
35052
  }
35912
35053
  };
35913
35054
  }
35055
+ await clearBreaker(absolutePath);
35914
35056
  try {
35915
35057
  await saveEnvFile({
35916
35058
  envPath: absolutePath,
@@ -35943,214 +35085,25 @@ async function runRefreshLocked(inputs) {
35943
35085
  };
35944
35086
  }
35945
35087
  }
35946
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
35947
- const {
35948
- resolveEnvFilePath = resolveEnvFilePathAsync,
35949
- loadEnvFile = loadEnvFileAsync,
35950
- saveEnvFile = saveEnvFileAsync,
35951
- getFs = getFileSystem,
35952
- refreshToken: refreshTokenFn = refreshAccessToken,
35953
- resolveConfig = resolveConfigAsync,
35954
- robotFallback = tryRobotClientFallback
35955
- } = deps;
35956
- if (isRobotAuthEnforced()) {
35957
- if (isEnvAuthEnabled()) {
35958
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
35959
- }
35960
- const robotCreds = await robotFallback({ force: true });
35961
- if (!robotCreds) {
35962
- return {
35963
- loginStatus: "Not logged in",
35964
- 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.`
35965
- };
35966
- }
35967
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
35968
- return {
35969
- loginStatus: "Logged in",
35970
- accessToken: robotCreds.accessToken,
35971
- baseUrl: robotCreds.baseUrl,
35972
- organizationName: robotCreds.organizationName,
35973
- organizationId: robotCreds.organizationId,
35974
- tenantName: robotCreds.tenantName,
35975
- tenantId: robotCreds.tenantId,
35976
- issuer: robotCreds.issuer,
35977
- expiration: expiration2,
35978
- source: "robot" /* Robot */
35979
- };
35980
- }
35981
- if (isEnvAuthEnabled()) {
35982
- return readAuthFromEnv();
35983
- }
35984
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
35985
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
35986
- if (absolutePath === undefined) {
35987
- const robotCreds = await robotFallback();
35988
- if (robotCreds) {
35989
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
35990
- const status = {
35991
- loginStatus: "Logged in",
35992
- accessToken: robotCreds.accessToken,
35993
- baseUrl: robotCreds.baseUrl,
35994
- organizationName: robotCreds.organizationName,
35995
- organizationId: robotCreds.organizationId,
35996
- tenantName: robotCreds.tenantName,
35997
- tenantId: robotCreds.tenantId,
35998
- issuer: robotCreds.issuer,
35999
- expiration: expiration2,
36000
- source: "robot" /* Robot */
36001
- };
36002
- return status;
36003
- }
36004
- return { loginStatus: "Not logged in" };
36005
- }
36006
- let credentials;
36007
- try {
36008
- credentials = await loadEnvFile({ envPath: absolutePath });
36009
- } catch (error) {
36010
- if (isFileNotFoundError(error)) {
36011
- return { loginStatus: "Not logged in" };
36012
- }
36013
- throw error;
36014
- }
36015
- if (!credentials.UIPATH_ACCESS_TOKEN) {
36016
- return { loginStatus: "Not logged in" };
36017
- }
36018
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
36019
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
36020
- let expiration = getTokenExpiration(accessToken);
36021
- let persistenceWarning;
36022
- let lockReleaseFailed = false;
36023
- let tokenRefresh;
36024
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
36025
- const tryGlobalCredsHint = async () => {
36026
- const fs7 = getFs();
36027
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
36028
- if (absolutePath === globalPath)
36029
- return;
36030
- if (!await fs7.exists(globalPath))
36031
- return;
36032
- try {
36033
- const globalCreds = await loadEnvFile({ envPath: globalPath });
36034
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
36035
- return;
36036
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
36037
- if (globalExp && globalExp <= new Date)
36038
- return;
36039
- 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.`;
36040
- } catch {
36041
- return;
36042
- }
36043
- };
36044
- if (expiration && expiration <= outerThreshold && refreshToken) {
36045
- let release;
36046
- try {
36047
- release = await getFs().acquireLock(absolutePath);
36048
- } catch (error) {
36049
- const msg = errorMessage(error);
36050
- const globalHint = await tryGlobalCredsHint();
36051
- if (globalHint) {
36052
- return {
36053
- loginStatus: "Expired",
36054
- accessToken,
36055
- refreshToken,
36056
- baseUrl: credentials.UIPATH_URL,
36057
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
36058
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
36059
- tenantName: credentials.UIPATH_TENANT_NAME,
36060
- tenantId: credentials.UIPATH_TENANT_ID,
36061
- expiration,
36062
- source: "file" /* File */,
36063
- hint: globalHint,
36064
- tokenRefresh: {
36065
- attempted: false,
36066
- success: false,
36067
- errorMessage: `lock acquisition failed: ${msg}`
36068
- }
36069
- };
36070
- }
36071
- return {
36072
- loginStatus: "Refresh Failed",
36073
- 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.",
36074
- tokenRefresh: {
36075
- attempted: false,
36076
- success: false,
36077
- errorMessage: `lock acquisition failed: ${msg}`
36078
- }
36079
- };
36080
- }
36081
- let lockedFailure;
36082
- try {
36083
- const outcome = await runRefreshLocked({
36084
- absolutePath,
36085
- refreshToken,
36086
- customAuthority: credentials.UIPATH_URL,
36087
- ensureTokenValidityMinutes,
36088
- loadEnvFile,
36089
- saveEnvFile,
36090
- refreshFn: refreshTokenFn,
36091
- resolveConfig
36092
- });
36093
- if (outcome.kind === "fail") {
36094
- lockedFailure = outcome.status;
36095
- } else {
36096
- accessToken = outcome.accessToken;
36097
- refreshToken = outcome.refreshToken;
36098
- expiration = outcome.expiration;
36099
- tokenRefresh = outcome.tokenRefresh;
36100
- if (outcome.persistenceWarning) {
36101
- persistenceWarning = outcome.persistenceWarning;
36102
- }
36103
- }
36104
- } finally {
36105
- try {
36106
- await release();
36107
- } catch {
36108
- lockReleaseFailed = true;
36109
- }
36110
- }
36111
- if (lockedFailure) {
36112
- const globalHint = await tryGlobalCredsHint();
36113
- const base = globalHint ? {
36114
- ...lockedFailure,
36115
- loginStatus: "Expired",
36116
- hint: globalHint
36117
- } : lockedFailure;
36118
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
36119
- }
36120
- }
36121
- const result = {
36122
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
36123
- accessToken,
36124
- refreshToken,
36125
- baseUrl: credentials.UIPATH_URL,
36126
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
36127
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
36128
- tenantName: credentials.UIPATH_TENANT_NAME,
36129
- tenantId: credentials.UIPATH_TENANT_ID,
36130
- expiration,
36131
- source: "file" /* File */,
36132
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
36133
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
36134
- ...tokenRefresh ? { tokenRefresh } : {}
36135
- };
36136
- if (result.loginStatus === "Expired") {
36137
- const globalHint = await tryGlobalCredsHint();
36138
- if (globalHint) {
36139
- result.hint = globalHint;
36140
- }
36141
- }
36142
- return result;
36143
- };
36144
- var isFileNotFoundError = (error) => {
36145
- if (!(error instanceof Object))
36146
- return false;
36147
- return error.code === "ENOENT";
36148
- };
36149
- var getLoginStatusAsync = async (options = {}) => {
36150
- return getLoginStatusWithDeps(options);
36151
- };
35088
+ function normalizeTokenRefreshFailure() {
35089
+ return "stored refresh token is invalid or expired";
35090
+ }
35091
+ function normalizeTokenRefreshUnavailableFailure() {
35092
+ return "token refresh failed before authentication completed";
35093
+ }
35094
+ function errorMessage(error) {
35095
+ return error instanceof Error ? error.message : String(error);
35096
+ }
36152
35097
  // ../auth/src/interactive.ts
36153
35098
  init_src();
35099
+
35100
+ // ../auth/src/selectTenant.ts
35101
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
35102
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
35103
+ var TENANT_SELECTION_CODES = new Set([
35104
+ TENANT_SELECTION_REQUIRED_CODE,
35105
+ INVALID_TENANT_CODE
35106
+ ]);
36154
35107
  // ../auth/src/logout.ts
36155
35108
  init_src();
36156
35109
 
@@ -37563,7 +36516,7 @@ class Doc {
37563
36516
  var version = {
37564
36517
  major: 4,
37565
36518
  minor: 4,
37566
- patch: 1
36519
+ patch: 3
37567
36520
  };
37568
36521
 
37569
36522
  // ../../node_modules/zod/v4/core/schemas.js
@@ -38109,11 +37062,11 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
38109
37062
  return payload;
38110
37063
  };
38111
37064
  });
38112
- function handleArrayResult(result, final, index2) {
37065
+ function handleArrayResult(result, final, index) {
38113
37066
  if (result.issues.length) {
38114
- final.issues.push(...prefixIssues(index2, result.issues));
37067
+ final.issues.push(...prefixIssues(index, result.issues));
38115
37068
  }
38116
- final.value[index2] = result.value;
37069
+ final.value[index] = result.value;
38117
37070
  }
38118
37071
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
38119
37072
  $ZodType.init(inst, def);
@@ -38594,14 +37547,14 @@ function mergeValues(a, b) {
38594
37547
  return { valid: false, mergeErrorPath: [] };
38595
37548
  }
38596
37549
  const newArray = [];
38597
- for (let index2 = 0;index2 < a.length; index2++) {
38598
- const itemA = a[index2];
38599
- const itemB = b[index2];
37550
+ for (let index = 0;index < a.length; index++) {
37551
+ const itemA = a[index];
37552
+ const itemB = b[index];
38600
37553
  const sharedValue = mergeValues(itemA, itemB);
38601
37554
  if (!sharedValue.valid) {
38602
37555
  return {
38603
37556
  valid: false,
38604
- mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
37557
+ mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
38605
37558
  };
38606
37559
  }
38607
37560
  newArray.push(sharedValue.data);
@@ -38819,6 +37772,7 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
38819
37772
  });
38820
37773
  var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
38821
37774
  $ZodType.init(inst, def);
37775
+ inst._zod.optin = "optional";
38822
37776
  inst._zod.parse = (payload, ctx) => {
38823
37777
  if (ctx.direction === "backward") {
38824
37778
  throw new $ZodEncodeError(inst.constructor.name);
@@ -38828,6 +37782,7 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) =>
38828
37782
  const output = _out instanceof Promise ? _out : Promise.resolve(_out);
38829
37783
  return output.then((output2) => {
38830
37784
  payload.value = output2;
37785
+ payload.fallback = true;
38831
37786
  return payload;
38832
37787
  });
38833
37788
  }
@@ -38835,11 +37790,12 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) =>
38835
37790
  throw new $ZodAsyncError;
38836
37791
  }
38837
37792
  payload.value = _out;
37793
+ payload.fallback = true;
38838
37794
  return payload;
38839
37795
  };
38840
37796
  });
38841
37797
  function handleOptionalResult(result, input) {
38842
- if (result.issues.length && input === undefined) {
37798
+ if (input === undefined && (result.issues.length || result.fallback)) {
38843
37799
  return { issues: [], value: undefined };
38844
37800
  }
38845
37801
  return result;
@@ -38857,10 +37813,11 @@ var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
38857
37813
  });
38858
37814
  inst._zod.parse = (payload, ctx) => {
38859
37815
  if (def.innerType._zod.optin === "optional") {
37816
+ const input = payload.value;
38860
37817
  const result = def.innerType._zod.run(payload, ctx);
38861
37818
  if (result instanceof Promise)
38862
- return result.then((r) => handleOptionalResult(r, payload.value));
38863
- return handleOptionalResult(result, payload.value);
37819
+ return result.then((r) => handleOptionalResult(r, input));
37820
+ return handleOptionalResult(result, input);
38864
37821
  }
38865
37822
  if (payload.value === undefined) {
38866
37823
  return payload;
@@ -38959,7 +37916,7 @@ function handleNonOptionalResult(payload, inst) {
38959
37916
  }
38960
37917
  var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
38961
37918
  $ZodType.init(inst, def);
38962
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
37919
+ inst._zod.optin = "optional";
38963
37920
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
38964
37921
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
38965
37922
  inst._zod.parse = (payload, ctx) => {
@@ -38979,6 +37936,7 @@ var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
38979
37936
  input: payload.value
38980
37937
  });
38981
37938
  payload.issues = [];
37939
+ payload.fallback = true;
38982
37940
  }
38983
37941
  return payload;
38984
37942
  });
@@ -38993,6 +37951,7 @@ var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
38993
37951
  input: payload.value
38994
37952
  });
38995
37953
  payload.issues = [];
37954
+ payload.fallback = true;
38996
37955
  }
38997
37956
  return payload;
38998
37957
  };
@@ -39023,8 +37982,11 @@ function handlePipeResult(left, next, ctx) {
39023
37982
  left.aborted = true;
39024
37983
  return left;
39025
37984
  }
39026
- return next._zod.run({ value: left.value, issues: left.issues }, ctx);
37985
+ return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
39027
37986
  }
37987
+ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => {
37988
+ $ZodPipe.init(inst, def);
37989
+ });
39028
37990
  var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
39029
37991
  $ZodType.init(inst, def);
39030
37992
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
@@ -40053,6 +39015,8 @@ function isTransforming(_schema, _ctx) {
40053
39015
  return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
40054
39016
  }
40055
39017
  if (def.type === "pipe") {
39018
+ if (_schema._zod.traits.has("$ZodCodec"))
39019
+ return true;
40056
39020
  return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
40057
39021
  }
40058
39022
  if (def.type === "object") {
@@ -40413,7 +39377,8 @@ var catchProcessor = (schema, ctx, json, params) => {
40413
39377
  };
40414
39378
  var pipeProcessor = (schema, ctx, _json, params) => {
40415
39379
  const def = schema._zod.def;
40416
- const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
39380
+ const inIsTransform = def.in._zod.traits.has("$ZodTransform");
39381
+ const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
40417
39382
  process9(innerType, ctx, params);
40418
39383
  const seen = ctx.seen.get(schema);
40419
39384
  seen.ref = innerType;
@@ -41305,10 +40270,12 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
41305
40270
  if (output instanceof Promise) {
41306
40271
  return output.then((output2) => {
41307
40272
  payload.value = output2;
40273
+ payload.fallback = true;
41308
40274
  return payload;
41309
40275
  });
41310
40276
  }
41311
40277
  payload.value = output;
40278
+ payload.fallback = true;
41312
40279
  return payload;
41313
40280
  };
41314
40281
  });
@@ -41426,6 +40393,10 @@ function pipe(in_, out) {
41426
40393
  out
41427
40394
  });
41428
40395
  }
40396
+ var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => {
40397
+ ZodPipe.init(inst, def);
40398
+ $ZodPreprocess.init(inst, def);
40399
+ });
41429
40400
  var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
41430
40401
  $ZodReadonly.init(inst, def);
41431
40402
  ZodType.init(inst, def);
@@ -41453,7 +40424,11 @@ function superRefine(fn, params) {
41453
40424
  return _superRefine(fn, params);
41454
40425
  }
41455
40426
  function preprocess(fn, schema) {
41456
- return pipe(transform(fn), schema);
40427
+ return new ZodPreprocess({
40428
+ type: "pipe",
40429
+ in: transform(fn),
40430
+ out: schema
40431
+ });
41457
40432
  }
41458
40433
  // ../../node_modules/zod/v4/classic/compat.js
41459
40434
  var ZodIssueCode = {
@@ -44702,27 +43677,34 @@ var LF = 10;
44702
43677
  var CR = 13;
44703
43678
  var SPACE = 32;
44704
43679
  function noop(_arg) {}
44705
- function createParser(callbacks) {
44706
- if (typeof callbacks == "function")
44707
- throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
44708
- const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];
44709
- let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
43680
+ function createParser(config2) {
43681
+ if (typeof config2 == "function")
43682
+ throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
43683
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = [];
43684
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
44710
43685
  function feed(chunk) {
43686
+ if (terminated)
43687
+ throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");
44711
43688
  if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
44712
43689
  const trailing2 = processLines(chunk);
44713
- trailing2 !== "" && pendingFragments.push(trailing2);
43690
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
44714
43691
  return;
44715
43692
  }
44716
43693
  if (chunk.indexOf(`
44717
43694
  `) === -1 && chunk.indexOf("\r") === -1) {
44718
- pendingFragments.push(chunk);
43695
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
44719
43696
  return;
44720
43697
  }
44721
43698
  pendingFragments.push(chunk);
44722
43699
  const input = pendingFragments.join("");
44723
- pendingFragments.length = 0;
43700
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
44724
43701
  const trailing = processLines(input);
44725
- trailing !== "" && pendingFragments.push(trailing);
43702
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
43703
+ }
43704
+ function checkBufferSize() {
43705
+ maxBufferSize !== undefined && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = undefined, data = "", dataLines = 0, eventType = undefined, onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
43706
+ type: "max-buffer-size-exceeded"
43707
+ }))));
44726
43708
  }
44727
43709
  function processLines(chunk) {
44728
43710
  let searchIndex = 0;
@@ -44834,7 +43816,7 @@ ${value}`, dataLines++;
44834
43816
  const incompleteLine = pendingFragments.join("");
44835
43817
  parseLine(incompleteLine, 0, incompleteLine.length);
44836
43818
  }
44837
- isFirstChunk = true, id = undefined, data = "", dataLines = 0, eventType = undefined, pendingFragments.length = 0;
43819
+ isFirstChunk = true, id = undefined, data = "", dataLines = 0, eventType = undefined, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
44838
43820
  }
44839
43821
  return { feed, reset };
44840
43822
  }
@@ -44847,7 +43829,7 @@ function isEventPrefix(chunk, i, firstCharCode) {
44847
43829
 
44848
43830
  // ../../node_modules/eventsource-parser/dist/stream.js
44849
43831
  class EventSourceParserStream extends TransformStream {
44850
- constructor({ onError, onRetry, onComment } = {}) {
43832
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
44851
43833
  let parser;
44852
43834
  super({
44853
43835
  start(controller) {
@@ -44856,10 +43838,11 @@ class EventSourceParserStream extends TransformStream {
44856
43838
  controller.enqueue(event);
44857
43839
  },
44858
43840
  onError(error2) {
44859
- onError === "terminate" ? controller.error(error2) : typeof onError == "function" && onError(error2);
43841
+ typeof onError == "function" && onError(error2), (onError === "terminate" || error2.type === "max-buffer-size-exceeded") && controller.error(error2);
44860
43842
  },
44861
43843
  onRetry,
44862
- onComment
43844
+ onComment,
43845
+ maxBufferSize
44863
43846
  });
44864
43847
  },
44865
43848
  transform(chunk) {
@@ -45419,3 +44402,5 @@ export {
45419
44402
  registerCommands,
45420
44403
  metadata
45421
44404
  };
44405
+
44406
+ //# debugId=3C3D00942299C13864756E2164756E21