@uipath/oms-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 +882 -1917
  2. package/dist/tool.js +887 -1921
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -13534,8 +13534,8 @@ var require_Subscription = __commonJS((exports) => {
13534
13534
  if (_parentOrParents instanceof Subscription2) {
13535
13535
  _parentOrParents.remove(this);
13536
13536
  } else if (_parentOrParents !== null) {
13537
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
13538
- var parent_1 = _parentOrParents[index2];
13537
+ for (var index = 0;index < _parentOrParents.length; ++index) {
13538
+ var parent_1 = _parentOrParents[index];
13539
13539
  parent_1.remove(this);
13540
13540
  }
13541
13541
  }
@@ -13550,10 +13550,10 @@ var require_Subscription = __commonJS((exports) => {
13550
13550
  }
13551
13551
  }
13552
13552
  if (isArray_1.isArray(_subscriptions)) {
13553
- var index2 = -1;
13553
+ var index = -1;
13554
13554
  var len = _subscriptions.length;
13555
- while (++index2 < len) {
13556
- var sub2 = _subscriptions[index2];
13555
+ while (++index < len) {
13556
+ var sub2 = _subscriptions[index];
13557
13557
  if (isObject_1.isObject(sub2)) {
13558
13558
  try {
13559
13559
  sub2.unsubscribe();
@@ -14983,13 +14983,13 @@ var require_AsyncAction = __commonJS((exports) => {
14983
14983
  var id = this.id;
14984
14984
  var scheduler = this.scheduler;
14985
14985
  var actions = scheduler.actions;
14986
- var index2 = actions.indexOf(this);
14986
+ var index = actions.indexOf(this);
14987
14987
  this.work = null;
14988
14988
  this.state = null;
14989
14989
  this.pending = false;
14990
14990
  this.scheduler = null;
14991
- if (index2 !== -1) {
14992
- actions.splice(index2, 1);
14991
+ if (index !== -1) {
14992
+ actions.splice(index, 1);
14993
14993
  }
14994
14994
  if (id != null) {
14995
14995
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -15833,17 +15833,17 @@ var require_AsapScheduler = __commonJS((exports) => {
15833
15833
  this.scheduled = undefined;
15834
15834
  var actions = this.actions;
15835
15835
  var error;
15836
- var index2 = -1;
15836
+ var index = -1;
15837
15837
  var count = actions.length;
15838
15838
  action = action || actions.shift();
15839
15839
  do {
15840
15840
  if (error = action.execute(action.state, action.delay)) {
15841
15841
  break;
15842
15842
  }
15843
- } while (++index2 < count && (action = actions.shift()));
15843
+ } while (++index < count && (action = actions.shift()));
15844
15844
  this.active = false;
15845
15845
  if (error) {
15846
- while (++index2 < count && (action = actions.shift())) {
15846
+ while (++index < count && (action = actions.shift())) {
15847
15847
  action.unsubscribe();
15848
15848
  }
15849
15849
  throw error;
@@ -15966,17 +15966,17 @@ var require_AnimationFrameScheduler = __commonJS((exports) => {
15966
15966
  this.scheduled = undefined;
15967
15967
  var actions = this.actions;
15968
15968
  var error;
15969
- var index2 = -1;
15969
+ var index = -1;
15970
15970
  var count = actions.length;
15971
15971
  action = action || actions.shift();
15972
15972
  do {
15973
15973
  if (error = action.execute(action.state, action.delay)) {
15974
15974
  break;
15975
15975
  }
15976
- } while (++index2 < count && (action = actions.shift()));
15976
+ } while (++index < count && (action = actions.shift()));
15977
15977
  this.active = false;
15978
15978
  if (error) {
15979
- while (++index2 < count && (action = actions.shift())) {
15979
+ while (++index < count && (action = actions.shift())) {
15980
15980
  action.unsubscribe();
15981
15981
  }
15982
15982
  throw error;
@@ -16060,16 +16060,16 @@ var require_VirtualTimeScheduler = __commonJS((exports) => {
16060
16060
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
16061
16061
  var VirtualAction = function(_super) {
16062
16062
  __extends(VirtualAction2, _super);
16063
- function VirtualAction2(scheduler, work, index2) {
16064
- if (index2 === undefined) {
16065
- index2 = scheduler.index += 1;
16063
+ function VirtualAction2(scheduler, work, index) {
16064
+ if (index === undefined) {
16065
+ index = scheduler.index += 1;
16066
16066
  }
16067
16067
  var _this = _super.call(this, scheduler, work) || this;
16068
16068
  _this.scheduler = scheduler;
16069
16069
  _this.work = work;
16070
- _this.index = index2;
16070
+ _this.index = index;
16071
16071
  _this.active = true;
16072
- _this.index = scheduler.index = index2;
16072
+ _this.index = scheduler.index = index;
16073
16073
  return _this;
16074
16074
  }
16075
16075
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -17216,9 +17216,9 @@ var require_mergeMap = __commonJS((exports) => {
17216
17216
  };
17217
17217
  MergeMapSubscriber2.prototype._tryNext = function(value) {
17218
17218
  var result;
17219
- var index2 = this.index++;
17219
+ var index = this.index++;
17220
17220
  try {
17221
- result = this.project(value, index2);
17221
+ result = this.project(value, index);
17222
17222
  } catch (err) {
17223
17223
  this.destination.error(err);
17224
17224
  return;
@@ -17798,12 +17798,12 @@ var require_pairs2 = __commonJS((exports) => {
17798
17798
  }
17799
17799
  exports.pairs = pairs;
17800
17800
  function dispatch(state) {
17801
- var { keys, index: index2, subscriber, subscription, obj } = state;
17801
+ var { keys, index, subscriber, subscription, obj } = state;
17802
17802
  if (!subscriber.closed) {
17803
- if (index2 < keys.length) {
17804
- var key = keys[index2];
17803
+ if (index < keys.length) {
17804
+ var key = keys[index];
17805
17805
  subscriber.next([key, obj[key]]);
17806
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
17806
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
17807
17807
  } else {
17808
17808
  subscriber.complete();
17809
17809
  }
@@ -18016,18 +18016,18 @@ var require_range = __commonJS((exports) => {
18016
18016
  count = start;
18017
18017
  start = 0;
18018
18018
  }
18019
- var index2 = 0;
18019
+ var index = 0;
18020
18020
  var current = start;
18021
18021
  if (scheduler) {
18022
18022
  return scheduler.schedule(dispatch, 0, {
18023
- index: index2,
18023
+ index,
18024
18024
  count,
18025
18025
  start,
18026
18026
  subscriber
18027
18027
  });
18028
18028
  } else {
18029
18029
  do {
18030
- if (index2++ >= count) {
18030
+ if (index++ >= count) {
18031
18031
  subscriber.complete();
18032
18032
  break;
18033
18033
  }
@@ -18042,8 +18042,8 @@ var require_range = __commonJS((exports) => {
18042
18042
  }
18043
18043
  exports.range = range;
18044
18044
  function dispatch(state) {
18045
- var { start, index: index2, count, subscriber } = state;
18046
- if (index2 >= count) {
18045
+ var { start, index, count, subscriber } = state;
18046
+ if (index >= count) {
18047
18047
  subscriber.complete();
18048
18048
  return;
18049
18049
  }
@@ -18051,7 +18051,7 @@ var require_range = __commonJS((exports) => {
18051
18051
  if (subscriber.closed) {
18052
18052
  return;
18053
18053
  }
18054
- state.index = index2 + 1;
18054
+ state.index = index + 1;
18055
18055
  state.start = start + 1;
18056
18056
  this.schedule(state);
18057
18057
  }
@@ -18089,14 +18089,14 @@ var require_timer = __commonJS((exports) => {
18089
18089
  }
18090
18090
  exports.timer = timer;
18091
18091
  function dispatch(state) {
18092
- var { index: index2, period, subscriber } = state;
18093
- subscriber.next(index2);
18092
+ var { index, period, subscriber } = state;
18093
+ subscriber.next(index);
18094
18094
  if (subscriber.closed) {
18095
18095
  return;
18096
18096
  } else if (period === -1) {
18097
18097
  return subscriber.complete();
18098
18098
  }
18099
- state.index = index2 + 1;
18099
+ state.index = index + 1;
18100
18100
  this.schedule(state, period);
18101
18101
  }
18102
18102
  });
@@ -21260,7 +21260,7 @@ var {
21260
21260
  var package_default = {
21261
21261
  name: "@uipath/oms-tool",
21262
21262
  license: "MIT",
21263
- version: "1.196.0",
21263
+ version: "1.197.0-preview.59",
21264
21264
  description: "CLI plugin for the UiPath Organization Management Service.",
21265
21265
  private: false,
21266
21266
  repository: {
@@ -21286,7 +21286,7 @@ var package_default = {
21286
21286
  "dist"
21287
21287
  ],
21288
21288
  scripts: {
21289
- build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander && bun build ./src/index.ts --outdir dist --format esm --target node",
21289
+ build: "bun build ./src/tool.ts --outdir dist --format esm --target node --external commander --sourcemap=linked && bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked",
21290
21290
  package: "bun run build && bun pm pack",
21291
21291
  lint: "biome check .",
21292
21292
  "lint:fix": "biome check --write .",
@@ -21350,27 +21350,54 @@ var NETWORK_ERROR_CODES = new Set([
21350
21350
  "ENETUNREACH",
21351
21351
  "EAI_FAIL"
21352
21352
  ]);
21353
- function isHtmlDocument(body) {
21354
- return /^\s*(<!doctype html|<html\b)/i.test(body);
21355
- }
21356
- function extractNetworkErrorCode(error) {
21357
- if (error === null || typeof error !== "object") {
21358
- return;
21359
- }
21360
- const err = error;
21361
- const code = typeof err.code === "string" ? err.code : undefined;
21362
- if (code && NETWORK_ERROR_CODES.has(code)) {
21363
- return code;
21364
- }
21365
- const cause = err.cause;
21366
- if (cause !== null && typeof cause === "object") {
21367
- const causeCode = cause.code;
21368
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
21369
- return causeCode;
21353
+ var TLS_ERROR_CODES = new Set([
21354
+ "SELF_SIGNED_CERT_IN_CHAIN",
21355
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
21356
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
21357
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21358
+ "UNABLE_TO_GET_ISSUER_CERT",
21359
+ "CERT_HAS_EXPIRED",
21360
+ "CERT_UNTRUSTED",
21361
+ "ERR_TLS_CERT_ALTNAME_INVALID"
21362
+ ]);
21363
+ 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.";
21364
+ 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.";
21365
+ function describeConnectivityError(error) {
21366
+ let current = error;
21367
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
21368
+ const cur = current;
21369
+ const code = typeof cur.code === "string" ? cur.code : undefined;
21370
+ const message = typeof cur.message === "string" ? cur.message : undefined;
21371
+ if (code && TLS_ERROR_CODES.has(code)) {
21372
+ return {
21373
+ code,
21374
+ kind: "tls",
21375
+ message: message ?? code,
21376
+ instructions: TLS_INSTRUCTIONS
21377
+ };
21378
+ }
21379
+ if (code && NETWORK_ERROR_CODES.has(code)) {
21380
+ return {
21381
+ code,
21382
+ kind: "network",
21383
+ message: message ?? code,
21384
+ instructions: NETWORK_INSTRUCTIONS
21385
+ };
21370
21386
  }
21387
+ current = cur.cause;
21371
21388
  }
21372
21389
  return;
21373
21390
  }
21391
+ function parseHttpStatusFromMessage(message) {
21392
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
21393
+ if (!match)
21394
+ return;
21395
+ const status = Number(match[1]);
21396
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
21397
+ }
21398
+ function isHtmlDocument(body) {
21399
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
21400
+ }
21374
21401
  function retryHintForRetryAfter(seconds) {
21375
21402
  if (seconds <= 1) {
21376
21403
  return "RetryAfter1Second";
@@ -21411,15 +21438,28 @@ function classifyError(status, error) {
21411
21438
  if (status !== undefined && status >= 500 && status < 600) {
21412
21439
  return { errorCode: "server_error", retry: "RetryLater" };
21413
21440
  }
21414
- if (extractNetworkErrorCode(error)) {
21415
- return { errorCode: "network_error", retry: "RetryLater" };
21441
+ const connectivity = describeConnectivityError(error);
21442
+ if (connectivity) {
21443
+ return {
21444
+ errorCode: "network_error",
21445
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
21446
+ };
21416
21447
  }
21417
21448
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
21418
21449
  }
21450
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
21451
+ if (extractedMessage) {
21452
+ return `HTTP ${status}: ${extractedMessage}`;
21453
+ }
21454
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
21455
+ }
21419
21456
  async function extractErrorDetails(error, options) {
21420
21457
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
21421
21458
  const response = err.response;
21422
- const status = err.status ?? response?.status;
21459
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21460
+ const explicitStatus = err.status ?? response?.status;
21461
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
21462
+ const status = explicitStatus ?? inferredStatus;
21423
21463
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
21424
21464
  let rawBody;
21425
21465
  let extractedMessage;
@@ -21454,7 +21494,6 @@ async function extractErrorDetails(error, options) {
21454
21494
  }
21455
21495
  }
21456
21496
  }
21457
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
21458
21497
  let message;
21459
21498
  let result = "Failure";
21460
21499
  const classification = classifyError(status, error);
@@ -21468,10 +21507,10 @@ async function extractErrorDetails(error, options) {
21468
21507
  } else if (status === 405) {
21469
21508
  message = DEFAULT_405;
21470
21509
  } else if (status === 400 || status === 422) {
21471
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21510
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21472
21511
  result = "ValidationError";
21473
21512
  } else if (status === 429) {
21474
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
21513
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
21475
21514
  } else if (extractedMessage) {
21476
21515
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
21477
21516
  message = rawMessage;
@@ -21479,7 +21518,9 @@ async function extractErrorDetails(error, options) {
21479
21518
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
21480
21519
  }
21481
21520
  } else if (status) {
21482
- if (rawMessage === "Unknown error" && response) {
21521
+ if (inferredStatus !== undefined) {
21522
+ message = rawMessage;
21523
+ } else if (rawMessage === "Unknown error" && response) {
21483
21524
  const statusText = response.statusText;
21484
21525
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
21485
21526
  } else {
@@ -21488,6 +21529,12 @@ async function extractErrorDetails(error, options) {
21488
21529
  } else {
21489
21530
  message = rawMessage;
21490
21531
  }
21532
+ if (status === undefined) {
21533
+ const connectivity = describeConnectivityError(error);
21534
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
21535
+ message = `${message}: ${connectivity.message}`;
21536
+ }
21537
+ }
21491
21538
  let details = rawMessage;
21492
21539
  if (rawBody) {
21493
21540
  if (parsedBody) {
@@ -21639,6 +21686,7 @@ var CONSOLE_FALLBACK = {
21639
21686
  writeLog: (str) => process.stdout.write(str),
21640
21687
  capabilities: {
21641
21688
  isInteractive: false,
21689
+ canReadInput: false,
21642
21690
  supportsColor: false,
21643
21691
  outputWidth: 80
21644
21692
  }
@@ -26839,6 +26887,29 @@ function isPlainRecord(value) {
26839
26887
  const prototype = Object.getPrototypeOf(value);
26840
26888
  return prototype === Object.prototype || prototype === null;
26841
26889
  }
26890
+ function extractPagedRows(value) {
26891
+ if (Array.isArray(value) || !isPlainRecord(value))
26892
+ return null;
26893
+ const entries = Object.values(value);
26894
+ if (entries.length === 0)
26895
+ return null;
26896
+ let rows = null;
26897
+ let hasScalarSibling = false;
26898
+ for (const entry of entries) {
26899
+ if (Array.isArray(entry)) {
26900
+ if (rows !== null)
26901
+ return null;
26902
+ rows = entry;
26903
+ } else if (entry !== null && typeof entry === "object") {
26904
+ return null;
26905
+ } else {
26906
+ hasScalarSibling = true;
26907
+ }
26908
+ }
26909
+ if (rows === null || !hasScalarSibling)
26910
+ return null;
26911
+ return rows;
26912
+ }
26842
26913
  function toLowerCamelCaseKey(key) {
26843
26914
  if (!key)
26844
26915
  return key;
@@ -26903,7 +26974,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26903
26974
  break;
26904
26975
  case "plain": {
26905
26976
  if ("Data" in data && data.Data != null) {
26906
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
26977
+ const pagedRows = extractPagedRows(data.Data);
26978
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
26907
26979
  items.forEach((item) => {
26908
26980
  const values = Object.values(item).map((v) => v ?? "").join("\t");
26909
26981
  logFn(values);
@@ -26915,10 +26987,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
26915
26987
  break;
26916
26988
  }
26917
26989
  default: {
26918
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
26990
+ const hasData = "Data" in data && data.Data != null;
26991
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
26992
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
26993
+ if (hasData && !(rows !== null && rows.length === 0)) {
26919
26994
  const logValue = data.Log;
26920
- if (Array.isArray(data.Data)) {
26921
- printResizableTable(data.Data, logFn, logValue);
26995
+ if (rows !== null) {
26996
+ printResizableTable(rows, logFn, logValue);
26922
26997
  } else {
26923
26998
  printVerticalTable(data.Data, logFn, logValue);
26924
26999
  }
@@ -27106,6 +27181,44 @@ function defaultErrorCodeForResult(result) {
27106
27181
  return "unknown_error";
27107
27182
  }
27108
27183
  }
27184
+ function parseHttpStatusFromMessage2(message) {
27185
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
27186
+ if (!match)
27187
+ return;
27188
+ const status = Number(match[1]);
27189
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
27190
+ }
27191
+ function defaultErrorCodeForHttpStatus(status) {
27192
+ if (status === undefined)
27193
+ return;
27194
+ if (status === 400 || status === 409 || status === 422) {
27195
+ return "invalid_argument";
27196
+ }
27197
+ if (status === 401)
27198
+ return "authentication_required";
27199
+ if (status === 403)
27200
+ return "permission_denied";
27201
+ if (status === 404)
27202
+ return "not_found";
27203
+ if (status === 405)
27204
+ return "method_not_allowed";
27205
+ if (status === 408)
27206
+ return "timeout";
27207
+ if (status === 429)
27208
+ return "rate_limited";
27209
+ if (status >= 500 && status < 600)
27210
+ return "server_error";
27211
+ return;
27212
+ }
27213
+ function defaultErrorCodeForFailure(data) {
27214
+ if (data.Result === RESULTS.Failure) {
27215
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
27216
+ const errorCode = defaultErrorCodeForHttpStatus(status);
27217
+ if (errorCode)
27218
+ return errorCode;
27219
+ }
27220
+ return defaultErrorCodeForResult(data.Result);
27221
+ }
27109
27222
  function defaultRetryForErrorCode(errorCode) {
27110
27223
  switch (errorCode) {
27111
27224
  case "network_error":
@@ -27135,16 +27248,19 @@ var OutputFormatter;
27135
27248
  OutputFormatter.success = success;
27136
27249
  function error(data) {
27137
27250
  data.Log ??= getLogFilePath() || undefined;
27138
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
27251
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
27139
27252
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
27140
27253
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
27141
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
27142
- result: data.Result,
27143
- errorCode: data.ErrorCode,
27144
- retry: data.Retry,
27145
- message: data.Message
27146
- });
27147
- logOutput(normalizeOutputKeys(data), getOutputFormat());
27254
+ const { SuppressTelemetry, ...envelope } = data;
27255
+ if (!SuppressTelemetry) {
27256
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
27257
+ result: data.Result,
27258
+ errorCode: data.ErrorCode,
27259
+ retry: data.Retry,
27260
+ message: data.Message
27261
+ });
27262
+ }
27263
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
27148
27264
  }
27149
27265
  OutputFormatter.error = error;
27150
27266
  function emitList(code, items, opts) {
@@ -27434,1653 +27550,236 @@ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
27434
27550
  var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
27435
27551
  // ../../common/src/interactivity-context.ts
27436
27552
  var modeSlot = singleton("InteractivityMode");
27437
- // ../../../node_modules/jsonpath-plus/dist/index-node-esm.js
27438
- import vm from "vm";
27553
+ // ../../common/src/polling/types.ts
27554
+ var PollOutcome = {
27555
+ Completed: "completed",
27556
+ Timeout: "timeout",
27557
+ Interrupted: "interrupted",
27558
+ Aborted: "aborted",
27559
+ Failed: "failed"
27560
+ };
27439
27561
 
27440
- class Hooks {
27441
- add(name, callback, first) {
27442
- if (typeof arguments[0] != "string") {
27443
- for (let name2 in arguments[0]) {
27444
- this.add(name2, arguments[0][name2], arguments[1]);
27445
- }
27446
- } else {
27447
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
27448
- this[name2] = this[name2] || [];
27449
- if (callback) {
27450
- this[name2][first ? "unshift" : "push"](callback);
27451
- }
27452
- }, this);
27453
- }
27454
- }
27455
- run(name, env) {
27456
- this[name] = this[name] || [];
27457
- this[name].forEach(function(callback) {
27458
- callback.call(env && env.context ? env.context : env, env);
27459
- });
27460
- }
27562
+ // ../../common/src/polling/poll-failure-mapping.ts
27563
+ var REASON_BY_OUTCOME = {
27564
+ [PollOutcome.Timeout]: "poll_timeout",
27565
+ [PollOutcome.Failed]: "poll_failed",
27566
+ [PollOutcome.Interrupted]: "poll_failed",
27567
+ [PollOutcome.Aborted]: "poll_aborted"
27568
+ };
27569
+ // ../../common/src/polling/terminal-statuses.ts
27570
+ var TERMINAL_STATUSES = new Set([
27571
+ "completed",
27572
+ "successful",
27573
+ "faulted",
27574
+ "failed",
27575
+ "cancelled",
27576
+ "canceled",
27577
+ "stopped",
27578
+ "finished"
27579
+ ]);
27580
+ var FAILURE_STATUSES = new Set([
27581
+ "faulted",
27582
+ "failed",
27583
+ "cancelled",
27584
+ "canceled",
27585
+ "stopped"
27586
+ ]);
27587
+ // ../../common/src/preview.ts
27588
+ var previewSlot = singleton("PreviewBuild");
27589
+ function isPreviewBuild() {
27590
+ return previewSlot.get(false) ?? false;
27461
27591
  }
27462
-
27463
- class Plugins {
27464
- constructor(jsep) {
27465
- this.jsep = jsep;
27466
- this.registered = {};
27592
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
27593
+ if (isPreviewBuild()) {
27594
+ return this.command(nameAndArgs, opts);
27467
27595
  }
27468
- register(...plugins) {
27469
- plugins.forEach((plugin) => {
27470
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
27471
- throw new Error("Invalid JSEP plugin format");
27472
- }
27473
- if (this.registered[plugin.name]) {
27474
- return;
27475
- }
27476
- plugin.init(this.jsep);
27477
- this.registered[plugin.name] = plugin;
27478
- });
27596
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
27597
+ };
27598
+ // ../../common/src/screen-logger.ts
27599
+ var ScreenLogger;
27600
+ ((ScreenLogger) => {
27601
+ function progress(message) {
27602
+ getOutputSink().writeErr(`${message}
27603
+ `);
27479
27604
  }
27605
+ ScreenLogger.progress = progress;
27606
+ })(ScreenLogger ||= {});
27607
+ // ../../common/src/sdk-user-agent.ts
27608
+ var USER_AGENT_HEADER = "User-Agent";
27609
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
27610
+ function userAgentPatchKey(userAgent) {
27611
+ return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
27480
27612
  }
27481
-
27482
- class Jsep {
27483
- static get version() {
27484
- return "1.4.0";
27485
- }
27486
- static toString() {
27487
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
27488
- }
27489
- static addUnaryOp(op_name) {
27490
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
27491
- Jsep.unary_ops[op_name] = 1;
27492
- return Jsep;
27493
- }
27494
- static addBinaryOp(op_name, precedence, isRightAssociative) {
27495
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
27496
- Jsep.binary_ops[op_name] = precedence;
27497
- if (isRightAssociative) {
27498
- Jsep.right_associative.add(op_name);
27499
- } else {
27500
- Jsep.right_associative.delete(op_name);
27613
+ function splitUserAgentTokens(value) {
27614
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
27615
+ }
27616
+ function appendUserAgentToken(value, userAgent) {
27617
+ const tokens = splitUserAgentTokens(value);
27618
+ const seen = new Set(tokens);
27619
+ for (const token of splitUserAgentTokens(userAgent)) {
27620
+ if (!seen.has(token)) {
27621
+ tokens.push(token);
27622
+ seen.add(token);
27501
27623
  }
27502
- return Jsep;
27503
27624
  }
27504
- static addIdentifierChar(char) {
27505
- Jsep.additional_identifier_chars.add(char);
27506
- return Jsep;
27507
- }
27508
- static addLiteral(literal_name, literal_value) {
27509
- Jsep.literals[literal_name] = literal_value;
27510
- return Jsep;
27625
+ return tokens.join(" ");
27626
+ }
27627
+ function getEffectiveUserAgent(userAgent) {
27628
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
27629
+ }
27630
+ function getHeaderName(headers, headerName) {
27631
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
27632
+ }
27633
+ function getSdkUserAgentToken(pkg) {
27634
+ const packageName = pkg.name.replace(/^@uipath\//, "");
27635
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
27636
+ }
27637
+ function addSdkUserAgentHeader(headers, userAgent) {
27638
+ const result = { ...headers ?? {} };
27639
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
27640
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
27641
+ return result;
27642
+ }
27643
+ function asHeaderRecord(headers) {
27644
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
27645
+ }
27646
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
27647
+ return async (requestContext) => {
27648
+ const initWithHeaders = {
27649
+ ...requestContext.init,
27650
+ headers: forward(asHeaderRecord(requestContext.init.headers))
27651
+ };
27652
+ const override = typeof initOverrides === "function" ? await initOverrides({
27653
+ ...requestContext,
27654
+ init: initWithHeaders
27655
+ }) : initOverrides;
27656
+ return {
27657
+ ...override ?? {},
27658
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
27659
+ };
27660
+ };
27661
+ }
27662
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
27663
+ const prototype = BaseApiClass.prototype;
27664
+ if (prototype[patchKey]) {
27665
+ return;
27511
27666
  }
27512
- static removeUnaryOp(op_name) {
27513
- delete Jsep.unary_ops[op_name];
27514
- if (op_name.length === Jsep.max_unop_len) {
27515
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
27516
- }
27517
- return Jsep;
27667
+ if (typeof prototype.request !== "function") {
27668
+ throw new Error("Generated BaseAPI request function not found.");
27518
27669
  }
27519
- static removeAllUnaryOps() {
27520
- Jsep.unary_ops = {};
27521
- Jsep.max_unop_len = 0;
27522
- return Jsep;
27670
+ const originalRequest = prototype.request;
27671
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
27672
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
27673
+ };
27674
+ Object.defineProperty(prototype, patchKey, {
27675
+ value: true
27676
+ });
27677
+ }
27678
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
27679
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
27680
+ }
27681
+ // ../../common/src/tool-provider.ts
27682
+ var factorySlot = singleton("PackagerFactoryProvider");
27683
+ // ../oms-sdk/generated/v1/src/runtime.ts
27684
+ var BASE_PATH = "http://localhost".replace(/\/+$/, "");
27685
+
27686
+ class Configuration {
27687
+ configuration;
27688
+ constructor(configuration = {}) {
27689
+ this.configuration = configuration;
27523
27690
  }
27524
- static removeIdentifierChar(char) {
27525
- Jsep.additional_identifier_chars.delete(char);
27526
- return Jsep;
27691
+ set config(configuration) {
27692
+ this.configuration = configuration;
27527
27693
  }
27528
- static removeBinaryOp(op_name) {
27529
- delete Jsep.binary_ops[op_name];
27530
- if (op_name.length === Jsep.max_binop_len) {
27531
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
27532
- }
27533
- Jsep.right_associative.delete(op_name);
27534
- return Jsep;
27694
+ get basePath() {
27695
+ return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
27535
27696
  }
27536
- static removeAllBinaryOps() {
27537
- Jsep.binary_ops = {};
27538
- Jsep.max_binop_len = 0;
27539
- return Jsep;
27697
+ get fetchApi() {
27698
+ return this.configuration.fetchApi;
27540
27699
  }
27541
- static removeLiteral(literal_name) {
27542
- delete Jsep.literals[literal_name];
27543
- return Jsep;
27700
+ get middleware() {
27701
+ return this.configuration.middleware || [];
27544
27702
  }
27545
- static removeAllLiterals() {
27546
- Jsep.literals = {};
27547
- return Jsep;
27703
+ get queryParamsStringify() {
27704
+ return this.configuration.queryParamsStringify || querystring;
27548
27705
  }
27549
- get char() {
27550
- return this.expr.charAt(this.index);
27706
+ get username() {
27707
+ return this.configuration.username;
27551
27708
  }
27552
- get code() {
27553
- return this.expr.charCodeAt(this.index);
27709
+ get password() {
27710
+ return this.configuration.password;
27554
27711
  }
27555
- constructor(expr) {
27556
- this.expr = expr;
27557
- this.index = 0;
27712
+ get apiKey() {
27713
+ const apiKey = this.configuration.apiKey;
27714
+ if (apiKey) {
27715
+ return typeof apiKey === "function" ? apiKey : () => apiKey;
27716
+ }
27717
+ return;
27558
27718
  }
27559
- static parse(expr) {
27560
- return new Jsep(expr).parse();
27719
+ get accessToken() {
27720
+ const accessToken = this.configuration.accessToken;
27721
+ if (accessToken) {
27722
+ return typeof accessToken === "function" ? accessToken : async () => accessToken;
27723
+ }
27724
+ return;
27561
27725
  }
27562
- static getMaxKeyLen(obj) {
27563
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
27726
+ get headers() {
27727
+ return this.configuration.headers;
27564
27728
  }
27565
- static isDecimalDigit(ch) {
27566
- return ch >= 48 && ch <= 57;
27729
+ get credentials() {
27730
+ return this.configuration.credentials;
27567
27731
  }
27568
- static binaryPrecedence(op_val) {
27569
- return Jsep.binary_ops[op_val] || 0;
27732
+ }
27733
+ var DefaultConfig = new Configuration;
27734
+
27735
+ class BaseAPI {
27736
+ configuration;
27737
+ static jsonRegex = new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", "i");
27738
+ middleware;
27739
+ constructor(configuration = DefaultConfig) {
27740
+ this.configuration = configuration;
27741
+ this.middleware = configuration.middleware;
27570
27742
  }
27571
- static isIdentifierStart(ch) {
27572
- 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));
27743
+ withMiddleware(...middlewares) {
27744
+ const next = this.clone();
27745
+ next.middleware = next.middleware.concat(...middlewares);
27746
+ return next;
27573
27747
  }
27574
- static isIdentifierPart(ch) {
27575
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
27748
+ withPreMiddleware(...preMiddlewares) {
27749
+ const middlewares = preMiddlewares.map((pre) => ({ pre }));
27750
+ return this.withMiddleware(...middlewares);
27576
27751
  }
27577
- throwError(message) {
27578
- const error = new Error(message + " at character " + this.index);
27579
- error.index = this.index;
27580
- error.description = message;
27581
- throw error;
27752
+ withPostMiddleware(...postMiddlewares) {
27753
+ const middlewares = postMiddlewares.map((post) => ({ post }));
27754
+ return this.withMiddleware(...middlewares);
27582
27755
  }
27583
- runHook(name, node) {
27584
- if (Jsep.hooks[name]) {
27585
- const env = {
27586
- context: this,
27587
- node
27588
- };
27589
- Jsep.hooks.run(name, env);
27590
- return env.node;
27756
+ isJsonMime(mime) {
27757
+ if (!mime) {
27758
+ return false;
27591
27759
  }
27592
- return node;
27760
+ return BaseAPI.jsonRegex.test(mime);
27593
27761
  }
27594
- searchHook(name) {
27595
- if (Jsep.hooks[name]) {
27596
- const env = {
27597
- context: this
27598
- };
27599
- Jsep.hooks[name].find(function(callback) {
27600
- callback.call(env.context, env);
27601
- return env.node;
27602
- });
27603
- return env.node;
27762
+ async request(context, initOverrides) {
27763
+ const { url, init } = await this.createFetchParams(context, initOverrides);
27764
+ const response = await this.fetchApi(url, init);
27765
+ if (response && (response.status >= 200 && response.status < 300)) {
27766
+ return response;
27604
27767
  }
27768
+ throw new ResponseError(response, "Response returned an error code");
27605
27769
  }
27606
- gobbleSpaces() {
27607
- let ch = this.code;
27608
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
27609
- ch = this.expr.charCodeAt(++this.index);
27770
+ async createFetchParams(context, initOverrides) {
27771
+ let url = this.configuration.basePath + context.path;
27772
+ if (context.query !== undefined && Object.keys(context.query).length !== 0) {
27773
+ url += "?" + this.configuration.queryParamsStringify(context.query);
27610
27774
  }
27611
- this.runHook("gobble-spaces");
27612
- }
27613
- parse() {
27614
- this.runHook("before-all");
27615
- const nodes = this.gobbleExpressions();
27616
- const node = nodes.length === 1 ? nodes[0] : {
27617
- type: Jsep.COMPOUND,
27618
- body: nodes
27619
- };
27620
- return this.runHook("after-all", node);
27621
- }
27622
- gobbleExpressions(untilICode) {
27623
- let nodes = [], ch_i, node;
27624
- while (this.index < this.expr.length) {
27625
- ch_i = this.code;
27626
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
27627
- this.index++;
27628
- } else {
27629
- if (node = this.gobbleExpression()) {
27630
- nodes.push(node);
27631
- } else if (this.index < this.expr.length) {
27632
- if (ch_i === untilICode) {
27633
- break;
27634
- }
27635
- this.throwError('Unexpected "' + this.char + '"');
27636
- }
27637
- }
27638
- }
27639
- return nodes;
27640
- }
27641
- gobbleExpression() {
27642
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
27643
- this.gobbleSpaces();
27644
- return this.runHook("after-expression", node);
27645
- }
27646
- gobbleBinaryOp() {
27647
- this.gobbleSpaces();
27648
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
27649
- let tc_len = to_check.length;
27650
- while (tc_len > 0) {
27651
- 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)))) {
27652
- this.index += tc_len;
27653
- return to_check;
27654
- }
27655
- to_check = to_check.substr(0, --tc_len);
27656
- }
27657
- return false;
27658
- }
27659
- gobbleBinaryExpression() {
27660
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
27661
- left = this.gobbleToken();
27662
- if (!left) {
27663
- return left;
27664
- }
27665
- biop = this.gobbleBinaryOp();
27666
- if (!biop) {
27667
- return left;
27668
- }
27669
- biop_info = {
27670
- value: biop,
27671
- prec: Jsep.binaryPrecedence(biop),
27672
- right_a: Jsep.right_associative.has(biop)
27673
- };
27674
- right = this.gobbleToken();
27675
- if (!right) {
27676
- this.throwError("Expected expression after " + biop);
27677
- }
27678
- stack = [left, biop_info, right];
27679
- while (biop = this.gobbleBinaryOp()) {
27680
- prec = Jsep.binaryPrecedence(biop);
27681
- if (prec === 0) {
27682
- this.index -= biop.length;
27683
- break;
27684
- }
27685
- biop_info = {
27686
- value: biop,
27687
- prec,
27688
- right_a: Jsep.right_associative.has(biop)
27689
- };
27690
- cur_biop = biop;
27691
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
27692
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
27693
- right = stack.pop();
27694
- biop = stack.pop().value;
27695
- left = stack.pop();
27696
- node = {
27697
- type: Jsep.BINARY_EXP,
27698
- operator: biop,
27699
- left,
27700
- right
27701
- };
27702
- stack.push(node);
27703
- }
27704
- node = this.gobbleToken();
27705
- if (!node) {
27706
- this.throwError("Expected expression after " + cur_biop);
27707
- }
27708
- stack.push(biop_info, node);
27709
- }
27710
- i = stack.length - 1;
27711
- node = stack[i];
27712
- while (i > 1) {
27713
- node = {
27714
- type: Jsep.BINARY_EXP,
27715
- operator: stack[i - 1].value,
27716
- left: stack[i - 2],
27717
- right: node
27718
- };
27719
- i -= 2;
27720
- }
27721
- return node;
27722
- }
27723
- gobbleToken() {
27724
- let ch, to_check, tc_len, node;
27725
- this.gobbleSpaces();
27726
- node = this.searchHook("gobble-token");
27727
- if (node) {
27728
- return this.runHook("after-token", node);
27729
- }
27730
- ch = this.code;
27731
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
27732
- return this.gobbleNumericLiteral();
27733
- }
27734
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
27735
- node = this.gobbleStringLiteral();
27736
- } else if (ch === Jsep.OBRACK_CODE) {
27737
- node = this.gobbleArray();
27738
- } else {
27739
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
27740
- tc_len = to_check.length;
27741
- while (tc_len > 0) {
27742
- 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)))) {
27743
- this.index += tc_len;
27744
- const argument = this.gobbleToken();
27745
- if (!argument) {
27746
- this.throwError("missing unaryOp argument");
27747
- }
27748
- return this.runHook("after-token", {
27749
- type: Jsep.UNARY_EXP,
27750
- operator: to_check,
27751
- argument,
27752
- prefix: true
27753
- });
27754
- }
27755
- to_check = to_check.substr(0, --tc_len);
27756
- }
27757
- if (Jsep.isIdentifierStart(ch)) {
27758
- node = this.gobbleIdentifier();
27759
- if (Jsep.literals.hasOwnProperty(node.name)) {
27760
- node = {
27761
- type: Jsep.LITERAL,
27762
- value: Jsep.literals[node.name],
27763
- raw: node.name
27764
- };
27765
- } else if (node.name === Jsep.this_str) {
27766
- node = {
27767
- type: Jsep.THIS_EXP
27768
- };
27769
- }
27770
- } else if (ch === Jsep.OPAREN_CODE) {
27771
- node = this.gobbleGroup();
27772
- }
27773
- }
27774
- if (!node) {
27775
- return this.runHook("after-token", false);
27776
- }
27777
- node = this.gobbleTokenProperty(node);
27778
- return this.runHook("after-token", node);
27779
- }
27780
- gobbleTokenProperty(node) {
27781
- this.gobbleSpaces();
27782
- let ch = this.code;
27783
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
27784
- let optional;
27785
- if (ch === Jsep.QUMARK_CODE) {
27786
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
27787
- break;
27788
- }
27789
- optional = true;
27790
- this.index += 2;
27791
- this.gobbleSpaces();
27792
- ch = this.code;
27793
- }
27794
- this.index++;
27795
- if (ch === Jsep.OBRACK_CODE) {
27796
- node = {
27797
- type: Jsep.MEMBER_EXP,
27798
- computed: true,
27799
- object: node,
27800
- property: this.gobbleExpression()
27801
- };
27802
- if (!node.property) {
27803
- this.throwError('Unexpected "' + this.char + '"');
27804
- }
27805
- this.gobbleSpaces();
27806
- ch = this.code;
27807
- if (ch !== Jsep.CBRACK_CODE) {
27808
- this.throwError("Unclosed [");
27809
- }
27810
- this.index++;
27811
- } else if (ch === Jsep.OPAREN_CODE) {
27812
- node = {
27813
- type: Jsep.CALL_EXP,
27814
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
27815
- callee: node
27816
- };
27817
- } else if (ch === Jsep.PERIOD_CODE || optional) {
27818
- if (optional) {
27819
- this.index--;
27820
- }
27821
- this.gobbleSpaces();
27822
- node = {
27823
- type: Jsep.MEMBER_EXP,
27824
- computed: false,
27825
- object: node,
27826
- property: this.gobbleIdentifier()
27827
- };
27828
- }
27829
- if (optional) {
27830
- node.optional = true;
27831
- }
27832
- this.gobbleSpaces();
27833
- ch = this.code;
27834
- }
27835
- return node;
27836
- }
27837
- gobbleNumericLiteral() {
27838
- let number = "", ch, chCode;
27839
- while (Jsep.isDecimalDigit(this.code)) {
27840
- number += this.expr.charAt(this.index++);
27841
- }
27842
- if (this.code === Jsep.PERIOD_CODE) {
27843
- number += this.expr.charAt(this.index++);
27844
- while (Jsep.isDecimalDigit(this.code)) {
27845
- number += this.expr.charAt(this.index++);
27846
- }
27847
- }
27848
- ch = this.char;
27849
- if (ch === "e" || ch === "E") {
27850
- number += this.expr.charAt(this.index++);
27851
- ch = this.char;
27852
- if (ch === "+" || ch === "-") {
27853
- number += this.expr.charAt(this.index++);
27854
- }
27855
- while (Jsep.isDecimalDigit(this.code)) {
27856
- number += this.expr.charAt(this.index++);
27857
- }
27858
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
27859
- this.throwError("Expected exponent (" + number + this.char + ")");
27860
- }
27861
- }
27862
- chCode = this.code;
27863
- if (Jsep.isIdentifierStart(chCode)) {
27864
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
27865
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
27866
- this.throwError("Unexpected period");
27867
- }
27868
- return {
27869
- type: Jsep.LITERAL,
27870
- value: parseFloat(number),
27871
- raw: number
27872
- };
27873
- }
27874
- gobbleStringLiteral() {
27875
- let str = "";
27876
- const startIndex = this.index;
27877
- const quote = this.expr.charAt(this.index++);
27878
- let closed = false;
27879
- while (this.index < this.expr.length) {
27880
- let ch = this.expr.charAt(this.index++);
27881
- if (ch === quote) {
27882
- closed = true;
27883
- break;
27884
- } else if (ch === "\\") {
27885
- ch = this.expr.charAt(this.index++);
27886
- switch (ch) {
27887
- case "n":
27888
- str += `
27889
- `;
27890
- break;
27891
- case "r":
27892
- str += "\r";
27893
- break;
27894
- case "t":
27895
- str += "\t";
27896
- break;
27897
- case "b":
27898
- str += "\b";
27899
- break;
27900
- case "f":
27901
- str += "\f";
27902
- break;
27903
- case "v":
27904
- str += "\v";
27905
- break;
27906
- default:
27907
- str += ch;
27908
- }
27909
- } else {
27910
- str += ch;
27911
- }
27912
- }
27913
- if (!closed) {
27914
- this.throwError('Unclosed quote after "' + str + '"');
27915
- }
27916
- return {
27917
- type: Jsep.LITERAL,
27918
- value: str,
27919
- raw: this.expr.substring(startIndex, this.index)
27920
- };
27921
- }
27922
- gobbleIdentifier() {
27923
- let ch = this.code, start = this.index;
27924
- if (Jsep.isIdentifierStart(ch)) {
27925
- this.index++;
27926
- } else {
27927
- this.throwError("Unexpected " + this.char);
27928
- }
27929
- while (this.index < this.expr.length) {
27930
- ch = this.code;
27931
- if (Jsep.isIdentifierPart(ch)) {
27932
- this.index++;
27933
- } else {
27934
- break;
27935
- }
27936
- }
27937
- return {
27938
- type: Jsep.IDENTIFIER,
27939
- name: this.expr.slice(start, this.index)
27940
- };
27941
- }
27942
- gobbleArguments(termination) {
27943
- const args = [];
27944
- let closed = false;
27945
- let separator_count = 0;
27946
- while (this.index < this.expr.length) {
27947
- this.gobbleSpaces();
27948
- let ch_i = this.code;
27949
- if (ch_i === termination) {
27950
- closed = true;
27951
- this.index++;
27952
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
27953
- this.throwError("Unexpected token " + String.fromCharCode(termination));
27954
- }
27955
- break;
27956
- } else if (ch_i === Jsep.COMMA_CODE) {
27957
- this.index++;
27958
- separator_count++;
27959
- if (separator_count !== args.length) {
27960
- if (termination === Jsep.CPAREN_CODE) {
27961
- this.throwError("Unexpected token ,");
27962
- } else if (termination === Jsep.CBRACK_CODE) {
27963
- for (let arg = args.length;arg < separator_count; arg++) {
27964
- args.push(null);
27965
- }
27966
- }
27967
- }
27968
- } else if (args.length !== separator_count && separator_count !== 0) {
27969
- this.throwError("Expected comma");
27970
- } else {
27971
- const node = this.gobbleExpression();
27972
- if (!node || node.type === Jsep.COMPOUND) {
27973
- this.throwError("Expected comma");
27974
- }
27975
- args.push(node);
27976
- }
27977
- }
27978
- if (!closed) {
27979
- this.throwError("Expected " + String.fromCharCode(termination));
27980
- }
27981
- return args;
27982
- }
27983
- gobbleGroup() {
27984
- this.index++;
27985
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
27986
- if (this.code === Jsep.CPAREN_CODE) {
27987
- this.index++;
27988
- if (nodes.length === 1) {
27989
- return nodes[0];
27990
- } else if (!nodes.length) {
27991
- return false;
27992
- } else {
27993
- return {
27994
- type: Jsep.SEQUENCE_EXP,
27995
- expressions: nodes
27996
- };
27997
- }
27998
- } else {
27999
- this.throwError("Unclosed (");
28000
- }
28001
- }
28002
- gobbleArray() {
28003
- this.index++;
28004
- return {
28005
- type: Jsep.ARRAY_EXP,
28006
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
28007
- };
28008
- }
28009
- }
28010
- var hooks = new Hooks;
28011
- Object.assign(Jsep, {
28012
- hooks,
28013
- plugins: new Plugins(Jsep),
28014
- COMPOUND: "Compound",
28015
- SEQUENCE_EXP: "SequenceExpression",
28016
- IDENTIFIER: "Identifier",
28017
- MEMBER_EXP: "MemberExpression",
28018
- LITERAL: "Literal",
28019
- THIS_EXP: "ThisExpression",
28020
- CALL_EXP: "CallExpression",
28021
- UNARY_EXP: "UnaryExpression",
28022
- BINARY_EXP: "BinaryExpression",
28023
- ARRAY_EXP: "ArrayExpression",
28024
- TAB_CODE: 9,
28025
- LF_CODE: 10,
28026
- CR_CODE: 13,
28027
- SPACE_CODE: 32,
28028
- PERIOD_CODE: 46,
28029
- COMMA_CODE: 44,
28030
- SQUOTE_CODE: 39,
28031
- DQUOTE_CODE: 34,
28032
- OPAREN_CODE: 40,
28033
- CPAREN_CODE: 41,
28034
- OBRACK_CODE: 91,
28035
- CBRACK_CODE: 93,
28036
- QUMARK_CODE: 63,
28037
- SEMCOL_CODE: 59,
28038
- COLON_CODE: 58,
28039
- unary_ops: {
28040
- "-": 1,
28041
- "!": 1,
28042
- "~": 1,
28043
- "+": 1
28044
- },
28045
- binary_ops: {
28046
- "||": 1,
28047
- "??": 1,
28048
- "&&": 2,
28049
- "|": 3,
28050
- "^": 4,
28051
- "&": 5,
28052
- "==": 6,
28053
- "!=": 6,
28054
- "===": 6,
28055
- "!==": 6,
28056
- "<": 7,
28057
- ">": 7,
28058
- "<=": 7,
28059
- ">=": 7,
28060
- "<<": 8,
28061
- ">>": 8,
28062
- ">>>": 8,
28063
- "+": 9,
28064
- "-": 9,
28065
- "*": 10,
28066
- "/": 10,
28067
- "%": 10,
28068
- "**": 11
28069
- },
28070
- right_associative: new Set(["**"]),
28071
- additional_identifier_chars: new Set(["$", "_"]),
28072
- literals: {
28073
- true: true,
28074
- false: false,
28075
- null: null
28076
- },
28077
- this_str: "this"
28078
- });
28079
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
28080
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
28081
- var jsep = (expr) => new Jsep(expr).parse();
28082
- var stdClassProps = Object.getOwnPropertyNames(class Test {
28083
- });
28084
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
28085
- jsep[m] = Jsep[m];
28086
- });
28087
- jsep.Jsep = Jsep;
28088
- var CONDITIONAL_EXP = "ConditionalExpression";
28089
- var ternary = {
28090
- name: "ternary",
28091
- init(jsep2) {
28092
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
28093
- if (env.node && this.code === jsep2.QUMARK_CODE) {
28094
- this.index++;
28095
- const test = env.node;
28096
- const consequent = this.gobbleExpression();
28097
- if (!consequent) {
28098
- this.throwError("Expected expression");
28099
- }
28100
- this.gobbleSpaces();
28101
- if (this.code === jsep2.COLON_CODE) {
28102
- this.index++;
28103
- const alternate = this.gobbleExpression();
28104
- if (!alternate) {
28105
- this.throwError("Expected expression");
28106
- }
28107
- env.node = {
28108
- type: CONDITIONAL_EXP,
28109
- test,
28110
- consequent,
28111
- alternate
28112
- };
28113
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
28114
- let newTest = test;
28115
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
28116
- newTest = newTest.right;
28117
- }
28118
- env.node.test = newTest.right;
28119
- newTest.right = env.node;
28120
- env.node = test;
28121
- }
28122
- } else {
28123
- this.throwError("Expected :");
28124
- }
28125
- }
28126
- });
28127
- }
28128
- };
28129
- jsep.plugins.register(ternary);
28130
- var FSLASH_CODE = 47;
28131
- var BSLASH_CODE = 92;
28132
- var index = {
28133
- name: "regex",
28134
- init(jsep2) {
28135
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
28136
- if (this.code === FSLASH_CODE) {
28137
- const patternIndex = ++this.index;
28138
- let inCharSet = false;
28139
- while (this.index < this.expr.length) {
28140
- if (this.code === FSLASH_CODE && !inCharSet) {
28141
- const pattern = this.expr.slice(patternIndex, this.index);
28142
- let flags = "";
28143
- while (++this.index < this.expr.length) {
28144
- const code = this.code;
28145
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
28146
- flags += this.char;
28147
- } else {
28148
- break;
28149
- }
28150
- }
28151
- let value;
28152
- try {
28153
- value = new RegExp(pattern, flags);
28154
- } catch (e) {
28155
- this.throwError(e.message);
28156
- }
28157
- env.node = {
28158
- type: jsep2.LITERAL,
28159
- value,
28160
- raw: this.expr.slice(patternIndex - 1, this.index)
28161
- };
28162
- env.node = this.gobbleTokenProperty(env.node);
28163
- return env.node;
28164
- }
28165
- if (this.code === jsep2.OBRACK_CODE) {
28166
- inCharSet = true;
28167
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
28168
- inCharSet = false;
28169
- }
28170
- this.index += this.code === BSLASH_CODE ? 2 : 1;
28171
- }
28172
- this.throwError("Unclosed Regex");
28173
- }
28174
- });
28175
- }
28176
- };
28177
- var PLUS_CODE = 43;
28178
- var MINUS_CODE = 45;
28179
- var plugin = {
28180
- name: "assignment",
28181
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
28182
- updateOperators: [PLUS_CODE, MINUS_CODE],
28183
- assignmentPrecedence: 0.9,
28184
- init(jsep2) {
28185
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
28186
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
28187
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
28188
- const code = this.code;
28189
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28190
- this.index += 2;
28191
- env.node = {
28192
- type: "UpdateExpression",
28193
- operator: code === PLUS_CODE ? "++" : "--",
28194
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
28195
- prefix: true
28196
- };
28197
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
28198
- this.throwError(`Unexpected ${env.node.operator}`);
28199
- }
28200
- }
28201
- });
28202
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
28203
- if (env.node) {
28204
- const code = this.code;
28205
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
28206
- if (!updateNodeTypes.includes(env.node.type)) {
28207
- this.throwError(`Unexpected ${env.node.operator}`);
28208
- }
28209
- this.index += 2;
28210
- env.node = {
28211
- type: "UpdateExpression",
28212
- operator: code === PLUS_CODE ? "++" : "--",
28213
- argument: env.node,
28214
- prefix: false
28215
- };
28216
- }
28217
- }
28218
- });
28219
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
28220
- if (env.node) {
28221
- updateBinariesToAssignments(env.node);
28222
- }
28223
- });
28224
- function updateBinariesToAssignments(node) {
28225
- if (plugin.assignmentOperators.has(node.operator)) {
28226
- node.type = "AssignmentExpression";
28227
- updateBinariesToAssignments(node.left);
28228
- updateBinariesToAssignments(node.right);
28229
- } else if (!node.operator) {
28230
- Object.values(node).forEach((val) => {
28231
- if (val && typeof val === "object") {
28232
- updateBinariesToAssignments(val);
28233
- }
28234
- });
28235
- }
28236
- }
28237
- }
28238
- };
28239
- jsep.plugins.register(index, plugin);
28240
- jsep.addUnaryOp("typeof");
28241
- jsep.addUnaryOp("void");
28242
- jsep.addLiteral("null", null);
28243
- jsep.addLiteral("undefined", undefined);
28244
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
28245
- var SafeEval = {
28246
- evalAst(ast, subs) {
28247
- switch (ast.type) {
28248
- case "BinaryExpression":
28249
- case "LogicalExpression":
28250
- return SafeEval.evalBinaryExpression(ast, subs);
28251
- case "Compound":
28252
- return SafeEval.evalCompound(ast, subs);
28253
- case "ConditionalExpression":
28254
- return SafeEval.evalConditionalExpression(ast, subs);
28255
- case "Identifier":
28256
- return SafeEval.evalIdentifier(ast, subs);
28257
- case "Literal":
28258
- return SafeEval.evalLiteral(ast, subs);
28259
- case "MemberExpression":
28260
- return SafeEval.evalMemberExpression(ast, subs);
28261
- case "UnaryExpression":
28262
- return SafeEval.evalUnaryExpression(ast, subs);
28263
- case "ArrayExpression":
28264
- return SafeEval.evalArrayExpression(ast, subs);
28265
- case "CallExpression":
28266
- return SafeEval.evalCallExpression(ast, subs);
28267
- case "AssignmentExpression":
28268
- return SafeEval.evalAssignmentExpression(ast, subs);
28269
- default:
28270
- throw SyntaxError("Unexpected expression", ast);
28271
- }
28272
- },
28273
- evalBinaryExpression(ast, subs) {
28274
- const result = {
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
- "==": (a, b) => a == b(),
28281
- "!=": (a, b) => a != b(),
28282
- "===": (a, b) => a === b(),
28283
- "!==": (a, b) => a !== b(),
28284
- "<": (a, b) => a < b(),
28285
- ">": (a, b) => a > b(),
28286
- "<=": (a, b) => a <= b(),
28287
- ">=": (a, b) => a >= b(),
28288
- "<<": (a, b) => a << b(),
28289
- ">>": (a, b) => a >> b(),
28290
- ">>>": (a, b) => a >>> b(),
28291
- "+": (a, b) => a + b(),
28292
- "-": (a, b) => a - b(),
28293
- "*": (a, b) => a * b(),
28294
- "/": (a, b) => a / b(),
28295
- "%": (a, b) => a % b()
28296
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
28297
- return result;
28298
- },
28299
- evalCompound(ast, subs) {
28300
- let last;
28301
- for (let i = 0;i < ast.body.length; i++) {
28302
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
28303
- i += 1;
28304
- }
28305
- const expr = ast.body[i];
28306
- last = SafeEval.evalAst(expr, subs);
28307
- }
28308
- return last;
28309
- },
28310
- evalConditionalExpression(ast, subs) {
28311
- if (SafeEval.evalAst(ast.test, subs)) {
28312
- return SafeEval.evalAst(ast.consequent, subs);
28313
- }
28314
- return SafeEval.evalAst(ast.alternate, subs);
28315
- },
28316
- evalIdentifier(ast, subs) {
28317
- if (Object.hasOwn(subs, ast.name)) {
28318
- return subs[ast.name];
28319
- }
28320
- throw ReferenceError(`${ast.name} is not defined`);
28321
- },
28322
- evalLiteral(ast) {
28323
- return ast.value;
28324
- },
28325
- evalMemberExpression(ast, subs) {
28326
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
28327
- const obj = SafeEval.evalAst(ast.object, subs);
28328
- if (obj === undefined || obj === null) {
28329
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28330
- }
28331
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
28332
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
28333
- }
28334
- const result = obj[prop];
28335
- if (typeof result === "function") {
28336
- return result.bind(obj);
28337
- }
28338
- return result;
28339
- },
28340
- evalUnaryExpression(ast, subs) {
28341
- const result = {
28342
- "-": (a) => -SafeEval.evalAst(a, subs),
28343
- "!": (a) => !SafeEval.evalAst(a, subs),
28344
- "~": (a) => ~SafeEval.evalAst(a, subs),
28345
- "+": (a) => +SafeEval.evalAst(a, subs),
28346
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
28347
- void: (a) => void SafeEval.evalAst(a, subs)
28348
- }[ast.operator](ast.argument);
28349
- return result;
28350
- },
28351
- evalArrayExpression(ast, subs) {
28352
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
28353
- },
28354
- evalCallExpression(ast, subs) {
28355
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
28356
- const func = SafeEval.evalAst(ast.callee, subs);
28357
- if (func === Function) {
28358
- throw new Error("Function constructor is disabled");
28359
- }
28360
- return func(...args);
28361
- },
28362
- evalAssignmentExpression(ast, subs) {
28363
- if (ast.left.type !== "Identifier") {
28364
- throw SyntaxError("Invalid left-hand side in assignment");
28365
- }
28366
- const id = ast.left.name;
28367
- const value = SafeEval.evalAst(ast.right, subs);
28368
- subs[id] = value;
28369
- return subs[id];
28370
- }
28371
- };
28372
-
28373
- class SafeScript {
28374
- constructor(expr) {
28375
- this.code = expr;
28376
- this.ast = jsep(this.code);
28377
- }
28378
- runInNewContext(context) {
28379
- const keyMap = Object.assign(Object.create(null), context);
28380
- return SafeEval.evalAst(this.ast, keyMap);
28381
- }
28382
- }
28383
- function push(arr, item) {
28384
- arr = arr.slice();
28385
- arr.push(item);
28386
- return arr;
28387
- }
28388
- function unshift(item, arr) {
28389
- arr = arr.slice();
28390
- arr.unshift(item);
28391
- return arr;
28392
- }
28393
-
28394
- class NewError extends Error {
28395
- constructor(value) {
28396
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
28397
- this.avoidNew = true;
28398
- this.value = value;
28399
- this.name = "NewError";
28400
- }
28401
- }
28402
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
28403
- if (!(this instanceof JSONPath)) {
28404
- try {
28405
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
28406
- } catch (e) {
28407
- if (!e.avoidNew) {
28408
- throw e;
28409
- }
28410
- return e.value;
28411
- }
28412
- }
28413
- if (typeof opts === "string") {
28414
- otherTypeCallback = callback;
28415
- callback = obj;
28416
- obj = expr;
28417
- expr = opts;
28418
- opts = null;
28419
- }
28420
- const optObj = opts && typeof opts === "object";
28421
- opts = opts || {};
28422
- this.json = opts.json || obj;
28423
- this.path = opts.path || expr;
28424
- this.resultType = opts.resultType || "value";
28425
- this.flatten = opts.flatten || false;
28426
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
28427
- this.sandbox = opts.sandbox || {};
28428
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
28429
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
28430
- this.parent = opts.parent || null;
28431
- this.parentProperty = opts.parentProperty || null;
28432
- this.callback = opts.callback || callback || null;
28433
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
28434
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
28435
- };
28436
- if (opts.autostart !== false) {
28437
- const args = {
28438
- path: optObj ? opts.path : expr
28439
- };
28440
- if (!optObj) {
28441
- args.json = obj;
28442
- } else if ("json" in opts) {
28443
- args.json = opts.json;
28444
- }
28445
- const ret = this.evaluate(args);
28446
- if (!ret || typeof ret !== "object") {
28447
- throw new NewError(ret);
28448
- }
28449
- return ret;
28450
- }
28451
- }
28452
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
28453
- let currParent = this.parent, currParentProperty = this.parentProperty;
28454
- let {
28455
- flatten,
28456
- wrap
28457
- } = this;
28458
- this.currResultType = this.resultType;
28459
- this.currEval = this.eval;
28460
- this.currSandbox = this.sandbox;
28461
- callback = callback || this.callback;
28462
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
28463
- json = json || this.json;
28464
- expr = expr || this.path;
28465
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
28466
- if (!expr.path && expr.path !== "") {
28467
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
28468
- }
28469
- if (!Object.hasOwn(expr, "json")) {
28470
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
28471
- }
28472
- ({
28473
- json
28474
- } = expr);
28475
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
28476
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
28477
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
28478
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
28479
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
28480
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
28481
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
28482
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
28483
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
28484
- expr = expr.path;
28485
- }
28486
- currParent = currParent || null;
28487
- currParentProperty = currParentProperty || null;
28488
- if (Array.isArray(expr)) {
28489
- expr = JSONPath.toPathString(expr);
28490
- }
28491
- if (!expr && expr !== "" || !json) {
28492
- return;
28493
- }
28494
- const exprList = JSONPath.toPathArray(expr);
28495
- if (exprList[0] === "$" && exprList.length > 1) {
28496
- exprList.shift();
28497
- }
28498
- this._hasParentSelector = null;
28499
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
28500
- return ea && !ea.isParentSelector;
28501
- });
28502
- if (!result.length) {
28503
- return wrap ? [] : undefined;
28504
- }
28505
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
28506
- return this._getPreferredOutput(result[0]);
28507
- }
28508
- return result.reduce((rslt, ea) => {
28509
- const valOrPath = this._getPreferredOutput(ea);
28510
- if (flatten && Array.isArray(valOrPath)) {
28511
- rslt = rslt.concat(valOrPath);
28512
- } else {
28513
- rslt.push(valOrPath);
28514
- }
28515
- return rslt;
28516
- }, []);
28517
- };
28518
- JSONPath.prototype._getPreferredOutput = function(ea) {
28519
- const resultType = this.currResultType;
28520
- switch (resultType) {
28521
- case "all": {
28522
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
28523
- ea.pointer = JSONPath.toPointer(path3);
28524
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
28525
- return ea;
28526
- }
28527
- case "value":
28528
- case "parent":
28529
- case "parentProperty":
28530
- return ea[resultType];
28531
- case "path":
28532
- return JSONPath.toPathString(ea[resultType]);
28533
- case "pointer":
28534
- return JSONPath.toPointer(ea.path);
28535
- default:
28536
- throw new TypeError("Unknown result type");
28537
- }
28538
- };
28539
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
28540
- if (callback) {
28541
- const preferredOutput = this._getPreferredOutput(fullRetObj);
28542
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
28543
- callback(preferredOutput, type, fullRetObj);
28544
- }
28545
- };
28546
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
28547
- let retObj;
28548
- if (!expr.length) {
28549
- retObj = {
28550
- path: path3,
28551
- value: val,
28552
- parent,
28553
- parentProperty: parentPropName,
28554
- hasArrExpr
28555
- };
28556
- this._handleCallback(retObj, callback, "value");
28557
- return retObj;
28558
- }
28559
- const loc = expr[0], x = expr.slice(1);
28560
- const ret = [];
28561
- function addRet(elems) {
28562
- if (Array.isArray(elems)) {
28563
- elems.forEach((t) => {
28564
- ret.push(t);
28565
- });
28566
- } else {
28567
- ret.push(elems);
28568
- }
28569
- }
28570
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
28571
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
28572
- } else if (loc === "*") {
28573
- this._walk(val, (m) => {
28574
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
28575
- });
28576
- } else if (loc === "..") {
28577
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
28578
- this._walk(val, (m) => {
28579
- if (typeof val[m] === "object") {
28580
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
28581
- }
28582
- });
28583
- } else if (loc === "^") {
28584
- this._hasParentSelector = true;
28585
- return {
28586
- path: path3.slice(0, -1),
28587
- expr: x,
28588
- isParentSelector: true
28589
- };
28590
- } else if (loc === "~") {
28591
- retObj = {
28592
- path: push(path3, loc),
28593
- value: parentPropName,
28594
- parent,
28595
- parentProperty: null
28596
- };
28597
- this._handleCallback(retObj, callback, "property");
28598
- return retObj;
28599
- } else if (loc === "$") {
28600
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
28601
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
28602
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
28603
- } else if (loc.indexOf("?(") === 0) {
28604
- if (this.currEval === false) {
28605
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
28606
- }
28607
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
28608
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
28609
- if (nested) {
28610
- this._walk(val, (m) => {
28611
- const npath = [nested[2]];
28612
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
28613
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
28614
- if (filterResults.length > 0) {
28615
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28616
- }
28617
- });
28618
- } else {
28619
- this._walk(val, (m) => {
28620
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
28621
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
28622
- }
28623
- });
28624
- }
28625
- } else if (loc[0] === "(") {
28626
- if (this.currEval === false) {
28627
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
28628
- }
28629
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
28630
- } else if (loc[0] === "@") {
28631
- let addType = false;
28632
- const valueType = loc.slice(1, -2);
28633
- switch (valueType) {
28634
- case "scalar":
28635
- if (!val || !["object", "function"].includes(typeof val)) {
28636
- addType = true;
28637
- }
28638
- break;
28639
- case "boolean":
28640
- case "string":
28641
- case "undefined":
28642
- case "function":
28643
- if (typeof val === valueType) {
28644
- addType = true;
28645
- }
28646
- break;
28647
- case "integer":
28648
- if (Number.isFinite(val) && !(val % 1)) {
28649
- addType = true;
28650
- }
28651
- break;
28652
- case "number":
28653
- if (Number.isFinite(val)) {
28654
- addType = true;
28655
- }
28656
- break;
28657
- case "nonFinite":
28658
- if (typeof val === "number" && !Number.isFinite(val)) {
28659
- addType = true;
28660
- }
28661
- break;
28662
- case "object":
28663
- if (val && typeof val === valueType) {
28664
- addType = true;
28665
- }
28666
- break;
28667
- case "array":
28668
- if (Array.isArray(val)) {
28669
- addType = true;
28670
- }
28671
- break;
28672
- case "other":
28673
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
28674
- break;
28675
- case "null":
28676
- if (val === null) {
28677
- addType = true;
28678
- }
28679
- break;
28680
- default:
28681
- throw new TypeError("Unknown value type " + valueType);
28682
- }
28683
- if (addType) {
28684
- retObj = {
28685
- path: path3,
28686
- value: val,
28687
- parent,
28688
- parentProperty: parentPropName
28689
- };
28690
- this._handleCallback(retObj, callback, "value");
28691
- return retObj;
28692
- }
28693
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
28694
- const locProp = loc.slice(1);
28695
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
28696
- } else if (loc.includes(",")) {
28697
- const parts = loc.split(",");
28698
- for (const part of parts) {
28699
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
28700
- }
28701
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
28702
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
28703
- }
28704
- if (this._hasParentSelector) {
28705
- for (let t = 0;t < ret.length; t++) {
28706
- const rett = ret[t];
28707
- if (rett && rett.isParentSelector) {
28708
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
28709
- if (Array.isArray(tmp)) {
28710
- ret[t] = tmp[0];
28711
- const tl = tmp.length;
28712
- for (let tt = 1;tt < tl; tt++) {
28713
- t++;
28714
- ret.splice(t, 0, tmp[tt]);
28715
- }
28716
- } else {
28717
- ret[t] = tmp;
28718
- }
28719
- }
28720
- }
28721
- }
28722
- return ret;
28723
- };
28724
- JSONPath.prototype._walk = function(val, f) {
28725
- if (Array.isArray(val)) {
28726
- const n = val.length;
28727
- for (let i = 0;i < n; i++) {
28728
- f(i);
28729
- }
28730
- } else if (val && typeof val === "object") {
28731
- Object.keys(val).forEach((m) => {
28732
- f(m);
28733
- });
28734
- }
28735
- };
28736
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
28737
- if (!Array.isArray(val)) {
28738
- return;
28739
- }
28740
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
28741
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
28742
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
28743
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
28744
- const ret = [];
28745
- for (let i = start;i < end; i += step) {
28746
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
28747
- tmp.forEach((t) => {
28748
- ret.push(t);
28749
- });
28750
- }
28751
- return ret;
28752
- };
28753
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
28754
- this.currSandbox._$_parentProperty = parentPropName;
28755
- this.currSandbox._$_parent = parent;
28756
- this.currSandbox._$_property = _vname;
28757
- this.currSandbox._$_root = this.json;
28758
- this.currSandbox._$_v = _v;
28759
- const containsPath = code.includes("@path");
28760
- if (containsPath) {
28761
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
28762
- }
28763
- const scriptCacheKey = this.currEval + "Script:" + code;
28764
- if (!JSONPath.cache[scriptCacheKey]) {
28765
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
28766
- if (containsPath) {
28767
- script = script.replaceAll("@path", "_$_path");
28768
- }
28769
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
28770
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
28771
- } else if (this.currEval === "native") {
28772
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
28773
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
28774
- const CurrEval = this.currEval;
28775
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
28776
- } else if (typeof this.currEval === "function") {
28777
- JSONPath.cache[scriptCacheKey] = {
28778
- runInNewContext: (context) => this.currEval(script, context)
28779
- };
28780
- } else {
28781
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
28782
- }
28783
- }
28784
- try {
28785
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
28786
- } catch (e) {
28787
- if (this.ignoreEvalErrors) {
28788
- return false;
28789
- }
28790
- throw new Error("jsonPath: " + e.message + ": " + code);
28791
- }
28792
- };
28793
- JSONPath.cache = {};
28794
- JSONPath.toPathString = function(pathArr) {
28795
- const x = pathArr, n = x.length;
28796
- let p = "$";
28797
- for (let i = 1;i < n; i++) {
28798
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28799
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
28800
- }
28801
- }
28802
- return p;
28803
- };
28804
- JSONPath.toPointer = function(pointer) {
28805
- const x = pointer, n = x.length;
28806
- let p = "";
28807
- for (let i = 1;i < n; i++) {
28808
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
28809
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
28810
- }
28811
- }
28812
- return p;
28813
- };
28814
- JSONPath.toPathArray = function(expr) {
28815
- const {
28816
- cache
28817
- } = JSONPath;
28818
- if (cache[expr]) {
28819
- return cache[expr].concat();
28820
- }
28821
- const subx = [];
28822
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
28823
- return "[#" + (subx.push($1) - 1) + "]";
28824
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
28825
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
28826
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
28827
- return ";" + ups.split("").join(";") + ";";
28828
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
28829
- const exprList = normalized.split(";").map(function(exp) {
28830
- const match = exp.match(/#(\d+)/u);
28831
- return !match || !match[1] ? exp : subx[match[1]];
28832
- });
28833
- cache[expr] = exprList;
28834
- return cache[expr].concat();
28835
- };
28836
- JSONPath.prototype.safeVm = {
28837
- Script: SafeScript
28838
- };
28839
- JSONPath.prototype.vm = vm;
28840
- // ../../common/src/polling/types.ts
28841
- var PollOutcome = {
28842
- Completed: "completed",
28843
- Timeout: "timeout",
28844
- Interrupted: "interrupted",
28845
- Aborted: "aborted",
28846
- Failed: "failed"
28847
- };
28848
-
28849
- // ../../common/src/polling/poll-failure-mapping.ts
28850
- var REASON_BY_OUTCOME = {
28851
- [PollOutcome.Timeout]: "poll_timeout",
28852
- [PollOutcome.Failed]: "poll_failed",
28853
- [PollOutcome.Interrupted]: "poll_failed",
28854
- [PollOutcome.Aborted]: "poll_aborted"
28855
- };
28856
- // ../../common/src/polling/terminal-statuses.ts
28857
- var TERMINAL_STATUSES = new Set([
28858
- "completed",
28859
- "successful",
28860
- "faulted",
28861
- "failed",
28862
- "cancelled",
28863
- "canceled",
28864
- "stopped",
28865
- "finished"
28866
- ]);
28867
- var FAILURE_STATUSES = new Set([
28868
- "faulted",
28869
- "failed",
28870
- "cancelled",
28871
- "canceled",
28872
- "stopped"
28873
- ]);
28874
- // ../../common/src/screen-logger.ts
28875
- var ScreenLogger;
28876
- ((ScreenLogger) => {
28877
- function progress(message) {
28878
- getOutputSink().writeErr(`${message}
28879
- `);
28880
- }
28881
- ScreenLogger.progress = progress;
28882
- })(ScreenLogger ||= {});
28883
- // ../../common/src/sdk-user-agent.ts
28884
- var USER_AGENT_HEADER = "User-Agent";
28885
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
28886
- function userAgentPatchKey(userAgent) {
28887
- return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
28888
- }
28889
- function splitUserAgentTokens(value) {
28890
- return value?.trim().split(/\s+/).filter(Boolean) ?? [];
28891
- }
28892
- function appendUserAgentToken(value, userAgent) {
28893
- const tokens = splitUserAgentTokens(value);
28894
- const seen = new Set(tokens);
28895
- for (const token of splitUserAgentTokens(userAgent)) {
28896
- if (!seen.has(token)) {
28897
- tokens.push(token);
28898
- seen.add(token);
28899
- }
28900
- }
28901
- return tokens.join(" ");
28902
- }
28903
- function getEffectiveUserAgent(userAgent) {
28904
- return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
28905
- }
28906
- function isHeadersLike(headers) {
28907
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
28908
- }
28909
- function getSdkUserAgentToken(pkg) {
28910
- const packageName = pkg.name.replace(/^@uipath\//, "");
28911
- return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
28912
- }
28913
- function addSdkUserAgentHeader(headers, userAgent) {
28914
- const result = { ...headers ?? {} };
28915
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
28916
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
28917
- if (headerName) {
28918
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
28919
- } else {
28920
- result[USER_AGENT_HEADER] = effectiveUserAgent;
28921
- }
28922
- return result;
28923
- }
28924
- function withSdkUserAgentHeader(headers, userAgent) {
28925
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
28926
- if (isHeadersLike(headers)) {
28927
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
28928
- return headers;
28929
- }
28930
- if (Array.isArray(headers)) {
28931
- const result = headers.map((entry) => {
28932
- const [key, value] = entry;
28933
- return [key, value];
28934
- });
28935
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
28936
- if (headerIndex >= 0) {
28937
- const [key, value] = result[headerIndex];
28938
- result[headerIndex] = [
28939
- key,
28940
- appendUserAgentToken(value, effectiveUserAgent)
28941
- ];
28942
- } else {
28943
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
28944
- }
28945
- return result;
28946
- }
28947
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
28948
- }
28949
- function withUserAgentInitOverride(initOverrides, userAgent) {
28950
- return async (requestContext) => {
28951
- const initWithUserAgent = {
28952
- ...requestContext.init,
28953
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
28954
- };
28955
- const override = typeof initOverrides === "function" ? await initOverrides({
28956
- ...requestContext,
28957
- init: initWithUserAgent
28958
- }) : initOverrides;
28959
- return {
28960
- ...override ?? {},
28961
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
28962
- };
28963
- };
28964
- }
28965
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
28966
- const prototype = BaseApiClass.prototype;
28967
- const patchKey = userAgentPatchKey(userAgent);
28968
- if (prototype[patchKey]) {
28969
- return;
28970
- }
28971
- if (typeof prototype.request !== "function") {
28972
- throw new Error("Generated BaseAPI request function not found.");
28973
- }
28974
- const originalRequest = prototype.request;
28975
- prototype.request = function requestWithUserAgent(context, initOverrides) {
28976
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
28977
- };
28978
- Object.defineProperty(prototype, patchKey, {
28979
- value: true
28980
- });
28981
- }
28982
- // ../../common/src/tool-provider.ts
28983
- var factorySlot = singleton("PackagerFactoryProvider");
28984
- // ../oms-sdk/generated/v1/src/runtime.ts
28985
- var BASE_PATH = "http://localhost".replace(/\/+$/, "");
28986
-
28987
- class Configuration {
28988
- configuration;
28989
- constructor(configuration = {}) {
28990
- this.configuration = configuration;
28991
- }
28992
- set config(configuration) {
28993
- this.configuration = configuration;
28994
- }
28995
- get basePath() {
28996
- return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
28997
- }
28998
- get fetchApi() {
28999
- return this.configuration.fetchApi;
29000
- }
29001
- get middleware() {
29002
- return this.configuration.middleware || [];
29003
- }
29004
- get queryParamsStringify() {
29005
- return this.configuration.queryParamsStringify || querystring;
29006
- }
29007
- get username() {
29008
- return this.configuration.username;
29009
- }
29010
- get password() {
29011
- return this.configuration.password;
29012
- }
29013
- get apiKey() {
29014
- const apiKey = this.configuration.apiKey;
29015
- if (apiKey) {
29016
- return typeof apiKey === "function" ? apiKey : () => apiKey;
29017
- }
29018
- return;
29019
- }
29020
- get accessToken() {
29021
- const accessToken = this.configuration.accessToken;
29022
- if (accessToken) {
29023
- return typeof accessToken === "function" ? accessToken : async () => accessToken;
29024
- }
29025
- return;
29026
- }
29027
- get headers() {
29028
- return this.configuration.headers;
29029
- }
29030
- get credentials() {
29031
- return this.configuration.credentials;
29032
- }
29033
- }
29034
- var DefaultConfig = new Configuration;
29035
-
29036
- class BaseAPI {
29037
- configuration;
29038
- static jsonRegex = new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", "i");
29039
- middleware;
29040
- constructor(configuration = DefaultConfig) {
29041
- this.configuration = configuration;
29042
- this.middleware = configuration.middleware;
29043
- }
29044
- withMiddleware(...middlewares) {
29045
- const next = this.clone();
29046
- next.middleware = next.middleware.concat(...middlewares);
29047
- return next;
29048
- }
29049
- withPreMiddleware(...preMiddlewares) {
29050
- const middlewares = preMiddlewares.map((pre) => ({ pre }));
29051
- return this.withMiddleware(...middlewares);
29052
- }
29053
- withPostMiddleware(...postMiddlewares) {
29054
- const middlewares = postMiddlewares.map((post) => ({ post }));
29055
- return this.withMiddleware(...middlewares);
29056
- }
29057
- isJsonMime(mime) {
29058
- if (!mime) {
29059
- return false;
29060
- }
29061
- return BaseAPI.jsonRegex.test(mime);
29062
- }
29063
- async request(context, initOverrides) {
29064
- const { url, init } = await this.createFetchParams(context, initOverrides);
29065
- const response = await this.fetchApi(url, init);
29066
- if (response && (response.status >= 200 && response.status < 300)) {
29067
- return response;
29068
- }
29069
- throw new ResponseError(response, "Response returned an error code");
29070
- }
29071
- async createFetchParams(context, initOverrides) {
29072
- let url = this.configuration.basePath + context.path;
29073
- if (context.query !== undefined && Object.keys(context.query).length !== 0) {
29074
- url += "?" + this.configuration.queryParamsStringify(context.query);
29075
- }
29076
- const headers = Object.assign({}, this.configuration.headers, context.headers);
29077
- Object.keys(headers).forEach((key) => headers[key] === undefined ? delete headers[key] : {});
29078
- const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
29079
- const initParams = {
29080
- method: context.method,
29081
- headers,
29082
- body: context.body,
29083
- credentials: this.configuration.credentials
27775
+ const headers = Object.assign({}, this.configuration.headers, context.headers);
27776
+ Object.keys(headers).forEach((key) => headers[key] === undefined ? delete headers[key] : {});
27777
+ const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
27778
+ const initParams = {
27779
+ method: context.method,
27780
+ headers,
27781
+ body: context.body,
27782
+ credentials: this.configuration.credentials
29084
27783
  };
29085
27784
  const overriddenInit = {
29086
27785
  ...initParams,
@@ -29796,7 +28495,7 @@ function querystringSingleKey3(key, value, keyPrefix = "") {
29796
28495
  var package_default2 = {
29797
28496
  name: "@uipath/oms-sdk",
29798
28497
  license: "MIT",
29799
- version: "1.196.0",
28498
+ version: "1.197.0",
29800
28499
  description: "SDK for the UiPath Organization Management Service API.",
29801
28500
  repository: {
29802
28501
  type: "git",
@@ -29826,7 +28525,7 @@ var package_default2 = {
29826
28525
  ],
29827
28526
  private: true,
29828
28527
  scripts: {
29829
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
28528
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
29830
28529
  generate: "bun run src/scripts/generate-sdk.ts",
29831
28530
  lint: "biome check ."
29832
28531
  },
@@ -34273,6 +32972,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
34273
32972
  }
34274
32973
  return url.pathname.length > 1 ? url.origin : baseUrl;
34275
32974
  };
32975
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
32976
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
32977
+ if (isExternalAppAuth)
32978
+ return requestedScopes;
32979
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
32980
+ };
34276
32981
  var resolveConfigAsync = async ({
34277
32982
  customAuthority,
34278
32983
  customClientId,
@@ -34303,7 +33008,7 @@ var resolveConfigAsync = async ({
34303
33008
  clientSecret = fileAuth.clientSecret;
34304
33009
  }
34305
33010
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
34306
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
33011
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
34307
33012
  return {
34308
33013
  clientId,
34309
33014
  clientSecret,
@@ -34318,6 +33023,76 @@ var resolveConfigAsync = async ({
34318
33023
  init_constants();
34319
33024
  // ../../auth/src/loginStatus.ts
34320
33025
  init_src();
33026
+
33027
+ // ../../auth/src/authProfile.ts
33028
+ init_src();
33029
+ init_constants();
33030
+ var DEFAULT_AUTH_PROFILE = "default";
33031
+ var PROFILE_DIR = "profiles";
33032
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
33033
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
33034
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
33035
+ var globalSlot2 = globalThis;
33036
+ function isAuthProfileStorage(value) {
33037
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
33038
+ }
33039
+ function createProfileStorage() {
33040
+ const [error, mod2] = catchError2(() => __require("node:async_hooks"));
33041
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
33042
+ return {
33043
+ getStore: () => {
33044
+ return;
33045
+ },
33046
+ run: (_store, fn) => fn()
33047
+ };
33048
+ }
33049
+ return new mod2.AsyncLocalStorage;
33050
+ }
33051
+ function getProfileStorage() {
33052
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
33053
+ if (isAuthProfileStorage(existing)) {
33054
+ return existing;
33055
+ }
33056
+ const storage = createProfileStorage();
33057
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
33058
+ return storage;
33059
+ }
33060
+ var profileStorage = getProfileStorage();
33061
+
33062
+ class AuthProfileValidationError extends Error {
33063
+ constructor(message) {
33064
+ super(message);
33065
+ this.name = "AuthProfileValidationError";
33066
+ }
33067
+ }
33068
+ function normalizeAuthProfileName(profile) {
33069
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
33070
+ return;
33071
+ }
33072
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
33073
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
33074
+ }
33075
+ return profile;
33076
+ }
33077
+ function getActiveAuthProfile() {
33078
+ const scopedState = profileStorage.getStore();
33079
+ if (scopedState !== undefined) {
33080
+ return scopedState.profile;
33081
+ }
33082
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
33083
+ }
33084
+ function resolveAuthProfileFilePath(profile) {
33085
+ const normalized = normalizeAuthProfileName(profile);
33086
+ if (normalized === undefined) {
33087
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
33088
+ }
33089
+ const fs7 = getFileSystem();
33090
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
33091
+ }
33092
+ function getActiveAuthProfileFilePath() {
33093
+ const profile = getActiveAuthProfile();
33094
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
33095
+ }
34321
33096
  // ../../auth/src/utils/jwt.ts
34322
33097
  class InvalidIssuerError extends Error {
34323
33098
  expected;
@@ -34446,23 +33221,74 @@ var readAuthFromEnv = () => {
34446
33221
  organizationId,
34447
33222
  tenantName,
34448
33223
  tenantId,
34449
- expiration
33224
+ expiration,
33225
+ source: "env" /* Env */
34450
33226
  };
34451
33227
  };
34452
33228
 
33229
+ // ../../auth/src/refreshCircuitBreaker.ts
33230
+ init_src();
33231
+ var BREAKER_SUFFIX = ".refresh-state";
33232
+ var BACKOFF_BASE_MS = 60000;
33233
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
33234
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
33235
+ async function refreshTokenFingerprint(refreshToken) {
33236
+ const bytes = new TextEncoder().encode(refreshToken);
33237
+ if (globalThis.crypto?.subtle) {
33238
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
33239
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
33240
+ }
33241
+ const { createHash } = await import("node:crypto");
33242
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
33243
+ }
33244
+ function breakerPathFor(authPath) {
33245
+ return `${authPath}${BREAKER_SUFFIX}`;
33246
+ }
33247
+ async function loadRefreshBreaker(authPath) {
33248
+ const fs7 = getFileSystem();
33249
+ try {
33250
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
33251
+ if (!content)
33252
+ return {};
33253
+ const parsed = JSON.parse(content);
33254
+ return parsed && typeof parsed === "object" ? parsed : {};
33255
+ } catch {
33256
+ return {};
33257
+ }
33258
+ }
33259
+ async function saveRefreshBreaker(authPath, state) {
33260
+ try {
33261
+ const fs7 = getFileSystem();
33262
+ const path3 = breakerPathFor(authPath);
33263
+ await fs7.mkdir(fs7.path.dirname(path3));
33264
+ const tempPath = `${path3}.tmp`;
33265
+ await fs7.writeFile(tempPath, JSON.stringify(state));
33266
+ await fs7.rename(tempPath, path3);
33267
+ } catch {}
33268
+ }
33269
+ async function clearRefreshBreaker(authPath) {
33270
+ const fs7 = getFileSystem();
33271
+ const path3 = breakerPathFor(authPath);
33272
+ try {
33273
+ if (await fs7.exists(path3)) {
33274
+ await fs7.rm(path3);
33275
+ }
33276
+ } catch {}
33277
+ }
33278
+ function nextBackoffMs(attempts) {
33279
+ const shift = Math.max(0, attempts - 1);
33280
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
33281
+ }
33282
+ function shouldSurface(state, nowMs) {
33283
+ if (state.lastSurfacedAtMs === undefined)
33284
+ return true;
33285
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
33286
+ }
33287
+
34453
33288
  // ../../auth/src/robotClientFallback.ts
34454
33289
  init_src();
34455
33290
  var DEFAULT_TIMEOUT_MS = 1000;
34456
33291
  var CLOSE_TIMEOUT_MS = 500;
34457
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
34458
- var printNoticeOnce = () => {
34459
- const slot = globalThis;
34460
- if (slot[NOTICE_SENTINEL])
34461
- return;
34462
- slot[NOTICE_SENTINEL] = true;
34463
- catchError2(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
34464
- `));
34465
- };
34466
33292
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
34467
33293
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
34468
33294
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -34578,7 +33404,6 @@ var tryRobotClientFallback = async (options = {}) => {
34578
33404
  issuerFromToken = issClaim;
34579
33405
  }
34580
33406
  }
34581
- printNoticeOnce();
34582
33407
  return {
34583
33408
  accessToken,
34584
33409
  baseUrl: parsedUrl.baseUrl,
@@ -34803,18 +33628,327 @@ var saveEnvFileAsync = async ({
34803
33628
  };
34804
33629
 
34805
33630
  // ../../auth/src/loginStatus.ts
34806
- function normalizeTokenRefreshFailure() {
34807
- return "stored refresh token is invalid or expired";
33631
+ var getLoginStatusAsync = async (options = {}) => {
33632
+ return getLoginStatusWithDeps(options);
33633
+ };
33634
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
33635
+ const {
33636
+ resolveEnvFilePath = resolveEnvFilePathAsync,
33637
+ loadEnvFile = loadEnvFileAsync,
33638
+ saveEnvFile = saveEnvFileAsync,
33639
+ getFs = getFileSystem,
33640
+ refreshToken: refreshTokenFn = refreshAccessToken,
33641
+ resolveConfig = resolveConfigAsync,
33642
+ robotFallback = tryRobotClientFallback,
33643
+ loadBreaker = loadRefreshBreaker,
33644
+ saveBreaker = saveRefreshBreaker,
33645
+ clearBreaker = clearRefreshBreaker
33646
+ } = deps;
33647
+ if (isRobotAuthEnforced()) {
33648
+ return resolveRobotEnforcedStatus(robotFallback);
33649
+ }
33650
+ if (isEnvAuthEnabled()) {
33651
+ return readAuthFromEnv();
33652
+ }
33653
+ const activeProfile = getActiveAuthProfile();
33654
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
33655
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
33656
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
33657
+ const { ensureTokenValidityMinutes } = options;
33658
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
33659
+ if (absolutePath === undefined) {
33660
+ if (usingActiveProfile) {
33661
+ return {
33662
+ loginStatus: "Not logged in",
33663
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
33664
+ };
33665
+ }
33666
+ return resolveBorrowedRobotStatus(robotFallback);
33667
+ }
33668
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
33669
+ if ("status" in loaded) {
33670
+ return loaded.status;
33671
+ }
33672
+ const { credentials } = loaded;
33673
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
33674
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
33675
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
33676
+ let tokens = {
33677
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
33678
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
33679
+ expiration,
33680
+ lockReleaseFailed: false
33681
+ };
33682
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
33683
+ if (expiration && expiration <= outerThreshold && refreshToken) {
33684
+ const refreshed = await attemptRefresh({
33685
+ absolutePath,
33686
+ credentials,
33687
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
33688
+ refreshToken,
33689
+ expiration,
33690
+ ensureTokenValidityMinutes,
33691
+ getFs,
33692
+ loadEnvFile,
33693
+ saveEnvFile,
33694
+ refreshFn: refreshTokenFn,
33695
+ resolveConfig,
33696
+ loadBreaker,
33697
+ saveBreaker,
33698
+ clearBreaker,
33699
+ globalHint
33700
+ });
33701
+ if (refreshed.kind === "terminal") {
33702
+ return refreshed.status;
33703
+ }
33704
+ tokens = refreshed.tokens;
33705
+ }
33706
+ return buildFileStatus(tokens, credentials, globalHint);
33707
+ };
33708
+ async function resolveRobotEnforcedStatus(robotFallback) {
33709
+ if (isEnvAuthEnabled()) {
33710
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
33711
+ }
33712
+ const robotCreds = await robotFallback({ force: true });
33713
+ if (!robotCreds) {
33714
+ return {
33715
+ loginStatus: "Not logged in",
33716
+ 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.`
33717
+ };
33718
+ }
33719
+ return buildRobotStatus(robotCreds);
34808
33720
  }
34809
- function normalizeTokenRefreshUnavailableFailure() {
34810
- return "token refresh failed before authentication completed";
33721
+ async function resolveBorrowedRobotStatus(robotFallback) {
33722
+ const robotCreds = await robotFallback();
33723
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
34811
33724
  }
34812
- function errorMessage(error) {
34813
- return error instanceof Error ? error.message : String(error);
33725
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
33726
+ let credentials;
33727
+ try {
33728
+ credentials = await loadEnvFile({ envPath: absolutePath });
33729
+ } catch (error) {
33730
+ if (isFileNotFoundError(error)) {
33731
+ return { status: { loginStatus: "Not logged in" } };
33732
+ }
33733
+ throw error;
33734
+ }
33735
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
33736
+ return { status: { loginStatus: "Not logged in" } };
33737
+ }
33738
+ return { credentials };
33739
+ }
33740
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
33741
+ const fs7 = getFs();
33742
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
33743
+ if (absolutePath === globalPath)
33744
+ return;
33745
+ if (!await fs7.exists(globalPath))
33746
+ return;
33747
+ try {
33748
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
33749
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
33750
+ return;
33751
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
33752
+ if (globalExp && globalExp <= new Date)
33753
+ return;
33754
+ 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.`;
33755
+ } catch {
33756
+ return;
33757
+ }
34814
33758
  }
34815
33759
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
34816
33760
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
34817
33761
  }
33762
+ async function attemptRefresh(ctx) {
33763
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
33764
+ if (shortCircuit) {
33765
+ return { kind: "terminal", status: shortCircuit };
33766
+ }
33767
+ let release;
33768
+ try {
33769
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
33770
+ } catch (error) {
33771
+ return {
33772
+ kind: "terminal",
33773
+ status: await lockAcquireFailureStatus(ctx, error)
33774
+ };
33775
+ }
33776
+ let lockedFailure;
33777
+ let lockReleaseFailed = false;
33778
+ let success;
33779
+ try {
33780
+ const outcome = await runRefreshLocked({
33781
+ absolutePath: ctx.absolutePath,
33782
+ refreshToken: ctx.refreshToken,
33783
+ customAuthority: ctx.credentials.UIPATH_URL,
33784
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
33785
+ loadEnvFile: ctx.loadEnvFile,
33786
+ saveEnvFile: ctx.saveEnvFile,
33787
+ refreshFn: ctx.refreshFn,
33788
+ resolveConfig: ctx.resolveConfig,
33789
+ loadBreaker: ctx.loadBreaker,
33790
+ saveBreaker: ctx.saveBreaker,
33791
+ clearBreaker: ctx.clearBreaker
33792
+ });
33793
+ if (outcome.kind === "fail") {
33794
+ lockedFailure = outcome.status;
33795
+ } else {
33796
+ success = outcome;
33797
+ }
33798
+ } finally {
33799
+ try {
33800
+ await release();
33801
+ } catch {
33802
+ lockReleaseFailed = true;
33803
+ }
33804
+ }
33805
+ if (lockedFailure) {
33806
+ const globalHint = await ctx.globalHint();
33807
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
33808
+ return {
33809
+ kind: "terminal",
33810
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
33811
+ };
33812
+ }
33813
+ return {
33814
+ kind: "refreshed",
33815
+ tokens: {
33816
+ accessToken: success?.accessToken,
33817
+ refreshToken: success?.refreshToken,
33818
+ expiration: success?.expiration,
33819
+ tokenRefresh: success?.tokenRefresh,
33820
+ persistenceWarning: success?.persistenceWarning,
33821
+ lockReleaseFailed
33822
+ }
33823
+ };
33824
+ }
33825
+ async function buildFileStatus(tokens, credentials, globalHint) {
33826
+ const result = {
33827
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
33828
+ accessToken: tokens.accessToken,
33829
+ refreshToken: tokens.refreshToken,
33830
+ baseUrl: credentials.UIPATH_URL,
33831
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
33832
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
33833
+ tenantName: credentials.UIPATH_TENANT_NAME,
33834
+ tenantId: credentials.UIPATH_TENANT_ID,
33835
+ expiration: tokens.expiration,
33836
+ source: "file" /* File */,
33837
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
33838
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
33839
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
33840
+ };
33841
+ if (result.loginStatus === "Expired") {
33842
+ const hint = await globalHint();
33843
+ if (hint) {
33844
+ result.hint = hint;
33845
+ }
33846
+ }
33847
+ return result;
33848
+ }
33849
+ function buildRobotStatus(robotCreds) {
33850
+ return {
33851
+ loginStatus: "Logged in",
33852
+ accessToken: robotCreds.accessToken,
33853
+ baseUrl: robotCreds.baseUrl,
33854
+ organizationName: robotCreds.organizationName,
33855
+ organizationId: robotCreds.organizationId,
33856
+ tenantName: robotCreds.tenantName,
33857
+ tenantId: robotCreds.tenantId,
33858
+ issuer: robotCreds.issuer,
33859
+ expiration: getTokenExpiration(robotCreds.accessToken),
33860
+ source: "robot" /* Robot */
33861
+ };
33862
+ }
33863
+ var isFileNotFoundError = (error) => {
33864
+ if (!(error instanceof Object))
33865
+ return false;
33866
+ return error.code === "ENOENT";
33867
+ };
33868
+ async function circuitBreakerShortCircuit(ctx) {
33869
+ const {
33870
+ absolutePath,
33871
+ refreshToken,
33872
+ accessToken,
33873
+ credentials,
33874
+ expiration,
33875
+ loadBreaker,
33876
+ saveBreaker,
33877
+ clearBreaker
33878
+ } = ctx;
33879
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
33880
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
33881
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
33882
+ await clearBreaker(absolutePath);
33883
+ breaker.deadTokenFp = undefined;
33884
+ }
33885
+ const nowMs = Date.now();
33886
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
33887
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
33888
+ if (!tokenIsDead && !inBackoff)
33889
+ return;
33890
+ const globalHint = await ctx.globalHint();
33891
+ const suppressed = !shouldSurface(breaker, nowMs);
33892
+ if (!suppressed) {
33893
+ await saveBreaker(absolutePath, {
33894
+ ...breaker,
33895
+ lastSurfacedAtMs: nowMs
33896
+ });
33897
+ }
33898
+ 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>.";
33899
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
33900
+ return {
33901
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
33902
+ ...globalHint ? {
33903
+ accessToken,
33904
+ refreshToken,
33905
+ baseUrl: credentials.UIPATH_URL,
33906
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
33907
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
33908
+ tenantName: credentials.UIPATH_TENANT_NAME,
33909
+ tenantId: credentials.UIPATH_TENANT_ID,
33910
+ expiration,
33911
+ source: "file" /* File */
33912
+ } : {},
33913
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
33914
+ refreshCircuitOpen: true,
33915
+ refreshTelemetrySuppressed: suppressed,
33916
+ tokenRefresh: { attempted: false, success: false }
33917
+ };
33918
+ }
33919
+ async function lockAcquireFailureStatus(ctx, error) {
33920
+ const msg = errorMessage(error);
33921
+ const globalHint = await ctx.globalHint();
33922
+ if (globalHint) {
33923
+ return {
33924
+ loginStatus: "Expired",
33925
+ accessToken: ctx.accessToken,
33926
+ refreshToken: ctx.refreshToken,
33927
+ baseUrl: ctx.credentials.UIPATH_URL,
33928
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
33929
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
33930
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
33931
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
33932
+ expiration: ctx.expiration,
33933
+ source: "file" /* File */,
33934
+ hint: globalHint,
33935
+ tokenRefresh: {
33936
+ attempted: false,
33937
+ success: false,
33938
+ errorMessage: `lock acquisition failed: ${msg}`
33939
+ }
33940
+ };
33941
+ }
33942
+ return {
33943
+ loginStatus: "Refresh Failed",
33944
+ 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.",
33945
+ tokenRefresh: {
33946
+ attempted: false,
33947
+ success: false,
33948
+ errorMessage: `lock acquisition failed: ${msg}`
33949
+ }
33950
+ };
33951
+ }
34818
33952
  async function runRefreshLocked(inputs) {
34819
33953
  const {
34820
33954
  absolutePath,
@@ -34824,7 +33958,10 @@ async function runRefreshLocked(inputs) {
34824
33958
  loadEnvFile,
34825
33959
  saveEnvFile,
34826
33960
  refreshFn,
34827
- resolveConfig
33961
+ resolveConfig,
33962
+ loadBreaker,
33963
+ saveBreaker,
33964
+ clearBreaker
34828
33965
  } = inputs;
34829
33966
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
34830
33967
  let fresh;
@@ -34847,6 +33984,7 @@ async function runRefreshLocked(inputs) {
34847
33984
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
34848
33985
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
34849
33986
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
33987
+ await clearBreaker(absolutePath);
34850
33988
  return {
34851
33989
  kind: "ok",
34852
33990
  accessToken: freshAccess,
@@ -34870,8 +34008,21 @@ async function runRefreshLocked(inputs) {
34870
34008
  refreshedRefresh = refreshed.refreshToken;
34871
34009
  } catch (error) {
34872
34010
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
34873
- 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.";
34011
+ 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.";
34874
34012
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
34013
+ const fp = await refreshTokenFingerprint(tokenForIdP);
34014
+ if (isOAuthFailure) {
34015
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
34016
+ } else {
34017
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
34018
+ const attempts = (prior.attempts ?? 0) + 1;
34019
+ await saveBreaker(absolutePath, {
34020
+ ...prior,
34021
+ deadTokenFp: undefined,
34022
+ attempts,
34023
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
34024
+ });
34025
+ }
34875
34026
  return {
34876
34027
  kind: "fail",
34877
34028
  status: {
@@ -34900,6 +34051,7 @@ async function runRefreshLocked(inputs) {
34900
34051
  }
34901
34052
  };
34902
34053
  }
34054
+ await clearBreaker(absolutePath);
34903
34055
  try {
34904
34056
  await saveEnvFile({
34905
34057
  envPath: absolutePath,
@@ -34932,214 +34084,25 @@ async function runRefreshLocked(inputs) {
34932
34084
  };
34933
34085
  }
34934
34086
  }
34935
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
34936
- const {
34937
- resolveEnvFilePath = resolveEnvFilePathAsync,
34938
- loadEnvFile = loadEnvFileAsync,
34939
- saveEnvFile = saveEnvFileAsync,
34940
- getFs = getFileSystem,
34941
- refreshToken: refreshTokenFn = refreshAccessToken,
34942
- resolveConfig = resolveConfigAsync,
34943
- robotFallback = tryRobotClientFallback
34944
- } = deps;
34945
- if (isRobotAuthEnforced()) {
34946
- if (isEnvAuthEnabled()) {
34947
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
34948
- }
34949
- const robotCreds = await robotFallback({ force: true });
34950
- if (!robotCreds) {
34951
- return {
34952
- loginStatus: "Not logged in",
34953
- 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.`
34954
- };
34955
- }
34956
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
34957
- return {
34958
- loginStatus: "Logged in",
34959
- accessToken: robotCreds.accessToken,
34960
- baseUrl: robotCreds.baseUrl,
34961
- organizationName: robotCreds.organizationName,
34962
- organizationId: robotCreds.organizationId,
34963
- tenantName: robotCreds.tenantName,
34964
- tenantId: robotCreds.tenantId,
34965
- issuer: robotCreds.issuer,
34966
- expiration: expiration2,
34967
- source: "robot" /* Robot */
34968
- };
34969
- }
34970
- if (isEnvAuthEnabled()) {
34971
- return readAuthFromEnv();
34972
- }
34973
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
34974
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
34975
- if (absolutePath === undefined) {
34976
- const robotCreds = await robotFallback();
34977
- if (robotCreds) {
34978
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
34979
- const status = {
34980
- loginStatus: "Logged in",
34981
- accessToken: robotCreds.accessToken,
34982
- baseUrl: robotCreds.baseUrl,
34983
- organizationName: robotCreds.organizationName,
34984
- organizationId: robotCreds.organizationId,
34985
- tenantName: robotCreds.tenantName,
34986
- tenantId: robotCreds.tenantId,
34987
- issuer: robotCreds.issuer,
34988
- expiration: expiration2,
34989
- source: "robot" /* Robot */
34990
- };
34991
- return status;
34992
- }
34993
- return { loginStatus: "Not logged in" };
34994
- }
34995
- let credentials;
34996
- try {
34997
- credentials = await loadEnvFile({ envPath: absolutePath });
34998
- } catch (error) {
34999
- if (isFileNotFoundError(error)) {
35000
- return { loginStatus: "Not logged in" };
35001
- }
35002
- throw error;
35003
- }
35004
- if (!credentials.UIPATH_ACCESS_TOKEN) {
35005
- return { loginStatus: "Not logged in" };
35006
- }
35007
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
35008
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
35009
- let expiration = getTokenExpiration(accessToken);
35010
- let persistenceWarning;
35011
- let lockReleaseFailed = false;
35012
- let tokenRefresh;
35013
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
35014
- const tryGlobalCredsHint = async () => {
35015
- const fs7 = getFs();
35016
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
35017
- if (absolutePath === globalPath)
35018
- return;
35019
- if (!await fs7.exists(globalPath))
35020
- return;
35021
- try {
35022
- const globalCreds = await loadEnvFile({ envPath: globalPath });
35023
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
35024
- return;
35025
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
35026
- if (globalExp && globalExp <= new Date)
35027
- return;
35028
- 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.`;
35029
- } catch {
35030
- return;
35031
- }
35032
- };
35033
- if (expiration && expiration <= outerThreshold && refreshToken) {
35034
- let release;
35035
- try {
35036
- release = await getFs().acquireLock(absolutePath);
35037
- } catch (error) {
35038
- const msg = errorMessage(error);
35039
- const globalHint = await tryGlobalCredsHint();
35040
- if (globalHint) {
35041
- return {
35042
- loginStatus: "Expired",
35043
- accessToken,
35044
- refreshToken,
35045
- baseUrl: credentials.UIPATH_URL,
35046
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
35047
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
35048
- tenantName: credentials.UIPATH_TENANT_NAME,
35049
- tenantId: credentials.UIPATH_TENANT_ID,
35050
- expiration,
35051
- source: "file" /* File */,
35052
- hint: globalHint,
35053
- tokenRefresh: {
35054
- attempted: false,
35055
- success: false,
35056
- errorMessage: `lock acquisition failed: ${msg}`
35057
- }
35058
- };
35059
- }
35060
- return {
35061
- loginStatus: "Refresh Failed",
35062
- 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.",
35063
- tokenRefresh: {
35064
- attempted: false,
35065
- success: false,
35066
- errorMessage: `lock acquisition failed: ${msg}`
35067
- }
35068
- };
35069
- }
35070
- let lockedFailure;
35071
- try {
35072
- const outcome = await runRefreshLocked({
35073
- absolutePath,
35074
- refreshToken,
35075
- customAuthority: credentials.UIPATH_URL,
35076
- ensureTokenValidityMinutes,
35077
- loadEnvFile,
35078
- saveEnvFile,
35079
- refreshFn: refreshTokenFn,
35080
- resolveConfig
35081
- });
35082
- if (outcome.kind === "fail") {
35083
- lockedFailure = outcome.status;
35084
- } else {
35085
- accessToken = outcome.accessToken;
35086
- refreshToken = outcome.refreshToken;
35087
- expiration = outcome.expiration;
35088
- tokenRefresh = outcome.tokenRefresh;
35089
- if (outcome.persistenceWarning) {
35090
- persistenceWarning = outcome.persistenceWarning;
35091
- }
35092
- }
35093
- } finally {
35094
- try {
35095
- await release();
35096
- } catch {
35097
- lockReleaseFailed = true;
35098
- }
35099
- }
35100
- if (lockedFailure) {
35101
- const globalHint = await tryGlobalCredsHint();
35102
- const base = globalHint ? {
35103
- ...lockedFailure,
35104
- loginStatus: "Expired",
35105
- hint: globalHint
35106
- } : lockedFailure;
35107
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
35108
- }
35109
- }
35110
- const result = {
35111
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
35112
- accessToken,
35113
- refreshToken,
35114
- baseUrl: credentials.UIPATH_URL,
35115
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
35116
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
35117
- tenantName: credentials.UIPATH_TENANT_NAME,
35118
- tenantId: credentials.UIPATH_TENANT_ID,
35119
- expiration,
35120
- source: "file" /* File */,
35121
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
35122
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
35123
- ...tokenRefresh ? { tokenRefresh } : {}
35124
- };
35125
- if (result.loginStatus === "Expired") {
35126
- const globalHint = await tryGlobalCredsHint();
35127
- if (globalHint) {
35128
- result.hint = globalHint;
35129
- }
35130
- }
35131
- return result;
35132
- };
35133
- var isFileNotFoundError = (error) => {
35134
- if (!(error instanceof Object))
35135
- return false;
35136
- return error.code === "ENOENT";
35137
- };
35138
- var getLoginStatusAsync = async (options = {}) => {
35139
- return getLoginStatusWithDeps(options);
35140
- };
34087
+ function normalizeTokenRefreshFailure() {
34088
+ return "stored refresh token is invalid or expired";
34089
+ }
34090
+ function normalizeTokenRefreshUnavailableFailure() {
34091
+ return "token refresh failed before authentication completed";
34092
+ }
34093
+ function errorMessage(error) {
34094
+ return error instanceof Error ? error.message : String(error);
34095
+ }
35141
34096
  // ../../auth/src/interactive.ts
35142
34097
  init_src();
34098
+
34099
+ // ../../auth/src/selectTenant.ts
34100
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
34101
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
34102
+ var TENANT_SELECTION_CODES = new Set([
34103
+ TENANT_SELECTION_REQUIRED_CODE,
34104
+ INVALID_TENANT_CODE
34105
+ ]);
35143
34106
  // ../../auth/src/logout.ts
35144
34107
  init_src();
35145
34108
 
@@ -36389,3 +35352,5 @@ var program2 = new Command;
36389
35352
  program2.name(metadata.commandPrefix).description(metadata.description).version(metadata.version);
36390
35353
  await registerCommands(program2);
36391
35354
  program2.parse(process.argv);
35355
+
35356
+ //# debugId=CBD818BFBE70D40364756E2164756E21