@uipath/identity-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 +884 -1917
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -13520,8 +13520,8 @@ var require_Subscription = __commonJS((exports) => {
13520
13520
  if (_parentOrParents instanceof Subscription2) {
13521
13521
  _parentOrParents.remove(this);
13522
13522
  } else if (_parentOrParents !== null) {
13523
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
13524
- var parent_1 = _parentOrParents[index2];
13523
+ for (var index = 0;index < _parentOrParents.length; ++index) {
13524
+ var parent_1 = _parentOrParents[index];
13525
13525
  parent_1.remove(this);
13526
13526
  }
13527
13527
  }
@@ -13536,10 +13536,10 @@ var require_Subscription = __commonJS((exports) => {
13536
13536
  }
13537
13537
  }
13538
13538
  if (isArray_1.isArray(_subscriptions)) {
13539
- var index2 = -1;
13539
+ var index = -1;
13540
13540
  var len = _subscriptions.length;
13541
- while (++index2 < len) {
13542
- var sub2 = _subscriptions[index2];
13541
+ while (++index < len) {
13542
+ var sub2 = _subscriptions[index];
13543
13543
  if (isObject_1.isObject(sub2)) {
13544
13544
  try {
13545
13545
  sub2.unsubscribe();
@@ -14969,13 +14969,13 @@ var require_AsyncAction = __commonJS((exports) => {
14969
14969
  var id = this.id;
14970
14970
  var scheduler = this.scheduler;
14971
14971
  var actions = scheduler.actions;
14972
- var index2 = actions.indexOf(this);
14972
+ var index = actions.indexOf(this);
14973
14973
  this.work = null;
14974
14974
  this.state = null;
14975
14975
  this.pending = false;
14976
14976
  this.scheduler = null;
14977
- if (index2 !== -1) {
14978
- actions.splice(index2, 1);
14977
+ if (index !== -1) {
14978
+ actions.splice(index, 1);
14979
14979
  }
14980
14980
  if (id != null) {
14981
14981
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -15819,17 +15819,17 @@ var require_AsapScheduler = __commonJS((exports) => {
15819
15819
  this.scheduled = undefined;
15820
15820
  var actions = this.actions;
15821
15821
  var error;
15822
- var index2 = -1;
15822
+ var index = -1;
15823
15823
  var count = actions.length;
15824
15824
  action = action || actions.shift();
15825
15825
  do {
15826
15826
  if (error = action.execute(action.state, action.delay)) {
15827
15827
  break;
15828
15828
  }
15829
- } while (++index2 < count && (action = actions.shift()));
15829
+ } while (++index < count && (action = actions.shift()));
15830
15830
  this.active = false;
15831
15831
  if (error) {
15832
- while (++index2 < count && (action = actions.shift())) {
15832
+ while (++index < count && (action = actions.shift())) {
15833
15833
  action.unsubscribe();
15834
15834
  }
15835
15835
  throw error;
@@ -15952,17 +15952,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
15952
15952
  this.scheduled = undefined;
15953
15953
  var actions = this.actions;
15954
15954
  var error;
15955
- var index2 = -1;
15955
+ var index = -1;
15956
15956
  var count = actions.length;
15957
15957
  action = action || actions.shift();
15958
15958
  do {
15959
15959
  if (error = action.execute(action.state, action.delay)) {
15960
15960
  break;
15961
15961
  }
15962
- } while (++index2 < count && (action = actions.shift()));
15962
+ } while (++index < count && (action = actions.shift()));
15963
15963
  this.active = false;
15964
15964
  if (error) {
15965
- while (++index2 < count && (action = actions.shift())) {
15965
+ while (++index < count && (action = actions.shift())) {
15966
15966
  action.unsubscribe();
15967
15967
  }
15968
15968
  throw error;
@@ -16046,16 +16046,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
16046
16046
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
16047
16047
  var VirtualAction = function(_super) {
16048
16048
  __extends(VirtualAction2, _super);
16049
- function VirtualAction2(scheduler, work, index2) {
16050
- if (index2 === undefined) {
16051
- index2 = scheduler.index += 1;
16049
+ function VirtualAction2(scheduler, work, index) {
16050
+ if (index === undefined) {
16051
+ index = scheduler.index += 1;
16052
16052
  }
16053
16053
  var _this = _super.call(this, scheduler, work) || this;
16054
16054
  _this.scheduler = scheduler;
16055
16055
  _this.work = work;
16056
- _this.index = index2;
16056
+ _this.index = index;
16057
16057
  _this.active = true;
16058
- _this.index = scheduler.index = index2;
16058
+ _this.index = scheduler.index = index;
16059
16059
  return _this;
16060
16060
  }
16061
16061
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -17202,9 +17202,9 @@ var require_mergeMap = __commonJS((exports) => {
17202
17202
  };
17203
17203
  MergeMapSubscriber2.prototype._tryNext = function(value) {
17204
17204
  var result;
17205
- var index2 = this.index++;
17205
+ var index = this.index++;
17206
17206
  try {
17207
- result = this.project(value, index2);
17207
+ result = this.project(value, index);
17208
17208
  } catch (err) {
17209
17209
  this.destination.error(err);
17210
17210
  return;
@@ -17784,12 +17784,12 @@ var require_pairs2 = __commonJS((exports) => {
17784
17784
  }
17785
17785
  exports.pairs = pairs;
17786
17786
  function dispatch(state) {
17787
- var { keys, index: index2, subscriber, subscription, obj } = state;
17787
+ var { keys, index, subscriber, subscription, obj } = state;
17788
17788
  if (!subscriber.closed) {
17789
- if (index2 < keys.length) {
17790
- var key = keys[index2];
17789
+ if (index < keys.length) {
17790
+ var key = keys[index];
17791
17791
  subscriber.next([key, obj[key]]);
17792
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
17792
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
17793
17793
  } else {
17794
17794
  subscriber.complete();
17795
17795
  }
@@ -18002,18 +18002,18 @@ var require_range = __commonJS((exports) => {
18002
18002
  count = start;
18003
18003
  start = 0;
18004
18004
  }
18005
- var index2 = 0;
18005
+ var index = 0;
18006
18006
  var current = start;
18007
18007
  if (scheduler) {
18008
18008
  return scheduler.schedule(dispatch, 0, {
18009
- index: index2,
18009
+ index,
18010
18010
  count,
18011
18011
  start,
18012
18012
  subscriber
18013
18013
  });
18014
18014
  } else {
18015
18015
  do {
18016
- if (index2++ >= count) {
18016
+ if (index++ >= count) {
18017
18017
  subscriber.complete();
18018
18018
  break;
18019
18019
  }
@@ -18028,8 +18028,8 @@ var require_range = __commonJS((exports) => {
18028
18028
  }
18029
18029
  exports.range = range;
18030
18030
  function dispatch(state) {
18031
- var { start, index: index2, count, subscriber } = state;
18032
- if (index2 >= count) {
18031
+ var { start, index, count, subscriber } = state;
18032
+ if (index >= count) {
18033
18033
  subscriber.complete();
18034
18034
  return;
18035
18035
  }
@@ -18037,7 +18037,7 @@ var require_range = __commonJS((exports) => {
18037
18037
  if (subscriber.closed) {
18038
18038
  return;
18039
18039
  }
18040
- state.index = index2 + 1;
18040
+ state.index = index + 1;
18041
18041
  state.start = start + 1;
18042
18042
  this.schedule(state);
18043
18043
  }
@@ -18075,14 +18075,14 @@ var require_timer = __commonJS((exports) => {
18075
18075
  }
18076
18076
  exports.timer = timer;
18077
18077
  function dispatch(state) {
18078
- var { index: index2, period, subscriber } = state;
18079
- subscriber.next(index2);
18078
+ var { index, period, subscriber } = state;
18079
+ subscriber.next(index);
18080
18080
  if (subscriber.closed) {
18081
18081
  return;
18082
18082
  } else if (period === -1) {
18083
18083
  return subscriber.complete();
18084
18084
  }
18085
- state.index = index2 + 1;
18085
+ state.index = index + 1;
18086
18086
  this.schedule(state, period);
18087
18087
  }
18088
18088
  });
@@ -21230,7 +21230,7 @@ var init_server = __esm(() => {
21230
21230
  var package_default = {
21231
21231
  name: "@uipath/identity-tool",
21232
21232
  license: "MIT",
21233
- version: "1.196.0",
21233
+ version: "1.197.0-preview.59",
21234
21234
  description: "Manage Identity Server users, groups, robot accounts, and external apps.",
21235
21235
  private: false,
21236
21236
  repository: {
@@ -21241,7 +21241,9 @@ var package_default = {
21241
21241
  publishConfig: {
21242
21242
  registry: "https://npm.pkg.github.com/@uipath"
21243
21243
  },
21244
- keywords: ["cli-tool"],
21244
+ keywords: [
21245
+ "cli-tool"
21246
+ ],
21245
21247
  type: "module",
21246
21248
  main: "./dist/tool.js",
21247
21249
  exports: {
@@ -21317,27 +21319,54 @@ var NETWORK_ERROR_CODES = new Set([
21317
21319
  "ENETUNREACH",
21318
21320
  "EAI_FAIL"
21319
21321
  ]);
21320
- function isHtmlDocument(body) {
21321
- return /^\s*(<!doctype html|<html\b)/i.test(body);
21322
- }
21323
- function extractNetworkErrorCode(error) {
21324
- if (error === null || typeof error !== "object") {
21325
- return;
21326
- }
21327
- const err = error;
21328
- const code = typeof err.code === "string" ? err.code : undefined;
21329
- if (code && NETWORK_ERROR_CODES.has(code)) {
21330
- return code;
21331
- }
21332
- const cause = err.cause;
21333
- if (cause !== null && typeof cause === "object") {
21334
- const causeCode = cause.code;
21335
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
21336
- return causeCode;
21322
+ var TLS_ERROR_CODES = new Set([
21323
+ "SELF_SIGNED_CERT_IN_CHAIN",
21324
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
21325
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
21326
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21327
+ "UNABLE_TO_GET_ISSUER_CERT",
21328
+ "CERT_HAS_EXPIRED",
21329
+ "CERT_UNTRUSTED",
21330
+ "ERR_TLS_CERT_ALTNAME_INVALID"
21331
+ ]);
21332
+ 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.";
21333
+ 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.";
21334
+ function describeConnectivityError(error) {
21335
+ let current = error;
21336
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
21337
+ const cur = current;
21338
+ const code = typeof cur.code === "string" ? cur.code : undefined;
21339
+ const message = typeof cur.message === "string" ? cur.message : undefined;
21340
+ if (code && TLS_ERROR_CODES.has(code)) {
21341
+ return {
21342
+ code,
21343
+ kind: "tls",
21344
+ message: message ?? code,
21345
+ instructions: TLS_INSTRUCTIONS
21346
+ };
21337
21347
  }
21348
+ if (code && NETWORK_ERROR_CODES.has(code)) {
21349
+ return {
21350
+ code,
21351
+ kind: "network",
21352
+ message: message ?? code,
21353
+ instructions: NETWORK_INSTRUCTIONS
21354
+ };
21355
+ }
21356
+ current = cur.cause;
21338
21357
  }
21339
21358
  return;
21340
21359
  }
21360
+ function parseHttpStatusFromMessage(message) {
21361
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
21362
+ if (!match)
21363
+ return;
21364
+ const status = Number(match[1]);
21365
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
21366
+ }
21367
+ function isHtmlDocument(body) {
21368
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
21369
+ }
21341
21370
  function retryHintForRetryAfter(seconds) {
21342
21371
  if (seconds <= 1) {
21343
21372
  return "RetryAfter1Second";
@@ -21378,15 +21407,28 @@ function classifyError(status, error) {
21378
21407
  if (status !== undefined && status >= 500 && status < 600) {
21379
21408
  return { errorCode: "server_error", retry: "RetryLater" };
21380
21409
  }
21381
- if (extractNetworkErrorCode(error)) {
21382
- return { errorCode: "network_error", retry: "RetryLater" };
21410
+ const connectivity = describeConnectivityError(error);
21411
+ if (connectivity) {
21412
+ return {
21413
+ errorCode: "network_error",
21414
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
21415
+ };
21383
21416
  }
21384
21417
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
21385
21418
  }
21419
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
21420
+ if (extractedMessage) {
21421
+ return `HTTP ${status}: ${extractedMessage}`;
21422
+ }
21423
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
21424
+ }
21386
21425
  async function extractErrorDetails(error, options) {
21387
21426
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
21388
21427
  const response = err.response;
21389
- const status = err.status ?? response?.status;
21428
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21429
+ const explicitStatus = err.status ?? response?.status;
21430
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
21431
+ const status = explicitStatus ?? inferredStatus;
21390
21432
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
21391
21433
  let rawBody;
21392
21434
  let extractedMessage;
@@ -21421,7 +21463,6 @@ async function extractErrorDetails(error, options) {
21421
21463
  }
21422
21464
  }
21423
21465
  }
21424
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21425
21466
  let message;
21426
21467
  let result = "Failure";
21427
21468
  const classification = classifyError(status, error);
@@ -21435,10 +21476,10 @@ async function extractErrorDetails(error, options) {
21435
21476
  } else if (status === 405) {
21436
21477
  message = DEFAULT_405;
21437
21478
  } else if (status === 400 || status === 422) {
21438
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21479
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21439
21480
  result = "ValidationError";
21440
21481
  } else if (status === 429) {
21441
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21482
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21442
21483
  } else if (extractedMessage) {
21443
21484
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
21444
21485
  message = rawMessage;
@@ -21446,7 +21487,9 @@ async function extractErrorDetails(error, options) {
21446
21487
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
21447
21488
  }
21448
21489
  } else if (status) {
21449
- if (rawMessage === "Unknown error" && response) {
21490
+ if (inferredStatus !== undefined) {
21491
+ message = rawMessage;
21492
+ } else if (rawMessage === "Unknown error" && response) {
21450
21493
  const statusText = response.statusText;
21451
21494
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
21452
21495
  } else {
@@ -21455,6 +21498,12 @@ async function extractErrorDetails(error, options) {
21455
21498
  } else {
21456
21499
  message = rawMessage;
21457
21500
  }
21501
+ if (status === undefined) {
21502
+ const connectivity = describeConnectivityError(error);
21503
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
21504
+ message = `${message}: ${connectivity.message}`;
21505
+ }
21506
+ }
21458
21507
  let details = rawMessage;
21459
21508
  if (rawBody) {
21460
21509
  if (parsedBody) {
@@ -21622,6 +21671,7 @@ var CONSOLE_FALLBACK = {
21622
21671
  writeLog: (str) => process.stdout.write(str),
21623
21672
  capabilities: {
21624
21673
  isInteractive: false,
21674
+ canReadInput: false,
21625
21675
  supportsColor: false,
21626
21676
  outputWidth: 80
21627
21677
  }
@@ -26822,6 +26872,29 @@ function isPlainRecord(value) {
26822
26872
  const prototype = Object.getPrototypeOf(value);
26823
26873
  return prototype === Object.prototype || prototype === null;
26824
26874
  }
26875
+ function extractPagedRows(value) {
26876
+ if (Array.isArray(value) || !isPlainRecord(value))
26877
+ return null;
26878
+ const entries = Object.values(value);
26879
+ if (entries.length === 0)
26880
+ return null;
26881
+ let rows = null;
26882
+ let hasScalarSibling = false;
26883
+ for (const entry of entries) {
26884
+ if (Array.isArray(entry)) {
26885
+ if (rows !== null)
26886
+ return null;
26887
+ rows = entry;
26888
+ } else if (entry !== null && typeof entry === "object") {
26889
+ return null;
26890
+ } else {
26891
+ hasScalarSibling = true;
26892
+ }
26893
+ }
26894
+ if (rows === null || !hasScalarSibling)
26895
+ return null;
26896
+ return rows;
26897
+ }
26825
26898
  function toLowerCamelCaseKey(key) {
26826
26899
  if (!key)
26827
26900
  return key;
@@ -26886,7 +26959,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26886
26959
  break;
26887
26960
  case "plain": {
26888
26961
  if ("Data" in data && data.Data != null) {
26889
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
26962
+ const pagedRows = extractPagedRows(data.Data);
26963
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
26890
26964
  items.forEach((item) => {
26891
26965
  const values = Object.values(item).map((v) => v ?? "").join("\t");
26892
26966
  logFn(values);
@@ -26898,10 +26972,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26898
26972
  break;
26899
26973
  }
26900
26974
  default: {
26901
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
26975
+ const hasData = "Data" in data && data.Data != null;
26976
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
26977
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
26978
+ if (hasData && !(rows !== null && rows.length === 0)) {
26902
26979
  const logValue = data.Log;
26903
- if (Array.isArray(data.Data)) {
26904
- printResizableTable(data.Data, logFn, logValue);
26980
+ if (rows !== null) {
26981
+ printResizableTable(rows, logFn, logValue);
26905
26982
  } else {
26906
26983
  printVerticalTable(data.Data, logFn, logValue);
26907
26984
  }
@@ -27089,6 +27166,44 @@ function defaultErrorCodeForResult(result) {
27089
27166
  return "unknown_error";
27090
27167
  }
27091
27168
  }
27169
+ function parseHttpStatusFromMessage2(message) {
27170
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
27171
+ if (!match)
27172
+ return;
27173
+ const status = Number(match[1]);
27174
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
27175
+ }
27176
+ function defaultErrorCodeForHttpStatus(status) {
27177
+ if (status === undefined)
27178
+ return;
27179
+ if (status === 400 || status === 409 || status === 422) {
27180
+ return "invalid_argument";
27181
+ }
27182
+ if (status === 401)
27183
+ return "authentication_required";
27184
+ if (status === 403)
27185
+ return "permission_denied";
27186
+ if (status === 404)
27187
+ return "not_found";
27188
+ if (status === 405)
27189
+ return "method_not_allowed";
27190
+ if (status === 408)
27191
+ return "timeout";
27192
+ if (status === 429)
27193
+ return "rate_limited";
27194
+ if (status >= 500 && status < 600)
27195
+ return "server_error";
27196
+ return;
27197
+ }
27198
+ function defaultErrorCodeForFailure(data) {
27199
+ if (data.Result === RESULTS.Failure) {
27200
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
27201
+ const errorCode = defaultErrorCodeForHttpStatus(status);
27202
+ if (errorCode)
27203
+ return errorCode;
27204
+ }
27205
+ return defaultErrorCodeForResult(data.Result);
27206
+ }
27092
27207
  function defaultRetryForErrorCode(errorCode) {
27093
27208
  switch (errorCode) {
27094
27209
  case "network_error":
@@ -27118,16 +27233,19 @@ var OutputFormatter;
27118
27233
  OutputFormatter.success = success;
27119
27234
  function error(data) {
27120
27235
  data.Log ??= getLogFilePath() || undefined;
27121
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
27236
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
27122
27237
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
27123
27238
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
27124
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
27125
- result: data.Result,
27126
- errorCode: data.ErrorCode,
27127
- retry: data.Retry,
27128
- message: data.Message
27129
- });
27130
- logOutput(normalizeOutputKeys(data), getOutputFormat());
27239
+ const { SuppressTelemetry, ...envelope } = data;
27240
+ if (!SuppressTelemetry) {
27241
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
27242
+ result: data.Result,
27243
+ errorCode: data.ErrorCode,
27244
+ retry: data.Retry,
27245
+ message: data.Message
27246
+ });
27247
+ }
27248
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
27131
27249
  }
27132
27250
  OutputFormatter.error = error;
27133
27251
  function emitList(code, items, opts) {
@@ -27418,1653 +27536,236 @@ var DEFAULT_PAGE_SIZE = 50;
27418
27536
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
27419
27537
  // ../../common/src/interactivity-context.ts
27420
27538
  var modeSlot = singleton("InteractivityMode");
27421
- // ../../../node_modules/jsonpath-plus/dist/index-node-esm.js
27422
- import vm from "vm";
27539
+ // ../../common/src/polling/types.ts
27540
+ var PollOutcome = {
27541
+ Completed: "completed",
27542
+ Timeout: "timeout",
27543
+ Interrupted: "interrupted",
27544
+ Aborted: "aborted",
27545
+ Failed: "failed"
27546
+ };
27423
27547
 
27424
- class Hooks {
27425
- add(name, callback, first) {
27426
- if (typeof arguments[0] != "string") {
27427
- for (let name2 in arguments[0]) {
27428
- this.add(name2, arguments[0][name2], arguments[1]);
27429
- }
27430
- } else {
27431
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27432
- this[name2] = this[name2] || [];
27433
- if (callback) {
27434
- this[name2][first ? "unshift" : "push"](callback);
27435
- }
27436
- }, this);
27437
- }
27438
- }
27439
- run(name, env) {
27440
- this[name] = this[name] || [];
27441
- this[name].forEach(function(callback) {
27442
- callback.call(env && env.context ? env.context : env, env);
27443
- });
27444
- }
27548
+ // ../../common/src/polling/poll-failure-mapping.ts
27549
+ var REASON_BY_OUTCOME = {
27550
+ [PollOutcome.Timeout]: "poll_timeout",
27551
+ [PollOutcome.Failed]: "poll_failed",
27552
+ [PollOutcome.Interrupted]: "poll_failed",
27553
+ [PollOutcome.Aborted]: "poll_aborted"
27554
+ };
27555
+ // ../../common/src/polling/terminal-statuses.ts
27556
+ var TERMINAL_STATUSES = new Set([
27557
+ "completed",
27558
+ "successful",
27559
+ "faulted",
27560
+ "failed",
27561
+ "cancelled",
27562
+ "canceled",
27563
+ "stopped",
27564
+ "finished"
27565
+ ]);
27566
+ var FAILURE_STATUSES = new Set([
27567
+ "faulted",
27568
+ "failed",
27569
+ "cancelled",
27570
+ "canceled",
27571
+ "stopped"
27572
+ ]);
27573
+ // ../../common/src/preview.ts
27574
+ var previewSlot = singleton("PreviewBuild");
27575
+ function isPreviewBuild() {
27576
+ return previewSlot.get(false) ?? false;
27445
27577
  }
27446
-
27447
- class Plugins {
27448
- constructor(jsep) {
27449
- this.jsep = jsep;
27450
- this.registered = {};
27578
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
27579
+ if (isPreviewBuild()) {
27580
+ return this.command(nameAndArgs, opts);
27451
27581
  }
27452
- register(...plugins) {
27453
- plugins.forEach((plugin) => {
27454
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27455
- throw new Error("Invalid JSEP plugin format");
27456
- }
27457
- if (this.registered[plugin.name]) {
27458
- return;
27459
- }
27460
- plugin.init(this.jsep);
27461
- this.registered[plugin.name] = plugin;
27462
- });
27582
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
27583
+ };
27584
+ // ../../common/src/screen-logger.ts
27585
+ var ScreenLogger;
27586
+ ((ScreenLogger) => {
27587
+ function progress(message) {
27588
+ getOutputSink().writeErr(`${message}
27589
+ `);
27463
27590
  }
27591
+ ScreenLogger.progress = progress;
27592
+ })(ScreenLogger ||= {});
27593
+ // ../../common/src/sdk-user-agent.ts
27594
+ var USER_AGENT_HEADER = "User-Agent";
27595
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
27596
+ function userAgentPatchKey(userAgent) {
27597
+ return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
27464
27598
  }
27465
-
27466
- class Jsep {
27467
- static get version() {
27468
- return "1.4.0";
27469
- }
27470
- static toString() {
27471
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27472
- }
27473
- static addUnaryOp(op_name) {
27474
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27475
- Jsep.unary_ops[op_name] = 1;
27476
- return Jsep;
27477
- }
27478
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27479
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27480
- Jsep.binary_ops[op_name] = precedence;
27481
- if (isRightAssociative) {
27482
- Jsep.right_associative.add(op_name);
27483
- } else {
27484
- Jsep.right_associative.delete(op_name);
27599
+ function splitUserAgentTokens(value) {
27600
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
27601
+ }
27602
+ function appendUserAgentToken(value, userAgent) {
27603
+ const tokens = splitUserAgentTokens(value);
27604
+ const seen = new Set(tokens);
27605
+ for (const token of splitUserAgentTokens(userAgent)) {
27606
+ if (!seen.has(token)) {
27607
+ tokens.push(token);
27608
+ seen.add(token);
27485
27609
  }
27486
- return Jsep;
27487
27610
  }
27488
- static addIdentifierChar(char) {
27489
- Jsep.additional_identifier_chars.add(char);
27490
- return Jsep;
27491
- }
27492
- static addLiteral(literal_name, literal_value) {
27493
- Jsep.literals[literal_name] = literal_value;
27494
- return Jsep;
27611
+ return tokens.join(" ");
27612
+ }
27613
+ function getEffectiveUserAgent(userAgent) {
27614
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
27615
+ }
27616
+ function getHeaderName(headers, headerName) {
27617
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
27618
+ }
27619
+ function getSdkUserAgentToken(pkg) {
27620
+ const packageName = pkg.name.replace(/^@uipath\//, "");
27621
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
27622
+ }
27623
+ function addSdkUserAgentHeader(headers, userAgent) {
27624
+ const result = { ...headers ?? {} };
27625
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
27626
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
27627
+ return result;
27628
+ }
27629
+ function asHeaderRecord(headers) {
27630
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
27631
+ }
27632
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
27633
+ return async (requestContext) => {
27634
+ const initWithHeaders = {
27635
+ ...requestContext.init,
27636
+ headers: forward(asHeaderRecord(requestContext.init.headers))
27637
+ };
27638
+ const override = typeof initOverrides === "function" ? await initOverrides({
27639
+ ...requestContext,
27640
+ init: initWithHeaders
27641
+ }) : initOverrides;
27642
+ return {
27643
+ ...override ?? {},
27644
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
27645
+ };
27646
+ };
27647
+ }
27648
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
27649
+ const prototype = BaseApiClass.prototype;
27650
+ if (prototype[patchKey]) {
27651
+ return;
27495
27652
  }
27496
- static removeUnaryOp(op_name) {
27497
- delete Jsep.unary_ops[op_name];
27498
- if (op_name.length === Jsep.max_unop_len) {
27499
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27500
- }
27501
- return Jsep;
27653
+ if (typeof prototype.request !== "function") {
27654
+ throw new Error("Generated BaseAPI request function not found.");
27502
27655
  }
27503
- static removeAllUnaryOps() {
27504
- Jsep.unary_ops = {};
27505
- Jsep.max_unop_len = 0;
27506
- return Jsep;
27656
+ const originalRequest = prototype.request;
27657
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
27658
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
27659
+ };
27660
+ Object.defineProperty(prototype, patchKey, {
27661
+ value: true
27662
+ });
27663
+ }
27664
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
27665
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
27666
+ }
27667
+ // ../../common/src/tool-provider.ts
27668
+ var factorySlot = singleton("PackagerFactoryProvider");
27669
+ // ../identity-sdk/generated/src/runtime.ts
27670
+ var BASE_PATH = "https://alpha.uipath.com/identity_".replace(/\/+$/, "");
27671
+
27672
+ class Configuration {
27673
+ configuration;
27674
+ constructor(configuration = {}) {
27675
+ this.configuration = configuration;
27507
27676
  }
27508
- static removeIdentifierChar(char) {
27509
- Jsep.additional_identifier_chars.delete(char);
27510
- return Jsep;
27677
+ set config(configuration) {
27678
+ this.configuration = configuration;
27511
27679
  }
27512
- static removeBinaryOp(op_name) {
27513
- delete Jsep.binary_ops[op_name];
27514
- if (op_name.length === Jsep.max_binop_len) {
27515
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27516
- }
27517
- Jsep.right_associative.delete(op_name);
27518
- return Jsep;
27680
+ get basePath() {
27681
+ return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
27519
27682
  }
27520
- static removeAllBinaryOps() {
27521
- Jsep.binary_ops = {};
27522
- Jsep.max_binop_len = 0;
27523
- return Jsep;
27683
+ get fetchApi() {
27684
+ return this.configuration.fetchApi;
27524
27685
  }
27525
- static removeLiteral(literal_name) {
27526
- delete Jsep.literals[literal_name];
27527
- return Jsep;
27686
+ get middleware() {
27687
+ return this.configuration.middleware || [];
27528
27688
  }
27529
- static removeAllLiterals() {
27530
- Jsep.literals = {};
27531
- return Jsep;
27689
+ get queryParamsStringify() {
27690
+ return this.configuration.queryParamsStringify || querystring;
27532
27691
  }
27533
- get char() {
27534
- return this.expr.charAt(this.index);
27692
+ get username() {
27693
+ return this.configuration.username;
27535
27694
  }
27536
- get code() {
27537
- return this.expr.charCodeAt(this.index);
27695
+ get password() {
27696
+ return this.configuration.password;
27538
27697
  }
27539
- constructor(expr) {
27540
- this.expr = expr;
27541
- this.index = 0;
27698
+ get apiKey() {
27699
+ const apiKey = this.configuration.apiKey;
27700
+ if (apiKey) {
27701
+ return typeof apiKey === "function" ? apiKey : () => apiKey;
27702
+ }
27703
+ return;
27542
27704
  }
27543
- static parse(expr) {
27544
- return new Jsep(expr).parse();
27705
+ get accessToken() {
27706
+ const accessToken = this.configuration.accessToken;
27707
+ if (accessToken) {
27708
+ return typeof accessToken === "function" ? accessToken : async () => accessToken;
27709
+ }
27710
+ return;
27545
27711
  }
27546
- static getMaxKeyLen(obj) {
27547
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27712
+ get headers() {
27713
+ return this.configuration.headers;
27548
27714
  }
27549
- static isDecimalDigit(ch) {
27550
- return ch >= 48 && ch <= 57;
27715
+ get credentials() {
27716
+ return this.configuration.credentials;
27551
27717
  }
27552
- static binaryPrecedence(op_val) {
27553
- return Jsep.binary_ops[op_val] || 0;
27718
+ }
27719
+ var DefaultConfig = new Configuration;
27720
+
27721
+ class BaseAPI {
27722
+ configuration;
27723
+ static jsonRegex = new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", "i");
27724
+ middleware;
27725
+ constructor(configuration = DefaultConfig) {
27726
+ this.configuration = configuration;
27727
+ this.middleware = configuration.middleware;
27554
27728
  }
27555
- static isIdentifierStart(ch) {
27556
- 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));
27729
+ withMiddleware(...middlewares) {
27730
+ const next = this.clone();
27731
+ next.middleware = next.middleware.concat(...middlewares);
27732
+ return next;
27557
27733
  }
27558
- static isIdentifierPart(ch) {
27559
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27734
+ withPreMiddleware(...preMiddlewares) {
27735
+ const middlewares = preMiddlewares.map((pre) => ({ pre }));
27736
+ return this.withMiddleware(...middlewares);
27560
27737
  }
27561
- throwError(message) {
27562
- const error = new Error(message + " at character " + this.index);
27563
- error.index = this.index;
27564
- error.description = message;
27565
- throw error;
27738
+ withPostMiddleware(...postMiddlewares) {
27739
+ const middlewares = postMiddlewares.map((post) => ({ post }));
27740
+ return this.withMiddleware(...middlewares);
27566
27741
  }
27567
- runHook(name, node) {
27568
- if (Jsep.hooks[name]) {
27569
- const env = {
27570
- context: this,
27571
- node
27572
- };
27573
- Jsep.hooks.run(name, env);
27574
- return env.node;
27742
+ isJsonMime(mime) {
27743
+ if (!mime) {
27744
+ return false;
27575
27745
  }
27576
- return node;
27746
+ return BaseAPI.jsonRegex.test(mime);
27577
27747
  }
27578
- searchHook(name) {
27579
- if (Jsep.hooks[name]) {
27580
- const env = {
27581
- context: this
27582
- };
27583
- Jsep.hooks[name].find(function(callback) {
27584
- callback.call(env.context, env);
27585
- return env.node;
27586
- });
27587
- return env.node;
27748
+ async request(context, initOverrides) {
27749
+ const { url, init } = await this.createFetchParams(context, initOverrides);
27750
+ const response = await this.fetchApi(url, init);
27751
+ if (response && (response.status >= 200 && response.status < 300)) {
27752
+ return response;
27588
27753
  }
27754
+ throw new ResponseError(response, "Response returned an error code");
27589
27755
  }
27590
- gobbleSpaces() {
27591
- let ch = this.code;
27592
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27593
- ch = this.expr.charCodeAt(++this.index);
27756
+ async createFetchParams(context, initOverrides) {
27757
+ let url = this.configuration.basePath + context.path;
27758
+ if (context.query !== undefined && Object.keys(context.query).length !== 0) {
27759
+ url += "?" + this.configuration.queryParamsStringify(context.query);
27594
27760
  }
27595
- this.runHook("gobble-spaces");
27596
- }
27597
- parse() {
27598
- this.runHook("before-all");
27599
- const nodes = this.gobbleExpressions();
27600
- const node = nodes.length === 1 ? nodes[0] : {
27601
- type: Jsep.COMPOUND,
27602
- body: nodes
27603
- };
27604
- return this.runHook("after-all", node);
27605
- }
27606
- gobbleExpressions(untilICode) {
27607
- let nodes = [], ch_i, node;
27608
- while (this.index < this.expr.length) {
27609
- ch_i = this.code;
27610
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27611
- this.index++;
27612
- } else {
27613
- if (node = this.gobbleExpression()) {
27614
- nodes.push(node);
27615
- } else if (this.index < this.expr.length) {
27616
- if (ch_i === untilICode) {
27617
- break;
27618
- }
27619
- this.throwError('Unexpected "' + this.char + '"');
27620
- }
27621
- }
27622
- }
27623
- return nodes;
27624
- }
27625
- gobbleExpression() {
27626
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27627
- this.gobbleSpaces();
27628
- return this.runHook("after-expression", node);
27629
- }
27630
- gobbleBinaryOp() {
27631
- this.gobbleSpaces();
27632
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27633
- let tc_len = to_check.length;
27634
- while (tc_len > 0) {
27635
- 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)))) {
27636
- this.index += tc_len;
27637
- return to_check;
27638
- }
27639
- to_check = to_check.substr(0, --tc_len);
27640
- }
27641
- return false;
27642
- }
27643
- gobbleBinaryExpression() {
27644
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27645
- left = this.gobbleToken();
27646
- if (!left) {
27647
- return left;
27648
- }
27649
- biop = this.gobbleBinaryOp();
27650
- if (!biop) {
27651
- return left;
27652
- }
27653
- biop_info = {
27654
- value: biop,
27655
- prec: Jsep.binaryPrecedence(biop),
27656
- right_a: Jsep.right_associative.has(biop)
27657
- };
27658
- right = this.gobbleToken();
27659
- if (!right) {
27660
- this.throwError("Expected expression after " + biop);
27661
- }
27662
- stack = [left, biop_info, right];
27663
- while (biop = this.gobbleBinaryOp()) {
27664
- prec = Jsep.binaryPrecedence(biop);
27665
- if (prec === 0) {
27666
- this.index -= biop.length;
27667
- break;
27668
- }
27669
- biop_info = {
27670
- value: biop,
27671
- prec,
27672
- right_a: Jsep.right_associative.has(biop)
27673
- };
27674
- cur_biop = biop;
27675
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27676
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27677
- right = stack.pop();
27678
- biop = stack.pop().value;
27679
- left = stack.pop();
27680
- node = {
27681
- type: Jsep.BINARY_EXP,
27682
- operator: biop,
27683
- left,
27684
- right
27685
- };
27686
- stack.push(node);
27687
- }
27688
- node = this.gobbleToken();
27689
- if (!node) {
27690
- this.throwError("Expected expression after " + cur_biop);
27691
- }
27692
- stack.push(biop_info, node);
27693
- }
27694
- i = stack.length - 1;
27695
- node = stack[i];
27696
- while (i > 1) {
27697
- node = {
27698
- type: Jsep.BINARY_EXP,
27699
- operator: stack[i - 1].value,
27700
- left: stack[i - 2],
27701
- right: node
27702
- };
27703
- i -= 2;
27704
- }
27705
- return node;
27706
- }
27707
- gobbleToken() {
27708
- let ch, to_check, tc_len, node;
27709
- this.gobbleSpaces();
27710
- node = this.searchHook("gobble-token");
27711
- if (node) {
27712
- return this.runHook("after-token", node);
27713
- }
27714
- ch = this.code;
27715
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27716
- return this.gobbleNumericLiteral();
27717
- }
27718
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27719
- node = this.gobbleStringLiteral();
27720
- } else if (ch === Jsep.OBRACK_CODE) {
27721
- node = this.gobbleArray();
27722
- } else {
27723
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27724
- tc_len = to_check.length;
27725
- while (tc_len > 0) {
27726
- 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)))) {
27727
- this.index += tc_len;
27728
- const argument = this.gobbleToken();
27729
- if (!argument) {
27730
- this.throwError("missing unaryOp argument");
27731
- }
27732
- return this.runHook("after-token", {
27733
- type: Jsep.UNARY_EXP,
27734
- operator: to_check,
27735
- argument,
27736
- prefix: true
27737
- });
27738
- }
27739
- to_check = to_check.substr(0, --tc_len);
27740
- }
27741
- if (Jsep.isIdentifierStart(ch)) {
27742
- node = this.gobbleIdentifier();
27743
- if (Jsep.literals.hasOwnProperty(node.name)) {
27744
- node = {
27745
- type: Jsep.LITERAL,
27746
- value: Jsep.literals[node.name],
27747
- raw: node.name
27748
- };
27749
- } else if (node.name === Jsep.this_str) {
27750
- node = {
27751
- type: Jsep.THIS_EXP
27752
- };
27753
- }
27754
- } else if (ch === Jsep.OPAREN_CODE) {
27755
- node = this.gobbleGroup();
27756
- }
27757
- }
27758
- if (!node) {
27759
- return this.runHook("after-token", false);
27760
- }
27761
- node = this.gobbleTokenProperty(node);
27762
- return this.runHook("after-token", node);
27763
- }
27764
- gobbleTokenProperty(node) {
27765
- this.gobbleSpaces();
27766
- let ch = this.code;
27767
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27768
- let optional;
27769
- if (ch === Jsep.QUMARK_CODE) {
27770
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27771
- break;
27772
- }
27773
- optional = true;
27774
- this.index += 2;
27775
- this.gobbleSpaces();
27776
- ch = this.code;
27777
- }
27778
- this.index++;
27779
- if (ch === Jsep.OBRACK_CODE) {
27780
- node = {
27781
- type: Jsep.MEMBER_EXP,
27782
- computed: true,
27783
- object: node,
27784
- property: this.gobbleExpression()
27785
- };
27786
- if (!node.property) {
27787
- this.throwError('Unexpected "' + this.char + '"');
27788
- }
27789
- this.gobbleSpaces();
27790
- ch = this.code;
27791
- if (ch !== Jsep.CBRACK_CODE) {
27792
- this.throwError("Unclosed [");
27793
- }
27794
- this.index++;
27795
- } else if (ch === Jsep.OPAREN_CODE) {
27796
- node = {
27797
- type: Jsep.CALL_EXP,
27798
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27799
- callee: node
27800
- };
27801
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27802
- if (optional) {
27803
- this.index--;
27804
- }
27805
- this.gobbleSpaces();
27806
- node = {
27807
- type: Jsep.MEMBER_EXP,
27808
- computed: false,
27809
- object: node,
27810
- property: this.gobbleIdentifier()
27811
- };
27812
- }
27813
- if (optional) {
27814
- node.optional = true;
27815
- }
27816
- this.gobbleSpaces();
27817
- ch = this.code;
27818
- }
27819
- return node;
27820
- }
27821
- gobbleNumericLiteral() {
27822
- let number = "", ch, chCode;
27823
- while (Jsep.isDecimalDigit(this.code)) {
27824
- number += this.expr.charAt(this.index++);
27825
- }
27826
- if (this.code === Jsep.PERIOD_CODE) {
27827
- number += this.expr.charAt(this.index++);
27828
- while (Jsep.isDecimalDigit(this.code)) {
27829
- number += this.expr.charAt(this.index++);
27830
- }
27831
- }
27832
- ch = this.char;
27833
- if (ch === "e" || ch === "E") {
27834
- number += this.expr.charAt(this.index++);
27835
- ch = this.char;
27836
- if (ch === "+" || ch === "-") {
27837
- number += this.expr.charAt(this.index++);
27838
- }
27839
- while (Jsep.isDecimalDigit(this.code)) {
27840
- number += this.expr.charAt(this.index++);
27841
- }
27842
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27843
- this.throwError("Expected exponent (" + number + this.char + ")");
27844
- }
27845
- }
27846
- chCode = this.code;
27847
- if (Jsep.isIdentifierStart(chCode)) {
27848
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27849
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27850
- this.throwError("Unexpected period");
27851
- }
27852
- return {
27853
- type: Jsep.LITERAL,
27854
- value: parseFloat(number),
27855
- raw: number
27856
- };
27857
- }
27858
- gobbleStringLiteral() {
27859
- let str = "";
27860
- const startIndex = this.index;
27861
- const quote = this.expr.charAt(this.index++);
27862
- let closed = false;
27863
- while (this.index < this.expr.length) {
27864
- let ch = this.expr.charAt(this.index++);
27865
- if (ch === quote) {
27866
- closed = true;
27867
- break;
27868
- } else if (ch === "\\") {
27869
- ch = this.expr.charAt(this.index++);
27870
- switch (ch) {
27871
- case "n":
27872
- str += `
27873
- `;
27874
- break;
27875
- case "r":
27876
- str += "\r";
27877
- break;
27878
- case "t":
27879
- str += "\t";
27880
- break;
27881
- case "b":
27882
- str += "\b";
27883
- break;
27884
- case "f":
27885
- str += "\f";
27886
- break;
27887
- case "v":
27888
- str += "\v";
27889
- break;
27890
- default:
27891
- str += ch;
27892
- }
27893
- } else {
27894
- str += ch;
27895
- }
27896
- }
27897
- if (!closed) {
27898
- this.throwError('Unclosed quote after "' + str + '"');
27899
- }
27900
- return {
27901
- type: Jsep.LITERAL,
27902
- value: str,
27903
- raw: this.expr.substring(startIndex, this.index)
27904
- };
27905
- }
27906
- gobbleIdentifier() {
27907
- let ch = this.code, start = this.index;
27908
- if (Jsep.isIdentifierStart(ch)) {
27909
- this.index++;
27910
- } else {
27911
- this.throwError("Unexpected " + this.char);
27912
- }
27913
- while (this.index < this.expr.length) {
27914
- ch = this.code;
27915
- if (Jsep.isIdentifierPart(ch)) {
27916
- this.index++;
27917
- } else {
27918
- break;
27919
- }
27920
- }
27921
- return {
27922
- type: Jsep.IDENTIFIER,
27923
- name: this.expr.slice(start, this.index)
27924
- };
27925
- }
27926
- gobbleArguments(termination) {
27927
- const args = [];
27928
- let closed = false;
27929
- let separator_count = 0;
27930
- while (this.index < this.expr.length) {
27931
- this.gobbleSpaces();
27932
- let ch_i = this.code;
27933
- if (ch_i === termination) {
27934
- closed = true;
27935
- this.index++;
27936
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
27937
- this.throwError("Unexpected token " + String.fromCharCode(termination));
27938
- }
27939
- break;
27940
- } else if (ch_i === Jsep.COMMA_CODE) {
27941
- this.index++;
27942
- separator_count++;
27943
- if (separator_count !== args.length) {
27944
- if (termination === Jsep.CPAREN_CODE) {
27945
- this.throwError("Unexpected token ,");
27946
- } else if (termination === Jsep.CBRACK_CODE) {
27947
- for (let arg = args.length;arg < separator_count; arg++) {
27948
- args.push(null);
27949
- }
27950
- }
27951
- }
27952
- } else if (args.length !== separator_count && separator_count !== 0) {
27953
- this.throwError("Expected comma");
27954
- } else {
27955
- const node = this.gobbleExpression();
27956
- if (!node || node.type === Jsep.COMPOUND) {
27957
- this.throwError("Expected comma");
27958
- }
27959
- args.push(node);
27960
- }
27961
- }
27962
- if (!closed) {
27963
- this.throwError("Expected " + String.fromCharCode(termination));
27964
- }
27965
- return args;
27966
- }
27967
- gobbleGroup() {
27968
- this.index++;
27969
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
27970
- if (this.code === Jsep.CPAREN_CODE) {
27971
- this.index++;
27972
- if (nodes.length === 1) {
27973
- return nodes[0];
27974
- } else if (!nodes.length) {
27975
- return false;
27976
- } else {
27977
- return {
27978
- type: Jsep.SEQUENCE_EXP,
27979
- expressions: nodes
27980
- };
27981
- }
27982
- } else {
27983
- this.throwError("Unclosed (");
27984
- }
27985
- }
27986
- gobbleArray() {
27987
- this.index++;
27988
- return {
27989
- type: Jsep.ARRAY_EXP,
27990
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
27991
- };
27992
- }
27993
- }
27994
- var hooks = new Hooks;
27995
- Object.assign(Jsep, {
27996
- hooks,
27997
- plugins: new Plugins(Jsep),
27998
- COMPOUND: "Compound",
27999
- SEQUENCE_EXP: "SequenceExpression",
28000
- IDENTIFIER: "Identifier",
28001
- MEMBER_EXP: "MemberExpression",
28002
- LITERAL: "Literal",
28003
- THIS_EXP: "ThisExpression",
28004
- CALL_EXP: "CallExpression",
28005
- UNARY_EXP: "UnaryExpression",
28006
- BINARY_EXP: "BinaryExpression",
28007
- ARRAY_EXP: "ArrayExpression",
28008
- TAB_CODE: 9,
28009
- LF_CODE: 10,
28010
- CR_CODE: 13,
28011
- SPACE_CODE: 32,
28012
- PERIOD_CODE: 46,
28013
- COMMA_CODE: 44,
28014
- SQUOTE_CODE: 39,
28015
- DQUOTE_CODE: 34,
28016
- OPAREN_CODE: 40,
28017
- CPAREN_CODE: 41,
28018
- OBRACK_CODE: 91,
28019
- CBRACK_CODE: 93,
28020
- QUMARK_CODE: 63,
28021
- SEMCOL_CODE: 59,
28022
- COLON_CODE: 58,
28023
- unary_ops: {
28024
- "-": 1,
28025
- "!": 1,
28026
- "~": 1,
28027
- "+": 1
28028
- },
28029
- binary_ops: {
28030
- "||": 1,
28031
- "??": 1,
28032
- "&&": 2,
28033
- "|": 3,
28034
- "^": 4,
28035
- "&": 5,
28036
- "==": 6,
28037
- "!=": 6,
28038
- "===": 6,
28039
- "!==": 6,
28040
- "<": 7,
28041
- ">": 7,
28042
- "<=": 7,
28043
- ">=": 7,
28044
- "<<": 8,
28045
- ">>": 8,
28046
- ">>>": 8,
28047
- "+": 9,
28048
- "-": 9,
28049
- "*": 10,
28050
- "/": 10,
28051
- "%": 10,
28052
- "**": 11
28053
- },
28054
- right_associative: new Set(["**"]),
28055
- additional_identifier_chars: new Set(["$", "_"]),
28056
- literals: {
28057
- true: true,
28058
- false: false,
28059
- null: null
28060
- },
28061
- this_str: "this"
28062
- });
28063
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
28064
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
28065
- var jsep = (expr) => new Jsep(expr).parse();
28066
- var stdClassProps = Object.getOwnPropertyNames(class Test {
28067
- });
28068
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
28069
- jsep[m] = Jsep[m];
28070
- });
28071
- jsep.Jsep = Jsep;
28072
- var CONDITIONAL_EXP = "ConditionalExpression";
28073
- var ternary = {
28074
- name: "ternary",
28075
- init(jsep2) {
28076
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
28077
- if (env.node && this.code === jsep2.QUMARK_CODE) {
28078
- this.index++;
28079
- const test = env.node;
28080
- const consequent = this.gobbleExpression();
28081
- if (!consequent) {
28082
- this.throwError("Expected expression");
28083
- }
28084
- this.gobbleSpaces();
28085
- if (this.code === jsep2.COLON_CODE) {
28086
- this.index++;
28087
- const alternate = this.gobbleExpression();
28088
- if (!alternate) {
28089
- this.throwError("Expected expression");
28090
- }
28091
- env.node = {
28092
- type: CONDITIONAL_EXP,
28093
- test,
28094
- consequent,
28095
- alternate
28096
- };
28097
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
28098
- let newTest = test;
28099
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
28100
- newTest = newTest.right;
28101
- }
28102
- env.node.test = newTest.right;
28103
- newTest.right = env.node;
28104
- env.node = test;
28105
- }
28106
- } else {
28107
- this.throwError("Expected :");
28108
- }
28109
- }
28110
- });
28111
- }
28112
- };
28113
- jsep.plugins.register(ternary);
28114
- var FSLASH_CODE = 47;
28115
- var BSLASH_CODE = 92;
28116
- var index = {
28117
- name: "regex",
28118
- init(jsep2) {
28119
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
28120
- if (this.code === FSLASH_CODE) {
28121
- const patternIndex = ++this.index;
28122
- let inCharSet = false;
28123
- while (this.index < this.expr.length) {
28124
- if (this.code === FSLASH_CODE && !inCharSet) {
28125
- const pattern = this.expr.slice(patternIndex, this.index);
28126
- let flags = "";
28127
- while (++this.index < this.expr.length) {
28128
- const code = this.code;
28129
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
28130
- flags += this.char;
28131
- } else {
28132
- break;
28133
- }
28134
- }
28135
- let value;
28136
- try {
28137
- value = new RegExp(pattern, flags);
28138
- } catch (e) {
28139
- this.throwError(e.message);
28140
- }
28141
- env.node = {
28142
- type: jsep2.LITERAL,
28143
- value,
28144
- raw: this.expr.slice(patternIndex - 1, this.index)
28145
- };
28146
- env.node = this.gobbleTokenProperty(env.node);
28147
- return env.node;
28148
- }
28149
- if (this.code === jsep2.OBRACK_CODE) {
28150
- inCharSet = true;
28151
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
28152
- inCharSet = false;
28153
- }
28154
- this.index += this.code === BSLASH_CODE ? 2 : 1;
28155
- }
28156
- this.throwError("Unclosed Regex");
28157
- }
28158
- });
28159
- }
28160
- };
28161
- var PLUS_CODE = 43;
28162
- var MINUS_CODE = 45;
28163
- var plugin = {
28164
- name: "assignment",
28165
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
28166
- updateOperators: [PLUS_CODE, MINUS_CODE],
28167
- assignmentPrecedence: 0.9,
28168
- init(jsep2) {
28169
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
28170
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
28171
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
28172
- const code = this.code;
28173
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28174
- this.index += 2;
28175
- env.node = {
28176
- type: "UpdateExpression",
28177
- operator: code === PLUS_CODE ? "++" : "--",
28178
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
28179
- prefix: true
28180
- };
28181
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
28182
- this.throwError(`Unexpected ${env.node.operator}`);
28183
- }
28184
- }
28185
- });
28186
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
28187
- if (env.node) {
28188
- const code = this.code;
28189
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28190
- if (!updateNodeTypes.includes(env.node.type)) {
28191
- this.throwError(`Unexpected ${env.node.operator}`);
28192
- }
28193
- this.index += 2;
28194
- env.node = {
28195
- type: "UpdateExpression",
28196
- operator: code === PLUS_CODE ? "++" : "--",
28197
- argument: env.node,
28198
- prefix: false
28199
- };
28200
- }
28201
- }
28202
- });
28203
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
28204
- if (env.node) {
28205
- updateBinariesToAssignments(env.node);
28206
- }
28207
- });
28208
- function updateBinariesToAssignments(node) {
28209
- if (plugin.assignmentOperators.has(node.operator)) {
28210
- node.type = "AssignmentExpression";
28211
- updateBinariesToAssignments(node.left);
28212
- updateBinariesToAssignments(node.right);
28213
- } else if (!node.operator) {
28214
- Object.values(node).forEach((val) => {
28215
- if (val && typeof val === "object") {
28216
- updateBinariesToAssignments(val);
28217
- }
28218
- });
28219
- }
28220
- }
28221
- }
28222
- };
28223
- jsep.plugins.register(index, plugin);
28224
- jsep.addUnaryOp("typeof");
28225
- jsep.addUnaryOp("void");
28226
- jsep.addLiteral("null", null);
28227
- jsep.addLiteral("undefined", undefined);
28228
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
28229
- var SafeEval = {
28230
- evalAst(ast, subs) {
28231
- switch (ast.type) {
28232
- case "BinaryExpression":
28233
- case "LogicalExpression":
28234
- return SafeEval.evalBinaryExpression(ast, subs);
28235
- case "Compound":
28236
- return SafeEval.evalCompound(ast, subs);
28237
- case "ConditionalExpression":
28238
- return SafeEval.evalConditionalExpression(ast, subs);
28239
- case "Identifier":
28240
- return SafeEval.evalIdentifier(ast, subs);
28241
- case "Literal":
28242
- return SafeEval.evalLiteral(ast, subs);
28243
- case "MemberExpression":
28244
- return SafeEval.evalMemberExpression(ast, subs);
28245
- case "UnaryExpression":
28246
- return SafeEval.evalUnaryExpression(ast, subs);
28247
- case "ArrayExpression":
28248
- return SafeEval.evalArrayExpression(ast, subs);
28249
- case "CallExpression":
28250
- return SafeEval.evalCallExpression(ast, subs);
28251
- case "AssignmentExpression":
28252
- return SafeEval.evalAssignmentExpression(ast, subs);
28253
- default:
28254
- throw SyntaxError("Unexpected expression", ast);
28255
- }
28256
- },
28257
- evalBinaryExpression(ast, subs) {
28258
- const result = {
28259
- "||": (a, b) => a || b(),
28260
- "&&": (a, b) => a && b(),
28261
- "|": (a, b) => a | b(),
28262
- "^": (a, b) => a ^ b(),
28263
- "&": (a, b) => a & b(),
28264
- "==": (a, b) => a == b(),
28265
- "!=": (a, b) => a != b(),
28266
- "===": (a, b) => a === b(),
28267
- "!==": (a, b) => a !== b(),
28268
- "<": (a, b) => a < b(),
28269
- ">": (a, b) => a > b(),
28270
- "<=": (a, b) => a <= b(),
28271
- ">=": (a, b) => a >= b(),
28272
- "<<": (a, b) => a << b(),
28273
- ">>": (a, b) => a >> b(),
28274
- ">>>": (a, b) => a >>> b(),
28275
- "+": (a, b) => a + b(),
28276
- "-": (a, b) => a - b(),
28277
- "*": (a, b) => a * b(),
28278
- "/": (a, b) => a / b(),
28279
- "%": (a, b) => a % b()
28280
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
28281
- return result;
28282
- },
28283
- evalCompound(ast, subs) {
28284
- let last;
28285
- for (let i = 0;i < ast.body.length; i++) {
28286
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28287
- i += 1;
28288
- }
28289
- const expr = ast.body[i];
28290
- last = SafeEval.evalAst(expr, subs);
28291
- }
28292
- return last;
28293
- },
28294
- evalConditionalExpression(ast, subs) {
28295
- if (SafeEval.evalAst(ast.test, subs)) {
28296
- return SafeEval.evalAst(ast.consequent, subs);
28297
- }
28298
- return SafeEval.evalAst(ast.alternate, subs);
28299
- },
28300
- evalIdentifier(ast, subs) {
28301
- if (Object.hasOwn(subs, ast.name)) {
28302
- return subs[ast.name];
28303
- }
28304
- throw ReferenceError(`${ast.name} is not defined`);
28305
- },
28306
- evalLiteral(ast) {
28307
- return ast.value;
28308
- },
28309
- evalMemberExpression(ast, subs) {
28310
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28311
- const obj = SafeEval.evalAst(ast.object, subs);
28312
- if (obj === undefined || obj === null) {
28313
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28314
- }
28315
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28316
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28317
- }
28318
- const result = obj[prop];
28319
- if (typeof result === "function") {
28320
- return result.bind(obj);
28321
- }
28322
- return result;
28323
- },
28324
- evalUnaryExpression(ast, subs) {
28325
- const result = {
28326
- "-": (a) => -SafeEval.evalAst(a, subs),
28327
- "!": (a) => !SafeEval.evalAst(a, subs),
28328
- "~": (a) => ~SafeEval.evalAst(a, subs),
28329
- "+": (a) => +SafeEval.evalAst(a, subs),
28330
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28331
- void: (a) => void SafeEval.evalAst(a, subs)
28332
- }[ast.operator](ast.argument);
28333
- return result;
28334
- },
28335
- evalArrayExpression(ast, subs) {
28336
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28337
- },
28338
- evalCallExpression(ast, subs) {
28339
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28340
- const func = SafeEval.evalAst(ast.callee, subs);
28341
- if (func === Function) {
28342
- throw new Error("Function constructor is disabled");
28343
- }
28344
- return func(...args);
28345
- },
28346
- evalAssignmentExpression(ast, subs) {
28347
- if (ast.left.type !== "Identifier") {
28348
- throw SyntaxError("Invalid left-hand side in assignment");
28349
- }
28350
- const id = ast.left.name;
28351
- const value = SafeEval.evalAst(ast.right, subs);
28352
- subs[id] = value;
28353
- return subs[id];
28354
- }
28355
- };
28356
-
28357
- class SafeScript {
28358
- constructor(expr) {
28359
- this.code = expr;
28360
- this.ast = jsep(this.code);
28361
- }
28362
- runInNewContext(context) {
28363
- const keyMap = Object.assign(Object.create(null), context);
28364
- return SafeEval.evalAst(this.ast, keyMap);
28365
- }
28366
- }
28367
- function push(arr, item) {
28368
- arr = arr.slice();
28369
- arr.push(item);
28370
- return arr;
28371
- }
28372
- function unshift(item, arr) {
28373
- arr = arr.slice();
28374
- arr.unshift(item);
28375
- return arr;
28376
- }
28377
-
28378
- class NewError extends Error {
28379
- constructor(value) {
28380
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28381
- this.avoidNew = true;
28382
- this.value = value;
28383
- this.name = "NewError";
28384
- }
28385
- }
28386
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28387
- if (!(this instanceof JSONPath)) {
28388
- try {
28389
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28390
- } catch (e) {
28391
- if (!e.avoidNew) {
28392
- throw e;
28393
- }
28394
- return e.value;
28395
- }
28396
- }
28397
- if (typeof opts === "string") {
28398
- otherTypeCallback = callback;
28399
- callback = obj;
28400
- obj = expr;
28401
- expr = opts;
28402
- opts = null;
28403
- }
28404
- const optObj = opts && typeof opts === "object";
28405
- opts = opts || {};
28406
- this.json = opts.json || obj;
28407
- this.path = opts.path || expr;
28408
- this.resultType = opts.resultType || "value";
28409
- this.flatten = opts.flatten || false;
28410
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28411
- this.sandbox = opts.sandbox || {};
28412
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28413
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28414
- this.parent = opts.parent || null;
28415
- this.parentProperty = opts.parentProperty || null;
28416
- this.callback = opts.callback || callback || null;
28417
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28418
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28419
- };
28420
- if (opts.autostart !== false) {
28421
- const args = {
28422
- path: optObj ? opts.path : expr
28423
- };
28424
- if (!optObj) {
28425
- args.json = obj;
28426
- } else if ("json" in opts) {
28427
- args.json = opts.json;
28428
- }
28429
- const ret = this.evaluate(args);
28430
- if (!ret || typeof ret !== "object") {
28431
- throw new NewError(ret);
28432
- }
28433
- return ret;
28434
- }
28435
- }
28436
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28437
- let currParent = this.parent, currParentProperty = this.parentProperty;
28438
- let {
28439
- flatten,
28440
- wrap
28441
- } = this;
28442
- this.currResultType = this.resultType;
28443
- this.currEval = this.eval;
28444
- this.currSandbox = this.sandbox;
28445
- callback = callback || this.callback;
28446
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28447
- json = json || this.json;
28448
- expr = expr || this.path;
28449
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28450
- if (!expr.path && expr.path !== "") {
28451
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28452
- }
28453
- if (!Object.hasOwn(expr, "json")) {
28454
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28455
- }
28456
- ({
28457
- json
28458
- } = expr);
28459
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28460
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28461
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28462
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28463
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28464
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28465
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28466
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28467
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28468
- expr = expr.path;
28469
- }
28470
- currParent = currParent || null;
28471
- currParentProperty = currParentProperty || null;
28472
- if (Array.isArray(expr)) {
28473
- expr = JSONPath.toPathString(expr);
28474
- }
28475
- if (!expr && expr !== "" || !json) {
28476
- return;
28477
- }
28478
- const exprList = JSONPath.toPathArray(expr);
28479
- if (exprList[0] === "$" && exprList.length > 1) {
28480
- exprList.shift();
28481
- }
28482
- this._hasParentSelector = null;
28483
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28484
- return ea && !ea.isParentSelector;
28485
- });
28486
- if (!result.length) {
28487
- return wrap ? [] : undefined;
28488
- }
28489
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28490
- return this._getPreferredOutput(result[0]);
28491
- }
28492
- return result.reduce((rslt, ea) => {
28493
- const valOrPath = this._getPreferredOutput(ea);
28494
- if (flatten && Array.isArray(valOrPath)) {
28495
- rslt = rslt.concat(valOrPath);
28496
- } else {
28497
- rslt.push(valOrPath);
28498
- }
28499
- return rslt;
28500
- }, []);
28501
- };
28502
- JSONPath.prototype._getPreferredOutput = function(ea) {
28503
- const resultType = this.currResultType;
28504
- switch (resultType) {
28505
- case "all": {
28506
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28507
- ea.pointer = JSONPath.toPointer(path3);
28508
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28509
- return ea;
28510
- }
28511
- case "value":
28512
- case "parent":
28513
- case "parentProperty":
28514
- return ea[resultType];
28515
- case "path":
28516
- return JSONPath.toPathString(ea[resultType]);
28517
- case "pointer":
28518
- return JSONPath.toPointer(ea.path);
28519
- default:
28520
- throw new TypeError("Unknown result type");
28521
- }
28522
- };
28523
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28524
- if (callback) {
28525
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28526
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28527
- callback(preferredOutput, type, fullRetObj);
28528
- }
28529
- };
28530
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28531
- let retObj;
28532
- if (!expr.length) {
28533
- retObj = {
28534
- path: path3,
28535
- value: val,
28536
- parent,
28537
- parentProperty: parentPropName,
28538
- hasArrExpr
28539
- };
28540
- this._handleCallback(retObj, callback, "value");
28541
- return retObj;
28542
- }
28543
- const loc = expr[0], x = expr.slice(1);
28544
- const ret = [];
28545
- function addRet(elems) {
28546
- if (Array.isArray(elems)) {
28547
- elems.forEach((t) => {
28548
- ret.push(t);
28549
- });
28550
- } else {
28551
- ret.push(elems);
28552
- }
28553
- }
28554
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28555
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28556
- } else if (loc === "*") {
28557
- this._walk(val, (m) => {
28558
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28559
- });
28560
- } else if (loc === "..") {
28561
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28562
- this._walk(val, (m) => {
28563
- if (typeof val[m] === "object") {
28564
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28565
- }
28566
- });
28567
- } else if (loc === "^") {
28568
- this._hasParentSelector = true;
28569
- return {
28570
- path: path3.slice(0, -1),
28571
- expr: x,
28572
- isParentSelector: true
28573
- };
28574
- } else if (loc === "~") {
28575
- retObj = {
28576
- path: push(path3, loc),
28577
- value: parentPropName,
28578
- parent,
28579
- parentProperty: null
28580
- };
28581
- this._handleCallback(retObj, callback, "property");
28582
- return retObj;
28583
- } else if (loc === "$") {
28584
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28585
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28586
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28587
- } else if (loc.indexOf("?(") === 0) {
28588
- if (this.currEval === false) {
28589
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28590
- }
28591
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28592
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28593
- if (nested) {
28594
- this._walk(val, (m) => {
28595
- const npath = [nested[2]];
28596
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28597
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28598
- if (filterResults.length > 0) {
28599
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28600
- }
28601
- });
28602
- } else {
28603
- this._walk(val, (m) => {
28604
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28605
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28606
- }
28607
- });
28608
- }
28609
- } else if (loc[0] === "(") {
28610
- if (this.currEval === false) {
28611
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
28612
- }
28613
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28614
- } else if (loc[0] === "@") {
28615
- let addType = false;
28616
- const valueType = loc.slice(1, -2);
28617
- switch (valueType) {
28618
- case "scalar":
28619
- if (!val || !["object", "function"].includes(typeof val)) {
28620
- addType = true;
28621
- }
28622
- break;
28623
- case "boolean":
28624
- case "string":
28625
- case "undefined":
28626
- case "function":
28627
- if (typeof val === valueType) {
28628
- addType = true;
28629
- }
28630
- break;
28631
- case "integer":
28632
- if (Number.isFinite(val) && !(val % 1)) {
28633
- addType = true;
28634
- }
28635
- break;
28636
- case "number":
28637
- if (Number.isFinite(val)) {
28638
- addType = true;
28639
- }
28640
- break;
28641
- case "nonFinite":
28642
- if (typeof val === "number" && !Number.isFinite(val)) {
28643
- addType = true;
28644
- }
28645
- break;
28646
- case "object":
28647
- if (val && typeof val === valueType) {
28648
- addType = true;
28649
- }
28650
- break;
28651
- case "array":
28652
- if (Array.isArray(val)) {
28653
- addType = true;
28654
- }
28655
- break;
28656
- case "other":
28657
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28658
- break;
28659
- case "null":
28660
- if (val === null) {
28661
- addType = true;
28662
- }
28663
- break;
28664
- default:
28665
- throw new TypeError("Unknown value type " + valueType);
28666
- }
28667
- if (addType) {
28668
- retObj = {
28669
- path: path3,
28670
- value: val,
28671
- parent,
28672
- parentProperty: parentPropName
28673
- };
28674
- this._handleCallback(retObj, callback, "value");
28675
- return retObj;
28676
- }
28677
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28678
- const locProp = loc.slice(1);
28679
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28680
- } else if (loc.includes(",")) {
28681
- const parts = loc.split(",");
28682
- for (const part of parts) {
28683
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28684
- }
28685
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28686
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28687
- }
28688
- if (this._hasParentSelector) {
28689
- for (let t = 0;t < ret.length; t++) {
28690
- const rett = ret[t];
28691
- if (rett && rett.isParentSelector) {
28692
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28693
- if (Array.isArray(tmp)) {
28694
- ret[t] = tmp[0];
28695
- const tl = tmp.length;
28696
- for (let tt = 1;tt < tl; tt++) {
28697
- t++;
28698
- ret.splice(t, 0, tmp[tt]);
28699
- }
28700
- } else {
28701
- ret[t] = tmp;
28702
- }
28703
- }
28704
- }
28705
- }
28706
- return ret;
28707
- };
28708
- JSONPath.prototype._walk = function(val, f) {
28709
- if (Array.isArray(val)) {
28710
- const n = val.length;
28711
- for (let i = 0;i < n; i++) {
28712
- f(i);
28713
- }
28714
- } else if (val && typeof val === "object") {
28715
- Object.keys(val).forEach((m) => {
28716
- f(m);
28717
- });
28718
- }
28719
- };
28720
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28721
- if (!Array.isArray(val)) {
28722
- return;
28723
- }
28724
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28725
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28726
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28727
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28728
- const ret = [];
28729
- for (let i = start;i < end; i += step) {
28730
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28731
- tmp.forEach((t) => {
28732
- ret.push(t);
28733
- });
28734
- }
28735
- return ret;
28736
- };
28737
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28738
- this.currSandbox._$_parentProperty = parentPropName;
28739
- this.currSandbox._$_parent = parent;
28740
- this.currSandbox._$_property = _vname;
28741
- this.currSandbox._$_root = this.json;
28742
- this.currSandbox._$_v = _v;
28743
- const containsPath = code.includes("@path");
28744
- if (containsPath) {
28745
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28746
- }
28747
- const scriptCacheKey = this.currEval + "Script:" + code;
28748
- if (!JSONPath.cache[scriptCacheKey]) {
28749
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28750
- if (containsPath) {
28751
- script = script.replaceAll("@path", "_$_path");
28752
- }
28753
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28754
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28755
- } else if (this.currEval === "native") {
28756
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28757
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28758
- const CurrEval = this.currEval;
28759
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28760
- } else if (typeof this.currEval === "function") {
28761
- JSONPath.cache[scriptCacheKey] = {
28762
- runInNewContext: (context) => this.currEval(script, context)
28763
- };
28764
- } else {
28765
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
28766
- }
28767
- }
28768
- try {
28769
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28770
- } catch (e) {
28771
- if (this.ignoreEvalErrors) {
28772
- return false;
28773
- }
28774
- throw new Error("jsonPath: " + e.message + ": " + code);
28775
- }
28776
- };
28777
- JSONPath.cache = {};
28778
- JSONPath.toPathString = function(pathArr) {
28779
- const x = pathArr, n = x.length;
28780
- let p = "$";
28781
- for (let i = 1;i < n; i++) {
28782
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28783
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28784
- }
28785
- }
28786
- return p;
28787
- };
28788
- JSONPath.toPointer = function(pointer) {
28789
- const x = pointer, n = x.length;
28790
- let p = "";
28791
- for (let i = 1;i < n; i++) {
28792
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28793
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
28794
- }
28795
- }
28796
- return p;
28797
- };
28798
- JSONPath.toPathArray = function(expr) {
28799
- const {
28800
- cache
28801
- } = JSONPath;
28802
- if (cache[expr]) {
28803
- return cache[expr].concat();
28804
- }
28805
- const subx = [];
28806
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28807
- return "[#" + (subx.push($1) - 1) + "]";
28808
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28809
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28810
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28811
- return ";" + ups.split("").join(";") + ";";
28812
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28813
- const exprList = normalized.split(";").map(function(exp) {
28814
- const match = exp.match(/#(\d+)/u);
28815
- return !match || !match[1] ? exp : subx[match[1]];
28816
- });
28817
- cache[expr] = exprList;
28818
- return cache[expr].concat();
28819
- };
28820
- JSONPath.prototype.safeVm = {
28821
- Script: SafeScript
28822
- };
28823
- JSONPath.prototype.vm = vm;
28824
- // ../../common/src/polling/types.ts
28825
- var PollOutcome = {
28826
- Completed: "completed",
28827
- Timeout: "timeout",
28828
- Interrupted: "interrupted",
28829
- Aborted: "aborted",
28830
- Failed: "failed"
28831
- };
28832
-
28833
- // ../../common/src/polling/poll-failure-mapping.ts
28834
- var REASON_BY_OUTCOME = {
28835
- [PollOutcome.Timeout]: "poll_timeout",
28836
- [PollOutcome.Failed]: "poll_failed",
28837
- [PollOutcome.Interrupted]: "poll_failed",
28838
- [PollOutcome.Aborted]: "poll_aborted"
28839
- };
28840
- // ../../common/src/polling/terminal-statuses.ts
28841
- var TERMINAL_STATUSES = new Set([
28842
- "completed",
28843
- "successful",
28844
- "faulted",
28845
- "failed",
28846
- "cancelled",
28847
- "canceled",
28848
- "stopped",
28849
- "finished"
28850
- ]);
28851
- var FAILURE_STATUSES = new Set([
28852
- "faulted",
28853
- "failed",
28854
- "cancelled",
28855
- "canceled",
28856
- "stopped"
28857
- ]);
28858
- // ../../common/src/screen-logger.ts
28859
- var ScreenLogger;
28860
- ((ScreenLogger) => {
28861
- function progress(message) {
28862
- getOutputSink().writeErr(`${message}
28863
- `);
28864
- }
28865
- ScreenLogger.progress = progress;
28866
- })(ScreenLogger ||= {});
28867
- // ../../common/src/sdk-user-agent.ts
28868
- var USER_AGENT_HEADER = "User-Agent";
28869
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
28870
- function userAgentPatchKey(userAgent) {
28871
- return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
28872
- }
28873
- function splitUserAgentTokens(value) {
28874
- return value?.trim().split(/\s+/).filter(Boolean) ?? [];
28875
- }
28876
- function appendUserAgentToken(value, userAgent) {
28877
- const tokens = splitUserAgentTokens(value);
28878
- const seen = new Set(tokens);
28879
- for (const token of splitUserAgentTokens(userAgent)) {
28880
- if (!seen.has(token)) {
28881
- tokens.push(token);
28882
- seen.add(token);
28883
- }
28884
- }
28885
- return tokens.join(" ");
28886
- }
28887
- function getEffectiveUserAgent(userAgent) {
28888
- return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
28889
- }
28890
- function isHeadersLike(headers) {
28891
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
28892
- }
28893
- function getSdkUserAgentToken(pkg) {
28894
- const packageName = pkg.name.replace(/^@uipath\//, "");
28895
- return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
28896
- }
28897
- function addSdkUserAgentHeader(headers, userAgent) {
28898
- const result = { ...headers ?? {} };
28899
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
28900
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
28901
- if (headerName) {
28902
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
28903
- } else {
28904
- result[USER_AGENT_HEADER] = effectiveUserAgent;
28905
- }
28906
- return result;
28907
- }
28908
- function withSdkUserAgentHeader(headers, userAgent) {
28909
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
28910
- if (isHeadersLike(headers)) {
28911
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
28912
- return headers;
28913
- }
28914
- if (Array.isArray(headers)) {
28915
- const result = headers.map((entry) => {
28916
- const [key, value] = entry;
28917
- return [key, value];
28918
- });
28919
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
28920
- if (headerIndex >= 0) {
28921
- const [key, value] = result[headerIndex];
28922
- result[headerIndex] = [
28923
- key,
28924
- appendUserAgentToken(value, effectiveUserAgent)
28925
- ];
28926
- } else {
28927
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
28928
- }
28929
- return result;
28930
- }
28931
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
28932
- }
28933
- function withUserAgentInitOverride(initOverrides, userAgent) {
28934
- return async (requestContext) => {
28935
- const initWithUserAgent = {
28936
- ...requestContext.init,
28937
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
28938
- };
28939
- const override = typeof initOverrides === "function" ? await initOverrides({
28940
- ...requestContext,
28941
- init: initWithUserAgent
28942
- }) : initOverrides;
28943
- return {
28944
- ...override ?? {},
28945
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
28946
- };
28947
- };
28948
- }
28949
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
28950
- const prototype = BaseApiClass.prototype;
28951
- const patchKey = userAgentPatchKey(userAgent);
28952
- if (prototype[patchKey]) {
28953
- return;
28954
- }
28955
- if (typeof prototype.request !== "function") {
28956
- throw new Error("Generated BaseAPI request function not found.");
28957
- }
28958
- const originalRequest = prototype.request;
28959
- prototype.request = function requestWithUserAgent(context, initOverrides) {
28960
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
28961
- };
28962
- Object.defineProperty(prototype, patchKey, {
28963
- value: true
28964
- });
28965
- }
28966
- // ../../common/src/tool-provider.ts
28967
- var factorySlot = singleton("PackagerFactoryProvider");
28968
- // ../identity-sdk/generated/src/runtime.ts
28969
- var BASE_PATH = "https://alpha.uipath.com/identity_".replace(/\/+$/, "");
28970
-
28971
- class Configuration {
28972
- configuration;
28973
- constructor(configuration = {}) {
28974
- this.configuration = configuration;
28975
- }
28976
- set config(configuration) {
28977
- this.configuration = configuration;
28978
- }
28979
- get basePath() {
28980
- return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
28981
- }
28982
- get fetchApi() {
28983
- return this.configuration.fetchApi;
28984
- }
28985
- get middleware() {
28986
- return this.configuration.middleware || [];
28987
- }
28988
- get queryParamsStringify() {
28989
- return this.configuration.queryParamsStringify || querystring;
28990
- }
28991
- get username() {
28992
- return this.configuration.username;
28993
- }
28994
- get password() {
28995
- return this.configuration.password;
28996
- }
28997
- get apiKey() {
28998
- const apiKey = this.configuration.apiKey;
28999
- if (apiKey) {
29000
- return typeof apiKey === "function" ? apiKey : () => apiKey;
29001
- }
29002
- return;
29003
- }
29004
- get accessToken() {
29005
- const accessToken = this.configuration.accessToken;
29006
- if (accessToken) {
29007
- return typeof accessToken === "function" ? accessToken : async () => accessToken;
29008
- }
29009
- return;
29010
- }
29011
- get headers() {
29012
- return this.configuration.headers;
29013
- }
29014
- get credentials() {
29015
- return this.configuration.credentials;
29016
- }
29017
- }
29018
- var DefaultConfig = new Configuration;
29019
-
29020
- class BaseAPI {
29021
- configuration;
29022
- static jsonRegex = new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", "i");
29023
- middleware;
29024
- constructor(configuration = DefaultConfig) {
29025
- this.configuration = configuration;
29026
- this.middleware = configuration.middleware;
29027
- }
29028
- withMiddleware(...middlewares) {
29029
- const next = this.clone();
29030
- next.middleware = next.middleware.concat(...middlewares);
29031
- return next;
29032
- }
29033
- withPreMiddleware(...preMiddlewares) {
29034
- const middlewares = preMiddlewares.map((pre) => ({ pre }));
29035
- return this.withMiddleware(...middlewares);
29036
- }
29037
- withPostMiddleware(...postMiddlewares) {
29038
- const middlewares = postMiddlewares.map((post) => ({ post }));
29039
- return this.withMiddleware(...middlewares);
29040
- }
29041
- isJsonMime(mime) {
29042
- if (!mime) {
29043
- return false;
29044
- }
29045
- return BaseAPI.jsonRegex.test(mime);
29046
- }
29047
- async request(context, initOverrides) {
29048
- const { url, init } = await this.createFetchParams(context, initOverrides);
29049
- const response = await this.fetchApi(url, init);
29050
- if (response && (response.status >= 200 && response.status < 300)) {
29051
- return response;
29052
- }
29053
- throw new ResponseError(response, "Response returned an error code");
29054
- }
29055
- async createFetchParams(context, initOverrides) {
29056
- let url = this.configuration.basePath + context.path;
29057
- if (context.query !== undefined && Object.keys(context.query).length !== 0) {
29058
- url += "?" + this.configuration.queryParamsStringify(context.query);
29059
- }
29060
- const headers = Object.assign({}, this.configuration.headers, context.headers);
29061
- Object.keys(headers).forEach((key) => headers[key] === undefined ? delete headers[key] : {});
29062
- const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
29063
- const initParams = {
29064
- method: context.method,
29065
- headers,
29066
- body: context.body,
29067
- credentials: this.configuration.credentials
27761
+ const headers = Object.assign({}, this.configuration.headers, context.headers);
27762
+ Object.keys(headers).forEach((key) => headers[key] === undefined ? delete headers[key] : {});
27763
+ const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
27764
+ const initParams = {
27765
+ method: context.method,
27766
+ headers,
27767
+ body: context.body,
27768
+ credentials: this.configuration.credentials
29068
27769
  };
29069
27770
  const overriddenInit = {
29070
27771
  ...initParams,
@@ -29227,7 +27928,7 @@ class TextApiResponse {
29227
27928
  var package_default2 = {
29228
27929
  name: "@uipath/identity-sdk",
29229
27930
  license: "MIT",
29230
- version: "1.196.0",
27931
+ version: "1.197.0",
29231
27932
  repository: {
29232
27933
  type: "git",
29233
27934
  url: "https://github.com/UiPath/cli.git",
@@ -29255,7 +27956,7 @@ var package_default2 = {
29255
27956
  ],
29256
27957
  private: true,
29257
27958
  scripts: {
29258
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
27959
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
29259
27960
  generate: "bun run src/scripts/generate-sdk.ts",
29260
27961
  lint: "biome check .",
29261
27962
  test: "vitest run",
@@ -31827,6 +30528,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
31827
30528
  }
31828
30529
  return url.pathname.length > 1 ? url.origin : baseUrl;
31829
30530
  };
30531
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
30532
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
30533
+ if (isExternalAppAuth)
30534
+ return requestedScopes;
30535
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
30536
+ };
31830
30537
  var resolveConfigAsync = async ({
31831
30538
  customAuthority,
31832
30539
  customClientId,
@@ -31857,7 +30564,7 @@ var resolveConfigAsync = async ({
31857
30564
  clientSecret = fileAuth.clientSecret;
31858
30565
  }
31859
30566
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
31860
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
30567
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
31861
30568
  return {
31862
30569
  clientId,
31863
30570
  clientSecret,
@@ -31872,6 +30579,76 @@ var resolveConfigAsync = async ({
31872
30579
  init_constants();
31873
30580
  // ../../auth/src/loginStatus.ts
31874
30581
  init_src();
30582
+
30583
+ // ../../auth/src/authProfile.ts
30584
+ init_src();
30585
+ init_constants();
30586
+ var DEFAULT_AUTH_PROFILE = "default";
30587
+ var PROFILE_DIR = "profiles";
30588
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
30589
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
30590
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
30591
+ var globalSlot2 = globalThis;
30592
+ function isAuthProfileStorage(value) {
30593
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
30594
+ }
30595
+ function createProfileStorage() {
30596
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
30597
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
30598
+ return {
30599
+ getStore: () => {
30600
+ return;
30601
+ },
30602
+ run: (_store, fn) => fn()
30603
+ };
30604
+ }
30605
+ return new mod2.AsyncLocalStorage;
30606
+ }
30607
+ function getProfileStorage() {
30608
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
30609
+ if (isAuthProfileStorage(existing)) {
30610
+ return existing;
30611
+ }
30612
+ const storage = createProfileStorage();
30613
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
30614
+ return storage;
30615
+ }
30616
+ var profileStorage = getProfileStorage();
30617
+
30618
+ class AuthProfileValidationError extends Error {
30619
+ constructor(message) {
30620
+ super(message);
30621
+ this.name = "AuthProfileValidationError";
30622
+ }
30623
+ }
30624
+ function normalizeAuthProfileName(profile) {
30625
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
30626
+ return;
30627
+ }
30628
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
30629
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
30630
+ }
30631
+ return profile;
30632
+ }
30633
+ function getActiveAuthProfile() {
30634
+ const scopedState = profileStorage.getStore();
30635
+ if (scopedState !== undefined) {
30636
+ return scopedState.profile;
30637
+ }
30638
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
30639
+ }
30640
+ function resolveAuthProfileFilePath(profile) {
30641
+ const normalized = normalizeAuthProfileName(profile);
30642
+ if (normalized === undefined) {
30643
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
30644
+ }
30645
+ const fs7 = getFileSystem();
30646
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
30647
+ }
30648
+ function getActiveAuthProfileFilePath() {
30649
+ const profile = getActiveAuthProfile();
30650
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
30651
+ }
31875
30652
  // ../../auth/src/utils/jwt.ts
31876
30653
  class InvalidIssuerError extends Error {
31877
30654
  expected;
@@ -32000,23 +30777,74 @@ var readAuthFromEnv = () => {
32000
30777
  organizationId,
32001
30778
  tenantName,
32002
30779
  tenantId,
32003
- expiration
30780
+ expiration,
30781
+ source: "env" /* Env */
32004
30782
  };
32005
30783
  };
32006
30784
 
30785
+ // ../../auth/src/refreshCircuitBreaker.ts
30786
+ init_src();
30787
+ var BREAKER_SUFFIX = ".refresh-state";
30788
+ var BACKOFF_BASE_MS = 60000;
30789
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
30790
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
30791
+ async function refreshTokenFingerprint(refreshToken) {
30792
+ const bytes = new TextEncoder().encode(refreshToken);
30793
+ if (globalThis.crypto?.subtle) {
30794
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
30795
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
30796
+ }
30797
+ const { createHash } = await import("node:crypto");
30798
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
30799
+ }
30800
+ function breakerPathFor(authPath) {
30801
+ return `${authPath}${BREAKER_SUFFIX}`;
30802
+ }
30803
+ async function loadRefreshBreaker(authPath) {
30804
+ const fs7 = getFileSystem();
30805
+ try {
30806
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
30807
+ if (!content)
30808
+ return {};
30809
+ const parsed = JSON.parse(content);
30810
+ return parsed && typeof parsed === "object" ? parsed : {};
30811
+ } catch {
30812
+ return {};
30813
+ }
30814
+ }
30815
+ async function saveRefreshBreaker(authPath, state) {
30816
+ try {
30817
+ const fs7 = getFileSystem();
30818
+ const path3 = breakerPathFor(authPath);
30819
+ await fs7.mkdir(fs7.path.dirname(path3));
30820
+ const tempPath = `${path3}.tmp`;
30821
+ await fs7.writeFile(tempPath, JSON.stringify(state));
30822
+ await fs7.rename(tempPath, path3);
30823
+ } catch {}
30824
+ }
30825
+ async function clearRefreshBreaker(authPath) {
30826
+ const fs7 = getFileSystem();
30827
+ const path3 = breakerPathFor(authPath);
30828
+ try {
30829
+ if (await fs7.exists(path3)) {
30830
+ await fs7.rm(path3);
30831
+ }
30832
+ } catch {}
30833
+ }
30834
+ function nextBackoffMs(attempts) {
30835
+ const shift = Math.max(0, attempts - 1);
30836
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
30837
+ }
30838
+ function shouldSurface(state, nowMs) {
30839
+ if (state.lastSurfacedAtMs === undefined)
30840
+ return true;
30841
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
30842
+ }
30843
+
32007
30844
  // ../../auth/src/robotClientFallback.ts
32008
30845
  init_src();
32009
30846
  var DEFAULT_TIMEOUT_MS = 1000;
32010
30847
  var CLOSE_TIMEOUT_MS = 500;
32011
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
32012
- var printNoticeOnce = () => {
32013
- const slot = globalThis;
32014
- if (slot[NOTICE_SENTINEL])
32015
- return;
32016
- slot[NOTICE_SENTINEL] = true;
32017
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
32018
- `));
32019
- };
32020
30848
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
32021
30849
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
32022
30850
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -32132,7 +30960,6 @@ var tryRobotClientFallback = async (options = {}) => {
32132
30960
  issuerFromToken = issClaim;
32133
30961
  }
32134
30962
  }
32135
- printNoticeOnce();
32136
30963
  return {
32137
30964
  accessToken,
32138
30965
  baseUrl: parsedUrl.baseUrl,
@@ -32357,18 +31184,327 @@ var saveEnvFileAsync = async ({
32357
31184
  };
32358
31185
 
32359
31186
  // ../../auth/src/loginStatus.ts
32360
- function normalizeTokenRefreshFailure() {
32361
- return "stored refresh token is invalid or expired";
31187
+ var getLoginStatusAsync = async (options = {}) => {
31188
+ return getLoginStatusWithDeps(options);
31189
+ };
31190
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
31191
+ const {
31192
+ resolveEnvFilePath = resolveEnvFilePathAsync,
31193
+ loadEnvFile = loadEnvFileAsync,
31194
+ saveEnvFile = saveEnvFileAsync,
31195
+ getFs = getFileSystem,
31196
+ refreshToken: refreshTokenFn = refreshAccessToken,
31197
+ resolveConfig = resolveConfigAsync,
31198
+ robotFallback = tryRobotClientFallback,
31199
+ loadBreaker = loadRefreshBreaker,
31200
+ saveBreaker = saveRefreshBreaker,
31201
+ clearBreaker = clearRefreshBreaker
31202
+ } = deps;
31203
+ if (isRobotAuthEnforced()) {
31204
+ return resolveRobotEnforcedStatus(robotFallback);
31205
+ }
31206
+ if (isEnvAuthEnabled()) {
31207
+ return readAuthFromEnv();
31208
+ }
31209
+ const activeProfile = getActiveAuthProfile();
31210
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
31211
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
31212
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
31213
+ const { ensureTokenValidityMinutes } = options;
31214
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
31215
+ if (absolutePath === undefined) {
31216
+ if (usingActiveProfile) {
31217
+ return {
31218
+ loginStatus: "Not logged in",
31219
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
31220
+ };
31221
+ }
31222
+ return resolveBorrowedRobotStatus(robotFallback);
31223
+ }
31224
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
31225
+ if ("status" in loaded) {
31226
+ return loaded.status;
31227
+ }
31228
+ const { credentials } = loaded;
31229
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
31230
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
31231
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
31232
+ let tokens = {
31233
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
31234
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
31235
+ expiration,
31236
+ lockReleaseFailed: false
31237
+ };
31238
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
31239
+ if (expiration && expiration <= outerThreshold && refreshToken) {
31240
+ const refreshed = await attemptRefresh({
31241
+ absolutePath,
31242
+ credentials,
31243
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
31244
+ refreshToken,
31245
+ expiration,
31246
+ ensureTokenValidityMinutes,
31247
+ getFs,
31248
+ loadEnvFile,
31249
+ saveEnvFile,
31250
+ refreshFn: refreshTokenFn,
31251
+ resolveConfig,
31252
+ loadBreaker,
31253
+ saveBreaker,
31254
+ clearBreaker,
31255
+ globalHint
31256
+ });
31257
+ if (refreshed.kind === "terminal") {
31258
+ return refreshed.status;
31259
+ }
31260
+ tokens = refreshed.tokens;
31261
+ }
31262
+ return buildFileStatus(tokens, credentials, globalHint);
31263
+ };
31264
+ async function resolveRobotEnforcedStatus(robotFallback) {
31265
+ if (isEnvAuthEnabled()) {
31266
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
31267
+ }
31268
+ const robotCreds = await robotFallback({ force: true });
31269
+ if (!robotCreds) {
31270
+ return {
31271
+ loginStatus: "Not logged in",
31272
+ 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.`
31273
+ };
31274
+ }
31275
+ return buildRobotStatus(robotCreds);
32362
31276
  }
32363
- function normalizeTokenRefreshUnavailableFailure() {
32364
- return "token refresh failed before authentication completed";
31277
+ async function resolveBorrowedRobotStatus(robotFallback) {
31278
+ const robotCreds = await robotFallback();
31279
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
32365
31280
  }
32366
- function errorMessage(error) {
32367
- return error instanceof Error ? error.message : String(error);
31281
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
31282
+ let credentials;
31283
+ try {
31284
+ credentials = await loadEnvFile({ envPath: absolutePath });
31285
+ } catch (error) {
31286
+ if (isFileNotFoundError(error)) {
31287
+ return { status: { loginStatus: "Not logged in" } };
31288
+ }
31289
+ throw error;
31290
+ }
31291
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
31292
+ return { status: { loginStatus: "Not logged in" } };
31293
+ }
31294
+ return { credentials };
31295
+ }
31296
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
31297
+ const fs7 = getFs();
31298
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
31299
+ if (absolutePath === globalPath)
31300
+ return;
31301
+ if (!await fs7.exists(globalPath))
31302
+ return;
31303
+ try {
31304
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
31305
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
31306
+ return;
31307
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
31308
+ if (globalExp && globalExp <= new Date)
31309
+ return;
31310
+ 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.`;
31311
+ } catch {
31312
+ return;
31313
+ }
32368
31314
  }
32369
31315
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
32370
31316
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
32371
31317
  }
31318
+ async function attemptRefresh(ctx) {
31319
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
31320
+ if (shortCircuit) {
31321
+ return { kind: "terminal", status: shortCircuit };
31322
+ }
31323
+ let release;
31324
+ try {
31325
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
31326
+ } catch (error) {
31327
+ return {
31328
+ kind: "terminal",
31329
+ status: await lockAcquireFailureStatus(ctx, error)
31330
+ };
31331
+ }
31332
+ let lockedFailure;
31333
+ let lockReleaseFailed = false;
31334
+ let success;
31335
+ try {
31336
+ const outcome = await runRefreshLocked({
31337
+ absolutePath: ctx.absolutePath,
31338
+ refreshToken: ctx.refreshToken,
31339
+ customAuthority: ctx.credentials.UIPATH_URL,
31340
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
31341
+ loadEnvFile: ctx.loadEnvFile,
31342
+ saveEnvFile: ctx.saveEnvFile,
31343
+ refreshFn: ctx.refreshFn,
31344
+ resolveConfig: ctx.resolveConfig,
31345
+ loadBreaker: ctx.loadBreaker,
31346
+ saveBreaker: ctx.saveBreaker,
31347
+ clearBreaker: ctx.clearBreaker
31348
+ });
31349
+ if (outcome.kind === "fail") {
31350
+ lockedFailure = outcome.status;
31351
+ } else {
31352
+ success = outcome;
31353
+ }
31354
+ } finally {
31355
+ try {
31356
+ await release();
31357
+ } catch {
31358
+ lockReleaseFailed = true;
31359
+ }
31360
+ }
31361
+ if (lockedFailure) {
31362
+ const globalHint = await ctx.globalHint();
31363
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
31364
+ return {
31365
+ kind: "terminal",
31366
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
31367
+ };
31368
+ }
31369
+ return {
31370
+ kind: "refreshed",
31371
+ tokens: {
31372
+ accessToken: success?.accessToken,
31373
+ refreshToken: success?.refreshToken,
31374
+ expiration: success?.expiration,
31375
+ tokenRefresh: success?.tokenRefresh,
31376
+ persistenceWarning: success?.persistenceWarning,
31377
+ lockReleaseFailed
31378
+ }
31379
+ };
31380
+ }
31381
+ async function buildFileStatus(tokens, credentials, globalHint) {
31382
+ const result = {
31383
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
31384
+ accessToken: tokens.accessToken,
31385
+ refreshToken: tokens.refreshToken,
31386
+ baseUrl: credentials.UIPATH_URL,
31387
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
31388
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
31389
+ tenantName: credentials.UIPATH_TENANT_NAME,
31390
+ tenantId: credentials.UIPATH_TENANT_ID,
31391
+ expiration: tokens.expiration,
31392
+ source: "file" /* File */,
31393
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
31394
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
31395
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
31396
+ };
31397
+ if (result.loginStatus === "Expired") {
31398
+ const hint = await globalHint();
31399
+ if (hint) {
31400
+ result.hint = hint;
31401
+ }
31402
+ }
31403
+ return result;
31404
+ }
31405
+ function buildRobotStatus(robotCreds) {
31406
+ return {
31407
+ loginStatus: "Logged in",
31408
+ accessToken: robotCreds.accessToken,
31409
+ baseUrl: robotCreds.baseUrl,
31410
+ organizationName: robotCreds.organizationName,
31411
+ organizationId: robotCreds.organizationId,
31412
+ tenantName: robotCreds.tenantName,
31413
+ tenantId: robotCreds.tenantId,
31414
+ issuer: robotCreds.issuer,
31415
+ expiration: getTokenExpiration(robotCreds.accessToken),
31416
+ source: "robot" /* Robot */
31417
+ };
31418
+ }
31419
+ var isFileNotFoundError = (error) => {
31420
+ if (!(error instanceof Object))
31421
+ return false;
31422
+ return error.code === "ENOENT";
31423
+ };
31424
+ async function circuitBreakerShortCircuit(ctx) {
31425
+ const {
31426
+ absolutePath,
31427
+ refreshToken,
31428
+ accessToken,
31429
+ credentials,
31430
+ expiration,
31431
+ loadBreaker,
31432
+ saveBreaker,
31433
+ clearBreaker
31434
+ } = ctx;
31435
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
31436
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
31437
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
31438
+ await clearBreaker(absolutePath);
31439
+ breaker.deadTokenFp = undefined;
31440
+ }
31441
+ const nowMs = Date.now();
31442
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
31443
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
31444
+ if (!tokenIsDead && !inBackoff)
31445
+ return;
31446
+ const globalHint = await ctx.globalHint();
31447
+ const suppressed = !shouldSurface(breaker, nowMs);
31448
+ if (!suppressed) {
31449
+ await saveBreaker(absolutePath, {
31450
+ ...breaker,
31451
+ lastSurfacedAtMs: nowMs
31452
+ });
31453
+ }
31454
+ 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>.";
31455
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
31456
+ return {
31457
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
31458
+ ...globalHint ? {
31459
+ accessToken,
31460
+ refreshToken,
31461
+ baseUrl: credentials.UIPATH_URL,
31462
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
31463
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
31464
+ tenantName: credentials.UIPATH_TENANT_NAME,
31465
+ tenantId: credentials.UIPATH_TENANT_ID,
31466
+ expiration,
31467
+ source: "file" /* File */
31468
+ } : {},
31469
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
31470
+ refreshCircuitOpen: true,
31471
+ refreshTelemetrySuppressed: suppressed,
31472
+ tokenRefresh: { attempted: false, success: false }
31473
+ };
31474
+ }
31475
+ async function lockAcquireFailureStatus(ctx, error) {
31476
+ const msg = errorMessage(error);
31477
+ const globalHint = await ctx.globalHint();
31478
+ if (globalHint) {
31479
+ return {
31480
+ loginStatus: "Expired",
31481
+ accessToken: ctx.accessToken,
31482
+ refreshToken: ctx.refreshToken,
31483
+ baseUrl: ctx.credentials.UIPATH_URL,
31484
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
31485
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
31486
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
31487
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
31488
+ expiration: ctx.expiration,
31489
+ source: "file" /* File */,
31490
+ hint: globalHint,
31491
+ tokenRefresh: {
31492
+ attempted: false,
31493
+ success: false,
31494
+ errorMessage: `lock acquisition failed: ${msg}`
31495
+ }
31496
+ };
31497
+ }
31498
+ return {
31499
+ loginStatus: "Refresh Failed",
31500
+ 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.",
31501
+ tokenRefresh: {
31502
+ attempted: false,
31503
+ success: false,
31504
+ errorMessage: `lock acquisition failed: ${msg}`
31505
+ }
31506
+ };
31507
+ }
32372
31508
  async function runRefreshLocked(inputs) {
32373
31509
  const {
32374
31510
  absolutePath,
@@ -32378,7 +31514,10 @@ async function runRefreshLocked(inputs) {
32378
31514
  loadEnvFile,
32379
31515
  saveEnvFile,
32380
31516
  refreshFn,
32381
- resolveConfig
31517
+ resolveConfig,
31518
+ loadBreaker,
31519
+ saveBreaker,
31520
+ clearBreaker
32382
31521
  } = inputs;
32383
31522
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
32384
31523
  let fresh;
@@ -32401,6 +31540,7 @@ async function runRefreshLocked(inputs) {
32401
31540
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
32402
31541
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
32403
31542
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
31543
+ await clearBreaker(absolutePath);
32404
31544
  return {
32405
31545
  kind: "ok",
32406
31546
  accessToken: freshAccess,
@@ -32424,8 +31564,21 @@ async function runRefreshLocked(inputs) {
32424
31564
  refreshedRefresh = refreshed.refreshToken;
32425
31565
  } catch (error) {
32426
31566
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
32427
- 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.";
31567
+ 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.";
32428
31568
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
31569
+ const fp = await refreshTokenFingerprint(tokenForIdP);
31570
+ if (isOAuthFailure) {
31571
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
31572
+ } else {
31573
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
31574
+ const attempts = (prior.attempts ?? 0) + 1;
31575
+ await saveBreaker(absolutePath, {
31576
+ ...prior,
31577
+ deadTokenFp: undefined,
31578
+ attempts,
31579
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
31580
+ });
31581
+ }
32429
31582
  return {
32430
31583
  kind: "fail",
32431
31584
  status: {
@@ -32454,6 +31607,7 @@ async function runRefreshLocked(inputs) {
32454
31607
  }
32455
31608
  };
32456
31609
  }
31610
+ await clearBreaker(absolutePath);
32457
31611
  try {
32458
31612
  await saveEnvFile({
32459
31613
  envPath: absolutePath,
@@ -32486,212 +31640,15 @@ async function runRefreshLocked(inputs) {
32486
31640
  };
32487
31641
  }
32488
31642
  }
32489
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
32490
- const {
32491
- resolveEnvFilePath = resolveEnvFilePathAsync,
32492
- loadEnvFile = loadEnvFileAsync,
32493
- saveEnvFile = saveEnvFileAsync,
32494
- getFs = getFileSystem,
32495
- refreshToken: refreshTokenFn = refreshAccessToken,
32496
- resolveConfig = resolveConfigAsync,
32497
- robotFallback = tryRobotClientFallback
32498
- } = deps;
32499
- if (isRobotAuthEnforced()) {
32500
- if (isEnvAuthEnabled()) {
32501
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
32502
- }
32503
- const robotCreds = await robotFallback({ force: true });
32504
- if (!robotCreds) {
32505
- return {
32506
- loginStatus: "Not logged in",
32507
- 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.`
32508
- };
32509
- }
32510
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
32511
- return {
32512
- loginStatus: "Logged in",
32513
- accessToken: robotCreds.accessToken,
32514
- baseUrl: robotCreds.baseUrl,
32515
- organizationName: robotCreds.organizationName,
32516
- organizationId: robotCreds.organizationId,
32517
- tenantName: robotCreds.tenantName,
32518
- tenantId: robotCreds.tenantId,
32519
- issuer: robotCreds.issuer,
32520
- expiration: expiration2,
32521
- source: "robot" /* Robot */
32522
- };
32523
- }
32524
- if (isEnvAuthEnabled()) {
32525
- return readAuthFromEnv();
32526
- }
32527
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
32528
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
32529
- if (absolutePath === undefined) {
32530
- const robotCreds = await robotFallback();
32531
- if (robotCreds) {
32532
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
32533
- const status = {
32534
- loginStatus: "Logged in",
32535
- accessToken: robotCreds.accessToken,
32536
- baseUrl: robotCreds.baseUrl,
32537
- organizationName: robotCreds.organizationName,
32538
- organizationId: robotCreds.organizationId,
32539
- tenantName: robotCreds.tenantName,
32540
- tenantId: robotCreds.tenantId,
32541
- issuer: robotCreds.issuer,
32542
- expiration: expiration2,
32543
- source: "robot" /* Robot */
32544
- };
32545
- return status;
32546
- }
32547
- return { loginStatus: "Not logged in" };
32548
- }
32549
- let credentials;
32550
- try {
32551
- credentials = await loadEnvFile({ envPath: absolutePath });
32552
- } catch (error) {
32553
- if (isFileNotFoundError(error)) {
32554
- return { loginStatus: "Not logged in" };
32555
- }
32556
- throw error;
32557
- }
32558
- if (!credentials.UIPATH_ACCESS_TOKEN) {
32559
- return { loginStatus: "Not logged in" };
32560
- }
32561
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
32562
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
32563
- let expiration = getTokenExpiration(accessToken);
32564
- let persistenceWarning;
32565
- let lockReleaseFailed = false;
32566
- let tokenRefresh;
32567
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
32568
- const tryGlobalCredsHint = async () => {
32569
- const fs7 = getFs();
32570
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
32571
- if (absolutePath === globalPath)
32572
- return;
32573
- if (!await fs7.exists(globalPath))
32574
- return;
32575
- try {
32576
- const globalCreds = await loadEnvFile({ envPath: globalPath });
32577
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
32578
- return;
32579
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
32580
- if (globalExp && globalExp <= new Date)
32581
- return;
32582
- 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.`;
32583
- } catch {
32584
- return;
32585
- }
32586
- };
32587
- if (expiration && expiration <= outerThreshold && refreshToken) {
32588
- let release;
32589
- try {
32590
- release = await getFs().acquireLock(absolutePath);
32591
- } catch (error) {
32592
- const msg = errorMessage(error);
32593
- const globalHint = await tryGlobalCredsHint();
32594
- if (globalHint) {
32595
- return {
32596
- loginStatus: "Expired",
32597
- accessToken,
32598
- refreshToken,
32599
- baseUrl: credentials.UIPATH_URL,
32600
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
32601
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
32602
- tenantName: credentials.UIPATH_TENANT_NAME,
32603
- tenantId: credentials.UIPATH_TENANT_ID,
32604
- expiration,
32605
- source: "file" /* File */,
32606
- hint: globalHint,
32607
- tokenRefresh: {
32608
- attempted: false,
32609
- success: false,
32610
- errorMessage: `lock acquisition failed: ${msg}`
32611
- }
32612
- };
32613
- }
32614
- return {
32615
- loginStatus: "Refresh Failed",
32616
- 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.",
32617
- tokenRefresh: {
32618
- attempted: false,
32619
- success: false,
32620
- errorMessage: `lock acquisition failed: ${msg}`
32621
- }
32622
- };
32623
- }
32624
- let lockedFailure;
32625
- try {
32626
- const outcome = await runRefreshLocked({
32627
- absolutePath,
32628
- refreshToken,
32629
- customAuthority: credentials.UIPATH_URL,
32630
- ensureTokenValidityMinutes,
32631
- loadEnvFile,
32632
- saveEnvFile,
32633
- refreshFn: refreshTokenFn,
32634
- resolveConfig
32635
- });
32636
- if (outcome.kind === "fail") {
32637
- lockedFailure = outcome.status;
32638
- } else {
32639
- accessToken = outcome.accessToken;
32640
- refreshToken = outcome.refreshToken;
32641
- expiration = outcome.expiration;
32642
- tokenRefresh = outcome.tokenRefresh;
32643
- if (outcome.persistenceWarning) {
32644
- persistenceWarning = outcome.persistenceWarning;
32645
- }
32646
- }
32647
- } finally {
32648
- try {
32649
- await release();
32650
- } catch {
32651
- lockReleaseFailed = true;
32652
- }
32653
- }
32654
- if (lockedFailure) {
32655
- const globalHint = await tryGlobalCredsHint();
32656
- const base = globalHint ? {
32657
- ...lockedFailure,
32658
- loginStatus: "Expired",
32659
- hint: globalHint
32660
- } : lockedFailure;
32661
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
32662
- }
32663
- }
32664
- const result = {
32665
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
32666
- accessToken,
32667
- refreshToken,
32668
- baseUrl: credentials.UIPATH_URL,
32669
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
32670
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
32671
- tenantName: credentials.UIPATH_TENANT_NAME,
32672
- tenantId: credentials.UIPATH_TENANT_ID,
32673
- expiration,
32674
- source: "file" /* File */,
32675
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
32676
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
32677
- ...tokenRefresh ? { tokenRefresh } : {}
32678
- };
32679
- if (result.loginStatus === "Expired") {
32680
- const globalHint = await tryGlobalCredsHint();
32681
- if (globalHint) {
32682
- result.hint = globalHint;
32683
- }
32684
- }
32685
- return result;
32686
- };
32687
- var isFileNotFoundError = (error) => {
32688
- if (!(error instanceof Object))
32689
- return false;
32690
- return error.code === "ENOENT";
32691
- };
32692
- var getLoginStatusAsync = async (options = {}) => {
32693
- return getLoginStatusWithDeps(options);
32694
- };
31643
+ function normalizeTokenRefreshFailure() {
31644
+ return "stored refresh token is invalid or expired";
31645
+ }
31646
+ function normalizeTokenRefreshUnavailableFailure() {
31647
+ return "token refresh failed before authentication completed";
31648
+ }
31649
+ function errorMessage(error) {
31650
+ return error instanceof Error ? error.message : String(error);
31651
+ }
32695
31652
 
32696
31653
  // ../../auth/src/authContext.ts
32697
31654
  var getAuthContext = async (options = {}) => {
@@ -32726,6 +31683,14 @@ var getAuthContext = async (options = {}) => {
32726
31683
  };
32727
31684
  // ../../auth/src/interactive.ts
32728
31685
  init_src();
31686
+
31687
+ // ../../auth/src/selectTenant.ts
31688
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
31689
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
31690
+ var TENANT_SELECTION_CODES = new Set([
31691
+ TENANT_SELECTION_REQUIRED_CODE,
31692
+ INVALID_TENANT_CODE
31693
+ ]);
32729
31694
  // ../../auth/src/logout.ts
32730
31695
  init_src();
32731
31696
 
@@ -35086,3 +34051,5 @@ export {
35086
34051
  registerCommands,
35087
34052
  metadata
35088
34053
  };
34054
+
34055
+ //# debugId=5D6FA25C683EDF2264756E2164756E21