All files / json-path/src JsonPathParser.ts

85.64% Statements 334/390
77.92% Branches 180/231
95.65% Functions 22/23
87.07% Lines 330/379

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 685 686 687 688 689 690 691 692 693 694 695 696          6x 6x     6x             290x           290x 290x 290x 278x   12x                 290x     290x 290x 3x   287x 287x     287x 477x 477x   476x 467x     278x       476x     476x 476x 45x   45x 4x         472x     472x   196x 196x   196x   6x 6x     190x 188x   276x   241x 241x     241x 271x 271x 269x 269x     269x 30x 30x   239x       239x 239x 1x   238x 35x   35x 10x 10x   25x 25x           467x 41x     426x       288x   288x   23x 23x 265x   137x 137x     137x 137x 22x 22x 22x     137x   137x 22x 22x     22x     137x 128x   28x 27x       100x 92x 91x     99x   30x 30x         30x 24x 24x     30x 11x 11x 11x 11x       30x     69x     69x           140x       140x 140x   140x 2x 2x 2x 2x 2x     140x       142x 142x   142x 8x 8x 8x 8x 8x     142x       150x       151x 151x   1x 1x 1x 1x   150x   3x 3x 3x 3x 3x     3x 3x   147x       147x 147x 147x 90x 90x 90x 90x     57x 17x 40x     40x   40x             201x 201x 201x     201x 201x 201x       201x     201x 1101x 1101x             900x   201x       201x 201x       96x 96x 96x 96x 96x   96x 96x 96x 136x   136x 136x 136x 136x 40x 40x 96x     96x 96x 96x 96x       377x       90x 55x 55x 35x 3x 3x 32x 1x 1x 31x 3x 3x 28x 14x 14x 14x 14x 14x           373x 373x   373x 105x 105x 105x 105x   96x 96x 96x     9x     277x 151x 151x 145x 145x   6x 126x         126x   52x 74x   65x 9x 3x 3x 6x 1x 1x 5x 5x 5x                                     145x 145x 325x 325x   325x 145x 180x 180x   145x       180x 180x     180x 180x 9x   9x         180x   154x 154x   154x           154x 154x   26x   17x 17x     17x 17x 17x 17x 17x     17x       17x       17x 17x     17x 9x   9x 2x 2x   7x 7x           180x 9x     171x       376x 376x 376x     376x 374x 374x                   374x     374x 1778x 1778x             1445x   333x       374x 374x       80x 80x 80x 80x 80x 511x 6x 505x 80x 79x 79x 79x 6x                                   2x   4x           192x 192x 192x     192x   16x       192x   1x       191x   52x   139x 320x 320x   181x   139x           191x   5x 5x     5x 13x 13x   8x   5x           191x 190x 190x                                                 191x 191x 191x      
/**
 * JSONPath parser implementation based on RFC 9535
 * https://www.rfc-editor.org/rfc/rfc9535.html
 */
 
import {Parser} from './Parser';
import {Ast} from './ast';
import type * as types from './types';
 
export class JsonPathParser extends Parser {
  /**
   * Parse a JSONPath expression string
   *
   * @param pathStr - JSONPath expression string (e.g., "$.store.book[0].title").
   * @returns Parse result with structured representation or error information.
   */
  public static parse = (pathStr: string): types.IParseResult => new JsonPathParser().parse(pathStr);
 
  /**
   * Parse a JSONPath expression string into a structured representation
   */
  parse(pathStr: string): types.IParseResult {
    try {
      this.reset(pathStr);
      const path = this.parseJSONPath();
      return {success: true, path};
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
        position: this.pos,
      };
    }
  }
 
  private parseJSONPath(): types.IJSONPath {
    const segments: types.IPathSegment[] = [];
 
    // Root path starts with $
    this.ws();
    if (!this.is('$')) {
      throw new Error('JSONPath must start with $');
    }
    this.skip(1); // Skip $
    this.ws(); // Skip whitespace after $
 
    // Parse segments
    while (!this.eof()) {
      this.ws();
      if (this.eof()) break;
 
      const segment = this.parsePathSegment();
      segments.push(segment);
    }
 
    return Ast.path(segments);
  }
 
  private parsePathSegment(): types.IPathSegment {
    this.ws();
 
    // Check for recursive descent (..)
    const recursive = this.is('..') as boolean;
    if (recursive) {
      this.skip(2); // Skip ..
      // After .., we must have a selector (RFC 9535 Section 2.5.2.1: "On its own, .. is not a valid segment")
      if (this.eof()) {
        throw new Error('Expected selector after ..');
      }
    }
 
    // Parse selectors
    const selectors: types.IAnySelector[] = [];
 
    // Handle different selector formats
    if (this.is('.')) {
      // Dot notation: .name, .*, etc.
      this.skip(1); // Skip .
      this.ws(); // Skip whitespace after .
 
      if (this.is('*')) {
        // Wildcard
        this.skip(1);
        selectors.push(Ast.selector.wildcard());
      } else {
        // Named selector
        const name = this.parseIdentifier();
        selectors.push(Ast.selector.named(name));
      }
    } else if (this.is('[')) {
      // Bracket notation: [index], ['name'], [*], [start:end], [a,b,c] etc.
      this.skip(1); // Skip [
      this.ws();
 
      // Parse comma-separated list of selectors
      do {
        this.ws();
        const selector = this.parseBracketSelector();
        selectors.push(selector);
        this.ws();
 
        // Check for comma to continue, or ] to end
        if (this.is(',')) {
          this.skip(1); // Skip comma
          this.ws();
        } else {
          break;
        }
      } while (!this.eof() && !this.is(']'));
 
      this.ws();
      if (!this.is(']')) {
        throw new Error('Expected ] to close bracket selector');
      }
      this.skip(1); // Skip ]
    } else if (recursive && this.match(/[a-zA-Z_*]/)) {
      // After recursive descent, we can have an identifier or wildcard
      if (this.is('*')) {
        this.skip(1);
        selectors.push(Ast.selector.wildcard());
      } else {
        const name = this.parseIdentifier();
        selectors.push(Ast.selector.named(name));
      }
    } else E{
      throw new Error('Expected . or [ to start path segment');
    }
 
    if (recursive && selectors.length === 1) {
      return Ast.segment([Ast.selector.recursiveDescent(selectors[0])]);
    }
 
    return Ast.segment(selectors, recursive || undefined);
  }
 
  private parseBracketSelector(): types.IAnySelector {
    this.ws();
 
    if (this.is('*')) {
      // Wildcard
      this.skip(1);
      return Ast.selector.wildcard();
    } else if (this.is('?')) {
      // Filter expression
      this.skip(1); // Skip ?
      this.ws();
 
      // Parentheses are optional according to RFC 9535, but commonly used
      let hasParens = false;
      if (this.is('(')) {
        hasParens = true;
        this.skip(1);
        this.ws();
      }
 
      const expression = this.parseFilterExpression();
 
      if (hasParens) {
        this.ws();
        Iif (!this.is(')')) {
          throw new Error('Expected ) to close filter expression');
        }
        this.skip(1);
      }
 
      return Ast.selector.filter(expression);
    } else if (this.is("'") || this.is('"')) {
      // Quoted string selector
      const name = this.parseString();
      return Ast.selector.named(name);
    } else {
      // Number or slice
      let first: number | undefined;
      if (!this.is(':')) {
        first = this.parseNumber();
        this.ws();
      }
 
      if (this.is(':')) {
        // Slice selector
        this.skip(1); // Skip :
        this.ws();
 
        let end: number | undefined;
        let step: number | undefined;
 
        if (!this.is(']') && !this.is(':') && !this.is(',')) {
          end = this.parseNumber();
          this.ws();
        }
 
        if (this.is(':')) {
          this.skip(1); // Skip :
          this.ws();
          if (!this.is(']') && !this.is(',')) {
            step = this.parseNumber();
          }
        }
 
        return Ast.selector.slice(first, end, step);
      } else {
        // Index selector
        Iif (first === undefined) {
          throw new Error('Expected index or slice');
        }
        return Ast.selector.index(first);
      }
    }
  }
 
  private parseFilterExpression(): types.IFilterExpression {
    return this.parseLogicalOrExpression();
  }
 
  private parseLogicalOrExpression(): types.IFilterExpression {
    let left = this.parseLogicalAndExpression();
    this.ws();
 
    while (this.is('||')) {
      this.skip(2);
      this.ws();
      const right = this.parseLogicalAndExpression();
      left = Ast.expression.logical('||', left, right);
      this.ws();
    }
 
    return left;
  }
 
  private parseLogicalAndExpression(): types.IFilterExpression {
    let left = this.parseComparisonExpression();
    this.ws();
 
    while (this.is('&&')) {
      this.skip(2);
      this.ws();
      const right = this.parseComparisonExpression();
      left = Ast.expression.logical('&&', left, right);
      this.ws();
    }
 
    return left;
  }
 
  private parseComparisonExpression(): types.IFilterExpression {
    return this.parseUnaryExpression();
  }
 
  private parseUnaryExpression(): types.IFilterExpression {
    this.ws();
    if (this.is('!')) {
      // Handle logical NOT operator
      this.skip(1);
      this.ws();
      const expression = this.parseUnaryExpression();
      return Ast.expression.negation(expression);
    }
    if (this.is('(')) {
      // Handle parenthesized expressions
      this.skip(1);
      this.ws();
      const expression = this.parseFilterExpression();
      this.ws();
      Iif (!this.is(')')) {
        throw new Error('Expected ) to close parenthesized expression');
      }
      this.skip(1);
      return Ast.expression.paren(expression);
    }
    return this.parsePrimaryExpression();
  }
 
  private parsePrimaryExpression(): types.IFilterExpression {
    const left = this.parseValueExpression();
    this.ws();
    if (this.isComparisonOperator()) {
      const operator = this.parseComparisonOperator();
      this.ws();
      const right = this.parseValueExpression();
      return Ast.expression.comparison(operator, left, right);
    }
    // If no comparison operator, this is an existence test
    if (left.type === 'path') {
      return Ast.expression.existence(left.path);
    } else Iif (left.type === 'current') {
      // @  by itself is an existence test for current node
      return Ast.expression.existence(Ast.path([]));
    } else if (left.type === 'function') {
      // Function expressions can be used as test expressions (e.g., $[?match(@.name, "pattern")])
      return left as types.IFilterExpression;
    }
    // If no comparison operator, treat as existence test
    return Ast.expression.existence(Ast.path([])); // TODO: implement proper existence test with the path
  }
 
  private parseFunctionName(): string {
    const {str, length} = this;
    const start = this.pos;
    let pos = start;
 
    // First character must be lowercase letter
    Iif (pos >= length) throw new Error('Expected function name');
    const firstCode = str.charCodeAt(pos);
    Iif (!(firstCode >= 97 && firstCode <= 122)) {
      // a-z
      throw new Error('Expected function name');
    }
    pos++;
 
    // Subsequent characters can be letter, digit, or underscore
    while (pos < length) {
      const code = str.charCodeAt(pos);
      if (
        (code >= 65 && code <= 90) || // A-Z
        (code >= 97 && code <= 122) || // a-z
        (code >= 48 && code <= 57) || // 0-9
        code === 95
      ) {
        // _
        pos++;
      } else {
        break;
      }
    }
 
    this.pos = pos;
    return str.slice(start, pos);
  }
 
  private parseFunctionExpression(): types.IFunctionExpression {
    const name = this.parseFunctionName();
    this.ws();
    Iif (!this.is('(')) throw new Error('Expected "(" after function name');
    this.skip(1); // Skip (
    this.ws();
 
    const args: (types.IValueExpression | types.IFilterExpression | types.IJSONPath)[] = [];
    if (!this.is(')')) {
      do {
        this.ws();
        // Try to parse as value expression first
        const arg = this.parseValueExpression();
        args.push(arg);
        this.ws();
        if (this.is(',')) {
          this.skip(1);
          this.ws();
        } else break;
      } while (!this.eof() && !this.is(')'));
    }
    this.ws();
    Iif (!this.is(')')) throw new Error('Expected ")" to close function arguments');
    this.skip(1);
    return Ast.expression.function(name, args);
  }
 
  private isComparisonOperator(): boolean {
    return this.is('==') || this.is('!=') || this.is('<=') || this.is('>=') || this.is('<') || this.is('>');
  }
 
  private parseComparisonOperator(): types.IComparisonExpression['operator'] {
    if (this.is('==')) {
      this.skip(2);
      return '==';
    } else if (this.is('!=')) {
      this.skip(2);
      return '!=';
    } else if (this.is('<=')) {
      this.skip(2);
      return '<=';
    } else if (this.is('>=')) {
      this.skip(2);
      return '>=';
    } else if (this.is('<')) {
      this.skip(1);
      return '<';
    } else if (this.is('>')) {
      this.skip(1);
      return '>';
    }
    throw new Error('Expected comparison operator');
  }
 
  private parseValueExpression(): types.IValueExpression {
    this.ws();
    const value = Ast.value;
    // Check for function expressions first
    if (this.match(/[a-z]/)) {
      const start = this.pos;
      const _name = this.parseFunctionName();
      this.ws();
      if (this.is('(')) {
        // It's a function call - reset and parse as function
        this.pos = start;
        const funcExpr = this.parseFunctionExpression();
        return value.function(funcExpr.name, funcExpr.args);
      } else {
        // Reset position, it's not a function
        this.pos = start;
      }
    }
    if (this.is('@')) {
      this.skip(1);
      if (this.is('.') || this.is('[')) {
        const segments = this.parseFilterPathSegments();
        return value.path(Ast.path(segments));
      }
      return value.current();
    } else Iif (this.is('$')) {
      // Root node path
      this.skip(1);
      const segments = this.parsePathSegments();
      return value.path(Ast.path(segments));
    } else if (this.is("'") || this.is('"')) {
      // String literal
      return value.literal(this.parseString());
    } else if (this.match(/[0-9-]/)) {
      // Number literal
      return value.literal(this.parseNumber());
    } else if (this.is('true')) {
      this.skip(4);
      return value.literal(true);
    } else if (this.is('false')) {
      this.skip(5);
      return value.literal(false);
    } else if (this.is('null')) {
      this.skip(4);
      return value.literal(null);
    }
    throw new Error('Expected value expression');
  }
 
  private parsePathSegments(): types.IPathSegment[] {
    const segments: types.IPathSegment[] = [];
    while (!this.eof()) {
      this.ws();
      Iif (this.eof()) break;
      // Check if we've reached a delimiter that ends the path
      Iif (this.is(')') || this.is(',') || this.is('&&') || this.is('||') || this.isComparisonOperator()) break;
      const segment = this.parsePathSegment();
      segments.push(segment);
    }
    return segments;
  }
 
  private parseFilterPathSegments(): types.IPathSegment[] {
    const segments: types.IPathSegment[] = [];
    while (!this.eof()) {
      this.ws();
      Iif (this.eof()) break;
      // Check if we've reached a delimiter that ends the path in filter context
      if (this.is(')') || this.is(',') || this.is('&&') || this.is('||') || this.isComparisonOperator() || this.is(']'))
        break;
      const segment = this.parseFilterPathSegment();
      segments.push(segment);
    }
    return segments;
  }
 
  private parseFilterPathSegment(): types.IPathSegment {
    this.ws();
    const selectors: types.IAnySelector[] = [];
 
    // Check for recursive descent (..)
    const recursive = this.is('..') as boolean;
    if (recursive) {
      this.skip(2); // Skip ..
      // After .., we should have a selector without requiring . or [
      Iif (this.eof()) {
        throw new Error('Expected selector after ..');
      }
    }
 
    if (this.is('.')) {
      // Dot notation: .name, .*, etc.
      this.skip(1); // Skip .
      this.ws(); // Skip whitespace after .
 
      Iif (this.is('*')) {
        // Wildcard
        this.skip(1);
        selectors.push(Ast.selector.wildcard());
      } else {
        // Named selector
        const name = this.parseIdentifier();
        selectors.push(Ast.selector.named(name));
      }
    } else if (this.is('[')) {
      // Bracket notation: [index], ['name'], [*], [start:end], [a,b,c] etc.
      this.skip(1); // Skip [
      this.ws();
 
      // Parse comma-separated list of selectors
      do {
        this.ws();
        const selector = this.parseBracketSelector();
        selectors.push(selector);
        this.ws();
 
        // Check for comma to continue, or ] to end
        Iif (this.is(',')) {
          this.skip(1); // Skip comma
          this.ws();
        } else {
          break;
        }
      } while (!this.eof() && !this.is(']'));
 
      this.ws();
      Iif (!this.is(']')) {
        throw new Error('Expected ] to close bracket selector');
      }
      this.skip(1); // Skip ]
    } else if (recursive && this.match(/[a-zA-Z_*]/)) {
      // After recursive descent, we can have an identifier or wildcard
      if (this.is('*')) {
        this.skip(1);
        selectors.push(Ast.selector.wildcard());
      } else {
        const name = this.parseIdentifier();
        selectors.push(Ast.selector.named(name));
      }
    } else E{
      throw new Error('Expected . or [ to start filter path segment');
    }
 
    if (recursive && selectors.length === 1) {
      return Ast.segment([Ast.selector.recursiveDescent(selectors[0])]);
    }
 
    return Ast.segment(selectors, recursive || undefined);
  }
 
  private parseIdentifier(): string {
    const {str, length} = this;
    const start = this.pos;
    let pos = start;
 
    // First character must be letter or underscore
    if (pos >= length) throw new Error('Expected identifier');
    const firstCode = str.charCodeAt(pos);
    Iif (
      !(
        (firstCode >= 65 && firstCode <= 90) || // A-Z
        (firstCode >= 97 && firstCode <= 122) || // a-z
        firstCode === 95
      )
    ) {
      // _
      throw new Error('Expected identifier');
    }
    pos++;
 
    // Subsequent characters can be letter, digit, or underscore
    while (pos < length) {
      const code = str.charCodeAt(pos);
      if (
        (code >= 65 && code <= 90) || // A-Z
        (code >= 97 && code <= 122) || // a-z
        (code >= 48 && code <= 57) || // 0-9
        code === 95
      ) {
        // _
        pos++;
      } else {
        break;
      }
    }
 
    this.pos = pos;
    return str.slice(start, pos);
  }
 
  private parseString(): string {
    const quote = this.peek();
    Iif (quote !== "'" && quote !== '"') throw new Error('Expected string literal');
    this.skip(1); // Skip opening quote
    const start = this.pos;
    while (!this.eof() && !this.is(quote))
      if (this.is('\\'))
        this.skip(2); // Skip escape sequence
      else this.skip(1);
    if (this.eof()) throw new Error('Unterminated string literal');
    const value = this.str.slice(start, this.pos);
    this.skip(1); // Skip closing quote
    return value.replace(/\\./g, (match: string) => {
      switch (match[1]) {
        case 'n':
          return '\n';
        case 't':
          return '\t';
        case 'r':
          return '\r';
        case 'b':
          return '\b';
        case 'f':
          return '\f';
        case '\\':
          return '\\';
        case '/':
          return '/';
        case '"':
          return '"';
        case "'":
          return "'";
        default:
          return match;
      }
    });
  }
 
  private parseNumber(): number {
    const {str, length} = this;
    const start = this.pos;
    let pos = start;
 
    // Optional minus sign
    if (pos < length && str.charCodeAt(pos) === 45) {
      // '-'
      pos++;
    }
 
    // Must have at least one digit
    if (pos >= length || str.charCodeAt(pos) < 48 || str.charCodeAt(pos) > 57) {
      // 0-9
      throw new Error('Expected number');
    }
 
    // Integer part
    if (str.charCodeAt(pos) === 48) {
      // '0'
      pos++;
    } else {
      while (pos < length) {
        const code = str.charCodeAt(pos);
        if (code >= 48 && code <= 57) {
          // 0-9
          pos++;
        } else {
          break;
        }
      }
    }
 
    // Optional decimal part
    if (pos < length && str.charCodeAt(pos) === 46) {
      // '.'
      pos++;
      Iif (pos >= length || str.charCodeAt(pos) < 48 || str.charCodeAt(pos) > 57) {
        throw new Error('Expected digit after decimal point');
      }
      while (pos < length) {
        const code = str.charCodeAt(pos);
        if (code >= 48 && code <= 57) {
          // 0-9
          pos++;
        } else {
          break;
        }
      }
    }
 
    // Optional exponent
    if (pos < length) {
      const code = str.charCodeAt(pos);
      Iif (code === 101 || code === 69) {
        // 'e' or 'E'
        pos++;
        Iif (pos < length) {
          const signCode = str.charCodeAt(pos);
          Iif (signCode === 43 || signCode === 45) {
            // '+' or '-'
            pos++;
          }
        }
        Iif (pos >= length || str.charCodeAt(pos) < 48 || str.charCodeAt(pos) > 57) {
          throw new Error('Expected digit in exponent');
        }
        while (pos < length) {
          const code = str.charCodeAt(pos);
          if (code >= 48 && code <= 57) {
            // 0-9
            pos++;
          } else {
            break;
          }
        }
      }
    }
 
    this.pos = pos;
    const numStr = str.slice(start, pos);
    return Number.parseFloat(numStr);
  }
}