/**
 * Copyright 2019 Twitter, Inc.
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 */ import { query as jsonpathQuery } from "jsonpath" ; import { Instance , CompileState , Ast , AT , sqrlInvariant , AstBuilder , Execution , } from "sqrl" ; const JSON_BRAKET_REGEX = /^\$\[([0-9]+|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\](.*)$/ ; export function register ( instance ) { instance . registerTransform ( function jsonValue ( state , ast ) : Ast { const pathAst = ast . args [ 1 ] ; if ( pathAst . type !== "constant" ) { throw new Error ( "Expected constant" ) ; } const fullPath = pathAst . value ; let path = fullPath ; let result = ast . args [ 0 ] ; while ( path !== "$" ) { let select = null ; if ( path . startsWith ( "$." ) ) { const match = /^\$\.([$_a-zA-Z][$_a-zA-Z0-9]*)(.*?)$/ . exec ( path ) ; if ( match ) { select = match [ 1 ] ; path = "$" + match [ 2 ] ; } } else if ( path . startsWith ( "$[" ) ) { const match = JSON_BRAKET_REGEX . exec ( path ) ; if ( match ) { select = match [ 1 ] ; path = "$" + match [ 2 ] ; if ( select . startsWith ( "'" ) || select . startsWith ( '"' ) ) { select = select . substring ( 1 , select . length - 1 ) ; select = select . replace ( /\\(.)/ , "$1" ) ; } } } sqrlInvariant ( ast , select , "JSONPath is not supported:: %s" , fullPath ) ; result = AstBuilder . call ( "attr" , [ result , AstBuilder . constant ( select ) ] ) ; } return result ; } , { args : [ AT . any , AT . constant . string ] , argstring : "object, path string" , docstring : "Returns the value at the given path in the JSON object" , } ) ; instance . registerSync ( function jsonPath ( state , data , path ) : any { todo const stringified = JSON . stringify ( data ) ; return jsonpathQuery ( JSON . parse ( stringified ) , path ) ; } , { args : [ AT . state , AT . any , AT . constant . string ] , argstring : "object, path string" , docstring : "Returns the values matching the given JSONPath query" , } ) ; }