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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +2 -0
  2. package/dist/tool.js +1219 -2002
  3. package/package.json +2 -2
package/dist/tool.js CHANGED
@@ -3057,27 +3057,42 @@ function settlePromiseLike2(thenable) {
3057
3057
  }
3058
3058
 
3059
3059
  // ../common/src/error-handler.ts
3060
- function isHtmlDocument(body) {
3061
- return /^\s*(<!doctype html|<html\b)/i.test(body);
3062
- }
3063
- function extractNetworkErrorCode(error) {
3064
- if (error === null || typeof error !== "object") {
3065
- return;
3066
- }
3067
- const err = error;
3068
- const code = typeof err.code === "string" ? err.code : undefined;
3069
- if (code && NETWORK_ERROR_CODES.has(code)) {
3070
- return code;
3071
- }
3072
- const cause = err.cause;
3073
- if (cause !== null && typeof cause === "object") {
3074
- const causeCode = cause.code;
3075
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
3076
- return causeCode;
3060
+ function describeConnectivityError(error) {
3061
+ let current = error;
3062
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
3063
+ const cur = current;
3064
+ const code = typeof cur.code === "string" ? cur.code : undefined;
3065
+ const message = typeof cur.message === "string" ? cur.message : undefined;
3066
+ if (code && TLS_ERROR_CODES.has(code)) {
3067
+ return {
3068
+ code,
3069
+ kind: "tls",
3070
+ message: message ?? code,
3071
+ instructions: TLS_INSTRUCTIONS
3072
+ };
3073
+ }
3074
+ if (code && NETWORK_ERROR_CODES.has(code)) {
3075
+ return {
3076
+ code,
3077
+ kind: "network",
3078
+ message: message ?? code,
3079
+ instructions: NETWORK_INSTRUCTIONS
3080
+ };
3077
3081
  }
3082
+ current = cur.cause;
3078
3083
  }
3079
3084
  return;
3080
3085
  }
3086
+ function parseHttpStatusFromMessage(message) {
3087
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
3088
+ if (!match)
3089
+ return;
3090
+ const status = Number(match[1]);
3091
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
3092
+ }
3093
+ function isHtmlDocument(body) {
3094
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
3095
+ }
3081
3096
  function retryHintForRetryAfter(seconds) {
3082
3097
  if (seconds <= 1) {
3083
3098
  return "RetryAfter1Second";
@@ -3118,15 +3133,28 @@ function classifyError(status, error) {
3118
3133
  if (status !== undefined && status >= 500 && status < 600) {
3119
3134
  return { errorCode: "server_error", retry: "RetryLater" };
3120
3135
  }
3121
- if (extractNetworkErrorCode(error)) {
3122
- return { errorCode: "network_error", retry: "RetryLater" };
3136
+ const connectivity = describeConnectivityError(error);
3137
+ if (connectivity) {
3138
+ return {
3139
+ errorCode: "network_error",
3140
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
3141
+ };
3123
3142
  }
3124
3143
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
3125
3144
  }
3145
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
3146
+ if (extractedMessage) {
3147
+ return `HTTP ${status}: ${extractedMessage}`;
3148
+ }
3149
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
3150
+ }
3126
3151
  async function extractErrorDetails(error, options) {
3127
3152
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
3128
3153
  const response = err.response;
3129
- const status = err.status ?? response?.status;
3154
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
3155
+ const explicitStatus = err.status ?? response?.status;
3156
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
3157
+ const status = explicitStatus ?? inferredStatus;
3130
3158
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
3131
3159
  let rawBody;
3132
3160
  let extractedMessage;
@@ -3161,7 +3189,6 @@ async function extractErrorDetails(error, options) {
3161
3189
  }
3162
3190
  }
3163
3191
  }
3164
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
3165
3192
  let message;
3166
3193
  let result = "Failure";
3167
3194
  const classification = classifyError(status, error);
@@ -3175,10 +3202,10 @@ async function extractErrorDetails(error, options) {
3175
3202
  } else if (status === 405) {
3176
3203
  message = DEFAULT_405;
3177
3204
  } else if (status === 400 || status === 422) {
3178
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
3205
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
3179
3206
  result = "ValidationError";
3180
3207
  } else if (status === 429) {
3181
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
3208
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
3182
3209
  } else if (extractedMessage) {
3183
3210
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
3184
3211
  message = rawMessage;
@@ -3186,7 +3213,9 @@ async function extractErrorDetails(error, options) {
3186
3213
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
3187
3214
  }
3188
3215
  } else if (status) {
3189
- if (rawMessage === "Unknown error" && response) {
3216
+ if (inferredStatus !== undefined) {
3217
+ message = rawMessage;
3218
+ } else if (rawMessage === "Unknown error" && response) {
3190
3219
  const statusText = response.statusText;
3191
3220
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
3192
3221
  } else {
@@ -3195,6 +3224,12 @@ async function extractErrorDetails(error, options) {
3195
3224
  } else {
3196
3225
  message = rawMessage;
3197
3226
  }
3227
+ if (status === undefined) {
3228
+ const connectivity = describeConnectivityError(error);
3229
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
3230
+ message = `${message}: ${connectivity.message}`;
3231
+ }
3232
+ }
3198
3233
  let details = rawMessage;
3199
3234
  if (rawBody) {
3200
3235
  if (parsedBody) {
@@ -3288,7 +3323,7 @@ async function extractErrorMessage(error, options) {
3288
3323
  const { message } = await extractErrorDetails(error, options);
3289
3324
  return message;
3290
3325
  }
3291
- var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.", DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.", DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.", HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.", NETWORK_ERROR_CODES;
3326
+ var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.", DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.", DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.", HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.", NETWORK_ERROR_CODES, TLS_ERROR_CODES, TLS_INSTRUCTIONS, NETWORK_INSTRUCTIONS;
3292
3327
  var init_error_handler = __esm(() => {
3293
3328
  NETWORK_ERROR_CODES = new Set([
3294
3329
  "ECONNREFUSED",
@@ -3301,6 +3336,18 @@ var init_error_handler = __esm(() => {
3301
3336
  "ENETUNREACH",
3302
3337
  "EAI_FAIL"
3303
3338
  ]);
3339
+ TLS_ERROR_CODES = new Set([
3340
+ "SELF_SIGNED_CERT_IN_CHAIN",
3341
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
3342
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
3343
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
3344
+ "UNABLE_TO_GET_ISSUER_CERT",
3345
+ "CERT_HAS_EXPIRED",
3346
+ "CERT_UNTRUSTED",
3347
+ "ERR_TLS_CERT_ALTNAME_INVALID"
3348
+ ]);
3349
+ 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.";
3350
+ 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.";
3304
3351
  });
3305
3352
 
3306
3353
  // ../common/src/attachment-binding.ts
@@ -3380,6 +3427,7 @@ var init_output_context = __esm(() => {
3380
3427
  writeLog: (str) => process.stdout.write(str),
3381
3428
  capabilities: {
3382
3429
  isInteractive: false,
3430
+ canReadInput: false,
3383
3431
  supportsColor: false,
3384
3432
  outputWidth: 80
3385
3433
  }
@@ -8386,12 +8434,12 @@ var init_node_context_storage = () => {};
8386
8434
 
8387
8435
  // ../common/src/telemetry/global-telemetry-properties.ts
8388
8436
  function getGlobalTelemetryProperties() {
8389
- return telemetryPropsSlot.get();
8437
+ return telemetryPropsSlot2.get();
8390
8438
  }
8391
- var telemetryPropsSlot;
8439
+ var telemetryPropsSlot2;
8392
8440
  var init_global_telemetry_properties = __esm(() => {
8393
8441
  init_singleton();
8394
- telemetryPropsSlot = singleton2("TelemetryDefaultProps");
8442
+ telemetryPropsSlot2 = singleton2("TelemetryDefaultProps");
8395
8443
  });
8396
8444
 
8397
8445
  // ../common/src/telemetry/telemetry-service.ts
@@ -8504,7 +8552,6 @@ var init_node_appinsights_telemetry_provider = __esm(() => {
8504
8552
  init_global_telemetry_properties();
8505
8553
  providerSlot = singleton2("TelemetryProvider");
8506
8554
  });
8507
-
8508
8555
  // ../common/src/telemetry/telemetry-init.ts
8509
8556
  function getGlobalTelemetryInstance() {
8510
8557
  const existing = telemetryInstanceSlot.get();
@@ -8572,6 +8619,29 @@ function isPlainRecord(value) {
8572
8619
  const prototype = Object.getPrototypeOf(value);
8573
8620
  return prototype === Object.prototype || prototype === null;
8574
8621
  }
8622
+ function extractPagedRows(value) {
8623
+ if (Array.isArray(value) || !isPlainRecord(value))
8624
+ return null;
8625
+ const entries = Object.values(value);
8626
+ if (entries.length === 0)
8627
+ return null;
8628
+ let rows = null;
8629
+ let hasScalarSibling = false;
8630
+ for (const entry of entries) {
8631
+ if (Array.isArray(entry)) {
8632
+ if (rows !== null)
8633
+ return null;
8634
+ rows = entry;
8635
+ } else if (entry !== null && typeof entry === "object") {
8636
+ return null;
8637
+ } else {
8638
+ hasScalarSibling = true;
8639
+ }
8640
+ }
8641
+ if (rows === null || !hasScalarSibling)
8642
+ return null;
8643
+ return rows;
8644
+ }
8575
8645
  function toLowerCamelCaseKey(key) {
8576
8646
  if (!key)
8577
8647
  return key;
@@ -8636,7 +8706,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
8636
8706
  break;
8637
8707
  case "plain": {
8638
8708
  if ("Data" in data && data.Data != null) {
8639
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
8709
+ const pagedRows = extractPagedRows(data.Data);
8710
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
8640
8711
  items.forEach((item) => {
8641
8712
  const values = Object.values(item).map((v) => v ?? "").join("\t");
8642
8713
  logFn(values);
@@ -8648,10 +8719,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
8648
8719
  break;
8649
8720
  }
8650
8721
  default: {
8651
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
8722
+ const hasData = "Data" in data && data.Data != null;
8723
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
8724
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
8725
+ if (hasData && !(rows !== null && rows.length === 0)) {
8652
8726
  const logValue = data.Log;
8653
- if (Array.isArray(data.Data)) {
8654
- printResizableTable(data.Data, logFn, logValue);
8727
+ if (rows !== null) {
8728
+ printResizableTable(rows, logFn, logValue);
8655
8729
  } else {
8656
8730
  printVerticalTable(data.Data, logFn, logValue);
8657
8731
  }
@@ -8824,6 +8898,44 @@ function defaultErrorCodeForResult(result) {
8824
8898
  return "unknown_error";
8825
8899
  }
8826
8900
  }
8901
+ function parseHttpStatusFromMessage2(message) {
8902
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
8903
+ if (!match)
8904
+ return;
8905
+ const status = Number(match[1]);
8906
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
8907
+ }
8908
+ function defaultErrorCodeForHttpStatus(status) {
8909
+ if (status === undefined)
8910
+ return;
8911
+ if (status === 400 || status === 409 || status === 422) {
8912
+ return "invalid_argument";
8913
+ }
8914
+ if (status === 401)
8915
+ return "authentication_required";
8916
+ if (status === 403)
8917
+ return "permission_denied";
8918
+ if (status === 404)
8919
+ return "not_found";
8920
+ if (status === 405)
8921
+ return "method_not_allowed";
8922
+ if (status === 408)
8923
+ return "timeout";
8924
+ if (status === 429)
8925
+ return "rate_limited";
8926
+ if (status >= 500 && status < 600)
8927
+ return "server_error";
8928
+ return;
8929
+ }
8930
+ function defaultErrorCodeForFailure(data) {
8931
+ if (data.Result === RESULTS.Failure) {
8932
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
8933
+ const errorCode2 = defaultErrorCodeForHttpStatus(status);
8934
+ if (errorCode2)
8935
+ return errorCode2;
8936
+ }
8937
+ return defaultErrorCodeForResult(data.Result);
8938
+ }
8827
8939
  function defaultRetryForErrorCode(errorCode2) {
8828
8940
  switch (errorCode2) {
8829
8941
  case "network_error":
@@ -8913,16 +9025,19 @@ var init_formatter = __esm(() => {
8913
9025
  OutputFormatter.success = success;
8914
9026
  function error(data) {
8915
9027
  data.Log ??= getLogFilePath() || undefined;
8916
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
9028
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
8917
9029
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
8918
9030
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
8919
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
8920
- result: data.Result,
8921
- errorCode: data.ErrorCode,
8922
- retry: data.Retry,
8923
- message: data.Message
8924
- });
8925
- logOutput(normalizeOutputKeys(data), getOutputFormat());
9031
+ const { SuppressTelemetry, ...envelope } = data;
9032
+ if (!SuppressTelemetry) {
9033
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
9034
+ result: data.Result,
9035
+ errorCode: data.ErrorCode,
9036
+ retry: data.Retry,
9037
+ message: data.Message
9038
+ });
9039
+ }
9040
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
8926
9041
  }
8927
9042
  OutputFormatter.error = error;
8928
9043
  function emitList(code, items, opts) {
@@ -9249,6 +9364,11 @@ var DEFAULT_PAGE_SIZE = 50, DEFAULT_AUTH_TIMEOUT_MS2;
9249
9364
  var init_constants2 = __esm(() => {
9250
9365
  DEFAULT_AUTH_TIMEOUT_MS2 = 5 * 60 * 1000;
9251
9366
  });
9367
+ // ../common/src/error-instructions.ts
9368
+ var init_error_instructions = __esm(() => {
9369
+ init_error_handler();
9370
+ });
9371
+
9252
9372
  // ../common/src/guid.ts
9253
9373
  var init_guid = () => {};
9254
9374
 
@@ -9260,1411 +9380,6 @@ var init_interactivity_context = __esm(() => {
9260
9380
  modeSlot = singleton2("InteractivityMode");
9261
9381
  });
9262
9382
 
9263
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
9264
- import vm from "vm";
9265
-
9266
- class Hooks {
9267
- add(name, callback, first) {
9268
- if (typeof arguments[0] != "string") {
9269
- for (let name2 in arguments[0]) {
9270
- this.add(name2, arguments[0][name2], arguments[1]);
9271
- }
9272
- } else {
9273
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
9274
- this[name2] = this[name2] || [];
9275
- if (callback) {
9276
- this[name2][first ? "unshift" : "push"](callback);
9277
- }
9278
- }, this);
9279
- }
9280
- }
9281
- run(name, env) {
9282
- this[name] = this[name] || [];
9283
- this[name].forEach(function(callback) {
9284
- callback.call(env && env.context ? env.context : env, env);
9285
- });
9286
- }
9287
- }
9288
-
9289
- class Plugins {
9290
- constructor(jsep) {
9291
- this.jsep = jsep;
9292
- this.registered = {};
9293
- }
9294
- register(...plugins) {
9295
- plugins.forEach((plugin) => {
9296
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
9297
- throw new Error("Invalid JSEP plugin format");
9298
- }
9299
- if (this.registered[plugin.name]) {
9300
- return;
9301
- }
9302
- plugin.init(this.jsep);
9303
- this.registered[plugin.name] = plugin;
9304
- });
9305
- }
9306
- }
9307
-
9308
- class Jsep {
9309
- static get version() {
9310
- return "1.4.0";
9311
- }
9312
- static toString() {
9313
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
9314
- }
9315
- static addUnaryOp(op_name) {
9316
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
9317
- Jsep.unary_ops[op_name] = 1;
9318
- return Jsep;
9319
- }
9320
- static addBinaryOp(op_name, precedence, isRightAssociative) {
9321
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
9322
- Jsep.binary_ops[op_name] = precedence;
9323
- if (isRightAssociative) {
9324
- Jsep.right_associative.add(op_name);
9325
- } else {
9326
- Jsep.right_associative.delete(op_name);
9327
- }
9328
- return Jsep;
9329
- }
9330
- static addIdentifierChar(char) {
9331
- Jsep.additional_identifier_chars.add(char);
9332
- return Jsep;
9333
- }
9334
- static addLiteral(literal_name, literal_value) {
9335
- Jsep.literals[literal_name] = literal_value;
9336
- return Jsep;
9337
- }
9338
- static removeUnaryOp(op_name) {
9339
- delete Jsep.unary_ops[op_name];
9340
- if (op_name.length === Jsep.max_unop_len) {
9341
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
9342
- }
9343
- return Jsep;
9344
- }
9345
- static removeAllUnaryOps() {
9346
- Jsep.unary_ops = {};
9347
- Jsep.max_unop_len = 0;
9348
- return Jsep;
9349
- }
9350
- static removeIdentifierChar(char) {
9351
- Jsep.additional_identifier_chars.delete(char);
9352
- return Jsep;
9353
- }
9354
- static removeBinaryOp(op_name) {
9355
- delete Jsep.binary_ops[op_name];
9356
- if (op_name.length === Jsep.max_binop_len) {
9357
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
9358
- }
9359
- Jsep.right_associative.delete(op_name);
9360
- return Jsep;
9361
- }
9362
- static removeAllBinaryOps() {
9363
- Jsep.binary_ops = {};
9364
- Jsep.max_binop_len = 0;
9365
- return Jsep;
9366
- }
9367
- static removeLiteral(literal_name) {
9368
- delete Jsep.literals[literal_name];
9369
- return Jsep;
9370
- }
9371
- static removeAllLiterals() {
9372
- Jsep.literals = {};
9373
- return Jsep;
9374
- }
9375
- get char() {
9376
- return this.expr.charAt(this.index);
9377
- }
9378
- get code() {
9379
- return this.expr.charCodeAt(this.index);
9380
- }
9381
- constructor(expr) {
9382
- this.expr = expr;
9383
- this.index = 0;
9384
- }
9385
- static parse(expr) {
9386
- return new Jsep(expr).parse();
9387
- }
9388
- static getMaxKeyLen(obj) {
9389
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
9390
- }
9391
- static isDecimalDigit(ch) {
9392
- return ch >= 48 && ch <= 57;
9393
- }
9394
- static binaryPrecedence(op_val) {
9395
- return Jsep.binary_ops[op_val] || 0;
9396
- }
9397
- static isIdentifierStart(ch) {
9398
- 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));
9399
- }
9400
- static isIdentifierPart(ch) {
9401
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
9402
- }
9403
- throwError(message) {
9404
- const error = new Error(message + " at character " + this.index);
9405
- error.index = this.index;
9406
- error.description = message;
9407
- throw error;
9408
- }
9409
- runHook(name, node) {
9410
- if (Jsep.hooks[name]) {
9411
- const env = {
9412
- context: this,
9413
- node
9414
- };
9415
- Jsep.hooks.run(name, env);
9416
- return env.node;
9417
- }
9418
- return node;
9419
- }
9420
- searchHook(name) {
9421
- if (Jsep.hooks[name]) {
9422
- const env = {
9423
- context: this
9424
- };
9425
- Jsep.hooks[name].find(function(callback) {
9426
- callback.call(env.context, env);
9427
- return env.node;
9428
- });
9429
- return env.node;
9430
- }
9431
- }
9432
- gobbleSpaces() {
9433
- let ch = this.code;
9434
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
9435
- ch = this.expr.charCodeAt(++this.index);
9436
- }
9437
- this.runHook("gobble-spaces");
9438
- }
9439
- parse() {
9440
- this.runHook("before-all");
9441
- const nodes = this.gobbleExpressions();
9442
- const node = nodes.length === 1 ? nodes[0] : {
9443
- type: Jsep.COMPOUND,
9444
- body: nodes
9445
- };
9446
- return this.runHook("after-all", node);
9447
- }
9448
- gobbleExpressions(untilICode) {
9449
- let nodes = [], ch_i, node;
9450
- while (this.index < this.expr.length) {
9451
- ch_i = this.code;
9452
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
9453
- this.index++;
9454
- } else {
9455
- if (node = this.gobbleExpression()) {
9456
- nodes.push(node);
9457
- } else if (this.index < this.expr.length) {
9458
- if (ch_i === untilICode) {
9459
- break;
9460
- }
9461
- this.throwError('Unexpected "' + this.char + '"');
9462
- }
9463
- }
9464
- }
9465
- return nodes;
9466
- }
9467
- gobbleExpression() {
9468
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
9469
- this.gobbleSpaces();
9470
- return this.runHook("after-expression", node);
9471
- }
9472
- gobbleBinaryOp() {
9473
- this.gobbleSpaces();
9474
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
9475
- let tc_len = to_check.length;
9476
- while (tc_len > 0) {
9477
- 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)))) {
9478
- this.index += tc_len;
9479
- return to_check;
9480
- }
9481
- to_check = to_check.substr(0, --tc_len);
9482
- }
9483
- return false;
9484
- }
9485
- gobbleBinaryExpression() {
9486
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
9487
- left = this.gobbleToken();
9488
- if (!left) {
9489
- return left;
9490
- }
9491
- biop = this.gobbleBinaryOp();
9492
- if (!biop) {
9493
- return left;
9494
- }
9495
- biop_info = {
9496
- value: biop,
9497
- prec: Jsep.binaryPrecedence(biop),
9498
- right_a: Jsep.right_associative.has(biop)
9499
- };
9500
- right = this.gobbleToken();
9501
- if (!right) {
9502
- this.throwError("Expected expression after " + biop);
9503
- }
9504
- stack = [left, biop_info, right];
9505
- while (biop = this.gobbleBinaryOp()) {
9506
- prec = Jsep.binaryPrecedence(biop);
9507
- if (prec === 0) {
9508
- this.index -= biop.length;
9509
- break;
9510
- }
9511
- biop_info = {
9512
- value: biop,
9513
- prec,
9514
- right_a: Jsep.right_associative.has(biop)
9515
- };
9516
- cur_biop = biop;
9517
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
9518
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
9519
- right = stack.pop();
9520
- biop = stack.pop().value;
9521
- left = stack.pop();
9522
- node = {
9523
- type: Jsep.BINARY_EXP,
9524
- operator: biop,
9525
- left,
9526
- right
9527
- };
9528
- stack.push(node);
9529
- }
9530
- node = this.gobbleToken();
9531
- if (!node) {
9532
- this.throwError("Expected expression after " + cur_biop);
9533
- }
9534
- stack.push(biop_info, node);
9535
- }
9536
- i = stack.length - 1;
9537
- node = stack[i];
9538
- while (i > 1) {
9539
- node = {
9540
- type: Jsep.BINARY_EXP,
9541
- operator: stack[i - 1].value,
9542
- left: stack[i - 2],
9543
- right: node
9544
- };
9545
- i -= 2;
9546
- }
9547
- return node;
9548
- }
9549
- gobbleToken() {
9550
- let ch, to_check, tc_len, node;
9551
- this.gobbleSpaces();
9552
- node = this.searchHook("gobble-token");
9553
- if (node) {
9554
- return this.runHook("after-token", node);
9555
- }
9556
- ch = this.code;
9557
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
9558
- return this.gobbleNumericLiteral();
9559
- }
9560
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
9561
- node = this.gobbleStringLiteral();
9562
- } else if (ch === Jsep.OBRACK_CODE) {
9563
- node = this.gobbleArray();
9564
- } else {
9565
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
9566
- tc_len = to_check.length;
9567
- while (tc_len > 0) {
9568
- 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)))) {
9569
- this.index += tc_len;
9570
- const argument = this.gobbleToken();
9571
- if (!argument) {
9572
- this.throwError("missing unaryOp argument");
9573
- }
9574
- return this.runHook("after-token", {
9575
- type: Jsep.UNARY_EXP,
9576
- operator: to_check,
9577
- argument,
9578
- prefix: true
9579
- });
9580
- }
9581
- to_check = to_check.substr(0, --tc_len);
9582
- }
9583
- if (Jsep.isIdentifierStart(ch)) {
9584
- node = this.gobbleIdentifier();
9585
- if (Jsep.literals.hasOwnProperty(node.name)) {
9586
- node = {
9587
- type: Jsep.LITERAL,
9588
- value: Jsep.literals[node.name],
9589
- raw: node.name
9590
- };
9591
- } else if (node.name === Jsep.this_str) {
9592
- node = {
9593
- type: Jsep.THIS_EXP
9594
- };
9595
- }
9596
- } else if (ch === Jsep.OPAREN_CODE) {
9597
- node = this.gobbleGroup();
9598
- }
9599
- }
9600
- if (!node) {
9601
- return this.runHook("after-token", false);
9602
- }
9603
- node = this.gobbleTokenProperty(node);
9604
- return this.runHook("after-token", node);
9605
- }
9606
- gobbleTokenProperty(node) {
9607
- this.gobbleSpaces();
9608
- let ch = this.code;
9609
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
9610
- let optional;
9611
- if (ch === Jsep.QUMARK_CODE) {
9612
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
9613
- break;
9614
- }
9615
- optional = true;
9616
- this.index += 2;
9617
- this.gobbleSpaces();
9618
- ch = this.code;
9619
- }
9620
- this.index++;
9621
- if (ch === Jsep.OBRACK_CODE) {
9622
- node = {
9623
- type: Jsep.MEMBER_EXP,
9624
- computed: true,
9625
- object: node,
9626
- property: this.gobbleExpression()
9627
- };
9628
- if (!node.property) {
9629
- this.throwError('Unexpected "' + this.char + '"');
9630
- }
9631
- this.gobbleSpaces();
9632
- ch = this.code;
9633
- if (ch !== Jsep.CBRACK_CODE) {
9634
- this.throwError("Unclosed [");
9635
- }
9636
- this.index++;
9637
- } else if (ch === Jsep.OPAREN_CODE) {
9638
- node = {
9639
- type: Jsep.CALL_EXP,
9640
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
9641
- callee: node
9642
- };
9643
- } else if (ch === Jsep.PERIOD_CODE || optional) {
9644
- if (optional) {
9645
- this.index--;
9646
- }
9647
- this.gobbleSpaces();
9648
- node = {
9649
- type: Jsep.MEMBER_EXP,
9650
- computed: false,
9651
- object: node,
9652
- property: this.gobbleIdentifier()
9653
- };
9654
- }
9655
- if (optional) {
9656
- node.optional = true;
9657
- }
9658
- this.gobbleSpaces();
9659
- ch = this.code;
9660
- }
9661
- return node;
9662
- }
9663
- gobbleNumericLiteral() {
9664
- let number = "", ch, chCode;
9665
- while (Jsep.isDecimalDigit(this.code)) {
9666
- number += this.expr.charAt(this.index++);
9667
- }
9668
- if (this.code === Jsep.PERIOD_CODE) {
9669
- number += this.expr.charAt(this.index++);
9670
- while (Jsep.isDecimalDigit(this.code)) {
9671
- number += this.expr.charAt(this.index++);
9672
- }
9673
- }
9674
- ch = this.char;
9675
- if (ch === "e" || ch === "E") {
9676
- number += this.expr.charAt(this.index++);
9677
- ch = this.char;
9678
- if (ch === "+" || ch === "-") {
9679
- number += this.expr.charAt(this.index++);
9680
- }
9681
- while (Jsep.isDecimalDigit(this.code)) {
9682
- number += this.expr.charAt(this.index++);
9683
- }
9684
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
9685
- this.throwError("Expected exponent (" + number + this.char + ")");
9686
- }
9687
- }
9688
- chCode = this.code;
9689
- if (Jsep.isIdentifierStart(chCode)) {
9690
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
9691
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
9692
- this.throwError("Unexpected period");
9693
- }
9694
- return {
9695
- type: Jsep.LITERAL,
9696
- value: parseFloat(number),
9697
- raw: number
9698
- };
9699
- }
9700
- gobbleStringLiteral() {
9701
- let str = "";
9702
- const startIndex = this.index;
9703
- const quote = this.expr.charAt(this.index++);
9704
- let closed = false;
9705
- while (this.index < this.expr.length) {
9706
- let ch = this.expr.charAt(this.index++);
9707
- if (ch === quote) {
9708
- closed = true;
9709
- break;
9710
- } else if (ch === "\\") {
9711
- ch = this.expr.charAt(this.index++);
9712
- switch (ch) {
9713
- case "n":
9714
- str += `
9715
- `;
9716
- break;
9717
- case "r":
9718
- str += "\r";
9719
- break;
9720
- case "t":
9721
- str += "\t";
9722
- break;
9723
- case "b":
9724
- str += "\b";
9725
- break;
9726
- case "f":
9727
- str += "\f";
9728
- break;
9729
- case "v":
9730
- str += "\v";
9731
- break;
9732
- default:
9733
- str += ch;
9734
- }
9735
- } else {
9736
- str += ch;
9737
- }
9738
- }
9739
- if (!closed) {
9740
- this.throwError('Unclosed quote after "' + str + '"');
9741
- }
9742
- return {
9743
- type: Jsep.LITERAL,
9744
- value: str,
9745
- raw: this.expr.substring(startIndex, this.index)
9746
- };
9747
- }
9748
- gobbleIdentifier() {
9749
- let ch = this.code, start = this.index;
9750
- if (Jsep.isIdentifierStart(ch)) {
9751
- this.index++;
9752
- } else {
9753
- this.throwError("Unexpected " + this.char);
9754
- }
9755
- while (this.index < this.expr.length) {
9756
- ch = this.code;
9757
- if (Jsep.isIdentifierPart(ch)) {
9758
- this.index++;
9759
- } else {
9760
- break;
9761
- }
9762
- }
9763
- return {
9764
- type: Jsep.IDENTIFIER,
9765
- name: this.expr.slice(start, this.index)
9766
- };
9767
- }
9768
- gobbleArguments(termination) {
9769
- const args = [];
9770
- let closed = false;
9771
- let separator_count = 0;
9772
- while (this.index < this.expr.length) {
9773
- this.gobbleSpaces();
9774
- let ch_i = this.code;
9775
- if (ch_i === termination) {
9776
- closed = true;
9777
- this.index++;
9778
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
9779
- this.throwError("Unexpected token " + String.fromCharCode(termination));
9780
- }
9781
- break;
9782
- } else if (ch_i === Jsep.COMMA_CODE) {
9783
- this.index++;
9784
- separator_count++;
9785
- if (separator_count !== args.length) {
9786
- if (termination === Jsep.CPAREN_CODE) {
9787
- this.throwError("Unexpected token ,");
9788
- } else if (termination === Jsep.CBRACK_CODE) {
9789
- for (let arg = args.length;arg < separator_count; arg++) {
9790
- args.push(null);
9791
- }
9792
- }
9793
- }
9794
- } else if (args.length !== separator_count && separator_count !== 0) {
9795
- this.throwError("Expected comma");
9796
- } else {
9797
- const node = this.gobbleExpression();
9798
- if (!node || node.type === Jsep.COMPOUND) {
9799
- this.throwError("Expected comma");
9800
- }
9801
- args.push(node);
9802
- }
9803
- }
9804
- if (!closed) {
9805
- this.throwError("Expected " + String.fromCharCode(termination));
9806
- }
9807
- return args;
9808
- }
9809
- gobbleGroup() {
9810
- this.index++;
9811
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
9812
- if (this.code === Jsep.CPAREN_CODE) {
9813
- this.index++;
9814
- if (nodes.length === 1) {
9815
- return nodes[0];
9816
- } else if (!nodes.length) {
9817
- return false;
9818
- } else {
9819
- return {
9820
- type: Jsep.SEQUENCE_EXP,
9821
- expressions: nodes
9822
- };
9823
- }
9824
- } else {
9825
- this.throwError("Unclosed (");
9826
- }
9827
- }
9828
- gobbleArray() {
9829
- this.index++;
9830
- return {
9831
- type: Jsep.ARRAY_EXP,
9832
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
9833
- };
9834
- }
9835
- }
9836
-
9837
- class SafeScript {
9838
- constructor(expr) {
9839
- this.code = expr;
9840
- this.ast = jsep(this.code);
9841
- }
9842
- runInNewContext(context) {
9843
- const keyMap = Object.assign(Object.create(null), context);
9844
- return SafeEval.evalAst(this.ast, keyMap);
9845
- }
9846
- }
9847
- function push(arr, item) {
9848
- arr = arr.slice();
9849
- arr.push(item);
9850
- return arr;
9851
- }
9852
- function unshift(item, arr) {
9853
- arr = arr.slice();
9854
- arr.unshift(item);
9855
- return arr;
9856
- }
9857
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
9858
- if (!(this instanceof JSONPath)) {
9859
- try {
9860
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
9861
- } catch (e) {
9862
- if (!e.avoidNew) {
9863
- throw e;
9864
- }
9865
- return e.value;
9866
- }
9867
- }
9868
- if (typeof opts === "string") {
9869
- otherTypeCallback = callback;
9870
- callback = obj;
9871
- obj = expr;
9872
- expr = opts;
9873
- opts = null;
9874
- }
9875
- const optObj = opts && typeof opts === "object";
9876
- opts = opts || {};
9877
- this.json = opts.json || obj;
9878
- this.path = opts.path || expr;
9879
- this.resultType = opts.resultType || "value";
9880
- this.flatten = opts.flatten || false;
9881
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
9882
- this.sandbox = opts.sandbox || {};
9883
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
9884
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
9885
- this.parent = opts.parent || null;
9886
- this.parentProperty = opts.parentProperty || null;
9887
- this.callback = opts.callback || callback || null;
9888
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
9889
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
9890
- };
9891
- if (opts.autostart !== false) {
9892
- const args = {
9893
- path: optObj ? opts.path : expr
9894
- };
9895
- if (!optObj) {
9896
- args.json = obj;
9897
- } else if ("json" in opts) {
9898
- args.json = opts.json;
9899
- }
9900
- const ret = this.evaluate(args);
9901
- if (!ret || typeof ret !== "object") {
9902
- throw new NewError(ret);
9903
- }
9904
- return ret;
9905
- }
9906
- }
9907
- var hooks, jsep = (expr) => new Jsep(expr).parse(), stdClassProps, CONDITIONAL_EXP = "ConditionalExpression", ternary, FSLASH_CODE = 47, BSLASH_CODE = 92, index, PLUS_CODE = 43, MINUS_CODE = 45, plugin, BLOCKED_PROTO_PROPERTIES, SafeEval, NewError;
9908
- var init_index_node_esm = __esm(() => {
9909
- hooks = new Hooks;
9910
- Object.assign(Jsep, {
9911
- hooks,
9912
- plugins: new Plugins(Jsep),
9913
- COMPOUND: "Compound",
9914
- SEQUENCE_EXP: "SequenceExpression",
9915
- IDENTIFIER: "Identifier",
9916
- MEMBER_EXP: "MemberExpression",
9917
- LITERAL: "Literal",
9918
- THIS_EXP: "ThisExpression",
9919
- CALL_EXP: "CallExpression",
9920
- UNARY_EXP: "UnaryExpression",
9921
- BINARY_EXP: "BinaryExpression",
9922
- ARRAY_EXP: "ArrayExpression",
9923
- TAB_CODE: 9,
9924
- LF_CODE: 10,
9925
- CR_CODE: 13,
9926
- SPACE_CODE: 32,
9927
- PERIOD_CODE: 46,
9928
- COMMA_CODE: 44,
9929
- SQUOTE_CODE: 39,
9930
- DQUOTE_CODE: 34,
9931
- OPAREN_CODE: 40,
9932
- CPAREN_CODE: 41,
9933
- OBRACK_CODE: 91,
9934
- CBRACK_CODE: 93,
9935
- QUMARK_CODE: 63,
9936
- SEMCOL_CODE: 59,
9937
- COLON_CODE: 58,
9938
- unary_ops: {
9939
- "-": 1,
9940
- "!": 1,
9941
- "~": 1,
9942
- "+": 1
9943
- },
9944
- binary_ops: {
9945
- "||": 1,
9946
- "??": 1,
9947
- "&&": 2,
9948
- "|": 3,
9949
- "^": 4,
9950
- "&": 5,
9951
- "==": 6,
9952
- "!=": 6,
9953
- "===": 6,
9954
- "!==": 6,
9955
- "<": 7,
9956
- ">": 7,
9957
- "<=": 7,
9958
- ">=": 7,
9959
- "<<": 8,
9960
- ">>": 8,
9961
- ">>>": 8,
9962
- "+": 9,
9963
- "-": 9,
9964
- "*": 10,
9965
- "/": 10,
9966
- "%": 10,
9967
- "**": 11
9968
- },
9969
- right_associative: new Set(["**"]),
9970
- additional_identifier_chars: new Set(["$", "_"]),
9971
- literals: {
9972
- true: true,
9973
- false: false,
9974
- null: null
9975
- },
9976
- this_str: "this"
9977
- });
9978
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
9979
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
9980
- stdClassProps = Object.getOwnPropertyNames(class Test {
9981
- });
9982
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
9983
- jsep[m] = Jsep[m];
9984
- });
9985
- jsep.Jsep = Jsep;
9986
- ternary = {
9987
- name: "ternary",
9988
- init(jsep2) {
9989
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
9990
- if (env.node && this.code === jsep2.QUMARK_CODE) {
9991
- this.index++;
9992
- const test = env.node;
9993
- const consequent = this.gobbleExpression();
9994
- if (!consequent) {
9995
- this.throwError("Expected expression");
9996
- }
9997
- this.gobbleSpaces();
9998
- if (this.code === jsep2.COLON_CODE) {
9999
- this.index++;
10000
- const alternate = this.gobbleExpression();
10001
- if (!alternate) {
10002
- this.throwError("Expected expression");
10003
- }
10004
- env.node = {
10005
- type: CONDITIONAL_EXP,
10006
- test,
10007
- consequent,
10008
- alternate
10009
- };
10010
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
10011
- let newTest = test;
10012
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
10013
- newTest = newTest.right;
10014
- }
10015
- env.node.test = newTest.right;
10016
- newTest.right = env.node;
10017
- env.node = test;
10018
- }
10019
- } else {
10020
- this.throwError("Expected :");
10021
- }
10022
- }
10023
- });
10024
- }
10025
- };
10026
- jsep.plugins.register(ternary);
10027
- index = {
10028
- name: "regex",
10029
- init(jsep2) {
10030
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
10031
- if (this.code === FSLASH_CODE) {
10032
- const patternIndex = ++this.index;
10033
- let inCharSet = false;
10034
- while (this.index < this.expr.length) {
10035
- if (this.code === FSLASH_CODE && !inCharSet) {
10036
- const pattern = this.expr.slice(patternIndex, this.index);
10037
- let flags = "";
10038
- while (++this.index < this.expr.length) {
10039
- const code = this.code;
10040
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
10041
- flags += this.char;
10042
- } else {
10043
- break;
10044
- }
10045
- }
10046
- let value;
10047
- try {
10048
- value = new RegExp(pattern, flags);
10049
- } catch (e) {
10050
- this.throwError(e.message);
10051
- }
10052
- env.node = {
10053
- type: jsep2.LITERAL,
10054
- value,
10055
- raw: this.expr.slice(patternIndex - 1, this.index)
10056
- };
10057
- env.node = this.gobbleTokenProperty(env.node);
10058
- return env.node;
10059
- }
10060
- if (this.code === jsep2.OBRACK_CODE) {
10061
- inCharSet = true;
10062
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
10063
- inCharSet = false;
10064
- }
10065
- this.index += this.code === BSLASH_CODE ? 2 : 1;
10066
- }
10067
- this.throwError("Unclosed Regex");
10068
- }
10069
- });
10070
- }
10071
- };
10072
- plugin = {
10073
- name: "assignment",
10074
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
10075
- updateOperators: [PLUS_CODE, MINUS_CODE],
10076
- assignmentPrecedence: 0.9,
10077
- init(jsep2) {
10078
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
10079
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
10080
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
10081
- const code = this.code;
10082
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
10083
- this.index += 2;
10084
- env.node = {
10085
- type: "UpdateExpression",
10086
- operator: code === PLUS_CODE ? "++" : "--",
10087
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
10088
- prefix: true
10089
- };
10090
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
10091
- this.throwError(`Unexpected ${env.node.operator}`);
10092
- }
10093
- }
10094
- });
10095
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
10096
- if (env.node) {
10097
- const code = this.code;
10098
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
10099
- if (!updateNodeTypes.includes(env.node.type)) {
10100
- this.throwError(`Unexpected ${env.node.operator}`);
10101
- }
10102
- this.index += 2;
10103
- env.node = {
10104
- type: "UpdateExpression",
10105
- operator: code === PLUS_CODE ? "++" : "--",
10106
- argument: env.node,
10107
- prefix: false
10108
- };
10109
- }
10110
- }
10111
- });
10112
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
10113
- if (env.node) {
10114
- updateBinariesToAssignments(env.node);
10115
- }
10116
- });
10117
- function updateBinariesToAssignments(node) {
10118
- if (plugin.assignmentOperators.has(node.operator)) {
10119
- node.type = "AssignmentExpression";
10120
- updateBinariesToAssignments(node.left);
10121
- updateBinariesToAssignments(node.right);
10122
- } else if (!node.operator) {
10123
- Object.values(node).forEach((val) => {
10124
- if (val && typeof val === "object") {
10125
- updateBinariesToAssignments(val);
10126
- }
10127
- });
10128
- }
10129
- }
10130
- }
10131
- };
10132
- jsep.plugins.register(index, plugin);
10133
- jsep.addUnaryOp("typeof");
10134
- jsep.addUnaryOp("void");
10135
- jsep.addLiteral("null", null);
10136
- jsep.addLiteral("undefined", undefined);
10137
- BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
10138
- SafeEval = {
10139
- evalAst(ast, subs) {
10140
- switch (ast.type) {
10141
- case "BinaryExpression":
10142
- case "LogicalExpression":
10143
- return SafeEval.evalBinaryExpression(ast, subs);
10144
- case "Compound":
10145
- return SafeEval.evalCompound(ast, subs);
10146
- case "ConditionalExpression":
10147
- return SafeEval.evalConditionalExpression(ast, subs);
10148
- case "Identifier":
10149
- return SafeEval.evalIdentifier(ast, subs);
10150
- case "Literal":
10151
- return SafeEval.evalLiteral(ast, subs);
10152
- case "MemberExpression":
10153
- return SafeEval.evalMemberExpression(ast, subs);
10154
- case "UnaryExpression":
10155
- return SafeEval.evalUnaryExpression(ast, subs);
10156
- case "ArrayExpression":
10157
- return SafeEval.evalArrayExpression(ast, subs);
10158
- case "CallExpression":
10159
- return SafeEval.evalCallExpression(ast, subs);
10160
- case "AssignmentExpression":
10161
- return SafeEval.evalAssignmentExpression(ast, subs);
10162
- default:
10163
- throw SyntaxError("Unexpected expression", ast);
10164
- }
10165
- },
10166
- evalBinaryExpression(ast, subs) {
10167
- const result = {
10168
- "||": (a, b) => a || b(),
10169
- "&&": (a, b) => a && b(),
10170
- "|": (a, b) => a | b(),
10171
- "^": (a, b) => a ^ b(),
10172
- "&": (a, b) => a & b(),
10173
- "==": (a, b) => a == b(),
10174
- "!=": (a, b) => a != b(),
10175
- "===": (a, b) => a === b(),
10176
- "!==": (a, b) => a !== b(),
10177
- "<": (a, b) => a < b(),
10178
- ">": (a, b) => a > b(),
10179
- "<=": (a, b) => a <= b(),
10180
- ">=": (a, b) => a >= b(),
10181
- "<<": (a, b) => a << b(),
10182
- ">>": (a, b) => a >> b(),
10183
- ">>>": (a, b) => a >>> b(),
10184
- "+": (a, b) => a + b(),
10185
- "-": (a, b) => a - b(),
10186
- "*": (a, b) => a * b(),
10187
- "/": (a, b) => a / b(),
10188
- "%": (a, b) => a % b()
10189
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
10190
- return result;
10191
- },
10192
- evalCompound(ast, subs) {
10193
- let last;
10194
- for (let i = 0;i < ast.body.length; i++) {
10195
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
10196
- i += 1;
10197
- }
10198
- const expr = ast.body[i];
10199
- last = SafeEval.evalAst(expr, subs);
10200
- }
10201
- return last;
10202
- },
10203
- evalConditionalExpression(ast, subs) {
10204
- if (SafeEval.evalAst(ast.test, subs)) {
10205
- return SafeEval.evalAst(ast.consequent, subs);
10206
- }
10207
- return SafeEval.evalAst(ast.alternate, subs);
10208
- },
10209
- evalIdentifier(ast, subs) {
10210
- if (Object.hasOwn(subs, ast.name)) {
10211
- return subs[ast.name];
10212
- }
10213
- throw ReferenceError(`${ast.name} is not defined`);
10214
- },
10215
- evalLiteral(ast) {
10216
- return ast.value;
10217
- },
10218
- evalMemberExpression(ast, subs) {
10219
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
10220
- const obj = SafeEval.evalAst(ast.object, subs);
10221
- if (obj === undefined || obj === null) {
10222
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
10223
- }
10224
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
10225
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
10226
- }
10227
- const result = obj[prop];
10228
- if (typeof result === "function") {
10229
- return result.bind(obj);
10230
- }
10231
- return result;
10232
- },
10233
- evalUnaryExpression(ast, subs) {
10234
- const result = {
10235
- "-": (a) => -SafeEval.evalAst(a, subs),
10236
- "!": (a) => !SafeEval.evalAst(a, subs),
10237
- "~": (a) => ~SafeEval.evalAst(a, subs),
10238
- "+": (a) => +SafeEval.evalAst(a, subs),
10239
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
10240
- void: (a) => void SafeEval.evalAst(a, subs)
10241
- }[ast.operator](ast.argument);
10242
- return result;
10243
- },
10244
- evalArrayExpression(ast, subs) {
10245
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
10246
- },
10247
- evalCallExpression(ast, subs) {
10248
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
10249
- const func = SafeEval.evalAst(ast.callee, subs);
10250
- if (func === Function) {
10251
- throw new Error("Function constructor is disabled");
10252
- }
10253
- return func(...args);
10254
- },
10255
- evalAssignmentExpression(ast, subs) {
10256
- if (ast.left.type !== "Identifier") {
10257
- throw SyntaxError("Invalid left-hand side in assignment");
10258
- }
10259
- const id = ast.left.name;
10260
- const value = SafeEval.evalAst(ast.right, subs);
10261
- subs[id] = value;
10262
- return subs[id];
10263
- }
10264
- };
10265
- NewError = class NewError extends Error {
10266
- constructor(value) {
10267
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
10268
- this.avoidNew = true;
10269
- this.value = value;
10270
- this.name = "NewError";
10271
- }
10272
- };
10273
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
10274
- let currParent = this.parent, currParentProperty = this.parentProperty;
10275
- let {
10276
- flatten,
10277
- wrap
10278
- } = this;
10279
- this.currResultType = this.resultType;
10280
- this.currEval = this.eval;
10281
- this.currSandbox = this.sandbox;
10282
- callback = callback || this.callback;
10283
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
10284
- json = json || this.json;
10285
- expr = expr || this.path;
10286
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
10287
- if (!expr.path && expr.path !== "") {
10288
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
10289
- }
10290
- if (!Object.hasOwn(expr, "json")) {
10291
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
10292
- }
10293
- ({
10294
- json
10295
- } = expr);
10296
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
10297
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
10298
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
10299
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
10300
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
10301
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
10302
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
10303
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
10304
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
10305
- expr = expr.path;
10306
- }
10307
- currParent = currParent || null;
10308
- currParentProperty = currParentProperty || null;
10309
- if (Array.isArray(expr)) {
10310
- expr = JSONPath.toPathString(expr);
10311
- }
10312
- if (!expr && expr !== "" || !json) {
10313
- return;
10314
- }
10315
- const exprList = JSONPath.toPathArray(expr);
10316
- if (exprList[0] === "$" && exprList.length > 1) {
10317
- exprList.shift();
10318
- }
10319
- this._hasParentSelector = null;
10320
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
10321
- return ea && !ea.isParentSelector;
10322
- });
10323
- if (!result.length) {
10324
- return wrap ? [] : undefined;
10325
- }
10326
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
10327
- return this._getPreferredOutput(result[0]);
10328
- }
10329
- return result.reduce((rslt, ea) => {
10330
- const valOrPath = this._getPreferredOutput(ea);
10331
- if (flatten && Array.isArray(valOrPath)) {
10332
- rslt = rslt.concat(valOrPath);
10333
- } else {
10334
- rslt.push(valOrPath);
10335
- }
10336
- return rslt;
10337
- }, []);
10338
- };
10339
- JSONPath.prototype._getPreferredOutput = function(ea) {
10340
- const resultType = this.currResultType;
10341
- switch (resultType) {
10342
- case "all": {
10343
- const path4 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
10344
- ea.pointer = JSONPath.toPointer(path4);
10345
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
10346
- return ea;
10347
- }
10348
- case "value":
10349
- case "parent":
10350
- case "parentProperty":
10351
- return ea[resultType];
10352
- case "path":
10353
- return JSONPath.toPathString(ea[resultType]);
10354
- case "pointer":
10355
- return JSONPath.toPointer(ea.path);
10356
- default:
10357
- throw new TypeError("Unknown result type");
10358
- }
10359
- };
10360
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
10361
- if (callback) {
10362
- const preferredOutput = this._getPreferredOutput(fullRetObj);
10363
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
10364
- callback(preferredOutput, type, fullRetObj);
10365
- }
10366
- };
10367
- JSONPath.prototype._trace = function(expr, val, path4, parent, parentPropName, callback, hasArrExpr, literalPriority) {
10368
- let retObj;
10369
- if (!expr.length) {
10370
- retObj = {
10371
- path: path4,
10372
- value: val,
10373
- parent,
10374
- parentProperty: parentPropName,
10375
- hasArrExpr
10376
- };
10377
- this._handleCallback(retObj, callback, "value");
10378
- return retObj;
10379
- }
10380
- const loc = expr[0], x = expr.slice(1);
10381
- const ret = [];
10382
- function addRet(elems) {
10383
- if (Array.isArray(elems)) {
10384
- elems.forEach((t) => {
10385
- ret.push(t);
10386
- });
10387
- } else {
10388
- ret.push(elems);
10389
- }
10390
- }
10391
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
10392
- addRet(this._trace(x, val[loc], push(path4, loc), val, loc, callback, hasArrExpr));
10393
- } else if (loc === "*") {
10394
- this._walk(val, (m) => {
10395
- addRet(this._trace(x, val[m], push(path4, m), val, m, callback, true, true));
10396
- });
10397
- } else if (loc === "..") {
10398
- addRet(this._trace(x, val, path4, parent, parentPropName, callback, hasArrExpr));
10399
- this._walk(val, (m) => {
10400
- if (typeof val[m] === "object") {
10401
- addRet(this._trace(expr.slice(), val[m], push(path4, m), val, m, callback, true));
10402
- }
10403
- });
10404
- } else if (loc === "^") {
10405
- this._hasParentSelector = true;
10406
- return {
10407
- path: path4.slice(0, -1),
10408
- expr: x,
10409
- isParentSelector: true
10410
- };
10411
- } else if (loc === "~") {
10412
- retObj = {
10413
- path: push(path4, loc),
10414
- value: parentPropName,
10415
- parent,
10416
- parentProperty: null
10417
- };
10418
- this._handleCallback(retObj, callback, "property");
10419
- return retObj;
10420
- } else if (loc === "$") {
10421
- addRet(this._trace(x, val, path4, null, null, callback, hasArrExpr));
10422
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
10423
- addRet(this._slice(loc, x, val, path4, parent, parentPropName, callback));
10424
- } else if (loc.indexOf("?(") === 0) {
10425
- if (this.currEval === false) {
10426
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
10427
- }
10428
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
10429
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
10430
- if (nested) {
10431
- this._walk(val, (m) => {
10432
- const npath = [nested[2]];
10433
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
10434
- const filterResults = this._trace(npath, nvalue, path4, parent, parentPropName, callback, true);
10435
- if (filterResults.length > 0) {
10436
- addRet(this._trace(x, val[m], push(path4, m), val, m, callback, true));
10437
- }
10438
- });
10439
- } else {
10440
- this._walk(val, (m) => {
10441
- if (this._eval(safeLoc, val[m], m, path4, parent, parentPropName)) {
10442
- addRet(this._trace(x, val[m], push(path4, m), val, m, callback, true));
10443
- }
10444
- });
10445
- }
10446
- } else if (loc[0] === "(") {
10447
- if (this.currEval === false) {
10448
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
10449
- }
10450
- addRet(this._trace(unshift(this._eval(loc, val, path4.at(-1), path4.slice(0, -1), parent, parentPropName), x), val, path4, parent, parentPropName, callback, hasArrExpr));
10451
- } else if (loc[0] === "@") {
10452
- let addType = false;
10453
- const valueType = loc.slice(1, -2);
10454
- switch (valueType) {
10455
- case "scalar":
10456
- if (!val || !["object", "function"].includes(typeof val)) {
10457
- addType = true;
10458
- }
10459
- break;
10460
- case "boolean":
10461
- case "string":
10462
- case "undefined":
10463
- case "function":
10464
- if (typeof val === valueType) {
10465
- addType = true;
10466
- }
10467
- break;
10468
- case "integer":
10469
- if (Number.isFinite(val) && !(val % 1)) {
10470
- addType = true;
10471
- }
10472
- break;
10473
- case "number":
10474
- if (Number.isFinite(val)) {
10475
- addType = true;
10476
- }
10477
- break;
10478
- case "nonFinite":
10479
- if (typeof val === "number" && !Number.isFinite(val)) {
10480
- addType = true;
10481
- }
10482
- break;
10483
- case "object":
10484
- if (val && typeof val === valueType) {
10485
- addType = true;
10486
- }
10487
- break;
10488
- case "array":
10489
- if (Array.isArray(val)) {
10490
- addType = true;
10491
- }
10492
- break;
10493
- case "other":
10494
- addType = this.currOtherTypeCallback(val, path4, parent, parentPropName);
10495
- break;
10496
- case "null":
10497
- if (val === null) {
10498
- addType = true;
10499
- }
10500
- break;
10501
- default:
10502
- throw new TypeError("Unknown value type " + valueType);
10503
- }
10504
- if (addType) {
10505
- retObj = {
10506
- path: path4,
10507
- value: val,
10508
- parent,
10509
- parentProperty: parentPropName
10510
- };
10511
- this._handleCallback(retObj, callback, "value");
10512
- return retObj;
10513
- }
10514
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
10515
- const locProp = loc.slice(1);
10516
- addRet(this._trace(x, val[locProp], push(path4, locProp), val, locProp, callback, hasArrExpr, true));
10517
- } else if (loc.includes(",")) {
10518
- const parts = loc.split(",");
10519
- for (const part of parts) {
10520
- addRet(this._trace(unshift(part, x), val, path4, parent, parentPropName, callback, true));
10521
- }
10522
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
10523
- addRet(this._trace(x, val[loc], push(path4, loc), val, loc, callback, hasArrExpr, true));
10524
- }
10525
- if (this._hasParentSelector) {
10526
- for (let t = 0;t < ret.length; t++) {
10527
- const rett = ret[t];
10528
- if (rett && rett.isParentSelector) {
10529
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
10530
- if (Array.isArray(tmp)) {
10531
- ret[t] = tmp[0];
10532
- const tl = tmp.length;
10533
- for (let tt = 1;tt < tl; tt++) {
10534
- t++;
10535
- ret.splice(t, 0, tmp[tt]);
10536
- }
10537
- } else {
10538
- ret[t] = tmp;
10539
- }
10540
- }
10541
- }
10542
- }
10543
- return ret;
10544
- };
10545
- JSONPath.prototype._walk = function(val, f) {
10546
- if (Array.isArray(val)) {
10547
- const n = val.length;
10548
- for (let i = 0;i < n; i++) {
10549
- f(i);
10550
- }
10551
- } else if (val && typeof val === "object") {
10552
- Object.keys(val).forEach((m) => {
10553
- f(m);
10554
- });
10555
- }
10556
- };
10557
- JSONPath.prototype._slice = function(loc, expr, val, path4, parent, parentPropName, callback) {
10558
- if (!Array.isArray(val)) {
10559
- return;
10560
- }
10561
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
10562
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
10563
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
10564
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
10565
- const ret = [];
10566
- for (let i = start;i < end; i += step) {
10567
- const tmp = this._trace(unshift(i, expr), val, path4, parent, parentPropName, callback, true);
10568
- tmp.forEach((t) => {
10569
- ret.push(t);
10570
- });
10571
- }
10572
- return ret;
10573
- };
10574
- JSONPath.prototype._eval = function(code, _v, _vname, path4, parent, parentPropName) {
10575
- this.currSandbox._$_parentProperty = parentPropName;
10576
- this.currSandbox._$_parent = parent;
10577
- this.currSandbox._$_property = _vname;
10578
- this.currSandbox._$_root = this.json;
10579
- this.currSandbox._$_v = _v;
10580
- const containsPath = code.includes("@path");
10581
- if (containsPath) {
10582
- this.currSandbox._$_path = JSONPath.toPathString(path4.concat([_vname]));
10583
- }
10584
- const scriptCacheKey = this.currEval + "Script:" + code;
10585
- if (!JSONPath.cache[scriptCacheKey]) {
10586
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
10587
- if (containsPath) {
10588
- script = script.replaceAll("@path", "_$_path");
10589
- }
10590
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
10591
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
10592
- } else if (this.currEval === "native") {
10593
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
10594
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
10595
- const CurrEval = this.currEval;
10596
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
10597
- } else if (typeof this.currEval === "function") {
10598
- JSONPath.cache[scriptCacheKey] = {
10599
- runInNewContext: (context) => this.currEval(script, context)
10600
- };
10601
- } else {
10602
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
10603
- }
10604
- }
10605
- try {
10606
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
10607
- } catch (e) {
10608
- if (this.ignoreEvalErrors) {
10609
- return false;
10610
- }
10611
- throw new Error("jsonPath: " + e.message + ": " + code);
10612
- }
10613
- };
10614
- JSONPath.cache = {};
10615
- JSONPath.toPathString = function(pathArr) {
10616
- const x = pathArr, n = x.length;
10617
- let p = "$";
10618
- for (let i = 1;i < n; i++) {
10619
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
10620
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
10621
- }
10622
- }
10623
- return p;
10624
- };
10625
- JSONPath.toPointer = function(pointer) {
10626
- const x = pointer, n = x.length;
10627
- let p = "";
10628
- for (let i = 1;i < n; i++) {
10629
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
10630
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
10631
- }
10632
- }
10633
- return p;
10634
- };
10635
- JSONPath.toPathArray = function(expr) {
10636
- const {
10637
- cache
10638
- } = JSONPath;
10639
- if (cache[expr]) {
10640
- return cache[expr].concat();
10641
- }
10642
- const subx = [];
10643
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
10644
- return "[#" + (subx.push($1) - 1) + "]";
10645
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
10646
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
10647
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
10648
- return ";" + ups.split("").join(";") + ";";
10649
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
10650
- const exprList = normalized.split(";").map(function(exp) {
10651
- const match = exp.match(/#(\d+)/u);
10652
- return !match || !match[1] ? exp : subx[match[1]];
10653
- });
10654
- cache[expr] = exprList;
10655
- return cache[expr].concat();
10656
- };
10657
- JSONPath.prototype.safeVm = {
10658
- Script: SafeScript
10659
- };
10660
- JSONPath.prototype.vm = vm;
10661
- });
10662
-
10663
- // ../common/src/jsonpath.ts
10664
- var init_jsonpath = __esm(() => {
10665
- init_index_node_esm();
10666
- });
10667
-
10668
9383
  // ../common/src/option-aliases.ts
10669
9384
  function resolveDeprecatedOptionAlias({
10670
9385
  preferredValue,
@@ -10779,6 +9494,23 @@ var init_polling = __esm(() => {
10779
9494
  init_types();
10780
9495
  });
10781
9496
 
9497
+ // ../common/src/preview.ts
9498
+ function isPreviewBuild() {
9499
+ return previewSlot.get(false) ?? false;
9500
+ }
9501
+ var previewSlot;
9502
+ var init_preview = __esm(() => {
9503
+ init_esm();
9504
+ init_singleton();
9505
+ previewSlot = singleton2("PreviewBuild");
9506
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
9507
+ if (isPreviewBuild()) {
9508
+ return this.command(nameAndArgs, opts);
9509
+ }
9510
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
9511
+ };
9512
+ });
9513
+
10782
9514
  // ../common/src/screen-logger.ts
10783
9515
  var ScreenLogger;
10784
9516
  var init_screen_logger = __esm(() => {
@@ -10813,8 +9545,8 @@ function appendUserAgentToken2(value, userAgent) {
10813
9545
  function getEffectiveUserAgent2(userAgent) {
10814
9546
  return appendUserAgentToken2(sdkUserAgentHostToken2.get(), userAgent);
10815
9547
  }
10816
- function isHeadersLike2(headers) {
10817
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
9548
+ function getHeaderName2(headers, headerName) {
9549
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
10818
9550
  }
10819
9551
  function getSdkUserAgentToken2(pkg) {
10820
9552
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -10822,59 +9554,31 @@ function getSdkUserAgentToken2(pkg) {
10822
9554
  }
10823
9555
  function addSdkUserAgentHeader2(headers, userAgent) {
10824
9556
  const result = { ...headers ?? {} };
10825
- const effectiveUserAgent = getEffectiveUserAgent2(userAgent);
10826
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER2.toLowerCase());
10827
- if (headerName) {
10828
- result[headerName] = appendUserAgentToken2(result[headerName], effectiveUserAgent);
10829
- } else {
10830
- result[USER_AGENT_HEADER2] = effectiveUserAgent;
10831
- }
9557
+ const headerName = getHeaderName2(result, USER_AGENT_HEADER2);
9558
+ result[headerName ?? USER_AGENT_HEADER2] = appendUserAgentToken2(headerName ? result[headerName] : undefined, getEffectiveUserAgent2(userAgent));
10832
9559
  return result;
10833
9560
  }
10834
- function withSdkUserAgentHeader2(headers, userAgent) {
10835
- const effectiveUserAgent = getEffectiveUserAgent2(userAgent);
10836
- if (isHeadersLike2(headers)) {
10837
- headers.set(USER_AGENT_HEADER2, appendUserAgentToken2(headers.get(USER_AGENT_HEADER2), effectiveUserAgent));
10838
- return headers;
10839
- }
10840
- if (Array.isArray(headers)) {
10841
- const result = headers.map((entry) => {
10842
- const [key, value] = entry;
10843
- return [key, value];
10844
- });
10845
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER2.toLowerCase());
10846
- if (headerIndex >= 0) {
10847
- const [key, value] = result[headerIndex];
10848
- result[headerIndex] = [
10849
- key,
10850
- appendUserAgentToken2(value, effectiveUserAgent)
10851
- ];
10852
- } else {
10853
- result.push([USER_AGENT_HEADER2, effectiveUserAgent]);
10854
- }
10855
- return result;
10856
- }
10857
- return addSdkUserAgentHeader2(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
9561
+ function asHeaderRecord2(headers) {
9562
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
10858
9563
  }
10859
- function withUserAgentInitOverride2(initOverrides, userAgent) {
9564
+ function withForwardedHeadersInitOverride2(initOverrides, forward) {
10860
9565
  return async (requestContext) => {
10861
- const initWithUserAgent = {
9566
+ const initWithHeaders = {
10862
9567
  ...requestContext.init,
10863
- headers: withSdkUserAgentHeader2(requestContext.init.headers, userAgent)
9568
+ headers: forward(asHeaderRecord2(requestContext.init.headers))
10864
9569
  };
10865
9570
  const override = typeof initOverrides === "function" ? await initOverrides({
10866
9571
  ...requestContext,
10867
- init: initWithUserAgent
9572
+ init: initWithHeaders
10868
9573
  }) : initOverrides;
10869
9574
  return {
10870
9575
  ...override ?? {},
10871
- headers: withSdkUserAgentHeader2(override?.headers ?? initWithUserAgent.headers, userAgent)
9576
+ headers: forward(asHeaderRecord2(override?.headers ?? initWithHeaders.headers))
10872
9577
  };
10873
9578
  };
10874
9579
  }
10875
- function installSdkUserAgentHeader2(BaseApiClass, userAgent) {
9580
+ function installRequestHeaderForwarding2(BaseApiClass, patchKey, forward) {
10876
9581
  const prototype = BaseApiClass.prototype;
10877
- const patchKey = userAgentPatchKey2(userAgent);
10878
9582
  if (prototype[patchKey]) {
10879
9583
  return;
10880
9584
  }
@@ -10882,16 +9586,20 @@ function installSdkUserAgentHeader2(BaseApiClass, userAgent) {
10882
9586
  throw new Error("Generated BaseAPI request function not found.");
10883
9587
  }
10884
9588
  const originalRequest = prototype.request;
10885
- prototype.request = function requestWithUserAgent(context, initOverrides) {
10886
- return originalRequest.call(this, context, withUserAgentInitOverride2(initOverrides, userAgent));
9589
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
9590
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride2(initOverrides, forward));
10887
9591
  };
10888
9592
  Object.defineProperty(prototype, patchKey, {
10889
9593
  value: true
10890
9594
  });
10891
9595
  }
9596
+ function installSdkUserAgentHeader2(BaseApiClass, userAgent) {
9597
+ installRequestHeaderForwarding2(BaseApiClass, userAgentPatchKey2(userAgent), (headers) => addSdkUserAgentHeader2(headers, userAgent));
9598
+ }
10892
9599
  var USER_AGENT_HEADER2 = "User-Agent", sdkUserAgentHostToken2;
10893
9600
  var init_sdk_user_agent = __esm(() => {
10894
9601
  init_singleton();
9602
+ init_global_telemetry_properties();
10895
9603
  sdkUserAgentHostToken2 = singleton2("SdkUserAgentHostToken");
10896
9604
  });
10897
9605
  // ../common/src/tool-provider.ts
@@ -10912,16 +9620,17 @@ var init_src3 = __esm(() => {
10912
9620
  init_confirmation();
10913
9621
  init_constants2();
10914
9622
  init_error_handler();
9623
+ init_error_instructions();
10915
9624
  init_formatter();
10916
9625
  init_guid();
10917
9626
  init_interactivity_context();
10918
- init_jsonpath();
10919
9627
  init_logger();
10920
9628
  init_option_aliases();
10921
9629
  init_option_validators();
10922
9630
  init_output_context();
10923
9631
  init_output_format_context();
10924
9632
  init_polling();
9633
+ init_preview();
10925
9634
  init_registry();
10926
9635
  init_screen_logger();
10927
9636
  init_sdk_user_agent();
@@ -11233,7 +9942,7 @@ var init_package = __esm(() => {
11233
9942
  package_default3 = {
11234
9943
  name: "@uipath/orchestrator-sdk",
11235
9944
  license: "MIT",
11236
- version: "1.196.0",
9945
+ version: "1.197.0",
11237
9946
  repository: {
11238
9947
  type: "git",
11239
9948
  url: "https://github.com/UiPath/cli.git",
@@ -11267,7 +9976,7 @@ var init_package = __esm(() => {
11267
9976
  ],
11268
9977
  private: true,
11269
9978
  scripts: {
11270
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && bun build ./src/index.browser.ts --outdir dist --format esm --target browser --external @uipath/auth --external @uipath/common && tsc -p tsconfig.build.json --noCheck",
9979
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && bun build ./src/index.browser.ts --outdir dist --format esm --target browser --external @uipath/auth --external @uipath/common --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
11271
9980
  generate: "bun run src/scripts/generate-sdk.ts",
11272
9981
  lint: "biome check .",
11273
9982
  test: "vitest run",
@@ -45734,7 +44443,7 @@ var init_constants3 = __esm(() => {
45734
44443
  });
45735
44444
 
45736
44445
  // ../auth/src/config.ts
45737
- var DEFAULT_CLIENT_ID2 = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00", AUTH_FILE_CONFIG_KEY2, globalSlot2, getAuthFileConfig2 = () => globalSlot2[AUTH_FILE_CONFIG_KEY2] ?? {}, InvalidBaseUrlError2, DEFAULT_SCOPES2, normalizeAndValidateBaseUrl2 = (rawUrl) => {
44446
+ var DEFAULT_CLIENT_ID2 = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00", AUTH_FILE_CONFIG_KEY2, globalSlot3, getAuthFileConfig2 = () => globalSlot3[AUTH_FILE_CONFIG_KEY2] ?? {}, InvalidBaseUrlError2, DEFAULT_SCOPES2, normalizeAndValidateBaseUrl2 = (rawUrl) => {
45738
44447
  let baseUrl = rawUrl;
45739
44448
  if (baseUrl.endsWith("/identity_/")) {
45740
44449
  baseUrl = baseUrl.slice(0, -11);
@@ -45753,6 +44462,11 @@ var DEFAULT_CLIENT_ID2 = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00", AUTH_FILE_CONFI
45753
44462
  throw new InvalidBaseUrlError2(baseUrl, `Authority must use https:// scheme, got ${url.protocol}//. OIDC token exchange requires TLS end-to-end.`);
45754
44463
  }
45755
44464
  return url.pathname.length > 1 ? url.origin : baseUrl;
44465
+ }, resolveScopes2 = (isExternalAppAuth, customScopes, fileScopes) => {
44466
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
44467
+ if (isExternalAppAuth)
44468
+ return requestedScopes;
44469
+ return [...new Set([...DEFAULT_SCOPES2, ...requestedScopes])];
45756
44470
  }, resolveConfigAsync2 = async ({
45757
44471
  customAuthority,
45758
44472
  customClientId,
@@ -45783,7 +44497,7 @@ var DEFAULT_CLIENT_ID2 = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00", AUTH_FILE_CONFI
45783
44497
  clientSecret = fileAuth.clientSecret;
45784
44498
  }
45785
44499
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID2 && Boolean(clientSecret);
45786
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES2;
44500
+ const scopes = resolveScopes2(isExternalAppAuth, customScopes, fileAuth.scopes);
45787
44501
  return {
45788
44502
  clientId,
45789
44503
  clientSecret,
@@ -45796,7 +44510,7 @@ var DEFAULT_CLIENT_ID2 = "36dea5b8-e8bb-423d-8e7b-c808df8f1c00", AUTH_FILE_CONFI
45796
44510
  var init_config = __esm(() => {
45797
44511
  init_constants3();
45798
44512
  AUTH_FILE_CONFIG_KEY2 = Symbol.for("@uipath/auth/AuthFileConfig");
45799
- globalSlot2 = globalThis;
44513
+ globalSlot3 = globalThis;
45800
44514
  InvalidBaseUrlError2 = class InvalidBaseUrlError2 extends Error {
45801
44515
  url;
45802
44516
  reason;
@@ -45824,6 +44538,76 @@ function isBrowser2() {
45824
44538
  return typeof globalThis !== "undefined" && "window" in globalThis && "document" in globalThis;
45825
44539
  }
45826
44540
 
44541
+ // ../auth/src/authProfile.ts
44542
+ function isAuthProfileStorage2(value) {
44543
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
44544
+ }
44545
+ function createProfileStorage2() {
44546
+ const [error, mod2] = catchError3(() => __require("node:async_hooks"));
44547
+ if (error || typeof mod2?.AsyncLocalStorage !== "function") {
44548
+ return {
44549
+ getStore: () => {
44550
+ return;
44551
+ },
44552
+ run: (_store, fn) => fn()
44553
+ };
44554
+ }
44555
+ return new mod2.AsyncLocalStorage;
44556
+ }
44557
+ function getProfileStorage2() {
44558
+ const existing = globalSlot5[AUTH_PROFILE_STORAGE_KEY2];
44559
+ if (isAuthProfileStorage2(existing)) {
44560
+ return existing;
44561
+ }
44562
+ const storage = createProfileStorage2();
44563
+ globalSlot5[AUTH_PROFILE_STORAGE_KEY2] = storage;
44564
+ return storage;
44565
+ }
44566
+ function normalizeAuthProfileName2(profile) {
44567
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE2) {
44568
+ return;
44569
+ }
44570
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE2.test(profile)) {
44571
+ throw new AuthProfileValidationError2(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
44572
+ }
44573
+ return profile;
44574
+ }
44575
+ function getActiveAuthProfile2() {
44576
+ const scopedState = profileStorage2.getStore();
44577
+ if (scopedState !== undefined) {
44578
+ return scopedState.profile;
44579
+ }
44580
+ return globalSlot5[ACTIVE_AUTH_PROFILE_KEY2]?.profile;
44581
+ }
44582
+ function resolveAuthProfileFilePath2(profile) {
44583
+ const normalized = normalizeAuthProfileName2(profile);
44584
+ if (normalized === undefined) {
44585
+ throw new AuthProfileValidationError2(`"${DEFAULT_AUTH_PROFILE2}" is the built-in profile and does not have a profile file path.`);
44586
+ }
44587
+ const fs8 = getFileSystem2();
44588
+ return fs8.path.join(fs8.env.homedir(), UIPATH_HOME_DIR2, PROFILE_DIR2, normalized, AUTH_FILENAME2);
44589
+ }
44590
+ function getActiveAuthProfileFilePath2() {
44591
+ const profile = getActiveAuthProfile2();
44592
+ return profile ? resolveAuthProfileFilePath2(profile) : undefined;
44593
+ }
44594
+ var DEFAULT_AUTH_PROFILE2 = "default", PROFILE_DIR2 = "profiles", PROFILE_NAME_RE2, ACTIVE_AUTH_PROFILE_KEY2, AUTH_PROFILE_STORAGE_KEY2, globalSlot5, profileStorage2, AuthProfileValidationError2;
44595
+ var init_authProfile = __esm(() => {
44596
+ init_src2();
44597
+ init_constants3();
44598
+ PROFILE_NAME_RE2 = /^[A-Za-z0-9._-]+$/;
44599
+ ACTIVE_AUTH_PROFILE_KEY2 = Symbol.for("@uipath/auth/ActiveAuthProfile");
44600
+ AUTH_PROFILE_STORAGE_KEY2 = Symbol.for("@uipath/auth/ProfileStorage");
44601
+ globalSlot5 = globalThis;
44602
+ profileStorage2 = getProfileStorage2();
44603
+ AuthProfileValidationError2 = class AuthProfileValidationError2 extends Error {
44604
+ constructor(message) {
44605
+ super(message);
44606
+ this.name = "AuthProfileValidationError";
44607
+ }
44608
+ };
44609
+ });
44610
+
45827
44611
  // ../auth/src/utils/jwt.ts
45828
44612
  var InvalidIssuerError2, parseJWT2 = (token) => {
45829
44613
  try {
@@ -45933,11 +44717,13 @@ var ENV_AUTH_ENABLE_VAR2 = "UIPATH_CLI_ENABLE_ENV_AUTH", ENFORCE_ROBOT_AUTH_VAR2
45933
44717
  organizationId,
45934
44718
  tenantName,
45935
44719
  tenantId,
45936
- expiration
44720
+ expiration,
44721
+ source: "env" /* Env */
45937
44722
  };
45938
44723
  };
45939
44724
  var init_envAuth = __esm(() => {
45940
44725
  init_config();
44726
+ init_loginStatus();
45941
44727
  init_jwt();
45942
44728
  ENV_AUTH_VARS2 = {
45943
44729
  token: "UIPATH_CLI_AUTH_TOKEN",
@@ -45954,6 +44740,66 @@ var init_envAuth = __esm(() => {
45954
44740
  };
45955
44741
  });
45956
44742
 
44743
+ // ../auth/src/refreshCircuitBreaker.ts
44744
+ async function refreshTokenFingerprint2(refreshToken) {
44745
+ const bytes = new TextEncoder().encode(refreshToken);
44746
+ if (globalThis.crypto?.subtle) {
44747
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
44748
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
44749
+ }
44750
+ const { createHash } = await import("node:crypto");
44751
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
44752
+ }
44753
+ function breakerPathFor2(authPath) {
44754
+ return `${authPath}${BREAKER_SUFFIX2}`;
44755
+ }
44756
+ async function loadRefreshBreaker2(authPath) {
44757
+ const fs8 = getFileSystem2();
44758
+ try {
44759
+ const content = await fs8.readFile(breakerPathFor2(authPath), "utf-8");
44760
+ if (!content)
44761
+ return {};
44762
+ const parsed = JSON.parse(content);
44763
+ return parsed && typeof parsed === "object" ? parsed : {};
44764
+ } catch {
44765
+ return {};
44766
+ }
44767
+ }
44768
+ async function saveRefreshBreaker2(authPath, state) {
44769
+ try {
44770
+ const fs8 = getFileSystem2();
44771
+ const path4 = breakerPathFor2(authPath);
44772
+ await fs8.mkdir(fs8.path.dirname(path4));
44773
+ const tempPath = `${path4}.tmp`;
44774
+ await fs8.writeFile(tempPath, JSON.stringify(state));
44775
+ await fs8.rename(tempPath, path4);
44776
+ } catch {}
44777
+ }
44778
+ async function clearRefreshBreaker2(authPath) {
44779
+ const fs8 = getFileSystem2();
44780
+ const path4 = breakerPathFor2(authPath);
44781
+ try {
44782
+ if (await fs8.exists(path4)) {
44783
+ await fs8.rm(path4);
44784
+ }
44785
+ } catch {}
44786
+ }
44787
+ function nextBackoffMs2(attempts) {
44788
+ const shift = Math.max(0, attempts - 1);
44789
+ return Math.min(BACKOFF_BASE_MS2 * 2 ** shift, BACKOFF_CAP_MS2);
44790
+ }
44791
+ function shouldSurface2(state, nowMs) {
44792
+ if (state.lastSurfacedAtMs === undefined)
44793
+ return true;
44794
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS2;
44795
+ }
44796
+ var BREAKER_SUFFIX2 = ".refresh-state", BACKOFF_BASE_MS2 = 60000, BACKOFF_CAP_MS2, SURFACE_WINDOW_MS2;
44797
+ var init_refreshCircuitBreaker = __esm(() => {
44798
+ init_src2();
44799
+ BACKOFF_CAP_MS2 = 60 * 60 * 1000;
44800
+ SURFACE_WINDOW_MS2 = 60 * 60 * 1000;
44801
+ });
44802
+
45957
44803
  // ../../node_modules/@uipath/coreipc/index.js
45958
44804
  var require_coreipc2 = __commonJS((exports, module) => {
45959
44805
  var __dirname = "/home/runner/work/cli/cli/node_modules/@uipath/coreipc";
@@ -56446,8 +55292,8 @@ var require_Subscription2 = __commonJS((exports) => {
56446
55292
  if (_parentOrParents instanceof Subscription2) {
56447
55293
  _parentOrParents.remove(this);
56448
55294
  } else if (_parentOrParents !== null) {
56449
- for (var index2 = 0;index2 < _parentOrParents.length; ++index2) {
56450
- var parent_1 = _parentOrParents[index2];
55295
+ for (var index = 0;index < _parentOrParents.length; ++index) {
55296
+ var parent_1 = _parentOrParents[index];
56451
55297
  parent_1.remove(this);
56452
55298
  }
56453
55299
  }
@@ -56462,10 +55308,10 @@ var require_Subscription2 = __commonJS((exports) => {
56462
55308
  }
56463
55309
  }
56464
55310
  if (isArray_1.isArray(_subscriptions)) {
56465
- var index2 = -1;
55311
+ var index = -1;
56466
55312
  var len = _subscriptions.length;
56467
- while (++index2 < len) {
56468
- var sub2 = _subscriptions[index2];
55313
+ while (++index < len) {
55314
+ var sub2 = _subscriptions[index];
56469
55315
  if (isObject_1.isObject(sub2)) {
56470
55316
  try {
56471
55317
  sub2.unsubscribe();
@@ -57895,13 +56741,13 @@ var require_AsyncAction2 = __commonJS((exports) => {
57895
56741
  var id = this.id;
57896
56742
  var scheduler = this.scheduler;
57897
56743
  var actions = scheduler.actions;
57898
- var index2 = actions.indexOf(this);
56744
+ var index = actions.indexOf(this);
57899
56745
  this.work = null;
57900
56746
  this.state = null;
57901
56747
  this.pending = false;
57902
56748
  this.scheduler = null;
57903
- if (index2 !== -1) {
57904
- actions.splice(index2, 1);
56749
+ if (index !== -1) {
56750
+ actions.splice(index, 1);
57905
56751
  }
57906
56752
  if (id != null) {
57907
56753
  this.id = this.recycleAsyncId(scheduler, id, null);
@@ -58745,17 +57591,17 @@ var require_AsapScheduler2 = __commonJS((exports) => {
58745
57591
  this.scheduled = undefined;
58746
57592
  var actions = this.actions;
58747
57593
  var error;
58748
- var index2 = -1;
57594
+ var index = -1;
58749
57595
  var count = actions.length;
58750
57596
  action = action || actions.shift();
58751
57597
  do {
58752
57598
  if (error = action.execute(action.state, action.delay)) {
58753
57599
  break;
58754
57600
  }
58755
- } while (++index2 < count && (action = actions.shift()));
57601
+ } while (++index < count && (action = actions.shift()));
58756
57602
  this.active = false;
58757
57603
  if (error) {
58758
- while (++index2 < count && (action = actions.shift())) {
57604
+ while (++index < count && (action = actions.shift())) {
58759
57605
  action.unsubscribe();
58760
57606
  }
58761
57607
  throw error;
@@ -58878,17 +57724,17 @@ var require_AnimationFrameScheduler2 = __commonJS((exports) => {
58878
57724
  this.scheduled = undefined;
58879
57725
  var actions = this.actions;
58880
57726
  var error;
58881
- var index2 = -1;
57727
+ var index = -1;
58882
57728
  var count = actions.length;
58883
57729
  action = action || actions.shift();
58884
57730
  do {
58885
57731
  if (error = action.execute(action.state, action.delay)) {
58886
57732
  break;
58887
57733
  }
58888
- } while (++index2 < count && (action = actions.shift()));
57734
+ } while (++index < count && (action = actions.shift()));
58889
57735
  this.active = false;
58890
57736
  if (error) {
58891
- while (++index2 < count && (action = actions.shift())) {
57737
+ while (++index < count && (action = actions.shift())) {
58892
57738
  action.unsubscribe();
58893
57739
  }
58894
57740
  throw error;
@@ -58972,16 +57818,16 @@ var require_VirtualTimeScheduler2 = __commonJS((exports) => {
58972
57818
  exports.VirtualTimeScheduler = VirtualTimeScheduler;
58973
57819
  var VirtualAction = function(_super) {
58974
57820
  __extends(VirtualAction2, _super);
58975
- function VirtualAction2(scheduler, work, index2) {
58976
- if (index2 === undefined) {
58977
- index2 = scheduler.index += 1;
57821
+ function VirtualAction2(scheduler, work, index) {
57822
+ if (index === undefined) {
57823
+ index = scheduler.index += 1;
58978
57824
  }
58979
57825
  var _this = _super.call(this, scheduler, work) || this;
58980
57826
  _this.scheduler = scheduler;
58981
57827
  _this.work = work;
58982
- _this.index = index2;
57828
+ _this.index = index;
58983
57829
  _this.active = true;
58984
- _this.index = scheduler.index = index2;
57830
+ _this.index = scheduler.index = index;
58985
57831
  return _this;
58986
57832
  }
58987
57833
  VirtualAction2.prototype.schedule = function(state, delay) {
@@ -60128,9 +58974,9 @@ var require_mergeMap2 = __commonJS((exports) => {
60128
58974
  };
60129
58975
  MergeMapSubscriber2.prototype._tryNext = function(value) {
60130
58976
  var result;
60131
- var index2 = this.index++;
58977
+ var index = this.index++;
60132
58978
  try {
60133
- result = this.project(value, index2);
58979
+ result = this.project(value, index);
60134
58980
  } catch (err) {
60135
58981
  this.destination.error(err);
60136
58982
  return;
@@ -60710,12 +59556,12 @@ var require_pairs3 = __commonJS((exports) => {
60710
59556
  }
60711
59557
  exports.pairs = pairs;
60712
59558
  function dispatch(state) {
60713
- var { keys, index: index2, subscriber, subscription, obj } = state;
59559
+ var { keys, index, subscriber, subscription, obj } = state;
60714
59560
  if (!subscriber.closed) {
60715
- if (index2 < keys.length) {
60716
- var key = keys[index2];
59561
+ if (index < keys.length) {
59562
+ var key = keys[index];
60717
59563
  subscriber.next([key, obj[key]]);
60718
- subscription.add(this.schedule({ keys, index: index2 + 1, subscriber, subscription, obj }));
59564
+ subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
60719
59565
  } else {
60720
59566
  subscriber.complete();
60721
59567
  }
@@ -60928,18 +59774,18 @@ var require_range2 = __commonJS((exports) => {
60928
59774
  count = start;
60929
59775
  start = 0;
60930
59776
  }
60931
- var index2 = 0;
59777
+ var index = 0;
60932
59778
  var current = start;
60933
59779
  if (scheduler) {
60934
59780
  return scheduler.schedule(dispatch, 0, {
60935
- index: index2,
59781
+ index,
60936
59782
  count,
60937
59783
  start,
60938
59784
  subscriber
60939
59785
  });
60940
59786
  } else {
60941
59787
  do {
60942
- if (index2++ >= count) {
59788
+ if (index++ >= count) {
60943
59789
  subscriber.complete();
60944
59790
  break;
60945
59791
  }
@@ -60954,8 +59800,8 @@ var require_range2 = __commonJS((exports) => {
60954
59800
  }
60955
59801
  exports.range = range;
60956
59802
  function dispatch(state) {
60957
- var { start, index: index2, count, subscriber } = state;
60958
- if (index2 >= count) {
59803
+ var { start, index, count, subscriber } = state;
59804
+ if (index >= count) {
60959
59805
  subscriber.complete();
60960
59806
  return;
60961
59807
  }
@@ -60963,7 +59809,7 @@ var require_range2 = __commonJS((exports) => {
60963
59809
  if (subscriber.closed) {
60964
59810
  return;
60965
59811
  }
60966
- state.index = index2 + 1;
59812
+ state.index = index + 1;
60967
59813
  state.start = start + 1;
60968
59814
  this.schedule(state);
60969
59815
  }
@@ -61001,14 +59847,14 @@ var require_timer2 = __commonJS((exports) => {
61001
59847
  }
61002
59848
  exports.timer = timer;
61003
59849
  function dispatch(state) {
61004
- var { index: index2, period, subscriber } = state;
61005
- subscriber.next(index2);
59850
+ var { index, period, subscriber } = state;
59851
+ subscriber.next(index);
61006
59852
  if (subscriber.closed) {
61007
59853
  return;
61008
59854
  } else if (period === -1) {
61009
59855
  return subscriber.complete();
61010
59856
  }
61011
- state.index = index2 + 1;
59857
+ state.index = index + 1;
61012
59858
  this.schedule(state, period);
61013
59859
  }
61014
59860
  });
@@ -64150,14 +62996,7 @@ var require_dist2 = __commonJS((exports) => {
64150
62996
  });
64151
62997
 
64152
62998
  // ../auth/src/robotClientFallback.ts
64153
- var DEFAULT_TIMEOUT_MS2 = 1000, CLOSE_TIMEOUT_MS2 = 500, NOTICE_SENTINEL2, printNoticeOnce2 = () => {
64154
- const slot = globalThis;
64155
- if (slot[NOTICE_SENTINEL2])
64156
- return;
64157
- slot[NOTICE_SENTINEL2] = true;
64158
- catchError3(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
64159
- `));
64160
- }, ROBOT_USER_SERVICES_PIPE2 = "UiPathUserServices", ROBOT_USER_SERVICES_ALTERNATE_PIPE2, PIPE_NAME_MAX_LENGTH2 = 103, getRobotIpcPipeNames2 = async () => {
62999
+ var DEFAULT_TIMEOUT_MS2 = 1000, CLOSE_TIMEOUT_MS2 = 500, ROBOT_USER_SERVICES_PIPE2 = "UiPathUserServices", ROBOT_USER_SERVICES_ALTERNATE_PIPE2, PIPE_NAME_MAX_LENGTH2 = 103, getRobotIpcPipeNames2 = async () => {
64161
63000
  const fs8 = getFileSystem2();
64162
63001
  const username = fs8.env.getenv("USER") ?? fs8.env.getenv("USERNAME");
64163
63002
  if (!username) {
@@ -64264,7 +63103,6 @@ var DEFAULT_TIMEOUT_MS2 = 1000, CLOSE_TIMEOUT_MS2 = 500, NOTICE_SENTINEL2, print
64264
63103
  issuerFromToken = issClaim;
64265
63104
  }
64266
63105
  }
64267
- printNoticeOnce2();
64268
63106
  return {
64269
63107
  accessToken,
64270
63108
  baseUrl: parsedUrl.baseUrl,
@@ -64283,7 +63121,6 @@ var DEFAULT_TIMEOUT_MS2 = 1000, CLOSE_TIMEOUT_MS2 = 500, NOTICE_SENTINEL2, print
64283
63121
  var init_robotClientFallback = __esm(() => {
64284
63122
  init_src2();
64285
63123
  init_jwt();
64286
- NOTICE_SENTINEL2 = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
64287
63124
  ROBOT_USER_SERVICES_ALTERNATE_PIPE2 = `${ROBOT_USER_SERVICES_PIPE2}Alternate`;
64288
63125
  });
64289
63126
 
@@ -64493,18 +63330,245 @@ var init_envFile = __esm(() => {
64493
63330
  });
64494
63331
 
64495
63332
  // ../auth/src/loginStatus.ts
64496
- function normalizeTokenRefreshFailure2() {
64497
- return "stored refresh token is invalid or expired";
63333
+ async function resolveRobotEnforcedStatus2(robotFallback) {
63334
+ if (isEnvAuthEnabled2()) {
63335
+ throw new EnvAuthConfigError2(`${ENV_AUTH_ENABLE_VAR2}=true and ${ENFORCE_ROBOT_AUTH_VAR2}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
63336
+ }
63337
+ const robotCreds = await robotFallback({ force: true });
63338
+ if (!robotCreds) {
63339
+ return {
63340
+ loginStatus: "Not logged in",
63341
+ hint: `${ENFORCE_ROBOT_AUTH_VAR2}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR2} to fall back to file or ` + `env-var authentication.`
63342
+ };
63343
+ }
63344
+ return buildRobotStatus2(robotCreds);
64498
63345
  }
64499
- function normalizeTokenRefreshUnavailableFailure2() {
64500
- return "token refresh failed before authentication completed";
63346
+ async function resolveBorrowedRobotStatus2(robotFallback) {
63347
+ const robotCreds = await robotFallback();
63348
+ return robotCreds ? buildRobotStatus2(robotCreds) : { loginStatus: "Not logged in" };
64501
63349
  }
64502
- function errorMessage2(error) {
64503
- return error instanceof Error ? error.message : String(error);
63350
+ async function loadFileCredentials2(loadEnvFile, absolutePath) {
63351
+ let credentials;
63352
+ try {
63353
+ credentials = await loadEnvFile({ envPath: absolutePath });
63354
+ } catch (error) {
63355
+ if (isFileNotFoundError2(error)) {
63356
+ return { status: { loginStatus: "Not logged in" } };
63357
+ }
63358
+ throw error;
63359
+ }
63360
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
63361
+ return { status: { loginStatus: "Not logged in" } };
63362
+ }
63363
+ return { credentials };
63364
+ }
63365
+ async function getGlobalCredsHint2(getFs, loadEnvFile, absolutePath, envFilePath) {
63366
+ const fs8 = getFs();
63367
+ const globalPath = fs8.path.join(fs8.env.homedir(), envFilePath);
63368
+ if (absolutePath === globalPath)
63369
+ return;
63370
+ if (!await fs8.exists(globalPath))
63371
+ return;
63372
+ try {
63373
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
63374
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
63375
+ return;
63376
+ const globalExp = getTokenExpiration2(globalCreds.UIPATH_ACCESS_TOKEN);
63377
+ if (globalExp && globalExp <= new Date)
63378
+ return;
63379
+ 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.`;
63380
+ } catch {
63381
+ return;
63382
+ }
64504
63383
  }
64505
63384
  function computeExpirationThreshold2(ensureTokenValidityMinutes) {
64506
63385
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
64507
63386
  }
63387
+ async function attemptRefresh2(ctx) {
63388
+ const shortCircuit = await circuitBreakerShortCircuit2(ctx);
63389
+ if (shortCircuit) {
63390
+ return { kind: "terminal", status: shortCircuit };
63391
+ }
63392
+ let release;
63393
+ try {
63394
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
63395
+ } catch (error) {
63396
+ return {
63397
+ kind: "terminal",
63398
+ status: await lockAcquireFailureStatus2(ctx, error)
63399
+ };
63400
+ }
63401
+ let lockedFailure;
63402
+ let lockReleaseFailed = false;
63403
+ let success;
63404
+ try {
63405
+ const outcome = await runRefreshLocked2({
63406
+ absolutePath: ctx.absolutePath,
63407
+ refreshToken: ctx.refreshToken,
63408
+ customAuthority: ctx.credentials.UIPATH_URL,
63409
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
63410
+ loadEnvFile: ctx.loadEnvFile,
63411
+ saveEnvFile: ctx.saveEnvFile,
63412
+ refreshFn: ctx.refreshFn,
63413
+ resolveConfig: ctx.resolveConfig,
63414
+ loadBreaker: ctx.loadBreaker,
63415
+ saveBreaker: ctx.saveBreaker,
63416
+ clearBreaker: ctx.clearBreaker
63417
+ });
63418
+ if (outcome.kind === "fail") {
63419
+ lockedFailure = outcome.status;
63420
+ } else {
63421
+ success = outcome;
63422
+ }
63423
+ } finally {
63424
+ try {
63425
+ await release();
63426
+ } catch {
63427
+ lockReleaseFailed = true;
63428
+ }
63429
+ }
63430
+ if (lockedFailure) {
63431
+ const globalHint = await ctx.globalHint();
63432
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
63433
+ return {
63434
+ kind: "terminal",
63435
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
63436
+ };
63437
+ }
63438
+ return {
63439
+ kind: "refreshed",
63440
+ tokens: {
63441
+ accessToken: success?.accessToken,
63442
+ refreshToken: success?.refreshToken,
63443
+ expiration: success?.expiration,
63444
+ tokenRefresh: success?.tokenRefresh,
63445
+ persistenceWarning: success?.persistenceWarning,
63446
+ lockReleaseFailed
63447
+ }
63448
+ };
63449
+ }
63450
+ async function buildFileStatus2(tokens, credentials, globalHint) {
63451
+ const result = {
63452
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
63453
+ accessToken: tokens.accessToken,
63454
+ refreshToken: tokens.refreshToken,
63455
+ baseUrl: credentials.UIPATH_URL,
63456
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
63457
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
63458
+ tenantName: credentials.UIPATH_TENANT_NAME,
63459
+ tenantId: credentials.UIPATH_TENANT_ID,
63460
+ expiration: tokens.expiration,
63461
+ source: "file" /* File */,
63462
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
63463
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
63464
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
63465
+ };
63466
+ if (result.loginStatus === "Expired") {
63467
+ const hint = await globalHint();
63468
+ if (hint) {
63469
+ result.hint = hint;
63470
+ }
63471
+ }
63472
+ return result;
63473
+ }
63474
+ function buildRobotStatus2(robotCreds) {
63475
+ return {
63476
+ loginStatus: "Logged in",
63477
+ accessToken: robotCreds.accessToken,
63478
+ baseUrl: robotCreds.baseUrl,
63479
+ organizationName: robotCreds.organizationName,
63480
+ organizationId: robotCreds.organizationId,
63481
+ tenantName: robotCreds.tenantName,
63482
+ tenantId: robotCreds.tenantId,
63483
+ issuer: robotCreds.issuer,
63484
+ expiration: getTokenExpiration2(robotCreds.accessToken),
63485
+ source: "robot" /* Robot */
63486
+ };
63487
+ }
63488
+ async function circuitBreakerShortCircuit2(ctx) {
63489
+ const {
63490
+ absolutePath,
63491
+ refreshToken,
63492
+ accessToken,
63493
+ credentials,
63494
+ expiration,
63495
+ loadBreaker,
63496
+ saveBreaker,
63497
+ clearBreaker
63498
+ } = ctx;
63499
+ const fingerprint = await refreshTokenFingerprint2(refreshToken);
63500
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
63501
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
63502
+ await clearBreaker(absolutePath);
63503
+ breaker.deadTokenFp = undefined;
63504
+ }
63505
+ const nowMs = Date.now();
63506
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
63507
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
63508
+ if (!tokenIsDead && !inBackoff)
63509
+ return;
63510
+ const globalHint = await ctx.globalHint();
63511
+ const suppressed = !shouldSurface2(breaker, nowMs);
63512
+ if (!suppressed) {
63513
+ await saveBreaker(absolutePath, {
63514
+ ...breaker,
63515
+ lastSurfacedAtMs: nowMs
63516
+ });
63517
+ }
63518
+ 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>.";
63519
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
63520
+ return {
63521
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
63522
+ ...globalHint ? {
63523
+ accessToken,
63524
+ refreshToken,
63525
+ baseUrl: credentials.UIPATH_URL,
63526
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
63527
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
63528
+ tenantName: credentials.UIPATH_TENANT_NAME,
63529
+ tenantId: credentials.UIPATH_TENANT_ID,
63530
+ expiration,
63531
+ source: "file" /* File */
63532
+ } : {},
63533
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
63534
+ refreshCircuitOpen: true,
63535
+ refreshTelemetrySuppressed: suppressed,
63536
+ tokenRefresh: { attempted: false, success: false }
63537
+ };
63538
+ }
63539
+ async function lockAcquireFailureStatus2(ctx, error) {
63540
+ const msg = errorMessage2(error);
63541
+ const globalHint = await ctx.globalHint();
63542
+ if (globalHint) {
63543
+ return {
63544
+ loginStatus: "Expired",
63545
+ accessToken: ctx.accessToken,
63546
+ refreshToken: ctx.refreshToken,
63547
+ baseUrl: ctx.credentials.UIPATH_URL,
63548
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
63549
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
63550
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
63551
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
63552
+ expiration: ctx.expiration,
63553
+ source: "file" /* File */,
63554
+ hint: globalHint,
63555
+ tokenRefresh: {
63556
+ attempted: false,
63557
+ success: false,
63558
+ errorMessage: `lock acquisition failed: ${msg}`
63559
+ }
63560
+ };
63561
+ }
63562
+ return {
63563
+ loginStatus: "Refresh Failed",
63564
+ 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.",
63565
+ tokenRefresh: {
63566
+ attempted: false,
63567
+ success: false,
63568
+ errorMessage: `lock acquisition failed: ${msg}`
63569
+ }
63570
+ };
63571
+ }
64508
63572
  async function runRefreshLocked2(inputs) {
64509
63573
  const {
64510
63574
  absolutePath,
@@ -64514,7 +63578,10 @@ async function runRefreshLocked2(inputs) {
64514
63578
  loadEnvFile,
64515
63579
  saveEnvFile,
64516
63580
  refreshFn,
64517
- resolveConfig
63581
+ resolveConfig,
63582
+ loadBreaker,
63583
+ saveBreaker,
63584
+ clearBreaker
64518
63585
  } = inputs;
64519
63586
  const expirationThreshold = computeExpirationThreshold2(ensureTokenValidityMinutes);
64520
63587
  let fresh;
@@ -64537,6 +63604,7 @@ async function runRefreshLocked2(inputs) {
64537
63604
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
64538
63605
  const freshExp = freshAccess ? getTokenExpiration2(freshAccess) : undefined;
64539
63606
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
63607
+ await clearBreaker(absolutePath);
64540
63608
  return {
64541
63609
  kind: "ok",
64542
63610
  accessToken: freshAccess,
@@ -64560,8 +63628,21 @@ async function runRefreshLocked2(inputs) {
64560
63628
  refreshedRefresh = refreshed.refreshToken;
64561
63629
  } catch (error) {
64562
63630
  const isOAuthFailure = isTokenRefreshOAuthFailure2(error);
64563
- 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.";
63631
+ 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.";
64564
63632
  const message = isOAuthFailure ? normalizeTokenRefreshFailure2() : normalizeTokenRefreshUnavailableFailure2();
63633
+ const fp = await refreshTokenFingerprint2(tokenForIdP);
63634
+ if (isOAuthFailure) {
63635
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
63636
+ } else {
63637
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
63638
+ const attempts = (prior.attempts ?? 0) + 1;
63639
+ await saveBreaker(absolutePath, {
63640
+ ...prior,
63641
+ deadTokenFp: undefined,
63642
+ attempts,
63643
+ backoffUntilMs: Date.now() + nextBackoffMs2(attempts)
63644
+ });
63645
+ }
64565
63646
  return {
64566
63647
  kind: "fail",
64567
63648
  status: {
@@ -64590,6 +63671,7 @@ async function runRefreshLocked2(inputs) {
64590
63671
  }
64591
63672
  };
64592
63673
  }
63674
+ await clearBreaker(absolutePath);
64593
63675
  try {
64594
63676
  await saveEnvFile({
64595
63677
  envPath: absolutePath,
@@ -64622,7 +63704,18 @@ async function runRefreshLocked2(inputs) {
64622
63704
  };
64623
63705
  }
64624
63706
  }
64625
- var getLoginStatusWithDeps2 = async (options = {}, deps = {}) => {
63707
+ function normalizeTokenRefreshFailure2() {
63708
+ return "stored refresh token is invalid or expired";
63709
+ }
63710
+ function normalizeTokenRefreshUnavailableFailure2() {
63711
+ return "token refresh failed before authentication completed";
63712
+ }
63713
+ function errorMessage2(error) {
63714
+ return error instanceof Error ? error.message : String(error);
63715
+ }
63716
+ var getLoginStatusAsync2 = async (options = {}) => {
63717
+ return getLoginStatusWithDeps2(options);
63718
+ }, getLoginStatusWithDeps2 = async (options = {}, deps = {}) => {
64626
63719
  const {
64627
63720
  resolveEnvFilePath = resolveEnvFilePathAsync2,
64628
63721
  loadEnvFile = loadEnvFileAsync2,
@@ -64630,206 +63723,82 @@ var getLoginStatusWithDeps2 = async (options = {}, deps = {}) => {
64630
63723
  getFs = getFileSystem2,
64631
63724
  refreshToken: refreshTokenFn = refreshAccessToken2,
64632
63725
  resolveConfig = resolveConfigAsync2,
64633
- robotFallback = tryRobotClientFallback2
63726
+ robotFallback = tryRobotClientFallback2,
63727
+ loadBreaker = loadRefreshBreaker2,
63728
+ saveBreaker = saveRefreshBreaker2,
63729
+ clearBreaker = clearRefreshBreaker2
64634
63730
  } = deps;
64635
63731
  if (isRobotAuthEnforced2()) {
64636
- if (isEnvAuthEnabled2()) {
64637
- throw new EnvAuthConfigError2(`${ENV_AUTH_ENABLE_VAR2}=true and ${ENFORCE_ROBOT_AUTH_VAR2}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
64638
- }
64639
- const robotCreds = await robotFallback({ force: true });
64640
- if (!robotCreds) {
64641
- return {
64642
- loginStatus: "Not logged in",
64643
- hint: `${ENFORCE_ROBOT_AUTH_VAR2}=true but the UiPath Robot ` + `session is unavailable. Start and sign in to the Assistant, ` + `or unset ${ENFORCE_ROBOT_AUTH_VAR2} to fall back to file or ` + `env-var authentication.`
64644
- };
64645
- }
64646
- const expiration2 = getTokenExpiration2(robotCreds.accessToken);
64647
- return {
64648
- loginStatus: "Logged in",
64649
- accessToken: robotCreds.accessToken,
64650
- baseUrl: robotCreds.baseUrl,
64651
- organizationName: robotCreds.organizationName,
64652
- organizationId: robotCreds.organizationId,
64653
- tenantName: robotCreds.tenantName,
64654
- tenantId: robotCreds.tenantId,
64655
- issuer: robotCreds.issuer,
64656
- expiration: expiration2,
64657
- source: "robot" /* Robot */
64658
- };
63732
+ return resolveRobotEnforcedStatus2(robotFallback);
64659
63733
  }
64660
63734
  if (isEnvAuthEnabled2()) {
64661
63735
  return readAuthFromEnv2();
64662
63736
  }
64663
- const { envFilePath = DEFAULT_ENV_FILENAME2, ensureTokenValidityMinutes } = options;
63737
+ const activeProfile = getActiveAuthProfile2();
63738
+ const activeProfileFilePath = getActiveAuthProfileFilePath2();
63739
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
63740
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME2;
63741
+ const { ensureTokenValidityMinutes } = options;
64664
63742
  const { absolutePath } = await resolveEnvFilePath(envFilePath);
64665
63743
  if (absolutePath === undefined) {
64666
- const robotCreds = await robotFallback();
64667
- if (robotCreds) {
64668
- const expiration2 = getTokenExpiration2(robotCreds.accessToken);
64669
- const status = {
64670
- loginStatus: "Logged in",
64671
- accessToken: robotCreds.accessToken,
64672
- baseUrl: robotCreds.baseUrl,
64673
- organizationName: robotCreds.organizationName,
64674
- organizationId: robotCreds.organizationId,
64675
- tenantName: robotCreds.tenantName,
64676
- tenantId: robotCreds.tenantId,
64677
- issuer: robotCreds.issuer,
64678
- expiration: expiration2,
64679
- source: "robot" /* Robot */
64680
- };
64681
- return status;
64682
- }
64683
- return { loginStatus: "Not logged in" };
64684
- }
64685
- let credentials;
64686
- try {
64687
- credentials = await loadEnvFile({ envPath: absolutePath });
64688
- } catch (error) {
64689
- if (isFileNotFoundError2(error)) {
64690
- return { loginStatus: "Not logged in" };
64691
- }
64692
- throw error;
64693
- }
64694
- if (!credentials.UIPATH_ACCESS_TOKEN) {
64695
- return { loginStatus: "Not logged in" };
64696
- }
64697
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
64698
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
64699
- let expiration = getTokenExpiration2(accessToken);
64700
- let persistenceWarning;
64701
- let lockReleaseFailed = false;
64702
- let tokenRefresh;
64703
- const outerThreshold = computeExpirationThreshold2(ensureTokenValidityMinutes);
64704
- const tryGlobalCredsHint = async () => {
64705
- const fs8 = getFs();
64706
- const globalPath = fs8.path.join(fs8.env.homedir(), envFilePath);
64707
- if (absolutePath === globalPath)
64708
- return;
64709
- if (!await fs8.exists(globalPath))
64710
- return;
64711
- try {
64712
- const globalCreds = await loadEnvFile({ envPath: globalPath });
64713
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
64714
- return;
64715
- const globalExp = getTokenExpiration2(globalCreds.UIPATH_ACCESS_TOKEN);
64716
- if (globalExp && globalExp <= new Date)
64717
- return;
64718
- 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.`;
64719
- } catch {
64720
- return;
64721
- }
64722
- };
64723
- if (expiration && expiration <= outerThreshold && refreshToken) {
64724
- let release;
64725
- try {
64726
- release = await getFs().acquireLock(absolutePath);
64727
- } catch (error) {
64728
- const msg = errorMessage2(error);
64729
- const globalHint = await tryGlobalCredsHint();
64730
- if (globalHint) {
64731
- return {
64732
- loginStatus: "Expired",
64733
- accessToken,
64734
- refreshToken,
64735
- baseUrl: credentials.UIPATH_URL,
64736
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
64737
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
64738
- tenantName: credentials.UIPATH_TENANT_NAME,
64739
- tenantId: credentials.UIPATH_TENANT_ID,
64740
- expiration,
64741
- source: "file" /* File */,
64742
- hint: globalHint,
64743
- tokenRefresh: {
64744
- attempted: false,
64745
- success: false,
64746
- errorMessage: `lock acquisition failed: ${msg}`
64747
- }
64748
- };
64749
- }
63744
+ if (usingActiveProfile) {
64750
63745
  return {
64751
- loginStatus: "Refresh Failed",
64752
- 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.",
64753
- tokenRefresh: {
64754
- attempted: false,
64755
- success: false,
64756
- errorMessage: `lock acquisition failed: ${msg}`
64757
- }
63746
+ loginStatus: "Not logged in",
63747
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
64758
63748
  };
64759
63749
  }
64760
- let lockedFailure;
64761
- try {
64762
- const outcome = await runRefreshLocked2({
64763
- absolutePath,
64764
- refreshToken,
64765
- customAuthority: credentials.UIPATH_URL,
64766
- ensureTokenValidityMinutes,
64767
- loadEnvFile,
64768
- saveEnvFile,
64769
- refreshFn: refreshTokenFn,
64770
- resolveConfig
64771
- });
64772
- if (outcome.kind === "fail") {
64773
- lockedFailure = outcome.status;
64774
- } else {
64775
- accessToken = outcome.accessToken;
64776
- refreshToken = outcome.refreshToken;
64777
- expiration = outcome.expiration;
64778
- tokenRefresh = outcome.tokenRefresh;
64779
- if (outcome.persistenceWarning) {
64780
- persistenceWarning = outcome.persistenceWarning;
64781
- }
64782
- }
64783
- } finally {
64784
- try {
64785
- await release();
64786
- } catch {
64787
- lockReleaseFailed = true;
64788
- }
64789
- }
64790
- if (lockedFailure) {
64791
- const globalHint = await tryGlobalCredsHint();
64792
- const base = globalHint ? {
64793
- ...lockedFailure,
64794
- loginStatus: "Expired",
64795
- hint: globalHint
64796
- } : lockedFailure;
64797
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
64798
- }
63750
+ return resolveBorrowedRobotStatus2(robotFallback);
64799
63751
  }
64800
- const result = {
64801
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
64802
- accessToken,
64803
- refreshToken,
64804
- baseUrl: credentials.UIPATH_URL,
64805
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
64806
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
64807
- tenantName: credentials.UIPATH_TENANT_NAME,
64808
- tenantId: credentials.UIPATH_TENANT_ID,
63752
+ const loaded = await loadFileCredentials2(loadEnvFile, absolutePath);
63753
+ if ("status" in loaded) {
63754
+ return loaded.status;
63755
+ }
63756
+ const { credentials } = loaded;
63757
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint2(getFs, loadEnvFile, absolutePath, envFilePath);
63758
+ const expiration = getTokenExpiration2(credentials.UIPATH_ACCESS_TOKEN);
63759
+ const outerThreshold = computeExpirationThreshold2(ensureTokenValidityMinutes);
63760
+ let tokens = {
63761
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
63762
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
64809
63763
  expiration,
64810
- source: "file" /* File */,
64811
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
64812
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
64813
- ...tokenRefresh ? { tokenRefresh } : {}
63764
+ lockReleaseFailed: false
64814
63765
  };
64815
- if (result.loginStatus === "Expired") {
64816
- const globalHint = await tryGlobalCredsHint();
64817
- if (globalHint) {
64818
- result.hint = globalHint;
63766
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
63767
+ if (expiration && expiration <= outerThreshold && refreshToken) {
63768
+ const refreshed = await attemptRefresh2({
63769
+ absolutePath,
63770
+ credentials,
63771
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
63772
+ refreshToken,
63773
+ expiration,
63774
+ ensureTokenValidityMinutes,
63775
+ getFs,
63776
+ loadEnvFile,
63777
+ saveEnvFile,
63778
+ refreshFn: refreshTokenFn,
63779
+ resolveConfig,
63780
+ loadBreaker,
63781
+ saveBreaker,
63782
+ clearBreaker,
63783
+ globalHint
63784
+ });
63785
+ if (refreshed.kind === "terminal") {
63786
+ return refreshed.status;
64819
63787
  }
63788
+ tokens = refreshed.tokens;
64820
63789
  }
64821
- return result;
63790
+ return buildFileStatus2(tokens, credentials, globalHint);
64822
63791
  }, isFileNotFoundError2 = (error) => {
64823
63792
  if (!(error instanceof Object))
64824
63793
  return false;
64825
63794
  return error.code === "ENOENT";
64826
- }, getLoginStatusAsync2 = async (options = {}) => {
64827
- return getLoginStatusWithDeps2(options);
64828
63795
  };
64829
63796
  var init_loginStatus = __esm(() => {
64830
63797
  init_src2();
63798
+ init_authProfile();
64831
63799
  init_config();
64832
63800
  init_envAuth();
63801
+ init_refreshCircuitBreaker();
64833
63802
  init_robotClientFallback();
64834
63803
  init_tokenRefresh();
64835
63804
  init_envFile();
@@ -64876,7 +63845,13 @@ var init_clientCredentials = __esm(() => {
64876
63845
  init_config();
64877
63846
  });
64878
63847
  // ../auth/src/selectTenant.ts
64879
- var init_selectTenant = () => {};
63848
+ var TENANT_SELECTION_REQUIRED_CODE2 = "TENANT_SELECTION_REQUIRED", INVALID_TENANT_CODE2 = "INVALID_TENANT", TENANT_SELECTION_CODES2;
63849
+ var init_selectTenant = __esm(() => {
63850
+ TENANT_SELECTION_CODES2 = new Set([
63851
+ TENANT_SELECTION_REQUIRED_CODE2,
63852
+ INVALID_TENANT_CODE2
63853
+ ]);
63854
+ });
64880
63855
 
64881
63856
  // ../auth/src/interactive.ts
64882
63857
  var init_interactive = __esm(() => {
@@ -64892,6 +63867,8 @@ var init_interactive = __esm(() => {
64892
63867
  // ../auth/src/logout.ts
64893
63868
  var init_logout = __esm(() => {
64894
63869
  init_src2();
63870
+ init_authProfile();
63871
+ init_refreshCircuitBreaker();
64895
63872
  init_envFile();
64896
63873
  });
64897
63874
  // ../auth/src/server.ts
@@ -64906,11 +63883,13 @@ var init_src5 = __esm(() => {
64906
63883
  init_oidc();
64907
63884
  init_config();
64908
63885
  init_envAuth();
63886
+ init_refreshCircuitBreaker();
64909
63887
  init_selectTenant();
64910
63888
  init_server2();
64911
63889
  init_envFile();
64912
63890
  init_jwt();
64913
63891
  init_authContext();
63892
+ init_authProfile();
64914
63893
  init_clientCredentials();
64915
63894
  init_interactive();
64916
63895
  init_loginStatus();
@@ -67581,7 +66560,7 @@ init_esm();
67581
66560
  var package_default = {
67582
66561
  name: "@uipath/agenthub-tool",
67583
66562
  license: "MIT",
67584
- version: "1.196.0",
66563
+ version: "1.197.0-preview.59",
67585
66564
  description: "Manage UiPath AgentHub MCP server registrations, tools, and remote A2A agents.",
67586
66565
  private: false,
67587
66566
  repository: {
@@ -86393,6 +85372,7 @@ function singleton(ctorOrName) {
86393
85372
  }
86394
85373
  };
86395
85374
  }
85375
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
86396
85376
  var USER_AGENT_HEADER = "User-Agent";
86397
85377
  var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
86398
85378
  function userAgentPatchKey(userAgent) {
@@ -86415,8 +85395,8 @@ function appendUserAgentToken(value, userAgent) {
86415
85395
  function getEffectiveUserAgent(userAgent) {
86416
85396
  return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
86417
85397
  }
86418
- function isHeadersLike(headers) {
86419
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
85398
+ function getHeaderName(headers, headerName) {
85399
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
86420
85400
  }
86421
85401
  function getSdkUserAgentToken(pkg) {
86422
85402
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -86424,59 +85404,31 @@ function getSdkUserAgentToken(pkg) {
86424
85404
  }
86425
85405
  function addSdkUserAgentHeader(headers, userAgent) {
86426
85406
  const result = { ...headers ?? {} };
86427
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
86428
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
86429
- if (headerName) {
86430
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
86431
- } else {
86432
- result[USER_AGENT_HEADER] = effectiveUserAgent;
86433
- }
85407
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
85408
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
86434
85409
  return result;
86435
85410
  }
86436
- function withSdkUserAgentHeader(headers, userAgent) {
86437
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
86438
- if (isHeadersLike(headers)) {
86439
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
86440
- return headers;
86441
- }
86442
- if (Array.isArray(headers)) {
86443
- const result = headers.map((entry) => {
86444
- const [key, value] = entry;
86445
- return [key, value];
86446
- });
86447
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
86448
- if (headerIndex >= 0) {
86449
- const [key, value] = result[headerIndex];
86450
- result[headerIndex] = [
86451
- key,
86452
- appendUserAgentToken(value, effectiveUserAgent)
86453
- ];
86454
- } else {
86455
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
86456
- }
86457
- return result;
86458
- }
86459
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
85411
+ function asHeaderRecord(headers) {
85412
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
86460
85413
  }
86461
- function withUserAgentInitOverride(initOverrides, userAgent) {
85414
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
86462
85415
  return async (requestContext) => {
86463
- const initWithUserAgent = {
85416
+ const initWithHeaders = {
86464
85417
  ...requestContext.init,
86465
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
85418
+ headers: forward(asHeaderRecord(requestContext.init.headers))
86466
85419
  };
86467
85420
  const override = typeof initOverrides === "function" ? await initOverrides({
86468
85421
  ...requestContext,
86469
- init: initWithUserAgent
85422
+ init: initWithHeaders
86470
85423
  }) : initOverrides;
86471
85424
  return {
86472
85425
  ...override ?? {},
86473
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
85426
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
86474
85427
  };
86475
85428
  };
86476
85429
  }
86477
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
85430
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
86478
85431
  const prototype = BaseApiClass.prototype;
86479
- const patchKey = userAgentPatchKey(userAgent);
86480
85432
  if (prototype[patchKey]) {
86481
85433
  return;
86482
85434
  }
@@ -86484,13 +85436,16 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
86484
85436
  throw new Error("Generated BaseAPI request function not found.");
86485
85437
  }
86486
85438
  const originalRequest = prototype.request;
86487
- prototype.request = function requestWithUserAgent(context, initOverrides) {
86488
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
85439
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
85440
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
86489
85441
  };
86490
85442
  Object.defineProperty(prototype, patchKey, {
86491
85443
  value: true
86492
85444
  });
86493
85445
  }
85446
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
85447
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
85448
+ }
86494
85449
  var BASE_PATH = "/uipattycyrhx/abizon_1/agenthub_".replace(/\/+$/, "");
86495
85450
 
86496
85451
  class Configuration {
@@ -86742,7 +85697,7 @@ class VoidApiResponse {
86742
85697
  var package_default2 = {
86743
85698
  name: "@uipath/agenthub-sdk",
86744
85699
  license: "MIT",
86745
- version: "1.196.0",
85700
+ version: "1.197.0",
86746
85701
  repository: {
86747
85702
  type: "git",
86748
85703
  url: "https://github.com/UiPath/cli.git",
@@ -86770,7 +85725,7 @@ var package_default2 = {
86770
85725
  ],
86771
85726
  private: true,
86772
85727
  scripts: {
86773
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
85728
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
86774
85729
  generate: "bun run src/scripts/generate-sdk.ts",
86775
85730
  lint: "biome check .",
86776
85731
  test: "vitest run",
@@ -87908,6 +86863,12 @@ var normalizeAndValidateBaseUrl = (rawUrl) => {
87908
86863
  }
87909
86864
  return url.pathname.length > 1 ? url.origin : baseUrl;
87910
86865
  };
86866
+ var resolveScopes = (isExternalAppAuth, customScopes, fileScopes) => {
86867
+ const requestedScopes = customScopes?.length ? customScopes : fileScopes ?? [];
86868
+ if (isExternalAppAuth)
86869
+ return requestedScopes;
86870
+ return [...new Set([...DEFAULT_SCOPES, ...requestedScopes])];
86871
+ };
87911
86872
  var resolveConfigAsync = async ({
87912
86873
  customAuthority,
87913
86874
  customClientId,
@@ -87938,7 +86899,7 @@ var resolveConfigAsync = async ({
87938
86899
  clientSecret = fileAuth.clientSecret;
87939
86900
  }
87940
86901
  const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
87941
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
86902
+ const scopes = resolveScopes(isExternalAppAuth, customScopes, fileAuth.scopes);
87942
86903
  return {
87943
86904
  clientId,
87944
86905
  clientSecret,
@@ -87950,6 +86911,74 @@ var resolveConfigAsync = async ({
87950
86911
  };
87951
86912
  init_constants();
87952
86913
  init_src();
86914
+ init_src();
86915
+ init_constants();
86916
+ var DEFAULT_AUTH_PROFILE = "default";
86917
+ var PROFILE_DIR = "profiles";
86918
+ var PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
86919
+ var ACTIVE_AUTH_PROFILE_KEY = Symbol.for("@uipath/auth/ActiveAuthProfile");
86920
+ var AUTH_PROFILE_STORAGE_KEY = Symbol.for("@uipath/auth/ProfileStorage");
86921
+ var globalSlot2 = globalThis;
86922
+ function isAuthProfileStorage(value) {
86923
+ return value !== null && typeof value === "object" && "getStore" in value && "run" in value;
86924
+ }
86925
+ function createProfileStorage() {
86926
+ const [error, mod] = catchError(() => __require2("node:async_hooks"));
86927
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
86928
+ return {
86929
+ getStore: () => {
86930
+ return;
86931
+ },
86932
+ run: (_store, fn) => fn()
86933
+ };
86934
+ }
86935
+ return new mod.AsyncLocalStorage;
86936
+ }
86937
+ function getProfileStorage() {
86938
+ const existing = globalSlot2[AUTH_PROFILE_STORAGE_KEY];
86939
+ if (isAuthProfileStorage(existing)) {
86940
+ return existing;
86941
+ }
86942
+ const storage = createProfileStorage();
86943
+ globalSlot2[AUTH_PROFILE_STORAGE_KEY] = storage;
86944
+ return storage;
86945
+ }
86946
+ var profileStorage = getProfileStorage();
86947
+
86948
+ class AuthProfileValidationError extends Error {
86949
+ constructor(message) {
86950
+ super(message);
86951
+ this.name = "AuthProfileValidationError";
86952
+ }
86953
+ }
86954
+ function normalizeAuthProfileName(profile) {
86955
+ if (profile === undefined || profile === DEFAULT_AUTH_PROFILE) {
86956
+ return;
86957
+ }
86958
+ if (profile.length === 0 || profile === "." || profile === ".." || !PROFILE_NAME_RE.test(profile)) {
86959
+ throw new AuthProfileValidationError(`Invalid profile name "${profile}". Profile names may contain only letters, numbers, '.', '_', and '-'.`);
86960
+ }
86961
+ return profile;
86962
+ }
86963
+ function getActiveAuthProfile() {
86964
+ const scopedState = profileStorage.getStore();
86965
+ if (scopedState !== undefined) {
86966
+ return scopedState.profile;
86967
+ }
86968
+ return globalSlot2[ACTIVE_AUTH_PROFILE_KEY]?.profile;
86969
+ }
86970
+ function resolveAuthProfileFilePath(profile) {
86971
+ const normalized = normalizeAuthProfileName(profile);
86972
+ if (normalized === undefined) {
86973
+ throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
86974
+ }
86975
+ const fs7 = getFileSystem();
86976
+ return fs7.path.join(fs7.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
86977
+ }
86978
+ function getActiveAuthProfileFilePath() {
86979
+ const profile = getActiveAuthProfile();
86980
+ return profile ? resolveAuthProfileFilePath(profile) : undefined;
86981
+ }
87953
86982
 
87954
86983
  class InvalidIssuerError extends Error {
87955
86984
  expected;
@@ -88076,21 +87105,70 @@ var readAuthFromEnv = () => {
88076
87105
  organizationId,
88077
87106
  tenantName,
88078
87107
  tenantId,
88079
- expiration
87108
+ expiration,
87109
+ source: "env"
88080
87110
  };
88081
87111
  };
88082
87112
  init_src();
87113
+ var BREAKER_SUFFIX = ".refresh-state";
87114
+ var BACKOFF_BASE_MS = 60000;
87115
+ var BACKOFF_CAP_MS = 60 * 60 * 1000;
87116
+ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
87117
+ async function refreshTokenFingerprint(refreshToken) {
87118
+ const bytes = new TextEncoder().encode(refreshToken);
87119
+ if (globalThis.crypto?.subtle) {
87120
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
87121
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
87122
+ }
87123
+ const { createHash } = await import("node:crypto");
87124
+ return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
87125
+ }
87126
+ function breakerPathFor(authPath) {
87127
+ return `${authPath}${BREAKER_SUFFIX}`;
87128
+ }
87129
+ async function loadRefreshBreaker(authPath) {
87130
+ const fs7 = getFileSystem();
87131
+ try {
87132
+ const content = await fs7.readFile(breakerPathFor(authPath), "utf-8");
87133
+ if (!content)
87134
+ return {};
87135
+ const parsed = JSON.parse(content);
87136
+ return parsed && typeof parsed === "object" ? parsed : {};
87137
+ } catch {
87138
+ return {};
87139
+ }
87140
+ }
87141
+ async function saveRefreshBreaker(authPath, state) {
87142
+ try {
87143
+ const fs7 = getFileSystem();
87144
+ const path3 = breakerPathFor(authPath);
87145
+ await fs7.mkdir(fs7.path.dirname(path3));
87146
+ const tempPath = `${path3}.tmp`;
87147
+ await fs7.writeFile(tempPath, JSON.stringify(state));
87148
+ await fs7.rename(tempPath, path3);
87149
+ } catch {}
87150
+ }
87151
+ async function clearRefreshBreaker(authPath) {
87152
+ const fs7 = getFileSystem();
87153
+ const path3 = breakerPathFor(authPath);
87154
+ try {
87155
+ if (await fs7.exists(path3)) {
87156
+ await fs7.rm(path3);
87157
+ }
87158
+ } catch {}
87159
+ }
87160
+ function nextBackoffMs(attempts) {
87161
+ const shift = Math.max(0, attempts - 1);
87162
+ return Math.min(BACKOFF_BASE_MS * 2 ** shift, BACKOFF_CAP_MS);
87163
+ }
87164
+ function shouldSurface(state, nowMs) {
87165
+ if (state.lastSurfacedAtMs === undefined)
87166
+ return true;
87167
+ return nowMs - state.lastSurfacedAtMs >= SURFACE_WINDOW_MS;
87168
+ }
87169
+ init_src();
88083
87170
  var DEFAULT_TIMEOUT_MS = 1000;
88084
87171
  var CLOSE_TIMEOUT_MS = 500;
88085
- var NOTICE_SENTINEL = Symbol.for("@uipath/auth/robotFallbackNoticePrinted");
88086
- var printNoticeOnce = () => {
88087
- const slot = globalThis;
88088
- if (slot[NOTICE_SENTINEL])
88089
- return;
88090
- slot[NOTICE_SENTINEL] = true;
88091
- catchError(() => process.stderr.write(`Using UiPath Robot credentials. Run 'uip login' for a dedicated session.
88092
- `));
88093
- };
88094
87172
  var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
88095
87173
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
88096
87174
  var PIPE_NAME_MAX_LENGTH = 103;
@@ -88206,7 +87284,6 @@ var tryRobotClientFallback = async (options = {}) => {
88206
87284
  issuerFromToken = issClaim;
88207
87285
  }
88208
87286
  }
88209
- printNoticeOnce();
88210
87287
  return {
88211
87288
  accessToken,
88212
87289
  baseUrl: parsedUrl.baseUrl,
@@ -88425,18 +87502,327 @@ var saveEnvFileAsync = async ({
88425
87502
  await fs7.writeFile(tempPath, content);
88426
87503
  await fs7.rename(tempPath, absolutePath);
88427
87504
  };
88428
- function normalizeTokenRefreshFailure() {
88429
- return "stored refresh token is invalid or expired";
87505
+ var getLoginStatusAsync = async (options = {}) => {
87506
+ return getLoginStatusWithDeps(options);
87507
+ };
87508
+ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
87509
+ const {
87510
+ resolveEnvFilePath = resolveEnvFilePathAsync,
87511
+ loadEnvFile = loadEnvFileAsync,
87512
+ saveEnvFile = saveEnvFileAsync,
87513
+ getFs = getFileSystem,
87514
+ refreshToken: refreshTokenFn = refreshAccessToken,
87515
+ resolveConfig = resolveConfigAsync,
87516
+ robotFallback = tryRobotClientFallback,
87517
+ loadBreaker = loadRefreshBreaker,
87518
+ saveBreaker = saveRefreshBreaker,
87519
+ clearBreaker = clearRefreshBreaker
87520
+ } = deps;
87521
+ if (isRobotAuthEnforced()) {
87522
+ return resolveRobotEnforcedStatus(robotFallback);
87523
+ }
87524
+ if (isEnvAuthEnabled()) {
87525
+ return readAuthFromEnv();
87526
+ }
87527
+ const activeProfile = getActiveAuthProfile();
87528
+ const activeProfileFilePath = getActiveAuthProfileFilePath();
87529
+ const usingActiveProfile = activeProfile !== undefined && (options.envFilePath === undefined || options.envFilePath === activeProfileFilePath);
87530
+ const envFilePath = options.envFilePath ?? activeProfileFilePath ?? DEFAULT_ENV_FILENAME;
87531
+ const { ensureTokenValidityMinutes } = options;
87532
+ const { absolutePath } = await resolveEnvFilePath(envFilePath);
87533
+ if (absolutePath === undefined) {
87534
+ if (usingActiveProfile) {
87535
+ return {
87536
+ loginStatus: "Not logged in",
87537
+ hint: `No credentials found for profile "${activeProfile}". Run 'uip login --profile ${activeProfile}' to authenticate this profile.`
87538
+ };
87539
+ }
87540
+ return resolveBorrowedRobotStatus(robotFallback);
87541
+ }
87542
+ const loaded = await loadFileCredentials(loadEnvFile, absolutePath);
87543
+ if ("status" in loaded) {
87544
+ return loaded.status;
87545
+ }
87546
+ const { credentials } = loaded;
87547
+ const globalHint = () => usingActiveProfile ? Promise.resolve(undefined) : getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath);
87548
+ const expiration = getTokenExpiration(credentials.UIPATH_ACCESS_TOKEN);
87549
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
87550
+ let tokens = {
87551
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
87552
+ refreshToken: credentials.UIPATH_REFRESH_TOKEN,
87553
+ expiration,
87554
+ lockReleaseFailed: false
87555
+ };
87556
+ const refreshToken = credentials.UIPATH_REFRESH_TOKEN;
87557
+ if (expiration && expiration <= outerThreshold && refreshToken) {
87558
+ const refreshed = await attemptRefresh({
87559
+ absolutePath,
87560
+ credentials,
87561
+ accessToken: credentials.UIPATH_ACCESS_TOKEN,
87562
+ refreshToken,
87563
+ expiration,
87564
+ ensureTokenValidityMinutes,
87565
+ getFs,
87566
+ loadEnvFile,
87567
+ saveEnvFile,
87568
+ refreshFn: refreshTokenFn,
87569
+ resolveConfig,
87570
+ loadBreaker,
87571
+ saveBreaker,
87572
+ clearBreaker,
87573
+ globalHint
87574
+ });
87575
+ if (refreshed.kind === "terminal") {
87576
+ return refreshed.status;
87577
+ }
87578
+ tokens = refreshed.tokens;
87579
+ }
87580
+ return buildFileStatus(tokens, credentials, globalHint);
87581
+ };
87582
+ async function resolveRobotEnforcedStatus(robotFallback) {
87583
+ if (isEnvAuthEnabled()) {
87584
+ throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true are mutually exclusive. Unset one of them and re-run.`);
87585
+ }
87586
+ const robotCreds = await robotFallback({ force: true });
87587
+ if (!robotCreds) {
87588
+ return {
87589
+ loginStatus: "Not logged in",
87590
+ 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.`
87591
+ };
87592
+ }
87593
+ return buildRobotStatus(robotCreds);
88430
87594
  }
88431
- function normalizeTokenRefreshUnavailableFailure() {
88432
- return "token refresh failed before authentication completed";
87595
+ async function resolveBorrowedRobotStatus(robotFallback) {
87596
+ const robotCreds = await robotFallback();
87597
+ return robotCreds ? buildRobotStatus(robotCreds) : { loginStatus: "Not logged in" };
88433
87598
  }
88434
- function errorMessage(error) {
88435
- return error instanceof Error ? error.message : String(error);
87599
+ async function loadFileCredentials(loadEnvFile, absolutePath) {
87600
+ let credentials;
87601
+ try {
87602
+ credentials = await loadEnvFile({ envPath: absolutePath });
87603
+ } catch (error) {
87604
+ if (isFileNotFoundError(error)) {
87605
+ return { status: { loginStatus: "Not logged in" } };
87606
+ }
87607
+ throw error;
87608
+ }
87609
+ if (!credentials.UIPATH_ACCESS_TOKEN) {
87610
+ return { status: { loginStatus: "Not logged in" } };
87611
+ }
87612
+ return { credentials };
87613
+ }
87614
+ async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
87615
+ const fs7 = getFs();
87616
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
87617
+ if (absolutePath === globalPath)
87618
+ return;
87619
+ if (!await fs7.exists(globalPath))
87620
+ return;
87621
+ try {
87622
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
87623
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
87624
+ return;
87625
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
87626
+ if (globalExp && globalExp <= new Date)
87627
+ return;
87628
+ 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.`;
87629
+ } catch {
87630
+ return;
87631
+ }
88436
87632
  }
88437
87633
  function computeExpirationThreshold(ensureTokenValidityMinutes) {
88438
87634
  return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
88439
87635
  }
87636
+ async function attemptRefresh(ctx) {
87637
+ const shortCircuit = await circuitBreakerShortCircuit(ctx);
87638
+ if (shortCircuit) {
87639
+ return { kind: "terminal", status: shortCircuit };
87640
+ }
87641
+ let release;
87642
+ try {
87643
+ release = await ctx.getFs().acquireLock(ctx.absolutePath);
87644
+ } catch (error) {
87645
+ return {
87646
+ kind: "terminal",
87647
+ status: await lockAcquireFailureStatus(ctx, error)
87648
+ };
87649
+ }
87650
+ let lockedFailure;
87651
+ let lockReleaseFailed = false;
87652
+ let success;
87653
+ try {
87654
+ const outcome = await runRefreshLocked({
87655
+ absolutePath: ctx.absolutePath,
87656
+ refreshToken: ctx.refreshToken,
87657
+ customAuthority: ctx.credentials.UIPATH_URL,
87658
+ ensureTokenValidityMinutes: ctx.ensureTokenValidityMinutes,
87659
+ loadEnvFile: ctx.loadEnvFile,
87660
+ saveEnvFile: ctx.saveEnvFile,
87661
+ refreshFn: ctx.refreshFn,
87662
+ resolveConfig: ctx.resolveConfig,
87663
+ loadBreaker: ctx.loadBreaker,
87664
+ saveBreaker: ctx.saveBreaker,
87665
+ clearBreaker: ctx.clearBreaker
87666
+ });
87667
+ if (outcome.kind === "fail") {
87668
+ lockedFailure = outcome.status;
87669
+ } else {
87670
+ success = outcome;
87671
+ }
87672
+ } finally {
87673
+ try {
87674
+ await release();
87675
+ } catch {
87676
+ lockReleaseFailed = true;
87677
+ }
87678
+ }
87679
+ if (lockedFailure) {
87680
+ const globalHint = await ctx.globalHint();
87681
+ const base = globalHint ? { ...lockedFailure, loginStatus: "Expired", hint: globalHint } : lockedFailure;
87682
+ return {
87683
+ kind: "terminal",
87684
+ status: lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base
87685
+ };
87686
+ }
87687
+ return {
87688
+ kind: "refreshed",
87689
+ tokens: {
87690
+ accessToken: success?.accessToken,
87691
+ refreshToken: success?.refreshToken,
87692
+ expiration: success?.expiration,
87693
+ tokenRefresh: success?.tokenRefresh,
87694
+ persistenceWarning: success?.persistenceWarning,
87695
+ lockReleaseFailed
87696
+ }
87697
+ };
87698
+ }
87699
+ async function buildFileStatus(tokens, credentials, globalHint) {
87700
+ const result = {
87701
+ loginStatus: tokens.expiration && tokens.expiration <= new Date ? "Expired" : "Logged in",
87702
+ accessToken: tokens.accessToken,
87703
+ refreshToken: tokens.refreshToken,
87704
+ baseUrl: credentials.UIPATH_URL,
87705
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
87706
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
87707
+ tenantName: credentials.UIPATH_TENANT_NAME,
87708
+ tenantId: credentials.UIPATH_TENANT_ID,
87709
+ expiration: tokens.expiration,
87710
+ source: "file",
87711
+ ...tokens.persistenceWarning ? { hint: tokens.persistenceWarning, persistenceFailed: true } : {},
87712
+ ...tokens.lockReleaseFailed ? { lockReleaseFailed: true } : {},
87713
+ ...tokens.tokenRefresh ? { tokenRefresh: tokens.tokenRefresh } : {}
87714
+ };
87715
+ if (result.loginStatus === "Expired") {
87716
+ const hint = await globalHint();
87717
+ if (hint) {
87718
+ result.hint = hint;
87719
+ }
87720
+ }
87721
+ return result;
87722
+ }
87723
+ function buildRobotStatus(robotCreds) {
87724
+ return {
87725
+ loginStatus: "Logged in",
87726
+ accessToken: robotCreds.accessToken,
87727
+ baseUrl: robotCreds.baseUrl,
87728
+ organizationName: robotCreds.organizationName,
87729
+ organizationId: robotCreds.organizationId,
87730
+ tenantName: robotCreds.tenantName,
87731
+ tenantId: robotCreds.tenantId,
87732
+ issuer: robotCreds.issuer,
87733
+ expiration: getTokenExpiration(robotCreds.accessToken),
87734
+ source: "robot"
87735
+ };
87736
+ }
87737
+ var isFileNotFoundError = (error) => {
87738
+ if (!(error instanceof Object))
87739
+ return false;
87740
+ return error.code === "ENOENT";
87741
+ };
87742
+ async function circuitBreakerShortCircuit(ctx) {
87743
+ const {
87744
+ absolutePath,
87745
+ refreshToken,
87746
+ accessToken,
87747
+ credentials,
87748
+ expiration,
87749
+ loadBreaker,
87750
+ saveBreaker,
87751
+ clearBreaker
87752
+ } = ctx;
87753
+ const fingerprint = await refreshTokenFingerprint(refreshToken);
87754
+ const breaker = await loadBreaker(absolutePath).catch(() => ({}));
87755
+ if (breaker.deadTokenFp && breaker.deadTokenFp !== fingerprint) {
87756
+ await clearBreaker(absolutePath);
87757
+ breaker.deadTokenFp = undefined;
87758
+ }
87759
+ const nowMs = Date.now();
87760
+ const tokenIsDead = breaker.deadTokenFp === fingerprint;
87761
+ const inBackoff = breaker.backoffUntilMs !== undefined && nowMs < breaker.backoffUntilMs;
87762
+ if (!tokenIsDead && !inBackoff)
87763
+ return;
87764
+ const globalHint = await ctx.globalHint();
87765
+ const suppressed = !shouldSurface(breaker, nowMs);
87766
+ if (!suppressed) {
87767
+ await saveBreaker(absolutePath, {
87768
+ ...breaker,
87769
+ lastSurfacedAtMs: nowMs
87770
+ });
87771
+ }
87772
+ 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>.";
87773
+ const backoffHint = "Token refresh is temporarily backed off after a recent network error and will retry automatically once the backoff window elapses.";
87774
+ return {
87775
+ loginStatus: globalHint ? "Expired" : "Refresh Failed",
87776
+ ...globalHint ? {
87777
+ accessToken,
87778
+ refreshToken,
87779
+ baseUrl: credentials.UIPATH_URL,
87780
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
87781
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
87782
+ tenantName: credentials.UIPATH_TENANT_NAME,
87783
+ tenantId: credentials.UIPATH_TENANT_ID,
87784
+ expiration,
87785
+ source: "file"
87786
+ } : {},
87787
+ hint: globalHint ?? (tokenIsDead ? deadHint : backoffHint),
87788
+ refreshCircuitOpen: true,
87789
+ refreshTelemetrySuppressed: suppressed,
87790
+ tokenRefresh: { attempted: false, success: false }
87791
+ };
87792
+ }
87793
+ async function lockAcquireFailureStatus(ctx, error) {
87794
+ const msg = errorMessage(error);
87795
+ const globalHint = await ctx.globalHint();
87796
+ if (globalHint) {
87797
+ return {
87798
+ loginStatus: "Expired",
87799
+ accessToken: ctx.accessToken,
87800
+ refreshToken: ctx.refreshToken,
87801
+ baseUrl: ctx.credentials.UIPATH_URL,
87802
+ organizationName: ctx.credentials.UIPATH_ORGANIZATION_NAME,
87803
+ organizationId: ctx.credentials.UIPATH_ORGANIZATION_ID,
87804
+ tenantName: ctx.credentials.UIPATH_TENANT_NAME,
87805
+ tenantId: ctx.credentials.UIPATH_TENANT_ID,
87806
+ expiration: ctx.expiration,
87807
+ source: "file",
87808
+ hint: globalHint,
87809
+ tokenRefresh: {
87810
+ attempted: false,
87811
+ success: false,
87812
+ errorMessage: `lock acquisition failed: ${msg}`
87813
+ }
87814
+ };
87815
+ }
87816
+ return {
87817
+ loginStatus: "Refresh Failed",
87818
+ 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.",
87819
+ tokenRefresh: {
87820
+ attempted: false,
87821
+ success: false,
87822
+ errorMessage: `lock acquisition failed: ${msg}`
87823
+ }
87824
+ };
87825
+ }
88440
87826
  async function runRefreshLocked(inputs) {
88441
87827
  const {
88442
87828
  absolutePath,
@@ -88446,7 +87832,10 @@ async function runRefreshLocked(inputs) {
88446
87832
  loadEnvFile,
88447
87833
  saveEnvFile,
88448
87834
  refreshFn,
88449
- resolveConfig
87835
+ resolveConfig,
87836
+ loadBreaker,
87837
+ saveBreaker,
87838
+ clearBreaker
88450
87839
  } = inputs;
88451
87840
  const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
88452
87841
  let fresh;
@@ -88469,6 +87858,7 @@ async function runRefreshLocked(inputs) {
88469
87858
  const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
88470
87859
  const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
88471
87860
  if (freshAccess && freshExp && freshExp > expirationThreshold) {
87861
+ await clearBreaker(absolutePath);
88472
87862
  return {
88473
87863
  kind: "ok",
88474
87864
  accessToken: freshAccess,
@@ -88492,8 +87882,21 @@ async function runRefreshLocked(inputs) {
88492
87882
  refreshedRefresh = refreshed.refreshToken;
88493
87883
  } catch (error) {
88494
87884
  const isOAuthFailure = isTokenRefreshOAuthFailure(error);
88495
- 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.";
87885
+ 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.";
88496
87886
  const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
87887
+ const fp = await refreshTokenFingerprint(tokenForIdP);
87888
+ if (isOAuthFailure) {
87889
+ await saveBreaker(absolutePath, { deadTokenFp: fp });
87890
+ } else {
87891
+ const prior = await loadBreaker(absolutePath).catch(() => ({}));
87892
+ const attempts = (prior.attempts ?? 0) + 1;
87893
+ await saveBreaker(absolutePath, {
87894
+ ...prior,
87895
+ deadTokenFp: undefined,
87896
+ attempts,
87897
+ backoffUntilMs: Date.now() + nextBackoffMs(attempts)
87898
+ });
87899
+ }
88497
87900
  return {
88498
87901
  kind: "fail",
88499
87902
  status: {
@@ -88522,6 +87925,7 @@ async function runRefreshLocked(inputs) {
88522
87925
  }
88523
87926
  };
88524
87927
  }
87928
+ await clearBreaker(absolutePath);
88525
87929
  try {
88526
87930
  await saveEnvFile({
88527
87931
  envPath: absolutePath,
@@ -88554,212 +87958,15 @@ async function runRefreshLocked(inputs) {
88554
87958
  };
88555
87959
  }
88556
87960
  }
88557
- var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
88558
- const {
88559
- resolveEnvFilePath = resolveEnvFilePathAsync,
88560
- loadEnvFile = loadEnvFileAsync,
88561
- saveEnvFile = saveEnvFileAsync,
88562
- getFs = getFileSystem,
88563
- refreshToken: refreshTokenFn = refreshAccessToken,
88564
- resolveConfig = resolveConfigAsync,
88565
- robotFallback = tryRobotClientFallback
88566
- } = deps;
88567
- if (isRobotAuthEnforced()) {
88568
- if (isEnvAuthEnabled()) {
88569
- throw new EnvAuthConfigError(`${ENV_AUTH_ENABLE_VAR}=true and ${ENFORCE_ROBOT_AUTH_VAR}=true ` + `are mutually exclusive. Unset one of them and re-run.`);
88570
- }
88571
- const robotCreds = await robotFallback({ force: true });
88572
- if (!robotCreds) {
88573
- return {
88574
- loginStatus: "Not logged in",
88575
- 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.`
88576
- };
88577
- }
88578
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
88579
- return {
88580
- loginStatus: "Logged in",
88581
- accessToken: robotCreds.accessToken,
88582
- baseUrl: robotCreds.baseUrl,
88583
- organizationName: robotCreds.organizationName,
88584
- organizationId: robotCreds.organizationId,
88585
- tenantName: robotCreds.tenantName,
88586
- tenantId: robotCreds.tenantId,
88587
- issuer: robotCreds.issuer,
88588
- expiration: expiration2,
88589
- source: "robot"
88590
- };
88591
- }
88592
- if (isEnvAuthEnabled()) {
88593
- return readAuthFromEnv();
88594
- }
88595
- const { envFilePath = DEFAULT_ENV_FILENAME, ensureTokenValidityMinutes } = options;
88596
- const { absolutePath } = await resolveEnvFilePath(envFilePath);
88597
- if (absolutePath === undefined) {
88598
- const robotCreds = await robotFallback();
88599
- if (robotCreds) {
88600
- const expiration2 = getTokenExpiration(robotCreds.accessToken);
88601
- const status = {
88602
- loginStatus: "Logged in",
88603
- accessToken: robotCreds.accessToken,
88604
- baseUrl: robotCreds.baseUrl,
88605
- organizationName: robotCreds.organizationName,
88606
- organizationId: robotCreds.organizationId,
88607
- tenantName: robotCreds.tenantName,
88608
- tenantId: robotCreds.tenantId,
88609
- issuer: robotCreds.issuer,
88610
- expiration: expiration2,
88611
- source: "robot"
88612
- };
88613
- return status;
88614
- }
88615
- return { loginStatus: "Not logged in" };
88616
- }
88617
- let credentials;
88618
- try {
88619
- credentials = await loadEnvFile({ envPath: absolutePath });
88620
- } catch (error) {
88621
- if (isFileNotFoundError(error)) {
88622
- return { loginStatus: "Not logged in" };
88623
- }
88624
- throw error;
88625
- }
88626
- if (!credentials.UIPATH_ACCESS_TOKEN) {
88627
- return { loginStatus: "Not logged in" };
88628
- }
88629
- let accessToken = credentials.UIPATH_ACCESS_TOKEN;
88630
- let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
88631
- let expiration = getTokenExpiration(accessToken);
88632
- let persistenceWarning;
88633
- let lockReleaseFailed = false;
88634
- let tokenRefresh;
88635
- const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
88636
- const tryGlobalCredsHint = async () => {
88637
- const fs7 = getFs();
88638
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
88639
- if (absolutePath === globalPath)
88640
- return;
88641
- if (!await fs7.exists(globalPath))
88642
- return;
88643
- try {
88644
- const globalCreds = await loadEnvFile({ envPath: globalPath });
88645
- if (!globalCreds.UIPATH_ACCESS_TOKEN)
88646
- return;
88647
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
88648
- if (globalExp && globalExp <= new Date)
88649
- return;
88650
- 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.`;
88651
- } catch {
88652
- return;
88653
- }
88654
- };
88655
- if (expiration && expiration <= outerThreshold && refreshToken) {
88656
- let release;
88657
- try {
88658
- release = await getFs().acquireLock(absolutePath);
88659
- } catch (error) {
88660
- const msg = errorMessage(error);
88661
- const globalHint = await tryGlobalCredsHint();
88662
- if (globalHint) {
88663
- return {
88664
- loginStatus: "Expired",
88665
- accessToken,
88666
- refreshToken,
88667
- baseUrl: credentials.UIPATH_URL,
88668
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
88669
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
88670
- tenantName: credentials.UIPATH_TENANT_NAME,
88671
- tenantId: credentials.UIPATH_TENANT_ID,
88672
- expiration,
88673
- source: "file",
88674
- hint: globalHint,
88675
- tokenRefresh: {
88676
- attempted: false,
88677
- success: false,
88678
- errorMessage: `lock acquisition failed: ${msg}`
88679
- }
88680
- };
88681
- }
88682
- return {
88683
- loginStatus: "Refresh Failed",
88684
- 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.",
88685
- tokenRefresh: {
88686
- attempted: false,
88687
- success: false,
88688
- errorMessage: `lock acquisition failed: ${msg}`
88689
- }
88690
- };
88691
- }
88692
- let lockedFailure;
88693
- try {
88694
- const outcome = await runRefreshLocked({
88695
- absolutePath,
88696
- refreshToken,
88697
- customAuthority: credentials.UIPATH_URL,
88698
- ensureTokenValidityMinutes,
88699
- loadEnvFile,
88700
- saveEnvFile,
88701
- refreshFn: refreshTokenFn,
88702
- resolveConfig
88703
- });
88704
- if (outcome.kind === "fail") {
88705
- lockedFailure = outcome.status;
88706
- } else {
88707
- accessToken = outcome.accessToken;
88708
- refreshToken = outcome.refreshToken;
88709
- expiration = outcome.expiration;
88710
- tokenRefresh = outcome.tokenRefresh;
88711
- if (outcome.persistenceWarning) {
88712
- persistenceWarning = outcome.persistenceWarning;
88713
- }
88714
- }
88715
- } finally {
88716
- try {
88717
- await release();
88718
- } catch {
88719
- lockReleaseFailed = true;
88720
- }
88721
- }
88722
- if (lockedFailure) {
88723
- const globalHint = await tryGlobalCredsHint();
88724
- const base = globalHint ? {
88725
- ...lockedFailure,
88726
- loginStatus: "Expired",
88727
- hint: globalHint
88728
- } : lockedFailure;
88729
- return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
88730
- }
88731
- }
88732
- const result = {
88733
- loginStatus: expiration && expiration <= new Date ? "Expired" : "Logged in",
88734
- accessToken,
88735
- refreshToken,
88736
- baseUrl: credentials.UIPATH_URL,
88737
- organizationName: credentials.UIPATH_ORGANIZATION_NAME,
88738
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
88739
- tenantName: credentials.UIPATH_TENANT_NAME,
88740
- tenantId: credentials.UIPATH_TENANT_ID,
88741
- expiration,
88742
- source: "file",
88743
- ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
88744
- ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
88745
- ...tokenRefresh ? { tokenRefresh } : {}
88746
- };
88747
- if (result.loginStatus === "Expired") {
88748
- const globalHint = await tryGlobalCredsHint();
88749
- if (globalHint) {
88750
- result.hint = globalHint;
88751
- }
88752
- }
88753
- return result;
88754
- };
88755
- var isFileNotFoundError = (error) => {
88756
- if (!(error instanceof Object))
88757
- return false;
88758
- return error.code === "ENOENT";
88759
- };
88760
- var getLoginStatusAsync = async (options = {}) => {
88761
- return getLoginStatusWithDeps(options);
88762
- };
87961
+ function normalizeTokenRefreshFailure() {
87962
+ return "stored refresh token is invalid or expired";
87963
+ }
87964
+ function normalizeTokenRefreshUnavailableFailure() {
87965
+ return "token refresh failed before authentication completed";
87966
+ }
87967
+ function errorMessage(error) {
87968
+ return error instanceof Error ? error.message : String(error);
87969
+ }
88763
87970
  var getAuthContext = async (options = {}) => {
88764
87971
  const status = await getLoginStatusAsync({
88765
87972
  ensureTokenValidityMinutes: options.ensureTokenValidityMinutes,
@@ -88791,6 +87998,12 @@ var getAuthContext = async (options = {}) => {
88791
87998
  };
88792
87999
  };
88793
88000
  init_src();
88001
+ var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
88002
+ var INVALID_TENANT_CODE = "INVALID_TENANT";
88003
+ var TENANT_SELECTION_CODES = new Set([
88004
+ TENANT_SELECTION_REQUIRED_CODE,
88005
+ INVALID_TENANT_CODE
88006
+ ]);
88794
88007
  init_src();
88795
88008
  init_server();
88796
88009
  async function createAgentHubConfig(options) {
@@ -88993,8 +88206,8 @@ var parsePairs = (values) => {
88993
88206
  if (!values?.length)
88994
88207
  return;
88995
88208
  return Object.fromEntries(values.map((value) => {
88996
- const index2 = value.indexOf("=");
88997
- return index2 === -1 ? [value, ""] : [value.slice(0, index2), value.slice(index2 + 1)];
88209
+ const index = value.indexOf("=");
88210
+ return index === -1 ? [value, ""] : [value.slice(0, index), value.slice(index + 1)];
88998
88211
  }));
88999
88212
  };
89000
88213
 
@@ -90582,7 +89795,7 @@ class TextApiResponse2 {
90582
89795
  var package_default4 = {
90583
89796
  name: "@uipath/integrationservice-sdk",
90584
89797
  license: "MIT",
90585
- version: "1.196.0",
89798
+ version: "1.197.0-preview.59",
90586
89799
  repository: {
90587
89800
  type: "git",
90588
89801
  url: "https://github.com/UiPath/cli.git",
@@ -90609,7 +89822,7 @@ var package_default4 = {
90609
89822
  "dist"
90610
89823
  ],
90611
89824
  scripts: {
90612
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
89825
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
90613
89826
  generate: "bun run src/scripts/generate-sdk.ts",
90614
89827
  lint: "biome check .",
90615
89828
  test: "vitest run",
@@ -96367,6 +95580,8 @@ async function createApiClient3(ApiClass, options) {
96367
95580
  const config = domain === "connections" ? await createConnectionsConfig(options) : await createElementsConfig(options);
96368
95581
  return new ApiClass(config);
96369
95582
  }
95583
+ // ../integrationservice-sdk/src/dap/essential-config.ts
95584
+ var JIT_INPUT_OPERATIONS = new Set(["create", "update", "replace"]);
96370
95585
  // ../integrationservice-sdk/src/dap/filter-builder/workflow-value.ts
96371
95586
  class WorkflowValue {
96372
95587
  isLiteral;
@@ -96587,7 +95802,7 @@ class CeqlHelper {
96587
95802
  if (fieldType.isSame(ClrTypeMock.Enum)) {
96588
95803
  value = CeqlHelper._getCeqlValueFromEnumValue(value);
96589
95804
  }
96590
- const expression = value == null ? StringExtensions.empty : value.isLiteral ? value.value : "${" + String(value.value) + "}";
95805
+ const expression = value == null ? StringExtensions.empty : value.isLiteral ? value.value : `\${${String(value.value)}}`;
96591
95806
  const valueExpression = CeqlHelper._isStringValue(fieldType) ? `'${String(expression).replace(/'/g, "''")}'` : `${expression}`;
96592
95807
  return CeqlHelper._composeSingleValueExpression(field, op, valueExpression);
96593
95808
  }
@@ -97122,7 +96337,7 @@ class JSONApiResponse5 {
97122
96337
  var package_default5 = {
97123
96338
  name: "@uipath/resourcecatalog-sdk",
97124
96339
  license: "MIT",
97125
- version: "1.196.0",
96340
+ version: "1.197.0",
97126
96341
  description: "SDK for the UiPath Resource Catalog Service API.",
97127
96342
  repository: {
97128
96343
  type: "git",
@@ -97151,7 +96366,7 @@ var package_default5 = {
97151
96366
  ],
97152
96367
  private: true,
97153
96368
  scripts: {
97154
- build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
96369
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
97155
96370
  generate: "bun run src/scripts/generate-sdk.ts",
97156
96371
  lint: "biome check ."
97157
96372
  },
@@ -99244,3 +98459,5 @@ export {
99244
98459
  metadata,
99245
98460
  createStandaloneProgram
99246
98461
  };
98462
+
98463
+ //# debugId=E98E22D2E42EC5EE64756E2164756E21