@uipath/common 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.
package/dist/index.js CHANGED
@@ -3010,27 +3010,54 @@ var NETWORK_ERROR_CODES = new Set([
3010
3010
  "ENETUNREACH",
3011
3011
  "EAI_FAIL"
3012
3012
  ]);
3013
- function isHtmlDocument(body) {
3014
- return /^\s*(<!doctype html|<html\b)/i.test(body);
3015
- }
3016
- function extractNetworkErrorCode(error) {
3017
- if (error === null || typeof error !== "object") {
3018
- return;
3019
- }
3020
- const err = error;
3021
- const code = typeof err.code === "string" ? err.code : undefined;
3022
- if (code && NETWORK_ERROR_CODES.has(code)) {
3023
- return code;
3024
- }
3025
- const cause = err.cause;
3026
- if (cause !== null && typeof cause === "object") {
3027
- const causeCode = cause.code;
3028
- if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode)) {
3029
- return causeCode;
3013
+ var TLS_ERROR_CODES = new Set([
3014
+ "SELF_SIGNED_CERT_IN_CHAIN",
3015
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
3016
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
3017
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
3018
+ "UNABLE_TO_GET_ISSUER_CERT",
3019
+ "CERT_HAS_EXPIRED",
3020
+ "CERT_UNTRUSTED",
3021
+ "ERR_TLS_CERT_ALTNAME_INVALID"
3022
+ ]);
3023
+ var TLS_INSTRUCTIONS = "The server's TLS certificate could not be verified. Most often a " + "corporate proxy/firewall re-signs HTTPS with a root CA that Node does " + "not trust — set NODE_EXTRA_CA_CERTS to that CA's PEM file (and HTTPS_PROXY " + "if you connect through a proxy). If the certificate is instead expired or " + "its hostname does not match, fix the endpoint URL or the system clock. " + "Then retry.";
3024
+ var NETWORK_INSTRUCTIONS = "Could not reach the UiPath service. Check your network connection and " + "VPN, confirm any HTTP_PROXY/HTTPS_PROXY/NO_PROXY settings are correct, " + "then retry.";
3025
+ function describeConnectivityError(error) {
3026
+ let current = error;
3027
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
3028
+ const cur = current;
3029
+ const code = typeof cur.code === "string" ? cur.code : undefined;
3030
+ const message = typeof cur.message === "string" ? cur.message : undefined;
3031
+ if (code && TLS_ERROR_CODES.has(code)) {
3032
+ return {
3033
+ code,
3034
+ kind: "tls",
3035
+ message: message ?? code,
3036
+ instructions: TLS_INSTRUCTIONS
3037
+ };
3030
3038
  }
3039
+ if (code && NETWORK_ERROR_CODES.has(code)) {
3040
+ return {
3041
+ code,
3042
+ kind: "network",
3043
+ message: message ?? code,
3044
+ instructions: NETWORK_INSTRUCTIONS
3045
+ };
3046
+ }
3047
+ current = cur.cause;
3031
3048
  }
3032
3049
  return;
3033
3050
  }
3051
+ function parseHttpStatusFromMessage(message) {
3052
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
3053
+ if (!match)
3054
+ return;
3055
+ const status = Number(match[1]);
3056
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
3057
+ }
3058
+ function isHtmlDocument(body) {
3059
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
3060
+ }
3034
3061
  function retryHintForRetryAfter(seconds) {
3035
3062
  if (seconds <= 1) {
3036
3063
  return "RetryAfter1Second";
@@ -3071,15 +3098,28 @@ function classifyError(status, error) {
3071
3098
  if (status !== undefined && status >= 500 && status < 600) {
3072
3099
  return { errorCode: "server_error", retry: "RetryLater" };
3073
3100
  }
3074
- if (extractNetworkErrorCode(error)) {
3075
- return { errorCode: "network_error", retry: "RetryLater" };
3101
+ const connectivity = describeConnectivityError(error);
3102
+ if (connectivity) {
3103
+ return {
3104
+ errorCode: "network_error",
3105
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
3106
+ };
3076
3107
  }
3077
3108
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
3078
3109
  }
3110
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
3111
+ if (extractedMessage) {
3112
+ return `HTTP ${status}: ${extractedMessage}`;
3113
+ }
3114
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
3115
+ }
3079
3116
  async function extractErrorDetails(error, options) {
3080
3117
  const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
3081
3118
  const response = err.response;
3082
- const status = err.status ?? response?.status;
3119
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
3120
+ const explicitStatus = err.status ?? response?.status;
3121
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
3122
+ const status = explicitStatus ?? inferredStatus;
3083
3123
  const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
3084
3124
  let rawBody;
3085
3125
  let extractedMessage;
@@ -3114,7 +3154,6 @@ async function extractErrorDetails(error, options) {
3114
3154
  }
3115
3155
  }
3116
3156
  }
3117
- const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
3118
3157
  let message;
3119
3158
  let result = "Failure";
3120
3159
  const classification = classifyError(status, error);
@@ -3128,10 +3167,10 @@ async function extractErrorDetails(error, options) {
3128
3167
  } else if (status === 405) {
3129
3168
  message = DEFAULT_405;
3130
3169
  } else if (status === 400 || status === 422) {
3131
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
3170
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
3132
3171
  result = "ValidationError";
3133
3172
  } else if (status === 429) {
3134
- message = extractedMessage ? `HTTP ${status}: ${extractedMessage}` : `HTTP ${status}: ${rawMessage}`;
3173
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
3135
3174
  } else if (extractedMessage) {
3136
3175
  if (isSuccessfulResponse && rawMessage !== "Unknown error") {
3137
3176
  message = rawMessage;
@@ -3139,7 +3178,9 @@ async function extractErrorDetails(error, options) {
3139
3178
  message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
3140
3179
  }
3141
3180
  } else if (status) {
3142
- if (rawMessage === "Unknown error" && response) {
3181
+ if (inferredStatus !== undefined) {
3182
+ message = rawMessage;
3183
+ } else if (rawMessage === "Unknown error" && response) {
3143
3184
  const statusText = response.statusText;
3144
3185
  message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
3145
3186
  } else {
@@ -3148,6 +3189,12 @@ async function extractErrorDetails(error, options) {
3148
3189
  } else {
3149
3190
  message = rawMessage;
3150
3191
  }
3192
+ if (status === undefined) {
3193
+ const connectivity = describeConnectivityError(error);
3194
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
3195
+ message = `${message}: ${connectivity.message}`;
3196
+ }
3197
+ }
3151
3198
  let details = rawMessage;
3152
3199
  if (rawBody) {
3153
3200
  if (parsedBody) {
@@ -3373,6 +3420,7 @@ var CONSOLE_FALLBACK = {
3373
3420
  writeLog: (str) => process.stdout.write(str),
3374
3421
  capabilities: {
3375
3422
  isInteractive: false,
3423
+ canReadInput: false,
3376
3424
  supportsColor: false,
3377
3425
  outputWidth: 80
3378
3426
  }
@@ -8919,6 +8967,12 @@ async function getOrCreateProvider(connectionString) {
8919
8967
  return initPromise;
8920
8968
  }
8921
8969
 
8970
+ // src/telemetry/telemetry-config.ts
8971
+ function isTelemetryDisabled() {
8972
+ const value = process.env.UIPATH_TELEMETRY_DISABLED;
8973
+ return value === "1" || value === "true";
8974
+ }
8975
+
8922
8976
  // src/telemetry/telemetry-init.ts
8923
8977
  var telemetryInstanceSlot = singleton("TelemetryService");
8924
8978
  var DEFAULT_AI_CONNECTION_STRING = atob("SW5zdHJ1bWVudGF0aW9uS2V5PTliZDM3NDgyLTgxMGUtNDQyYS1hYWE2LWQzOGVmNjVjNjY3NDtJbmdlc3Rpb25FbmRwb2ludD1odHRwczovL3dlc3RldXJvcGUtNS5pbi5hcHBsaWNhdGlvbmluc2lnaHRzLmF6dXJlLmNvbS87TGl2ZUVuZHBvaW50PWh0dHBzOi8vd2VzdGV1cm9wZS5saXZlZGlhZ25vc3RpY3MubW9uaXRvci5henVyZS5jb20vO0FwcGxpY2F0aW9uSWQ9MzU2OTdlZjEtOGJkMC00ZjE5LWEyN2MtZDg3Y2NhYzY2ZDJj");
@@ -8928,10 +8982,6 @@ function getConnectionString() {
8928
8982
  async function createAppInsightsProvider() {
8929
8983
  return getOrCreateProvider(getConnectionString());
8930
8984
  }
8931
- function isTelemetryDisabled() {
8932
- const value = process.env.UIPATH_TELEMETRY_DISABLED;
8933
- return value === "1" || value === "true";
8934
- }
8935
8985
  var telemetryProviderInstance;
8936
8986
  var telemetryFlushShutdownPromise;
8937
8987
  async function createTelemetryProvider() {
@@ -9126,6 +9176,7 @@ class FailureOutput {
9126
9176
  Context;
9127
9177
  Log;
9128
9178
  Data;
9179
+ SuppressTelemetry;
9129
9180
  constructor(result, message, instructions, context, errorCode, retry) {
9130
9181
  this.Result = result;
9131
9182
  this.Message = message;
@@ -9160,6 +9211,29 @@ function isPlainRecord(value) {
9160
9211
  const prototype = Object.getPrototypeOf(value);
9161
9212
  return prototype === Object.prototype || prototype === null;
9162
9213
  }
9214
+ function extractPagedRows(value) {
9215
+ if (Array.isArray(value) || !isPlainRecord(value))
9216
+ return null;
9217
+ const entries = Object.values(value);
9218
+ if (entries.length === 0)
9219
+ return null;
9220
+ let rows = null;
9221
+ let hasScalarSibling = false;
9222
+ for (const entry of entries) {
9223
+ if (Array.isArray(entry)) {
9224
+ if (rows !== null)
9225
+ return null;
9226
+ rows = entry;
9227
+ } else if (entry !== null && typeof entry === "object") {
9228
+ return null;
9229
+ } else {
9230
+ hasScalarSibling = true;
9231
+ }
9232
+ }
9233
+ if (rows === null || !hasScalarSibling)
9234
+ return null;
9235
+ return rows;
9236
+ }
9163
9237
  function toLowerCamelCaseKey(key) {
9164
9238
  if (!key)
9165
9239
  return key;
@@ -9224,7 +9298,8 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
9224
9298
  break;
9225
9299
  case "plain": {
9226
9300
  if ("Data" in data && data.Data != null) {
9227
- const items = Array.isArray(data.Data) ? data.Data : [data.Data];
9301
+ const pagedRows = extractPagedRows(data.Data);
9302
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
9228
9303
  items.forEach((item) => {
9229
9304
  const values = Object.values(item).map((v) => v ?? "").join("\t");
9230
9305
  logFn(values);
@@ -9236,10 +9311,13 @@ function printOutput(data, format = "json", logFn, asciiSafe = false) {
9236
9311
  break;
9237
9312
  }
9238
9313
  default: {
9239
- if ("Data" in data && data.Data != null && !(Array.isArray(data.Data) && data.Data.length === 0)) {
9314
+ const hasData = "Data" in data && data.Data != null;
9315
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
9316
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
9317
+ if (hasData && !(rows !== null && rows.length === 0)) {
9240
9318
  const logValue = data.Log;
9241
- if (Array.isArray(data.Data)) {
9242
- printResizableTable(data.Data, logFn, logValue);
9319
+ if (rows !== null) {
9320
+ printResizableTable(rows, logFn, logValue);
9243
9321
  } else {
9244
9322
  printVerticalTable(data.Data, logFn, logValue);
9245
9323
  }
@@ -9436,6 +9514,44 @@ function defaultErrorCodeForResult(result) {
9436
9514
  return "unknown_error";
9437
9515
  }
9438
9516
  }
9517
+ function parseHttpStatusFromMessage2(message) {
9518
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
9519
+ if (!match)
9520
+ return;
9521
+ const status = Number(match[1]);
9522
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
9523
+ }
9524
+ function defaultErrorCodeForHttpStatus(status) {
9525
+ if (status === undefined)
9526
+ return;
9527
+ if (status === 400 || status === 409 || status === 422) {
9528
+ return "invalid_argument";
9529
+ }
9530
+ if (status === 401)
9531
+ return "authentication_required";
9532
+ if (status === 403)
9533
+ return "permission_denied";
9534
+ if (status === 404)
9535
+ return "not_found";
9536
+ if (status === 405)
9537
+ return "method_not_allowed";
9538
+ if (status === 408)
9539
+ return "timeout";
9540
+ if (status === 429)
9541
+ return "rate_limited";
9542
+ if (status >= 500 && status < 600)
9543
+ return "server_error";
9544
+ return;
9545
+ }
9546
+ function defaultErrorCodeForFailure(data) {
9547
+ if (data.Result === RESULTS.Failure) {
9548
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
9549
+ const errorCode = defaultErrorCodeForHttpStatus(status);
9550
+ if (errorCode)
9551
+ return errorCode;
9552
+ }
9553
+ return defaultErrorCodeForResult(data.Result);
9554
+ }
9439
9555
  function defaultRetryForErrorCode(errorCode) {
9440
9556
  switch (errorCode) {
9441
9557
  case "network_error":
@@ -9465,16 +9581,19 @@ var OutputFormatter;
9465
9581
  OutputFormatter.success = success;
9466
9582
  function error(data) {
9467
9583
  data.Log ??= getLogFilePath() || undefined;
9468
- data.ErrorCode ??= defaultErrorCodeForResult(data.Result);
9584
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
9469
9585
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
9470
9586
  process.exitCode = EXIT_CODES[data.Result] ?? 1;
9471
- telemetry.trackEvent(CommonTelemetryEvents.Error, {
9472
- result: data.Result,
9473
- errorCode: data.ErrorCode,
9474
- retry: data.Retry,
9475
- message: data.Message
9476
- });
9477
- logOutput(normalizeOutputKeys(data), getOutputFormat());
9587
+ const { SuppressTelemetry, ...envelope } = data;
9588
+ if (!SuppressTelemetry) {
9589
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
9590
+ result: data.Result,
9591
+ errorCode: data.ErrorCode,
9592
+ retry: data.Retry,
9593
+ message: data.Message
9594
+ });
9595
+ }
9596
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
9478
9597
  }
9479
9598
  OutputFormatter.error = error;
9480
9599
  function emitList(code, items, opts) {
@@ -9810,7 +9929,7 @@ function format(first, ...rest) {
9810
9929
  });
9811
9930
  const extra = rest.slice(i);
9812
9931
  if (extra.length > 0) {
9813
- return result + " " + extra.map(String).join(" ");
9932
+ return `${result} ${extra.map(String).join(" ")}`;
9814
9933
  }
9815
9934
  return result;
9816
9935
  }
@@ -9944,6 +10063,10 @@ function instructionsFor(ctx, err) {
9944
10063
  if (status !== undefined && status >= 500 && status < 600) {
9945
10064
  return "Orchestrator returned a server error — retry; if it persists, check service status";
9946
10065
  }
10066
+ const connectivity = describeConnectivityError(err);
10067
+ if (connectivity) {
10068
+ return connectivity.instructions;
10069
+ }
9947
10070
  return GENERIC;
9948
10071
  }
9949
10072
  }
@@ -9959,7 +10082,7 @@ function setInteractivityMode(mode) {
9959
10082
  modeSlot.set(mode);
9960
10083
  }
9961
10084
  function getInteractivityMode() {
9962
- return modeSlot.get("never") ?? "never";
10085
+ return modeSlot.get("auto") ?? "auto";
9963
10086
  }
9964
10087
  function canPrompt() {
9965
10088
  const mode = getInteractivityMode();
@@ -9969,1430 +10092,8 @@ function canPrompt() {
9969
10092
  if (mode === "never") {
9970
10093
  return false;
9971
10094
  }
9972
- return getOutputSink().capabilities.isInteractive;
9973
- }
9974
- // ../../node_modules/jsonpath-plus/dist/index-node-esm.js
9975
- import vm from "vm";
9976
-
9977
- class Hooks {
9978
- add(name, callback, first) {
9979
- if (typeof arguments[0] != "string") {
9980
- for (let name2 in arguments[0]) {
9981
- this.add(name2, arguments[0][name2], arguments[1]);
9982
- }
9983
- } else {
9984
- (Array.isArray(name) ? name : [name]).forEach(function(name2) {
9985
- this[name2] = this[name2] || [];
9986
- if (callback) {
9987
- this[name2][first ? "unshift" : "push"](callback);
9988
- }
9989
- }, this);
9990
- }
9991
- }
9992
- run(name, env) {
9993
- this[name] = this[name] || [];
9994
- this[name].forEach(function(callback) {
9995
- callback.call(env && env.context ? env.context : env, env);
9996
- });
9997
- }
9998
- }
9999
-
10000
- class Plugins {
10001
- constructor(jsep) {
10002
- this.jsep = jsep;
10003
- this.registered = {};
10004
- }
10005
- register(...plugins) {
10006
- plugins.forEach((plugin) => {
10007
- if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
10008
- throw new Error("Invalid JSEP plugin format");
10009
- }
10010
- if (this.registered[plugin.name]) {
10011
- return;
10012
- }
10013
- plugin.init(this.jsep);
10014
- this.registered[plugin.name] = plugin;
10015
- });
10016
- }
10017
- }
10018
-
10019
- class Jsep {
10020
- static get version() {
10021
- return "1.4.0";
10022
- }
10023
- static toString() {
10024
- return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
10025
- }
10026
- static addUnaryOp(op_name) {
10027
- Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
10028
- Jsep.unary_ops[op_name] = 1;
10029
- return Jsep;
10030
- }
10031
- static addBinaryOp(op_name, precedence, isRightAssociative) {
10032
- Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
10033
- Jsep.binary_ops[op_name] = precedence;
10034
- if (isRightAssociative) {
10035
- Jsep.right_associative.add(op_name);
10036
- } else {
10037
- Jsep.right_associative.delete(op_name);
10038
- }
10039
- return Jsep;
10040
- }
10041
- static addIdentifierChar(char) {
10042
- Jsep.additional_identifier_chars.add(char);
10043
- return Jsep;
10044
- }
10045
- static addLiteral(literal_name, literal_value) {
10046
- Jsep.literals[literal_name] = literal_value;
10047
- return Jsep;
10048
- }
10049
- static removeUnaryOp(op_name) {
10050
- delete Jsep.unary_ops[op_name];
10051
- if (op_name.length === Jsep.max_unop_len) {
10052
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
10053
- }
10054
- return Jsep;
10055
- }
10056
- static removeAllUnaryOps() {
10057
- Jsep.unary_ops = {};
10058
- Jsep.max_unop_len = 0;
10059
- return Jsep;
10060
- }
10061
- static removeIdentifierChar(char) {
10062
- Jsep.additional_identifier_chars.delete(char);
10063
- return Jsep;
10064
- }
10065
- static removeBinaryOp(op_name) {
10066
- delete Jsep.binary_ops[op_name];
10067
- if (op_name.length === Jsep.max_binop_len) {
10068
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
10069
- }
10070
- Jsep.right_associative.delete(op_name);
10071
- return Jsep;
10072
- }
10073
- static removeAllBinaryOps() {
10074
- Jsep.binary_ops = {};
10075
- Jsep.max_binop_len = 0;
10076
- return Jsep;
10077
- }
10078
- static removeLiteral(literal_name) {
10079
- delete Jsep.literals[literal_name];
10080
- return Jsep;
10081
- }
10082
- static removeAllLiterals() {
10083
- Jsep.literals = {};
10084
- return Jsep;
10085
- }
10086
- get char() {
10087
- return this.expr.charAt(this.index);
10088
- }
10089
- get code() {
10090
- return this.expr.charCodeAt(this.index);
10091
- }
10092
- constructor(expr) {
10093
- this.expr = expr;
10094
- this.index = 0;
10095
- }
10096
- static parse(expr) {
10097
- return new Jsep(expr).parse();
10098
- }
10099
- static getMaxKeyLen(obj) {
10100
- return Math.max(0, ...Object.keys(obj).map((k) => k.length));
10101
- }
10102
- static isDecimalDigit(ch) {
10103
- return ch >= 48 && ch <= 57;
10104
- }
10105
- static binaryPrecedence(op_val) {
10106
- return Jsep.binary_ops[op_val] || 0;
10107
- }
10108
- static isIdentifierStart(ch) {
10109
- 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));
10110
- }
10111
- static isIdentifierPart(ch) {
10112
- return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
10113
- }
10114
- throwError(message) {
10115
- const error = new Error(message + " at character " + this.index);
10116
- error.index = this.index;
10117
- error.description = message;
10118
- throw error;
10119
- }
10120
- runHook(name, node) {
10121
- if (Jsep.hooks[name]) {
10122
- const env = {
10123
- context: this,
10124
- node
10125
- };
10126
- Jsep.hooks.run(name, env);
10127
- return env.node;
10128
- }
10129
- return node;
10130
- }
10131
- searchHook(name) {
10132
- if (Jsep.hooks[name]) {
10133
- const env = {
10134
- context: this
10135
- };
10136
- Jsep.hooks[name].find(function(callback) {
10137
- callback.call(env.context, env);
10138
- return env.node;
10139
- });
10140
- return env.node;
10141
- }
10142
- }
10143
- gobbleSpaces() {
10144
- let ch = this.code;
10145
- while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
10146
- ch = this.expr.charCodeAt(++this.index);
10147
- }
10148
- this.runHook("gobble-spaces");
10149
- }
10150
- parse() {
10151
- this.runHook("before-all");
10152
- const nodes = this.gobbleExpressions();
10153
- const node = nodes.length === 1 ? nodes[0] : {
10154
- type: Jsep.COMPOUND,
10155
- body: nodes
10156
- };
10157
- return this.runHook("after-all", node);
10158
- }
10159
- gobbleExpressions(untilICode) {
10160
- let nodes = [], ch_i, node;
10161
- while (this.index < this.expr.length) {
10162
- ch_i = this.code;
10163
- if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
10164
- this.index++;
10165
- } else {
10166
- if (node = this.gobbleExpression()) {
10167
- nodes.push(node);
10168
- } else if (this.index < this.expr.length) {
10169
- if (ch_i === untilICode) {
10170
- break;
10171
- }
10172
- this.throwError('Unexpected "' + this.char + '"');
10173
- }
10174
- }
10175
- }
10176
- return nodes;
10177
- }
10178
- gobbleExpression() {
10179
- const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
10180
- this.gobbleSpaces();
10181
- return this.runHook("after-expression", node);
10182
- }
10183
- gobbleBinaryOp() {
10184
- this.gobbleSpaces();
10185
- let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
10186
- let tc_len = to_check.length;
10187
- while (tc_len > 0) {
10188
- 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)))) {
10189
- this.index += tc_len;
10190
- return to_check;
10191
- }
10192
- to_check = to_check.substr(0, --tc_len);
10193
- }
10194
- return false;
10195
- }
10196
- gobbleBinaryExpression() {
10197
- let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
10198
- left = this.gobbleToken();
10199
- if (!left) {
10200
- return left;
10201
- }
10202
- biop = this.gobbleBinaryOp();
10203
- if (!biop) {
10204
- return left;
10205
- }
10206
- biop_info = {
10207
- value: biop,
10208
- prec: Jsep.binaryPrecedence(biop),
10209
- right_a: Jsep.right_associative.has(biop)
10210
- };
10211
- right = this.gobbleToken();
10212
- if (!right) {
10213
- this.throwError("Expected expression after " + biop);
10214
- }
10215
- stack = [left, biop_info, right];
10216
- while (biop = this.gobbleBinaryOp()) {
10217
- prec = Jsep.binaryPrecedence(biop);
10218
- if (prec === 0) {
10219
- this.index -= biop.length;
10220
- break;
10221
- }
10222
- biop_info = {
10223
- value: biop,
10224
- prec,
10225
- right_a: Jsep.right_associative.has(biop)
10226
- };
10227
- cur_biop = biop;
10228
- const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
10229
- while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
10230
- right = stack.pop();
10231
- biop = stack.pop().value;
10232
- left = stack.pop();
10233
- node = {
10234
- type: Jsep.BINARY_EXP,
10235
- operator: biop,
10236
- left,
10237
- right
10238
- };
10239
- stack.push(node);
10240
- }
10241
- node = this.gobbleToken();
10242
- if (!node) {
10243
- this.throwError("Expected expression after " + cur_biop);
10244
- }
10245
- stack.push(biop_info, node);
10246
- }
10247
- i = stack.length - 1;
10248
- node = stack[i];
10249
- while (i > 1) {
10250
- node = {
10251
- type: Jsep.BINARY_EXP,
10252
- operator: stack[i - 1].value,
10253
- left: stack[i - 2],
10254
- right: node
10255
- };
10256
- i -= 2;
10257
- }
10258
- return node;
10259
- }
10260
- gobbleToken() {
10261
- let ch, to_check, tc_len, node;
10262
- this.gobbleSpaces();
10263
- node = this.searchHook("gobble-token");
10264
- if (node) {
10265
- return this.runHook("after-token", node);
10266
- }
10267
- ch = this.code;
10268
- if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
10269
- return this.gobbleNumericLiteral();
10270
- }
10271
- if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
10272
- node = this.gobbleStringLiteral();
10273
- } else if (ch === Jsep.OBRACK_CODE) {
10274
- node = this.gobbleArray();
10275
- } else {
10276
- to_check = this.expr.substr(this.index, Jsep.max_unop_len);
10277
- tc_len = to_check.length;
10278
- while (tc_len > 0) {
10279
- 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)))) {
10280
- this.index += tc_len;
10281
- const argument = this.gobbleToken();
10282
- if (!argument) {
10283
- this.throwError("missing unaryOp argument");
10284
- }
10285
- return this.runHook("after-token", {
10286
- type: Jsep.UNARY_EXP,
10287
- operator: to_check,
10288
- argument,
10289
- prefix: true
10290
- });
10291
- }
10292
- to_check = to_check.substr(0, --tc_len);
10293
- }
10294
- if (Jsep.isIdentifierStart(ch)) {
10295
- node = this.gobbleIdentifier();
10296
- if (Jsep.literals.hasOwnProperty(node.name)) {
10297
- node = {
10298
- type: Jsep.LITERAL,
10299
- value: Jsep.literals[node.name],
10300
- raw: node.name
10301
- };
10302
- } else if (node.name === Jsep.this_str) {
10303
- node = {
10304
- type: Jsep.THIS_EXP
10305
- };
10306
- }
10307
- } else if (ch === Jsep.OPAREN_CODE) {
10308
- node = this.gobbleGroup();
10309
- }
10310
- }
10311
- if (!node) {
10312
- return this.runHook("after-token", false);
10313
- }
10314
- node = this.gobbleTokenProperty(node);
10315
- return this.runHook("after-token", node);
10316
- }
10317
- gobbleTokenProperty(node) {
10318
- this.gobbleSpaces();
10319
- let ch = this.code;
10320
- while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
10321
- let optional;
10322
- if (ch === Jsep.QUMARK_CODE) {
10323
- if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
10324
- break;
10325
- }
10326
- optional = true;
10327
- this.index += 2;
10328
- this.gobbleSpaces();
10329
- ch = this.code;
10330
- }
10331
- this.index++;
10332
- if (ch === Jsep.OBRACK_CODE) {
10333
- node = {
10334
- type: Jsep.MEMBER_EXP,
10335
- computed: true,
10336
- object: node,
10337
- property: this.gobbleExpression()
10338
- };
10339
- if (!node.property) {
10340
- this.throwError('Unexpected "' + this.char + '"');
10341
- }
10342
- this.gobbleSpaces();
10343
- ch = this.code;
10344
- if (ch !== Jsep.CBRACK_CODE) {
10345
- this.throwError("Unclosed [");
10346
- }
10347
- this.index++;
10348
- } else if (ch === Jsep.OPAREN_CODE) {
10349
- node = {
10350
- type: Jsep.CALL_EXP,
10351
- arguments: this.gobbleArguments(Jsep.CPAREN_CODE),
10352
- callee: node
10353
- };
10354
- } else if (ch === Jsep.PERIOD_CODE || optional) {
10355
- if (optional) {
10356
- this.index--;
10357
- }
10358
- this.gobbleSpaces();
10359
- node = {
10360
- type: Jsep.MEMBER_EXP,
10361
- computed: false,
10362
- object: node,
10363
- property: this.gobbleIdentifier()
10364
- };
10365
- }
10366
- if (optional) {
10367
- node.optional = true;
10368
- }
10369
- this.gobbleSpaces();
10370
- ch = this.code;
10371
- }
10372
- return node;
10373
- }
10374
- gobbleNumericLiteral() {
10375
- let number = "", ch, chCode;
10376
- while (Jsep.isDecimalDigit(this.code)) {
10377
- number += this.expr.charAt(this.index++);
10378
- }
10379
- if (this.code === Jsep.PERIOD_CODE) {
10380
- number += this.expr.charAt(this.index++);
10381
- while (Jsep.isDecimalDigit(this.code)) {
10382
- number += this.expr.charAt(this.index++);
10383
- }
10384
- }
10385
- ch = this.char;
10386
- if (ch === "e" || ch === "E") {
10387
- number += this.expr.charAt(this.index++);
10388
- ch = this.char;
10389
- if (ch === "+" || ch === "-") {
10390
- number += this.expr.charAt(this.index++);
10391
- }
10392
- while (Jsep.isDecimalDigit(this.code)) {
10393
- number += this.expr.charAt(this.index++);
10394
- }
10395
- if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
10396
- this.throwError("Expected exponent (" + number + this.char + ")");
10397
- }
10398
- }
10399
- chCode = this.code;
10400
- if (Jsep.isIdentifierStart(chCode)) {
10401
- this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
10402
- } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
10403
- this.throwError("Unexpected period");
10404
- }
10405
- return {
10406
- type: Jsep.LITERAL,
10407
- value: parseFloat(number),
10408
- raw: number
10409
- };
10410
- }
10411
- gobbleStringLiteral() {
10412
- let str = "";
10413
- const startIndex = this.index;
10414
- const quote = this.expr.charAt(this.index++);
10415
- let closed = false;
10416
- while (this.index < this.expr.length) {
10417
- let ch = this.expr.charAt(this.index++);
10418
- if (ch === quote) {
10419
- closed = true;
10420
- break;
10421
- } else if (ch === "\\") {
10422
- ch = this.expr.charAt(this.index++);
10423
- switch (ch) {
10424
- case "n":
10425
- str += `
10426
- `;
10427
- break;
10428
- case "r":
10429
- str += "\r";
10430
- break;
10431
- case "t":
10432
- str += "\t";
10433
- break;
10434
- case "b":
10435
- str += "\b";
10436
- break;
10437
- case "f":
10438
- str += "\f";
10439
- break;
10440
- case "v":
10441
- str += "\v";
10442
- break;
10443
- default:
10444
- str += ch;
10445
- }
10446
- } else {
10447
- str += ch;
10448
- }
10449
- }
10450
- if (!closed) {
10451
- this.throwError('Unclosed quote after "' + str + '"');
10452
- }
10453
- return {
10454
- type: Jsep.LITERAL,
10455
- value: str,
10456
- raw: this.expr.substring(startIndex, this.index)
10457
- };
10458
- }
10459
- gobbleIdentifier() {
10460
- let ch = this.code, start = this.index;
10461
- if (Jsep.isIdentifierStart(ch)) {
10462
- this.index++;
10463
- } else {
10464
- this.throwError("Unexpected " + this.char);
10465
- }
10466
- while (this.index < this.expr.length) {
10467
- ch = this.code;
10468
- if (Jsep.isIdentifierPart(ch)) {
10469
- this.index++;
10470
- } else {
10471
- break;
10472
- }
10473
- }
10474
- return {
10475
- type: Jsep.IDENTIFIER,
10476
- name: this.expr.slice(start, this.index)
10477
- };
10478
- }
10479
- gobbleArguments(termination) {
10480
- const args = [];
10481
- let closed = false;
10482
- let separator_count = 0;
10483
- while (this.index < this.expr.length) {
10484
- this.gobbleSpaces();
10485
- let ch_i = this.code;
10486
- if (ch_i === termination) {
10487
- closed = true;
10488
- this.index++;
10489
- if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
10490
- this.throwError("Unexpected token " + String.fromCharCode(termination));
10491
- }
10492
- break;
10493
- } else if (ch_i === Jsep.COMMA_CODE) {
10494
- this.index++;
10495
- separator_count++;
10496
- if (separator_count !== args.length) {
10497
- if (termination === Jsep.CPAREN_CODE) {
10498
- this.throwError("Unexpected token ,");
10499
- } else if (termination === Jsep.CBRACK_CODE) {
10500
- for (let arg = args.length;arg < separator_count; arg++) {
10501
- args.push(null);
10502
- }
10503
- }
10504
- }
10505
- } else if (args.length !== separator_count && separator_count !== 0) {
10506
- this.throwError("Expected comma");
10507
- } else {
10508
- const node = this.gobbleExpression();
10509
- if (!node || node.type === Jsep.COMPOUND) {
10510
- this.throwError("Expected comma");
10511
- }
10512
- args.push(node);
10513
- }
10514
- }
10515
- if (!closed) {
10516
- this.throwError("Expected " + String.fromCharCode(termination));
10517
- }
10518
- return args;
10519
- }
10520
- gobbleGroup() {
10521
- this.index++;
10522
- let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
10523
- if (this.code === Jsep.CPAREN_CODE) {
10524
- this.index++;
10525
- if (nodes.length === 1) {
10526
- return nodes[0];
10527
- } else if (!nodes.length) {
10528
- return false;
10529
- } else {
10530
- return {
10531
- type: Jsep.SEQUENCE_EXP,
10532
- expressions: nodes
10533
- };
10534
- }
10535
- } else {
10536
- this.throwError("Unclosed (");
10537
- }
10538
- }
10539
- gobbleArray() {
10540
- this.index++;
10541
- return {
10542
- type: Jsep.ARRAY_EXP,
10543
- elements: this.gobbleArguments(Jsep.CBRACK_CODE)
10544
- };
10545
- }
10546
- }
10547
- var hooks = new Hooks;
10548
- Object.assign(Jsep, {
10549
- hooks,
10550
- plugins: new Plugins(Jsep),
10551
- COMPOUND: "Compound",
10552
- SEQUENCE_EXP: "SequenceExpression",
10553
- IDENTIFIER: "Identifier",
10554
- MEMBER_EXP: "MemberExpression",
10555
- LITERAL: "Literal",
10556
- THIS_EXP: "ThisExpression",
10557
- CALL_EXP: "CallExpression",
10558
- UNARY_EXP: "UnaryExpression",
10559
- BINARY_EXP: "BinaryExpression",
10560
- ARRAY_EXP: "ArrayExpression",
10561
- TAB_CODE: 9,
10562
- LF_CODE: 10,
10563
- CR_CODE: 13,
10564
- SPACE_CODE: 32,
10565
- PERIOD_CODE: 46,
10566
- COMMA_CODE: 44,
10567
- SQUOTE_CODE: 39,
10568
- DQUOTE_CODE: 34,
10569
- OPAREN_CODE: 40,
10570
- CPAREN_CODE: 41,
10571
- OBRACK_CODE: 91,
10572
- CBRACK_CODE: 93,
10573
- QUMARK_CODE: 63,
10574
- SEMCOL_CODE: 59,
10575
- COLON_CODE: 58,
10576
- unary_ops: {
10577
- "-": 1,
10578
- "!": 1,
10579
- "~": 1,
10580
- "+": 1
10581
- },
10582
- binary_ops: {
10583
- "||": 1,
10584
- "??": 1,
10585
- "&&": 2,
10586
- "|": 3,
10587
- "^": 4,
10588
- "&": 5,
10589
- "==": 6,
10590
- "!=": 6,
10591
- "===": 6,
10592
- "!==": 6,
10593
- "<": 7,
10594
- ">": 7,
10595
- "<=": 7,
10596
- ">=": 7,
10597
- "<<": 8,
10598
- ">>": 8,
10599
- ">>>": 8,
10600
- "+": 9,
10601
- "-": 9,
10602
- "*": 10,
10603
- "/": 10,
10604
- "%": 10,
10605
- "**": 11
10606
- },
10607
- right_associative: new Set(["**"]),
10608
- additional_identifier_chars: new Set(["$", "_"]),
10609
- literals: {
10610
- true: true,
10611
- false: false,
10612
- null: null
10613
- },
10614
- this_str: "this"
10615
- });
10616
- Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
10617
- Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
10618
- var jsep = (expr) => new Jsep(expr).parse();
10619
- var stdClassProps = Object.getOwnPropertyNames(class Test {
10620
- });
10621
- Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach((m) => {
10622
- jsep[m] = Jsep[m];
10623
- });
10624
- jsep.Jsep = Jsep;
10625
- var CONDITIONAL_EXP = "ConditionalExpression";
10626
- var ternary = {
10627
- name: "ternary",
10628
- init(jsep2) {
10629
- jsep2.hooks.add("after-expression", function gobbleTernary(env) {
10630
- if (env.node && this.code === jsep2.QUMARK_CODE) {
10631
- this.index++;
10632
- const test = env.node;
10633
- const consequent = this.gobbleExpression();
10634
- if (!consequent) {
10635
- this.throwError("Expected expression");
10636
- }
10637
- this.gobbleSpaces();
10638
- if (this.code === jsep2.COLON_CODE) {
10639
- this.index++;
10640
- const alternate = this.gobbleExpression();
10641
- if (!alternate) {
10642
- this.throwError("Expected expression");
10643
- }
10644
- env.node = {
10645
- type: CONDITIONAL_EXP,
10646
- test,
10647
- consequent,
10648
- alternate
10649
- };
10650
- if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
10651
- let newTest = test;
10652
- while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
10653
- newTest = newTest.right;
10654
- }
10655
- env.node.test = newTest.right;
10656
- newTest.right = env.node;
10657
- env.node = test;
10658
- }
10659
- } else {
10660
- this.throwError("Expected :");
10661
- }
10662
- }
10663
- });
10664
- }
10665
- };
10666
- jsep.plugins.register(ternary);
10667
- var FSLASH_CODE = 47;
10668
- var BSLASH_CODE = 92;
10669
- var index = {
10670
- name: "regex",
10671
- init(jsep2) {
10672
- jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
10673
- if (this.code === FSLASH_CODE) {
10674
- const patternIndex = ++this.index;
10675
- let inCharSet = false;
10676
- while (this.index < this.expr.length) {
10677
- if (this.code === FSLASH_CODE && !inCharSet) {
10678
- const pattern = this.expr.slice(patternIndex, this.index);
10679
- let flags = "";
10680
- while (++this.index < this.expr.length) {
10681
- const code = this.code;
10682
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
10683
- flags += this.char;
10684
- } else {
10685
- break;
10686
- }
10687
- }
10688
- let value;
10689
- try {
10690
- value = new RegExp(pattern, flags);
10691
- } catch (e) {
10692
- this.throwError(e.message);
10693
- }
10694
- env.node = {
10695
- type: jsep2.LITERAL,
10696
- value,
10697
- raw: this.expr.slice(patternIndex - 1, this.index)
10698
- };
10699
- env.node = this.gobbleTokenProperty(env.node);
10700
- return env.node;
10701
- }
10702
- if (this.code === jsep2.OBRACK_CODE) {
10703
- inCharSet = true;
10704
- } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
10705
- inCharSet = false;
10706
- }
10707
- this.index += this.code === BSLASH_CODE ? 2 : 1;
10708
- }
10709
- this.throwError("Unclosed Regex");
10710
- }
10711
- });
10712
- }
10713
- };
10714
- var PLUS_CODE = 43;
10715
- var MINUS_CODE = 45;
10716
- var plugin = {
10717
- name: "assignment",
10718
- assignmentOperators: new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
10719
- updateOperators: [PLUS_CODE, MINUS_CODE],
10720
- assignmentPrecedence: 0.9,
10721
- init(jsep2) {
10722
- const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
10723
- plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
10724
- jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
10725
- const code = this.code;
10726
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
10727
- this.index += 2;
10728
- env.node = {
10729
- type: "UpdateExpression",
10730
- operator: code === PLUS_CODE ? "++" : "--",
10731
- argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
10732
- prefix: true
10733
- };
10734
- if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
10735
- this.throwError(`Unexpected ${env.node.operator}`);
10736
- }
10737
- }
10738
- });
10739
- jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
10740
- if (env.node) {
10741
- const code = this.code;
10742
- if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
10743
- if (!updateNodeTypes.includes(env.node.type)) {
10744
- this.throwError(`Unexpected ${env.node.operator}`);
10745
- }
10746
- this.index += 2;
10747
- env.node = {
10748
- type: "UpdateExpression",
10749
- operator: code === PLUS_CODE ? "++" : "--",
10750
- argument: env.node,
10751
- prefix: false
10752
- };
10753
- }
10754
- }
10755
- });
10756
- jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
10757
- if (env.node) {
10758
- updateBinariesToAssignments(env.node);
10759
- }
10760
- });
10761
- function updateBinariesToAssignments(node) {
10762
- if (plugin.assignmentOperators.has(node.operator)) {
10763
- node.type = "AssignmentExpression";
10764
- updateBinariesToAssignments(node.left);
10765
- updateBinariesToAssignments(node.right);
10766
- } else if (!node.operator) {
10767
- Object.values(node).forEach((val) => {
10768
- if (val && typeof val === "object") {
10769
- updateBinariesToAssignments(val);
10770
- }
10771
- });
10772
- }
10773
- }
10774
- }
10775
- };
10776
- jsep.plugins.register(index, plugin);
10777
- jsep.addUnaryOp("typeof");
10778
- jsep.addUnaryOp("void");
10779
- jsep.addLiteral("null", null);
10780
- jsep.addLiteral("undefined", undefined);
10781
- var BLOCKED_PROTO_PROPERTIES = new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
10782
- var SafeEval = {
10783
- evalAst(ast, subs) {
10784
- switch (ast.type) {
10785
- case "BinaryExpression":
10786
- case "LogicalExpression":
10787
- return SafeEval.evalBinaryExpression(ast, subs);
10788
- case "Compound":
10789
- return SafeEval.evalCompound(ast, subs);
10790
- case "ConditionalExpression":
10791
- return SafeEval.evalConditionalExpression(ast, subs);
10792
- case "Identifier":
10793
- return SafeEval.evalIdentifier(ast, subs);
10794
- case "Literal":
10795
- return SafeEval.evalLiteral(ast, subs);
10796
- case "MemberExpression":
10797
- return SafeEval.evalMemberExpression(ast, subs);
10798
- case "UnaryExpression":
10799
- return SafeEval.evalUnaryExpression(ast, subs);
10800
- case "ArrayExpression":
10801
- return SafeEval.evalArrayExpression(ast, subs);
10802
- case "CallExpression":
10803
- return SafeEval.evalCallExpression(ast, subs);
10804
- case "AssignmentExpression":
10805
- return SafeEval.evalAssignmentExpression(ast, subs);
10806
- default:
10807
- throw SyntaxError("Unexpected expression", ast);
10808
- }
10809
- },
10810
- evalBinaryExpression(ast, subs) {
10811
- const result = {
10812
- "||": (a, b) => a || b(),
10813
- "&&": (a, b) => a && b(),
10814
- "|": (a, b) => a | b(),
10815
- "^": (a, b) => a ^ b(),
10816
- "&": (a, b) => a & b(),
10817
- "==": (a, b) => a == b(),
10818
- "!=": (a, b) => a != b(),
10819
- "===": (a, b) => a === b(),
10820
- "!==": (a, b) => a !== b(),
10821
- "<": (a, b) => a < b(),
10822
- ">": (a, b) => a > b(),
10823
- "<=": (a, b) => a <= b(),
10824
- ">=": (a, b) => a >= b(),
10825
- "<<": (a, b) => a << b(),
10826
- ">>": (a, b) => a >> b(),
10827
- ">>>": (a, b) => a >>> b(),
10828
- "+": (a, b) => a + b(),
10829
- "-": (a, b) => a - b(),
10830
- "*": (a, b) => a * b(),
10831
- "/": (a, b) => a / b(),
10832
- "%": (a, b) => a % b()
10833
- }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
10834
- return result;
10835
- },
10836
- evalCompound(ast, subs) {
10837
- let last;
10838
- for (let i = 0;i < ast.body.length; i++) {
10839
- if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
10840
- i += 1;
10841
- }
10842
- const expr = ast.body[i];
10843
- last = SafeEval.evalAst(expr, subs);
10844
- }
10845
- return last;
10846
- },
10847
- evalConditionalExpression(ast, subs) {
10848
- if (SafeEval.evalAst(ast.test, subs)) {
10849
- return SafeEval.evalAst(ast.consequent, subs);
10850
- }
10851
- return SafeEval.evalAst(ast.alternate, subs);
10852
- },
10853
- evalIdentifier(ast, subs) {
10854
- if (Object.hasOwn(subs, ast.name)) {
10855
- return subs[ast.name];
10856
- }
10857
- throw ReferenceError(`${ast.name} is not defined`);
10858
- },
10859
- evalLiteral(ast) {
10860
- return ast.value;
10861
- },
10862
- evalMemberExpression(ast, subs) {
10863
- const prop = String(ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name);
10864
- const obj = SafeEval.evalAst(ast.object, subs);
10865
- if (obj === undefined || obj === null) {
10866
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
10867
- }
10868
- if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
10869
- throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
10870
- }
10871
- const result = obj[prop];
10872
- if (typeof result === "function") {
10873
- return result.bind(obj);
10874
- }
10875
- return result;
10876
- },
10877
- evalUnaryExpression(ast, subs) {
10878
- const result = {
10879
- "-": (a) => -SafeEval.evalAst(a, subs),
10880
- "!": (a) => !SafeEval.evalAst(a, subs),
10881
- "~": (a) => ~SafeEval.evalAst(a, subs),
10882
- "+": (a) => +SafeEval.evalAst(a, subs),
10883
- typeof: (a) => typeof SafeEval.evalAst(a, subs),
10884
- void: (a) => void SafeEval.evalAst(a, subs)
10885
- }[ast.operator](ast.argument);
10886
- return result;
10887
- },
10888
- evalArrayExpression(ast, subs) {
10889
- return ast.elements.map((el) => SafeEval.evalAst(el, subs));
10890
- },
10891
- evalCallExpression(ast, subs) {
10892
- const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
10893
- const func = SafeEval.evalAst(ast.callee, subs);
10894
- if (func === Function) {
10895
- throw new Error("Function constructor is disabled");
10896
- }
10897
- return func(...args);
10898
- },
10899
- evalAssignmentExpression(ast, subs) {
10900
- if (ast.left.type !== "Identifier") {
10901
- throw SyntaxError("Invalid left-hand side in assignment");
10902
- }
10903
- const id = ast.left.name;
10904
- const value = SafeEval.evalAst(ast.right, subs);
10905
- subs[id] = value;
10906
- return subs[id];
10907
- }
10908
- };
10909
-
10910
- class SafeScript {
10911
- constructor(expr) {
10912
- this.code = expr;
10913
- this.ast = jsep(this.code);
10914
- }
10915
- runInNewContext(context) {
10916
- const keyMap = Object.assign(Object.create(null), context);
10917
- return SafeEval.evalAst(this.ast, keyMap);
10918
- }
10919
- }
10920
- function push(arr, item) {
10921
- arr = arr.slice();
10922
- arr.push(item);
10923
- return arr;
10924
- }
10925
- function unshift(item, arr) {
10926
- arr = arr.slice();
10927
- arr.unshift(item);
10928
- return arr;
10929
- }
10930
-
10931
- class NewError extends Error {
10932
- constructor(value) {
10933
- super('JSONPath should not be called with "new" (it prevents return ' + "of (unwrapped) scalar values)");
10934
- this.avoidNew = true;
10935
- this.value = value;
10936
- this.name = "NewError";
10937
- }
10938
- }
10939
- function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
10940
- if (!(this instanceof JSONPath)) {
10941
- try {
10942
- return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
10943
- } catch (e) {
10944
- if (!e.avoidNew) {
10945
- throw e;
10946
- }
10947
- return e.value;
10948
- }
10949
- }
10950
- if (typeof opts === "string") {
10951
- otherTypeCallback = callback;
10952
- callback = obj;
10953
- obj = expr;
10954
- expr = opts;
10955
- opts = null;
10956
- }
10957
- const optObj = opts && typeof opts === "object";
10958
- opts = opts || {};
10959
- this.json = opts.json || obj;
10960
- this.path = opts.path || expr;
10961
- this.resultType = opts.resultType || "value";
10962
- this.flatten = opts.flatten || false;
10963
- this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
10964
- this.sandbox = opts.sandbox || {};
10965
- this.eval = opts.eval === undefined ? "safe" : opts.eval;
10966
- this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
10967
- this.parent = opts.parent || null;
10968
- this.parentProperty = opts.parentProperty || null;
10969
- this.callback = opts.callback || callback || null;
10970
- this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
10971
- throw new TypeError("You must supply an otherTypeCallback callback option " + "with the @other() operator.");
10972
- };
10973
- if (opts.autostart !== false) {
10974
- const args = {
10975
- path: optObj ? opts.path : expr
10976
- };
10977
- if (!optObj) {
10978
- args.json = obj;
10979
- } else if ("json" in opts) {
10980
- args.json = opts.json;
10981
- }
10982
- const ret = this.evaluate(args);
10983
- if (!ret || typeof ret !== "object") {
10984
- throw new NewError(ret);
10985
- }
10986
- return ret;
10987
- }
10988
- }
10989
- JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
10990
- let currParent = this.parent, currParentProperty = this.parentProperty;
10991
- let {
10992
- flatten,
10993
- wrap
10994
- } = this;
10995
- this.currResultType = this.resultType;
10996
- this.currEval = this.eval;
10997
- this.currSandbox = this.sandbox;
10998
- callback = callback || this.callback;
10999
- this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
11000
- json = json || this.json;
11001
- expr = expr || this.path;
11002
- if (expr && typeof expr === "object" && !Array.isArray(expr)) {
11003
- if (!expr.path && expr.path !== "") {
11004
- throw new TypeError('You must supply a "path" property when providing an object ' + "argument to JSONPath.evaluate().");
11005
- }
11006
- if (!Object.hasOwn(expr, "json")) {
11007
- throw new TypeError('You must supply a "json" property when providing an object ' + "argument to JSONPath.evaluate().");
11008
- }
11009
- ({
11010
- json
11011
- } = expr);
11012
- flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
11013
- this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
11014
- this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
11015
- wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
11016
- this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
11017
- callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
11018
- this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
11019
- currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
11020
- currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
11021
- expr = expr.path;
11022
- }
11023
- currParent = currParent || null;
11024
- currParentProperty = currParentProperty || null;
11025
- if (Array.isArray(expr)) {
11026
- expr = JSONPath.toPathString(expr);
11027
- }
11028
- if (!expr && expr !== "" || !json) {
11029
- return;
11030
- }
11031
- const exprList = JSONPath.toPathArray(expr);
11032
- if (exprList[0] === "$" && exprList.length > 1) {
11033
- exprList.shift();
11034
- }
11035
- this._hasParentSelector = null;
11036
- const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
11037
- return ea && !ea.isParentSelector;
11038
- });
11039
- if (!result.length) {
11040
- return wrap ? [] : undefined;
11041
- }
11042
- if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
11043
- return this._getPreferredOutput(result[0]);
11044
- }
11045
- return result.reduce((rslt, ea) => {
11046
- const valOrPath = this._getPreferredOutput(ea);
11047
- if (flatten && Array.isArray(valOrPath)) {
11048
- rslt = rslt.concat(valOrPath);
11049
- } else {
11050
- rslt.push(valOrPath);
11051
- }
11052
- return rslt;
11053
- }, []);
11054
- };
11055
- JSONPath.prototype._getPreferredOutput = function(ea) {
11056
- const resultType = this.currResultType;
11057
- switch (resultType) {
11058
- case "all": {
11059
- const path3 = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
11060
- ea.pointer = JSONPath.toPointer(path3);
11061
- ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
11062
- return ea;
11063
- }
11064
- case "value":
11065
- case "parent":
11066
- case "parentProperty":
11067
- return ea[resultType];
11068
- case "path":
11069
- return JSONPath.toPathString(ea[resultType]);
11070
- case "pointer":
11071
- return JSONPath.toPointer(ea.path);
11072
- default:
11073
- throw new TypeError("Unknown result type");
11074
- }
11075
- };
11076
- JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
11077
- if (callback) {
11078
- const preferredOutput = this._getPreferredOutput(fullRetObj);
11079
- fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
11080
- callback(preferredOutput, type, fullRetObj);
11081
- }
11082
- };
11083
- JSONPath.prototype._trace = function(expr, val, path3, parent, parentPropName, callback, hasArrExpr, literalPriority) {
11084
- let retObj;
11085
- if (!expr.length) {
11086
- retObj = {
11087
- path: path3,
11088
- value: val,
11089
- parent,
11090
- parentProperty: parentPropName,
11091
- hasArrExpr
11092
- };
11093
- this._handleCallback(retObj, callback, "value");
11094
- return retObj;
11095
- }
11096
- const loc = expr[0], x = expr.slice(1);
11097
- const ret = [];
11098
- function addRet(elems) {
11099
- if (Array.isArray(elems)) {
11100
- elems.forEach((t) => {
11101
- ret.push(t);
11102
- });
11103
- } else {
11104
- ret.push(elems);
11105
- }
11106
- }
11107
- if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
11108
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr));
11109
- } else if (loc === "*") {
11110
- this._walk(val, (m) => {
11111
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true, true));
11112
- });
11113
- } else if (loc === "..") {
11114
- addRet(this._trace(x, val, path3, parent, parentPropName, callback, hasArrExpr));
11115
- this._walk(val, (m) => {
11116
- if (typeof val[m] === "object") {
11117
- addRet(this._trace(expr.slice(), val[m], push(path3, m), val, m, callback, true));
11118
- }
11119
- });
11120
- } else if (loc === "^") {
11121
- this._hasParentSelector = true;
11122
- return {
11123
- path: path3.slice(0, -1),
11124
- expr: x,
11125
- isParentSelector: true
11126
- };
11127
- } else if (loc === "~") {
11128
- retObj = {
11129
- path: push(path3, loc),
11130
- value: parentPropName,
11131
- parent,
11132
- parentProperty: null
11133
- };
11134
- this._handleCallback(retObj, callback, "property");
11135
- return retObj;
11136
- } else if (loc === "$") {
11137
- addRet(this._trace(x, val, path3, null, null, callback, hasArrExpr));
11138
- } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
11139
- addRet(this._slice(loc, x, val, path3, parent, parentPropName, callback));
11140
- } else if (loc.indexOf("?(") === 0) {
11141
- if (this.currEval === false) {
11142
- throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
11143
- }
11144
- const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
11145
- const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
11146
- if (nested) {
11147
- this._walk(val, (m) => {
11148
- const npath = [nested[2]];
11149
- const nvalue = nested[1] ? val[m][nested[1]] : val[m];
11150
- const filterResults = this._trace(npath, nvalue, path3, parent, parentPropName, callback, true);
11151
- if (filterResults.length > 0) {
11152
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
11153
- }
11154
- });
11155
- } else {
11156
- this._walk(val, (m) => {
11157
- if (this._eval(safeLoc, val[m], m, path3, parent, parentPropName)) {
11158
- addRet(this._trace(x, val[m], push(path3, m), val, m, callback, true));
11159
- }
11160
- });
11161
- }
11162
- } else if (loc[0] === "(") {
11163
- if (this.currEval === false) {
11164
- throw new Error("Eval [(expr)] prevented in JSONPath expression.");
11165
- }
11166
- addRet(this._trace(unshift(this._eval(loc, val, path3.at(-1), path3.slice(0, -1), parent, parentPropName), x), val, path3, parent, parentPropName, callback, hasArrExpr));
11167
- } else if (loc[0] === "@") {
11168
- let addType = false;
11169
- const valueType = loc.slice(1, -2);
11170
- switch (valueType) {
11171
- case "scalar":
11172
- if (!val || !["object", "function"].includes(typeof val)) {
11173
- addType = true;
11174
- }
11175
- break;
11176
- case "boolean":
11177
- case "string":
11178
- case "undefined":
11179
- case "function":
11180
- if (typeof val === valueType) {
11181
- addType = true;
11182
- }
11183
- break;
11184
- case "integer":
11185
- if (Number.isFinite(val) && !(val % 1)) {
11186
- addType = true;
11187
- }
11188
- break;
11189
- case "number":
11190
- if (Number.isFinite(val)) {
11191
- addType = true;
11192
- }
11193
- break;
11194
- case "nonFinite":
11195
- if (typeof val === "number" && !Number.isFinite(val)) {
11196
- addType = true;
11197
- }
11198
- break;
11199
- case "object":
11200
- if (val && typeof val === valueType) {
11201
- addType = true;
11202
- }
11203
- break;
11204
- case "array":
11205
- if (Array.isArray(val)) {
11206
- addType = true;
11207
- }
11208
- break;
11209
- case "other":
11210
- addType = this.currOtherTypeCallback(val, path3, parent, parentPropName);
11211
- break;
11212
- case "null":
11213
- if (val === null) {
11214
- addType = true;
11215
- }
11216
- break;
11217
- default:
11218
- throw new TypeError("Unknown value type " + valueType);
11219
- }
11220
- if (addType) {
11221
- retObj = {
11222
- path: path3,
11223
- value: val,
11224
- parent,
11225
- parentProperty: parentPropName
11226
- };
11227
- this._handleCallback(retObj, callback, "value");
11228
- return retObj;
11229
- }
11230
- } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
11231
- const locProp = loc.slice(1);
11232
- addRet(this._trace(x, val[locProp], push(path3, locProp), val, locProp, callback, hasArrExpr, true));
11233
- } else if (loc.includes(",")) {
11234
- const parts = loc.split(",");
11235
- for (const part of parts) {
11236
- addRet(this._trace(unshift(part, x), val, path3, parent, parentPropName, callback, true));
11237
- }
11238
- } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
11239
- addRet(this._trace(x, val[loc], push(path3, loc), val, loc, callback, hasArrExpr, true));
11240
- }
11241
- if (this._hasParentSelector) {
11242
- for (let t = 0;t < ret.length; t++) {
11243
- const rett = ret[t];
11244
- if (rett && rett.isParentSelector) {
11245
- const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
11246
- if (Array.isArray(tmp)) {
11247
- ret[t] = tmp[0];
11248
- const tl = tmp.length;
11249
- for (let tt = 1;tt < tl; tt++) {
11250
- t++;
11251
- ret.splice(t, 0, tmp[tt]);
11252
- }
11253
- } else {
11254
- ret[t] = tmp;
11255
- }
11256
- }
11257
- }
11258
- }
11259
- return ret;
11260
- };
11261
- JSONPath.prototype._walk = function(val, f) {
11262
- if (Array.isArray(val)) {
11263
- const n = val.length;
11264
- for (let i = 0;i < n; i++) {
11265
- f(i);
11266
- }
11267
- } else if (val && typeof val === "object") {
11268
- Object.keys(val).forEach((m) => {
11269
- f(m);
11270
- });
11271
- }
11272
- };
11273
- JSONPath.prototype._slice = function(loc, expr, val, path3, parent, parentPropName, callback) {
11274
- if (!Array.isArray(val)) {
11275
- return;
11276
- }
11277
- const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
11278
- let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
11279
- start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
11280
- end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
11281
- const ret = [];
11282
- for (let i = start;i < end; i += step) {
11283
- const tmp = this._trace(unshift(i, expr), val, path3, parent, parentPropName, callback, true);
11284
- tmp.forEach((t) => {
11285
- ret.push(t);
11286
- });
11287
- }
11288
- return ret;
11289
- };
11290
- JSONPath.prototype._eval = function(code, _v, _vname, path3, parent, parentPropName) {
11291
- this.currSandbox._$_parentProperty = parentPropName;
11292
- this.currSandbox._$_parent = parent;
11293
- this.currSandbox._$_property = _vname;
11294
- this.currSandbox._$_root = this.json;
11295
- this.currSandbox._$_v = _v;
11296
- const containsPath = code.includes("@path");
11297
- if (containsPath) {
11298
- this.currSandbox._$_path = JSONPath.toPathString(path3.concat([_vname]));
11299
- }
11300
- const scriptCacheKey = this.currEval + "Script:" + code;
11301
- if (!JSONPath.cache[scriptCacheKey]) {
11302
- let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
11303
- if (containsPath) {
11304
- script = script.replaceAll("@path", "_$_path");
11305
- }
11306
- if (this.currEval === "safe" || this.currEval === true || this.currEval === undefined) {
11307
- JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
11308
- } else if (this.currEval === "native") {
11309
- JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
11310
- } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
11311
- const CurrEval = this.currEval;
11312
- JSONPath.cache[scriptCacheKey] = new CurrEval(script);
11313
- } else if (typeof this.currEval === "function") {
11314
- JSONPath.cache[scriptCacheKey] = {
11315
- runInNewContext: (context) => this.currEval(script, context)
11316
- };
11317
- } else {
11318
- throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
11319
- }
11320
- }
11321
- try {
11322
- return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
11323
- } catch (e) {
11324
- if (this.ignoreEvalErrors) {
11325
- return false;
11326
- }
11327
- throw new Error("jsonPath: " + e.message + ": " + code);
11328
- }
11329
- };
11330
- JSONPath.cache = {};
11331
- JSONPath.toPathString = function(pathArr) {
11332
- const x = pathArr, n = x.length;
11333
- let p = "$";
11334
- for (let i = 1;i < n; i++) {
11335
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
11336
- p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
11337
- }
11338
- }
11339
- return p;
11340
- };
11341
- JSONPath.toPointer = function(pointer) {
11342
- const x = pointer, n = x.length;
11343
- let p = "";
11344
- for (let i = 1;i < n; i++) {
11345
- if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
11346
- p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
11347
- }
11348
- }
11349
- return p;
11350
- };
11351
- JSONPath.toPathArray = function(expr) {
11352
- const {
11353
- cache
11354
- } = JSONPath;
11355
- if (cache[expr]) {
11356
- return cache[expr].concat();
11357
- }
11358
- const subx = [];
11359
- const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
11360
- return "[#" + (subx.push($1) - 1) + "]";
11361
- }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
11362
- return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
11363
- }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
11364
- return ";" + ups.split("").join(";") + ";";
11365
- }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
11366
- const exprList = normalized.split(";").map(function(exp) {
11367
- const match = exp.match(/#(\d+)/u);
11368
- return !match || !match[1] ? exp : subx[match[1]];
11369
- });
11370
- cache[expr] = exprList;
11371
- return cache[expr].concat();
11372
- };
11373
- JSONPath.prototype.safeVm = {
11374
- Script: SafeScript
11375
- };
11376
- JSONPath.prototype.vm = vm;
11377
-
11378
- // src/jsonpath.ts
11379
- function evaluateJsonPath(data, expression) {
11380
- const results = JSONPath({
11381
- path: expression,
11382
- json: data
11383
- });
11384
- if (results.length === 0) {
11385
- return "";
11386
- }
11387
- return results.map((v) => v !== null && typeof v === "object" ? JSON.stringify(v) : String(v ?? "")).join(`
11388
- `);
11389
- }
11390
-
11391
- class JsonPathError extends Error {
11392
- constructor(message) {
11393
- super(message);
11394
- this.name = "JsonPathError";
11395
- }
10095
+ const capabilities = getOutputSink().capabilities;
10096
+ return capabilities.isInteractive && capabilities.canReadInput;
11396
10097
  }
11397
10098
  // src/option-aliases.ts
11398
10099
  function resolveDeprecatedOptionAlias({
@@ -11506,10 +10207,14 @@ function buildActionCenterTaskUrl(baseUrl, org, tenant, taskId) {
11506
10207
  }
11507
10208
  // src/package-metadata-options.ts
11508
10209
  function registerPackageMetadataOptions(command) {
11509
- return command.option("--repository-url <url>", "Source repository URL (recorded in the package for traceability)").option("--repository-commit <sha>", "Source repository commit hash (recorded in the package for traceability)").option("--repository-branch <branch>", "Source repository branch").option("--repository-type <type>", "Source repository type (defaults to 'git' when --repository-url is set)").option("--release-notes <text>", "Release notes for the package").option("--project-url <url>", "Automation Hub idea URL");
10210
+ return command.option("--author <author>", "Package author").option("--description <text>", "Package description").option("--repository-url <url>", "Source repository URL (recorded in the package for traceability)").option("--repository-commit <sha>", "Source repository commit hash (recorded in the package for traceability)").option("--repository-branch <branch>", "Source repository branch").option("--repository-type <type>", "Source repository type (defaults to 'git' when --repository-url is set)").option("--release-notes <text>", "Release notes for the package").option("--project-url <url>", "Automation Hub idea URL");
11510
10211
  }
11511
10212
  function mapPackageMetadataOptions(opts) {
11512
10213
  const fields = {};
10214
+ if (opts.author !== undefined)
10215
+ fields.author = opts.author;
10216
+ if (opts.description !== undefined)
10217
+ fields.description = opts.description;
11513
10218
  if (opts.releaseNotes !== undefined)
11514
10219
  fields.releaseNotes = opts.releaseNotes;
11515
10220
  if (opts.projectUrl !== undefined)
@@ -12021,6 +10726,25 @@ function isFailureStatus(status) {
12021
10726
  function isSuccessStatus(status) {
12022
10727
  return isTerminalStatus(status) && !isFailureStatus(status);
12023
10728
  }
10729
+ // src/preview.ts
10730
+ var previewSlot = singleton("PreviewBuild");
10731
+ function setPreviewBuild(isPreview) {
10732
+ previewSlot.set(isPreview);
10733
+ }
10734
+ function isPreviewBuild() {
10735
+ return previewSlot.get(false) ?? false;
10736
+ }
10737
+ function previewOnly(register) {
10738
+ if (isPreviewBuild()) {
10739
+ register();
10740
+ }
10741
+ }
10742
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
10743
+ if (isPreviewBuild()) {
10744
+ return this.command(nameAndArgs, opts);
10745
+ }
10746
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
10747
+ };
12024
10748
  // src/screen-logger.ts
12025
10749
  var ScreenLogger;
12026
10750
  ((ScreenLogger) => {
@@ -12032,10 +10756,16 @@ var ScreenLogger;
12032
10756
  })(ScreenLogger ||= {});
12033
10757
  // src/sdk-user-agent.ts
12034
10758
  var USER_AGENT_HEADER = "User-Agent";
10759
+ var CODING_AGENT_HEADER = "x-coding-agent-info";
10760
+ var AGENT_PROPERTY = "agent";
10761
+ var CODING_AGENT_PROPERTY = "CodingAgent";
12035
10762
  var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
12036
10763
  function userAgentPatchKey(userAgent) {
12037
10764
  return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
12038
10765
  }
10766
+ function codingAgentPatchKey() {
10767
+ return Symbol.for("@uipath/common/sdk-coding-agent");
10768
+ }
12039
10769
  function splitUserAgentTokens(value) {
12040
10770
  return value?.trim().split(/\s+/).filter(Boolean) ?? [];
12041
10771
  }
@@ -12053,8 +10783,15 @@ function appendUserAgentToken(value, userAgent) {
12053
10783
  function getEffectiveUserAgent(userAgent) {
12054
10784
  return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
12055
10785
  }
12056
- function isHeadersLike(headers) {
12057
- return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
10786
+ function getHeaderName(headers, headerName) {
10787
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
10788
+ }
10789
+ function getSdkAgentInfo() {
10790
+ if (isTelemetryDisabled()) {
10791
+ return;
10792
+ }
10793
+ const agent = getGlobalTelemetryProperties()?.[AGENT_PROPERTY];
10794
+ return agent === undefined ? undefined : String(agent);
12058
10795
  }
12059
10796
  function getSdkUserAgentToken(pkg) {
12060
10797
  const packageName = pkg.name.replace(/^@uipath\//, "");
@@ -12069,59 +10806,42 @@ function setSdkUserAgentHostToken(token) {
12069
10806
  }
12070
10807
  function addSdkUserAgentHeader(headers, userAgent) {
12071
10808
  const result = { ...headers ?? {} };
12072
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
12073
- const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
12074
- if (headerName) {
12075
- result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
12076
- } else {
12077
- result[USER_AGENT_HEADER] = effectiveUserAgent;
12078
- }
10809
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
10810
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
12079
10811
  return result;
12080
10812
  }
12081
- function withSdkUserAgentHeader(headers, userAgent) {
12082
- const effectiveUserAgent = getEffectiveUserAgent(userAgent);
12083
- if (isHeadersLike(headers)) {
12084
- headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
12085
- return headers;
12086
- }
12087
- if (Array.isArray(headers)) {
12088
- const result = headers.map((entry) => {
12089
- const [key, value] = entry;
12090
- return [key, value];
12091
- });
12092
- const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
12093
- if (headerIndex >= 0) {
12094
- const [key, value] = result[headerIndex];
12095
- result[headerIndex] = [
12096
- key,
12097
- appendUserAgentToken(value, effectiveUserAgent)
12098
- ];
12099
- } else {
12100
- result.push([USER_AGENT_HEADER, effectiveUserAgent]);
12101
- }
10813
+ function addSdkCodingAgentHeader(headers, agent = getSdkAgentInfo()) {
10814
+ const result = { ...headers ?? {} };
10815
+ if (agent === undefined) {
12102
10816
  return result;
12103
10817
  }
12104
- return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
10818
+ const headerName = getHeaderName(result, CODING_AGENT_HEADER);
10819
+ result[headerName ?? CODING_AGENT_HEADER] = JSON.stringify({
10820
+ [CODING_AGENT_PROPERTY]: agent
10821
+ });
10822
+ return result;
12105
10823
  }
12106
- function withUserAgentInitOverride(initOverrides, userAgent) {
10824
+ function asHeaderRecord(headers) {
10825
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
10826
+ }
10827
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
12107
10828
  return async (requestContext) => {
12108
- const initWithUserAgent = {
10829
+ const initWithHeaders = {
12109
10830
  ...requestContext.init,
12110
- headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
10831
+ headers: forward(asHeaderRecord(requestContext.init.headers))
12111
10832
  };
12112
10833
  const override = typeof initOverrides === "function" ? await initOverrides({
12113
10834
  ...requestContext,
12114
- init: initWithUserAgent
10835
+ init: initWithHeaders
12115
10836
  }) : initOverrides;
12116
10837
  return {
12117
10838
  ...override ?? {},
12118
- headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
10839
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
12119
10840
  };
12120
10841
  };
12121
10842
  }
12122
- function installSdkUserAgentHeader(BaseApiClass, userAgent) {
10843
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
12123
10844
  const prototype = BaseApiClass.prototype;
12124
- const patchKey = userAgentPatchKey(userAgent);
12125
10845
  if (prototype[patchKey]) {
12126
10846
  return;
12127
10847
  }
@@ -12129,13 +10849,19 @@ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
12129
10849
  throw new Error("Generated BaseAPI request function not found.");
12130
10850
  }
12131
10851
  const originalRequest = prototype.request;
12132
- prototype.request = function requestWithUserAgent(context, initOverrides) {
12133
- return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
10852
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
10853
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
12134
10854
  };
12135
10855
  Object.defineProperty(prototype, patchKey, {
12136
10856
  value: true
12137
10857
  });
12138
10858
  }
10859
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
10860
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
10861
+ }
10862
+ function installSdkCodingAgentHeader(BaseApiClass) {
10863
+ installRequestHeaderForwarding(BaseApiClass, codingAgentPatchKey(), (headers) => addSdkCodingAgentHeader(headers));
10864
+ }
12139
10865
  // src/stdin.ts
12140
10866
  async function readStdin() {
12141
10867
  if (process.stdin.isTTY) {
@@ -12151,6 +10877,44 @@ async function readStdin() {
12151
10877
  process.stdin.on("error", reject);
12152
10878
  });
12153
10879
  }
10880
+ // src/telemetry/browser-context-storage.ts
10881
+ class BrowserContextStorage {
10882
+ contextStack = [];
10883
+ run(context, fn) {
10884
+ this.contextStack.push(context);
10885
+ try {
10886
+ const result = fn();
10887
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
10888
+ return result.finally(() => {
10889
+ this.contextStack.pop();
10890
+ });
10891
+ }
10892
+ this.contextStack.pop();
10893
+ return result;
10894
+ } catch (error) {
10895
+ this.contextStack.pop();
10896
+ throw error;
10897
+ }
10898
+ }
10899
+ getContext() {
10900
+ return this.contextStack.length > 0 ? this.contextStack[this.contextStack.length - 1] : undefined;
10901
+ }
10902
+ }
10903
+ // src/telemetry/console-telemetry-provider.ts
10904
+ class ConsoleTelemetryProvider {
10905
+ async trackEvent(eventName, _properties) {
10906
+ console.debug(`[Telemetry] Event: ${eventName}`);
10907
+ }
10908
+ async trackException(error, _properties) {
10909
+ console.error(`[Telemetry] Exception: ${error.message}`);
10910
+ }
10911
+ async trackRequest(name, duration, success, _properties) {
10912
+ console.debug(`[Telemetry] Request: ${name} (${duration}ms, ${success ? "ok" : "fail"})`);
10913
+ }
10914
+ async trackDependency(name, type, duration, success, _properties) {
10915
+ console.debug(`[Telemetry] Dependency: ${name} [${type}] (${duration}ms, ${success ? "ok" : "fail"})`);
10916
+ }
10917
+ }
12154
10918
  // src/tool-provider.ts
12155
10919
  var factorySlot = singleton("PackagerFactoryProvider");
12156
10920
  function setPackagerFactoryProvider(provider) {
@@ -12164,7 +10928,6 @@ async function ensurePackagerFactory(verb) {
12164
10928
  await provider(verb);
12165
10929
  }
12166
10930
  export {
12167
- withSdkUserAgentHeader,
12168
10931
  withCompleter,
12169
10932
  warnDeprecatedTenantOption,
12170
10933
  warnDeprecatedOptionAlias,
@@ -12175,6 +10938,7 @@ export {
12175
10938
  singleton,
12176
10939
  setSdkUserAgentHostToken,
12177
10940
  setProcessContextPollSignal,
10941
+ setPreviewBuild,
12178
10942
  setPackagerFactoryProvider,
12179
10943
  setOutputFormatExplicit,
12180
10944
  setOutputFormat,
@@ -12194,6 +10958,7 @@ export {
12194
10958
  readStdin,
12195
10959
  readRegistryValue,
12196
10960
  processContext,
10961
+ previewOnly,
12197
10962
  pollUntil,
12198
10963
  parsePositiveInteger,
12199
10964
  parseOffset,
@@ -12208,11 +10973,13 @@ export {
12208
10973
  isTerminalStatus,
12209
10974
  isTelemetryDisabled,
12210
10975
  isSuccessStatus,
10976
+ isPreviewBuild,
12211
10977
  isHtmlDocument,
12212
10978
  isGuid,
12213
10979
  isFailureStatus,
12214
10980
  instructionsFor,
12215
10981
  installSdkUserAgentHeader,
10982
+ installSdkCodingAgentHeader,
12216
10983
  installConsoleGuard,
12217
10984
  hashContent,
12218
10985
  getSdkUserAgentToken,
@@ -12230,9 +10997,9 @@ export {
12230
10997
  extractErrorMessage,
12231
10998
  extractErrorDetails,
12232
10999
  extractCommandHelp,
12233
- evaluateJsonPath,
12234
11000
  ensurePackagerFactory,
12235
11001
  detectAgent,
11002
+ describeConnectivityError,
12236
11003
  deriveCommandPath,
12237
11004
  createTelemetryProvider,
12238
11005
  createPollAbortController,
@@ -12247,6 +11014,7 @@ export {
12247
11014
  buildActionCenterInboxUrl,
12248
11015
  appendOption,
12249
11016
  addSdkUserAgentHeader,
11017
+ addSdkCodingAgentHeader,
12250
11018
  addHiddenDeprecatedTenantOption,
12251
11019
  UIPATH_HOME_DIR,
12252
11020
  TelemetryService,
@@ -12261,7 +11029,6 @@ export {
12261
11029
  NodeContextStorage,
12262
11030
  MIN_INTERVAL_MS,
12263
11031
  LogLevel,
12264
- JsonPathError,
12265
11032
  FilterEvaluationError,
12266
11033
  FailureOutput,
12267
11034
  ErrorDecision,
@@ -12273,11 +11040,15 @@ export {
12273
11040
  DEFAULT_FETCH_TIMEOUT_MS,
12274
11041
  DEFAULT_BASE_URL,
12275
11042
  DEFAULT_AUTH_TIMEOUT_MS,
11043
+ ConsoleTelemetryProvider,
12276
11044
  CommonTelemetryEvents,
12277
11045
  CONFIG_FILENAME,
12278
11046
  CLI_ERROR_CODES,
11047
+ BrowserContextStorage,
12279
11048
  BACKOFF_DEFAULTS,
12280
11049
  AUTH_FILENAME,
12281
11050
  ATTACHMENT_UPLOAD_INSTRUCTIONS,
12282
11051
  ATTACHMENT_INSTRUCTIONS
12283
11052
  };
11053
+
11054
+ //# debugId=847E01B3BD69934B64756E2164756E21