All files / json-path/src JsonPathEval.ts

81.81% Statements 270/330
68.85% Branches 157/228
96.77% Functions 30/31
85.91% Lines 244/284

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 6855x 5x                       5x 5x   101x 101x 101x 4x 97x   97x 97x           115x                 115x 115x       115x 115x 115x 115x 115x 114x 185x 185x   114x       2144x 2144x 2144x 2148x 2144x       2180x   2055x 2055x     16x 16x     18x 18x     10x 10x     49x 49x     32x 32x     2180x       2055x 2055x 2525x 2525x 2525x 630x   630x           16x 16x 40x 40x 40x 16x   16x 3x   16x 14x 14x 14x         18x 18x 123x 123x 123x   17x 43x   106x   42x   84x 84x                 10x     10x 1x     9x 9x 9x 9x 9x   8x       8x 6x 6x   2x 2x       8x 16x     8x 8x       8x 6x 6x   2x 2x       8x 6x 11x   2x 2x 9x             49x 49x 1866x 1866x       1866x 20x 13x   1846x   376x 808x 808x 808x 47x     1470x   294x   1136x 1136x 1136x 1136x                             32x 32x 32x   32x 32x     32x         2444x 2444x   2444x   396x 799x 799x   2048x   466x   1613x 1613x 1613x                 5611x   1895x   3632x   18x           66x             1895x 1895x           1895x 10x     10x     1885x   1849x   2x   10x       23x   1x             3632x   3632x                               18x 18x 18x 18x       66x       66x 66x                                   3968x   17x       1960x   1943x     1943x   1943x 1959x 1959x       1943x     48x               1852x 1852x     1852x 1852x     1852x     1852x     1824x     296x                 296x                     296x         34x     34x 34x     34x     34x 30x       4x         4x               114x   114x 114x 113x       1x                         25x   24x 24x       24x 16x   8x     24x   15x   9x 3x   6x 1x     5x                         7x   7x 7x       7x 7x                                     32x   32x   32x 32x     32x 32x   32x 6x     26x   26x 22x   4x                           34x   34x   34x 34x     34x 34x   34x 6x     28x   28x 28x                               15x   15x 15x       15x 15x                           178x 178x                           178x                    
import {JsonPathParser} from './JsonPathParser';
import {Value} from './Value';
import type * as types from './types';
 
/**
 * Function signature for JSONPath functions
 */
type JSONPathFunction = (
  args: (types.IValueExpression | types.IFilterExpression | types.IJSONPath)[],
  currentNode: Value,
  evaluator: JsonPathEval,
) => any;
 
export class JsonPathEval {
  public static run = (path: string | types.IJSONPath, data: unknown): Value[] => {
    let ast: types.IJSONPath;
    if (typeof path === 'string') {
      const parsed = JsonPathParser.parse(path);
      if (!parsed.success || !parsed.path || parsed.error)
        throw new Error(`Invalid JSONPath: ${parsed.error} [position = ${parsed.position}, path = ${path}]`);
      ast = parsed.path;
    } else East = path;
    const evaluator = new JsonPathEval(ast, data);
    return evaluator.eval();
  };
 
  /**
   * Function registry for JSONPath functions
   */
  protected readonly funcs = new Map<string, JSONPathFunction>([
    ['length', this.lengthFunction.bind(this)],
    ['count', this.countFunction.bind(this)],
    ['match', this.matchFunction.bind(this)],
    ['search', this.searchFunction.bind(this)],
    ['value', this.valueFunction.bind(this)],
  ]);
 
  constructor(
    public readonly path: types.IJSONPath,
    public readonly data: unknown,
  ) {}
 
  eval(): Value[] {
    let input: Value[] = [new Value(null, '$', this.data)];
    let output: Value[] = [];
    const segments = this.path.segments;
    const length = segments.length;
    if (length === 0) return input;
    for (let i = 0; i < length; i++) {
      output = this.evalSegment(input, segments[i]);
      input = output;
    }
    return output;
  }
 
  evalSegment(input: Value[], segment: types.IPathSegment): Value[] {
    const output: Value[] = [];
    const selectors = segment.selectors;
    const length = selectors.length;
    for (let i = 0; i < length; i++) this.evalSelector(input, selectors[i], output);
    return output;
  }
 
  evalSelector(inputs: Value[], selector: types.IAnySelector, output: Value[] = []): Value[] {
    switch (selector.type) {
      case 'name': {
        this.evalNamed(inputs, selector, output);
        break;
      }
      case 'index': {
        this.evalIndex(inputs, selector, output);
        break;
      }
      case 'wildcard': {
        this.evalWildcard(inputs, selector, output);
        break;
      }
      case 'slice': {
        this.evalSlice(inputs, selector, output);
        break;
      }
      case 'filter': {
        this.evalFilter(inputs, selector, output);
        break;
      }
      case 'recursive-descent': {
        this.evalRecursiveDescent(inputs, selector, output);
        break;
      }
    }
    return output;
  }
 
  protected evalNamed(inputs: Value[], selector: types.INamedSelector, output: Value[] = []): void {
    const length = inputs.length;
    for (let i = 0; i < length; i++) {
      const input = inputs[i];
      const data = input.data;
      if (data && typeof data === 'object' && !Array.isArray(data)) {
        const key = selector.name;
        // biome-ignore lint: object hasOwnProperty check is intentional, Object.hasOwn is too recent
        if (data.hasOwnProperty(key)) output.push(new Value(input, key, (data as any)[key]));
      }
    }
  }
 
  protected evalIndex(inputs: Value[], selector: types.IIndexSelector, output: Value[] = []): void {
    const length = inputs.length;
    for (let i = 0; i < length; i++) {
      const input = inputs[i];
      const data = input.data;
      if (!Array.isArray(data)) continue;
      let index = selector.index;
      // Handle negative indices
      if (index < 0) {
        index = data.length + index;
      }
      if (index < 0 || index >= data.length) continue;
      const child = data[index];
      Iif (child === undefined) continue;
      output.push(new Value(input, index, child));
    }
  }
 
  protected evalWildcard(inputs: Value[], selector: types.IWildcardSelector, output: Value[] = []): void {
    const length = inputs.length;
    for (let i = 0; i < length; i++) {
      const input = inputs[i];
      const data = input.data;
      if (Array.isArray(data)) {
        // For arrays, select all elements in order
        for (let j = 0; j < data.length; j++) {
          output.push(new Value(input, j, data[j]));
        }
      } else if (data && typeof data === 'object') {
        // For objects, select all member values (order is not guaranteed per RFC 9535)
        for (const key in data) {
          // biome-ignore lint: object hasOwnProperty check is intentional, Object.hasOwn is too recent
          if (data.hasOwnProperty(key)) {
            output.push(new Value(input, key, (data as any)[key]));
          }
        }
      }
      // For primitive values, wildcard selects nothing
    }
  }
 
  protected evalSlice(inputs: Value[], selector: types.ISliceSelector, output: Value[] = []): void {
    const step = selector.step !== undefined ? selector.step : 1;
 
    // Handle step = 0 case (no elements selected per RFC 9535)
    if (step === 0) {
      return;
    }
 
    const length = inputs.length;
    for (let i = 0; i < length; i++) {
      const input = inputs[i];
      const data = input.data;
      if (!Array.isArray(data)) continue;
 
      const len = data.length;
 
      // Determine default start and end based on step direction
      let start: number, end: number;
      if (step >= 0) {
        start = selector.start !== undefined ? selector.start : 0;
        end = selector.end !== undefined ? selector.end : len;
      } else {
        start = selector.start !== undefined ? selector.start : len - 1;
        end = selector.end !== undefined ? selector.end : -len - 1;
      }
 
      // Normalize start and end indices
      const normalizeIndex = (idx: number, length: number): number => {
        return idx >= 0 ? idx : length + idx;
      };
 
      const nStart = normalizeIndex(start, len);
      const nEnd = normalizeIndex(end, len);
 
      // Calculate bounds based on step direction
      let lower: number, upper: number;
      if (step >= 0) {
        lower = Math.min(Math.max(nStart, 0), len);
        upper = Math.min(Math.max(nEnd, 0), len);
      } else {
        upper = Math.min(Math.max(nStart, -1), len - 1);
        lower = Math.min(Math.max(nEnd, -1), len - 1);
      }
 
      // Select elements based on step direction
      if (step > 0) {
        for (let idx = lower; idx < upper; idx += step) {
          output.push(new Value(input, idx, data[idx]));
        }
      } else if (step < 0) {
        for (let idx = upper; idx > lower; idx += step) {
          output.push(new Value(input, idx, data[idx]));
        }
      }
    }
  }
 
  protected evalFilter(inputs: Value[], selector: types.IFilterSelector, output: Value[] = []): void {
    const length = inputs.length;
    for (let i = 0; i < length; i++) {
      const input = inputs[i];
      const data = input.data;
 
      // Special case: if this is a root-level filter on a single object,
      // treat the object itself as the element being filtered
      if (input.step === '$' && data && typeof data === 'object' && !Array.isArray(data)) {
        if (this.evalFilterExpression(selector.expression, input)) {
          output.push(input);
        }
      } else if (Array.isArray(data)) {
        // Filter array elements
        for (let j = 0; j < data.length; j++) {
          const element = data[j];
          const elementValue = new Value(input, j, element);
          if (this.evalFilterExpression(selector.expression, elementValue)) {
            output.push(elementValue);
          }
        }
      } else if (data && typeof data === 'object') {
        // Filter object member values
        for (const key in data) {
          // biome-ignore lint: object hasOwnProperty check is intentional, Object.hasOwn is too recent
          if (data.hasOwnProperty(key)) {
            const memberValue = (data as any)[key];
            const memberValueNode = new Value(input, key, memberValue);
            Iif (this.evalFilterExpression(selector.expression, memberValueNode)) {
              output.push(memberValueNode);
            }
          }
        }
      }
      // For primitive values, filter selects nothing
    }
  }
 
  protected evalRecursiveDescent(
    inputs: Value[],
    selector: types.IRecursiveDescentSelector,
    output: Value[] = [],
  ): void {
    const length = inputs.length;
    for (let i = 0; i < length; i++) {
      const input = inputs[i];
      // Collect all descendants (including the input node itself)
      const descendants: Value[] = [];
      this.collectDescendants(input, descendants);
 
      // Apply the wrapped selector to all descendants
      this.evalSelector(descendants, selector.selector, output);
    }
  }
 
  private collectDescendants(node: Value, output: Value[]): void {
    output.push(node);
    const data = node.data;
 
    if (Array.isArray(data)) {
      // Visit array elements in order
      for (let i = 0; i < data.length; i++) {
        const child = new Value(node, i, data[i]);
        this.collectDescendants(child, output);
      }
    } else if (data && typeof data === 'object') {
      // Visit object member values (order not guaranteed)
      for (const key in data) {
        // biome-ignore lint: object hasOwnProperty check is intentional, Object.hasOwn is too recent
        if (data.hasOwnProperty(key)) {
          const child = new Value(node, key, (data as any)[key]);
          this.collectDescendants(child, output);
        }
      }
    }
    // For primitive values, no children to visit
  }
 
  private evalFilterExpression(expression: types.IFilterExpression, currentNode: Value): boolean {
    // Simplified implementation of filter expression evaluation
    switch (expression.type) {
      case 'comparison':
        return this.evalComparisonExpression(expression, currentNode);
      case 'logical':
        return this.evalLogicalExpression(expression, currentNode);
      case 'existence':
        return this.evalExistenceExpression(expression, currentNode);
      case 'negation':
        return !this.evalFilterExpression(expression.expression, currentNode);
      case 'paren':
        return this.evalFilterExpression(expression.expression, currentNode);
      case 'function':
        return this.evalFunctionExpression(expression, currentNode);
      default:
        return false;
    }
  }
 
  private evalComparisonExpression(expression: types.IComparisonExpression, currentNode: Value): boolean {
    const leftValue = this.evalValueExpression(expression.left, currentNode);
    const rightValue = this.evalValueExpression(expression.right, currentNode);
 
    // JSONPath semantics: comparisons involving Nothing (undefined) evaluate to false,
    // except when both sides are Nothing and operator is equality.
    // BUT: functions can return valid values including 0, false, "", etc. Only treat
    // actual undefined (meaning "no result") as Nothing.
    if (leftValue === undefined || rightValue === undefined) {
      Iif (expression.operator === '==' && leftValue === undefined && rightValue === undefined) {
        return true;
      }
      return false;
    }
 
    switch (expression.operator) {
      case '==':
        return this.compareEqual(leftValue, rightValue);
      case '!=':
        return !this.compareEqual(leftValue, rightValue);
      case '<':
        return this.compareLess(leftValue, rightValue);
      case '<=':
        return this.compareLess(leftValue, rightValue) || this.compareEqual(leftValue, rightValue);
      case '>':
        return this.compareLess(rightValue, leftValue);
      case '>=':
        return this.compareLess(rightValue, leftValue) || this.compareEqual(leftValue, rightValue);
      default:
        return false;
    }
  }
 
  private evalLogicalExpression(expression: types.ILogicalExpression, currentNode: Value): boolean {
    switch (expression.operator) {
      case '&&':
        return (
          this.evalFilterExpression(expression.left, currentNode) &&
          this.evalFilterExpression(expression.right, currentNode)
        );
      case '||':
        return (
          this.evalFilterExpression(expression.left, currentNode) ||
          this.evalFilterExpression(expression.right, currentNode)
        );
      default:
        return false;
    }
  }
 
  private evalExistenceExpression(expression: types.IExistenceExpression, currentNode: Value): boolean {
    // Evaluate the path from the current node and check if it selects any nodes
    Iif (!expression.path.segments) return false;
    const evaluator = new JsonPathEval(expression.path, currentNode.data);
    const result = evaluator.eval();
    return result.length > 0;
  }
 
  private evalFunctionExpression(expression: types.IFunctionExpression, currentNode: Value): boolean {
    const result = this.evaluateFunction(expression, currentNode);
 
    // Functions in test expressions should return LogicalType
    // If the function returns a value, convert it to boolean
    if (typeof result === 'boolean') {
      return result;
    }
 
    // For count() and length() returning numbers, convert to boolean (non-zero is true)
    Iif (typeof result === 'number') {
      return result !== 0;
    }
 
    // For nodelists, true if non-empty
    Iif (Array.isArray(result)) {
      return result.length > 0;
    }
 
    // For other values, check if they exist (not null/undefined)
    return result != null;
  }
 
  private evalValueExpression(expression: types.IValueExpression, currentNode: Value): any {
    switch (expression.type) {
      case 'current':
        return currentNode.data;
      case 'root':
        return this.data;
      case 'literal':
        return expression.value;
      case 'path': {
        Iif (!expression.path.segments) return undefined;
 
        // Evaluate path segments starting from current node
        let currentResults = [currentNode];
 
        for (const segment of expression.path.segments) {
          currentResults = this.evalSegment(currentResults, segment);
          if (currentResults.length === 0) break; // No results, early exit
        }
 
        // For function arguments, we want the actual data, not Value objects
        return currentResults.map((v) => v.data);
      }
      case 'function':
        return this.evaluateFunction(expression, currentNode);
      default:
        return undefined;
    }
  }
 
  private compareEqual(left: any, right: any): boolean {
    // Handle empty nodelist/Nothing cases
    Iif (left === undefined && right === undefined) return true;
    Iif (left === undefined || right === undefined) return false;
 
    // Auto-unwrap single-element arrays for comparison (JSONPath behavior)
    if (Array.isArray(left) && left.length === 1) left = left[0];
    Iif (Array.isArray(right) && right.length === 1) right = right[0];
 
    // After unwrapping, check for undefined again
    Iif (left === undefined || right === undefined) return false;
 
    // Strict equality for primitives
    if (left === right) return true;
 
    // Type mismatch
    if (typeof left !== typeof right) return false;
 
    // Array comparison
    Iif (Array.isArray(left) && Array.isArray(right)) {
      Iif (left.length !== right.length) return false;
      for (let i = 0; i < left.length; i++) {
        Iif (!this.compareEqual(left[i], right[i])) return false;
      }
      return true;
    }
 
    // Object comparison
    Iif (left && right && typeof left === 'object' && typeof right === 'object') {
      const leftKeys = Object.keys(left);
      const rightKeys = Object.keys(right);
      Iif (leftKeys.length !== rightKeys.length) return false;
      for (const key of leftKeys) {
        Iif (!rightKeys.includes(key)) return false;
        Iif (!this.compareEqual(left[key], right[key])) return false;
      }
      return true;
    }
 
    return false;
  }
 
  private compareLess(left: any, right: any): boolean {
    // Handle empty nodelist/Nothing cases
    Iif (left === undefined || right === undefined) return false;
 
    // Auto-unwrap single-element arrays for comparison (JSONPath behavior)
    if (Array.isArray(left) && left.length === 1) left = left[0];
    Iif (Array.isArray(right) && right.length === 1) right = right[0];
 
    // After unwrapping, check for undefined again
    Iif (left === undefined || right === undefined) return false;
 
    // Both numbers
    if (typeof left === 'number' && typeof right === 'number') {
      return left < right;
    }
 
    // Both strings
    Iif (typeof left === 'string' && typeof right === 'string') {
      return left < right;
    }
 
    // Other types don't support < comparison
    return false;
  }
 
  /**
   * Evaluate a function expression according to RFC 9535
   * Uses the function registry for extensible function support
   */
  private evaluateFunction(expression: types.IFunctionExpression, currentNode: Value): any {
    const {name, args} = expression;
 
    const func = this.funcs.get(name);
    if (func) {
      return func(args, currentNode, this);
    }
 
    // Unknown function - return false for logical context, undefined for value context
    return false;
  }
 
  /**
   * length() function - returns the length of strings, arrays, or objects
   * Parameters: ValueType
   * Result: ValueType (unsigned integer or Nothing)
   */
  private lengthFunction(
    args: (types.IValueExpression | types.IFilterExpression | types.IJSONPath)[],
    currentNode: Value,
    evaluator: JsonPathEval,
  ): number | undefined {
    if (args.length !== 1) return undefined;
 
    const [arg] = args;
    const result = this.getValueFromArg(arg, currentNode, evaluator);
 
    // For length() function, we need the single value
    let value: any;
    if (Array.isArray(result)) {
      value = result.length === 1 ? result[0] : undefined;
    } else {
      value = result;
    }
 
    if (typeof value === 'string') {
      // Count Unicode scalar values
      return [...value].length;
    }
    if (Array.isArray(value)) {
      return value.length;
    }
    if (value && typeof value === 'object' && value !== null) {
      return Object.keys(value).length;
    }
 
    return undefined; // Nothing for other types
  }
 
  /**
   * count() function - returns the number of nodes in a nodelist
   * Parameters: NodesType
   * Result: ValueType (unsigned integer)
   */
  private countFunction(
    args: (types.IValueExpression | types.IFilterExpression | types.IJSONPath)[],
    currentNode: Value,
    evaluator: JsonPathEval,
  ): number {
    Iif (args.length !== 1) return 0;
 
    const [arg] = args;
    const result = this.getValueFromArg(arg, currentNode, evaluator);
 
    // Count logic based on RFC 9535:
    // For count(), we count the number of nodes selected by the expression
    if (Array.isArray(result)) {
      return result.length;
    } else Eif (result === undefined) {
      return 0;
    } else {
      // Single value = 1 node selected
      return 1;
    }
  }
 
  /**
   * match() function - tests if a string matches a regular expression (full match)
   * Parameters: ValueType (string), ValueType (string conforming to RFC9485)
   * Result: LogicalType
   */
  private matchFunction(
    args: (types.IValueExpression | types.IFilterExpression | types.IJSONPath)[],
    currentNode: Value,
    evaluator: JsonPathEval,
  ): boolean {
    Iif (args.length !== 2) return false;
 
    const [stringArg, regexArg] = args;
 
    const strResult = this.getValueFromArg(stringArg, currentNode, evaluator);
    const regexResult = this.getValueFromArg(regexArg, currentNode, evaluator);
 
    // Handle array results (get single value)
    const str = Array.isArray(strResult) ? (strResult.length === 1 ? strResult[0] : undefined) : strResult;
    const regex = Array.isArray(regexResult) ? (regexResult.length === 1 ? regexResult[0] : undefined) : regexResult;
 
    if (typeof str !== 'string' || typeof regex !== 'string') {
      return false;
    }
 
    try {
      // RFC 9485 I-Regexp is a subset of JavaScript regex
      const regExp = new RegExp(`^${regex}$`);
      return regExp.test(str);
    } catch {
      return false;
    }
  }
 
  /**
   * search() function - tests if a string contains a substring matching a regular expression
   * Parameters: ValueType (string), ValueType (string conforming to RFC9485)
   * Result: LogicalType
   */
  private searchFunction(
    args: (types.IValueExpression | types.IFilterExpression | types.IJSONPath)[],
    currentNode: Value,
    evaluator: JsonPathEval,
  ): boolean {
    Iif (args.length !== 2) return false;
 
    const [stringArg, regexArg] = args;
 
    const strResult = this.getValueFromArg(stringArg, currentNode, evaluator);
    const regexResult = this.getValueFromArg(regexArg, currentNode, evaluator);
 
    // Handle array results (get single value)
    const str = Array.isArray(strResult) ? (strResult.length === 1 ? strResult[0] : undefined) : strResult;
    const regex = Array.isArray(regexResult) ? (regexResult.length === 1 ? regexResult[0] : undefined) : regexResult;
 
    if (typeof str !== 'string' || typeof regex !== 'string') {
      return false;
    }
 
    try {
      // RFC 9485 I-Regexp is a subset of JavaScript regex
      const regExp = new RegExp(regex);
      return regExp.test(str);
    } catch {
      return false;
    }
  }
 
  /**
   * value() function - converts a nodelist to a single value
   * Parameters: NodesType
   * Result: ValueType
   */
  private valueFunction(
    args: (types.IValueExpression | types.IFilterExpression | types.IJSONPath)[],
    currentNode: Value,
    evaluator: JsonPathEval,
  ): any {
    Iif (args.length !== 1) return undefined;
 
    const [nodeArg] = args;
    const result = this.getValueFromArg(nodeArg, currentNode, evaluator);
 
    // For value() function, return single value if exactly one result,
    // otherwise undefined (following RFC 9535 value() semantics)
    if (Array.isArray(result)) {
      return result.length === 1 ? result[0] : undefined;
    } else E{
      return result;
    }
  }
 
  /**
   * Helper to get value from function argument
   */
  private getValueFromArg(
    arg: types.IValueExpression | types.IFilterExpression | types.IJSONPath,
    currentNode: Value,
    evaluator: JsonPathEval,
  ): any {
    if (this.isValueExpression(arg)) {
      return evaluator.evalValueExpression(arg, currentNode);
    } else IEif (this.isJSONPath(arg)) {
      // Regular $ expression - evaluate from root
      const evalInstance = new JsonPathEval(arg, currentNode.data);
      const result = evalInstance.eval();
      return result.length === 1 ? result[0].data : undefined;
    }
    return undefined;
  }
 
  /**
   * Type guard for ValueExpression
   */
  private isValueExpression(arg: any): arg is types.IValueExpression {
    return arg && typeof arg === 'object' && ['current', 'root', 'literal', 'path', 'function'].includes(arg.type);
  }
 
  /**
   * Type guard for JSONPath
   */
  private isJSONPath(arg: any): arg is types.IJSONPath {
    return arg && typeof arg === 'object' && Array.isArray(arg.segments);
  }
}