jsonpath

jsonpath库

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/452604/1101839/jsonpath.js

  1. //https://github.com/JSONPath-Plus/JSONPath
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.JSONPath = {}));
  6. })(this, (function (exports) { 'use strict';
  7.  
  8. function _typeof(obj) {
  9. "@babel/helpers - typeof";
  10.  
  11. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
  12. return typeof obj;
  13. } : function (obj) {
  14. return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  15. }, _typeof(obj);
  16. }
  17.  
  18. function _classCallCheck(instance, Constructor) {
  19. if (!(instance instanceof Constructor)) {
  20. throw new TypeError("Cannot call a class as a function");
  21. }
  22. }
  23.  
  24. function _defineProperties(target, props) {
  25. for (var i = 0; i < props.length; i++) {
  26. var descriptor = props[i];
  27. descriptor.enumerable = descriptor.enumerable || false;
  28. descriptor.configurable = true;
  29. if ("value" in descriptor) descriptor.writable = true;
  30. Object.defineProperty(target, descriptor.key, descriptor);
  31. }
  32. }
  33.  
  34. function _createClass(Constructor, protoProps, staticProps) {
  35. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  36. if (staticProps) _defineProperties(Constructor, staticProps);
  37. Object.defineProperty(Constructor, "prototype", {
  38. writable: false
  39. });
  40. return Constructor;
  41. }
  42.  
  43. function _inherits(subClass, superClass) {
  44. if (typeof superClass !== "function" && superClass !== null) {
  45. throw new TypeError("Super expression must either be null or a function");
  46. }
  47.  
  48. subClass.prototype = Object.create(superClass && superClass.prototype, {
  49. constructor: {
  50. value: subClass,
  51. writable: true,
  52. configurable: true
  53. }
  54. });
  55. Object.defineProperty(subClass, "prototype", {
  56. writable: false
  57. });
  58. if (superClass) _setPrototypeOf(subClass, superClass);
  59. }
  60.  
  61. function _getPrototypeOf(o) {
  62. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
  63. return o.__proto__ || Object.getPrototypeOf(o);
  64. };
  65. return _getPrototypeOf(o);
  66. }
  67.  
  68. function _setPrototypeOf(o, p) {
  69. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  70. o.__proto__ = p;
  71. return o;
  72. };
  73. return _setPrototypeOf(o, p);
  74. }
  75.  
  76. function _isNativeReflectConstruct() {
  77. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  78. if (Reflect.construct.sham) return false;
  79. if (typeof Proxy === "function") return true;
  80.  
  81. try {
  82. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  83. return true;
  84. } catch (e) {
  85. return false;
  86. }
  87. }
  88.  
  89. function _construct(Parent, args, Class) {
  90. if (_isNativeReflectConstruct()) {
  91. _construct = Reflect.construct.bind();
  92. } else {
  93. _construct = function _construct(Parent, args, Class) {
  94. var a = [null];
  95. a.push.apply(a, args);
  96. var Constructor = Function.bind.apply(Parent, a);
  97. var instance = new Constructor();
  98. if (Class) _setPrototypeOf(instance, Class.prototype);
  99. return instance;
  100. };
  101. }
  102.  
  103. return _construct.apply(null, arguments);
  104. }
  105.  
  106. function _isNativeFunction(fn) {
  107. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  108. }
  109.  
  110. function _wrapNativeSuper(Class) {
  111. var _cache = typeof Map === "function" ? new Map() : undefined;
  112.  
  113. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  114. if (Class === null || !_isNativeFunction(Class)) return Class;
  115.  
  116. if (typeof Class !== "function") {
  117. throw new TypeError("Super expression must either be null or a function");
  118. }
  119.  
  120. if (typeof _cache !== "undefined") {
  121. if (_cache.has(Class)) return _cache.get(Class);
  122.  
  123. _cache.set(Class, Wrapper);
  124. }
  125.  
  126. function Wrapper() {
  127. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  128. }
  129.  
  130. Wrapper.prototype = Object.create(Class.prototype, {
  131. constructor: {
  132. value: Wrapper,
  133. enumerable: false,
  134. writable: true,
  135. configurable: true
  136. }
  137. });
  138. return _setPrototypeOf(Wrapper, Class);
  139. };
  140.  
  141. return _wrapNativeSuper(Class);
  142. }
  143.  
  144. function _assertThisInitialized(self) {
  145. if (self === void 0) {
  146. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  147. }
  148.  
  149. return self;
  150. }
  151.  
  152. function _possibleConstructorReturn(self, call) {
  153. if (call && (typeof call === "object" || typeof call === "function")) {
  154. return call;
  155. } else if (call !== void 0) {
  156. throw new TypeError("Derived constructors may only return object or undefined");
  157. }
  158.  
  159. return _assertThisInitialized(self);
  160. }
  161.  
  162. function _createSuper(Derived) {
  163. var hasNativeReflectConstruct = _isNativeReflectConstruct();
  164.  
  165. return function _createSuperInternal() {
  166. var Super = _getPrototypeOf(Derived),
  167. result;
  168.  
  169. if (hasNativeReflectConstruct) {
  170. var NewTarget = _getPrototypeOf(this).constructor;
  171.  
  172. result = Reflect.construct(Super, arguments, NewTarget);
  173. } else {
  174. result = Super.apply(this, arguments);
  175. }
  176.  
  177. return _possibleConstructorReturn(this, result);
  178. };
  179. }
  180.  
  181. function _toConsumableArray(arr) {
  182. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  183. }
  184.  
  185. function _arrayWithoutHoles(arr) {
  186. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  187. }
  188.  
  189. function _iterableToArray(iter) {
  190. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  191. }
  192.  
  193. function _unsupportedIterableToArray(o, minLen) {
  194. if (!o) return;
  195. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  196. var n = Object.prototype.toString.call(o).slice(8, -1);
  197. if (n === "Object" && o.constructor) n = o.constructor.name;
  198. if (n === "Map" || n === "Set") return Array.from(o);
  199. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  200. }
  201.  
  202. function _arrayLikeToArray(arr, len) {
  203. if (len == null || len > arr.length) len = arr.length;
  204.  
  205. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  206.  
  207. return arr2;
  208. }
  209.  
  210. function _nonIterableSpread() {
  211. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  212. }
  213.  
  214. function _createForOfIteratorHelper(o, allowArrayLike) {
  215. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  216.  
  217. if (!it) {
  218. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  219. if (it) o = it;
  220. var i = 0;
  221.  
  222. var F = function () {};
  223.  
  224. return {
  225. s: F,
  226. n: function () {
  227. if (i >= o.length) return {
  228. done: true
  229. };
  230. return {
  231. done: false,
  232. value: o[i++]
  233. };
  234. },
  235. e: function (e) {
  236. throw e;
  237. },
  238. f: F
  239. };
  240. }
  241.  
  242. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  243. }
  244.  
  245. var normalCompletion = true,
  246. didErr = false,
  247. err;
  248. return {
  249. s: function () {
  250. it = it.call(o);
  251. },
  252. n: function () {
  253. var step = it.next();
  254. normalCompletion = step.done;
  255. return step;
  256. },
  257. e: function (e) {
  258. didErr = true;
  259. err = e;
  260. },
  261. f: function () {
  262. try {
  263. if (!normalCompletion && it.return != null) it.return();
  264. } finally {
  265. if (didErr) throw err;
  266. }
  267. }
  268. };
  269. }
  270.  
  271. var hasOwnProp = Object.prototype.hasOwnProperty;
  272. /**
  273. * @typedef {null|boolean|number|string|PlainObject|GenericArray} JSONObject
  274. */
  275.  
  276. /**
  277. * @typedef {any} AnyItem
  278. */
  279.  
  280. /**
  281. * @typedef {any} AnyResult
  282. */
  283.  
  284. /**
  285. * Copies array and then pushes item into it.
  286. * @param {GenericArray} arr Array to copy and into which to push
  287. * @param {AnyItem} item Array item to add (to end)
  288. * @returns {GenericArray} Copy of the original array
  289. */
  290.  
  291. function push(arr, item) {
  292. arr = arr.slice();
  293. arr.push(item);
  294. return arr;
  295. }
  296. /**
  297. * Copies array and then unshifts item into it.
  298. * @param {AnyItem} item Array item to add (to beginning)
  299. * @param {GenericArray} arr Array to copy and into which to unshift
  300. * @returns {GenericArray} Copy of the original array
  301. */
  302.  
  303.  
  304. function unshift(item, arr) {
  305. arr = arr.slice();
  306. arr.unshift(item);
  307. return arr;
  308. }
  309. /**
  310. * Caught when JSONPath is used without `new` but rethrown if with `new`
  311. * @extends Error
  312. */
  313.  
  314.  
  315. var NewError = /*#__PURE__*/function (_Error) {
  316. _inherits(NewError, _Error);
  317.  
  318. var _super = _createSuper(NewError);
  319.  
  320. /**
  321. * @param {AnyResult} value The evaluated scalar value
  322. */
  323. function NewError(value) {
  324. var _this;
  325.  
  326. _classCallCheck(this, NewError);
  327.  
  328. _this = _super.call(this, 'JSONPath should not be called with "new" (it prevents return ' + 'of (unwrapped) scalar values)');
  329. _this.avoidNew = true;
  330. _this.value = value;
  331. _this.name = 'NewError';
  332. return _this;
  333. }
  334.  
  335. return _createClass(NewError);
  336. }( /*#__PURE__*/_wrapNativeSuper(Error));
  337. /**
  338. * @typedef {PlainObject} ReturnObject
  339. * @property {string} path
  340. * @property {JSONObject} value
  341. * @property {PlainObject|GenericArray} parent
  342. * @property {string} parentProperty
  343. */
  344.  
  345. /**
  346. * @callback JSONPathCallback
  347. * @param {string|PlainObject} preferredOutput
  348. * @param {"value"|"property"} type
  349. * @param {ReturnObject} fullRetObj
  350. * @returns {void}
  351. */
  352.  
  353. /**
  354. * @callback OtherTypeCallback
  355. * @param {JSONObject} val
  356. * @param {string} path
  357. * @param {PlainObject|GenericArray} parent
  358. * @param {string} parentPropName
  359. * @returns {boolean}
  360. */
  361.  
  362. /* eslint-disable max-len -- Can make multiline type after https://github.com/syavorsky/comment-parser/issues/109 */
  363.  
  364. /**
  365. * @typedef {PlainObject} JSONPathOptions
  366. * @property {JSON} json
  367. * @property {string|string[]} path
  368. * @property {"value"|"path"|"pointer"|"parent"|"parentProperty"|"all"} [resultType="value"]
  369. * @property {boolean} [flatten=false]
  370. * @property {boolean} [wrap=true]
  371. * @property {PlainObject} [sandbox={}]
  372. * @property {boolean} [preventEval=false]
  373. * @property {PlainObject|GenericArray|null} [parent=null]
  374. * @property {string|null} [parentProperty=null]
  375. * @property {JSONPathCallback} [callback]
  376. * @property {OtherTypeCallback} [otherTypeCallback] Defaults to
  377. * function which throws on encountering `@other`
  378. * @property {boolean} [autostart=true]
  379. */
  380.  
  381. /* eslint-enable max-len -- Can make multiline type after https://github.com/syavorsky/comment-parser/issues/109 */
  382.  
  383. /**
  384. * @param {string|JSONPathOptions} opts If a string, will be treated as `expr`
  385. * @param {string} [expr] JSON path to evaluate
  386. * @param {JSON} [obj] JSON object to evaluate against
  387. * @param {JSONPathCallback} [callback] Passed 3 arguments: 1) desired payload
  388. * per `resultType`, 2) `"value"|"property"`, 3) Full returned object with
  389. * all payloads
  390. * @param {OtherTypeCallback} [otherTypeCallback] If `@other()` is at the end
  391. * of one's query, this will be invoked with the value of the item, its
  392. * path, its parent, and its parent's property name, and it should return
  393. * a boolean indicating whether the supplied value belongs to the "other"
  394. * type or not (or it may handle transformations and return `false`).
  395. * @returns {JSONPath}
  396. * @class
  397. */
  398.  
  399.  
  400. function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
  401. // eslint-disable-next-line no-restricted-syntax
  402. if (!(this instanceof JSONPath)) {
  403. try {
  404. return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
  405. } catch (e) {
  406. if (!e.avoidNew) {
  407. throw e;
  408. }
  409.  
  410. return e.value;
  411. }
  412. }
  413.  
  414. if (typeof opts === 'string') {
  415. otherTypeCallback = callback;
  416. callback = obj;
  417. obj = expr;
  418. expr = opts;
  419. opts = null;
  420. }
  421.  
  422. var optObj = opts && _typeof(opts) === 'object';
  423. opts = opts || {};
  424. this.json = opts.json || obj;
  425. this.path = opts.path || expr;
  426. this.resultType = opts.resultType || 'value';
  427. this.flatten = opts.flatten || false;
  428. this.wrap = hasOwnProp.call(opts, 'wrap') ? opts.wrap : true;
  429. this.sandbox = opts.sandbox || {};
  430. this.preventEval = opts.preventEval || false;
  431. this.parent = opts.parent || null;
  432. this.parentProperty = opts.parentProperty || null;
  433. this.callback = opts.callback || callback || null;
  434.  
  435. this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () {
  436. throw new TypeError('You must supply an otherTypeCallback callback option ' + 'with the @other() operator.');
  437. };
  438.  
  439. if (opts.autostart !== false) {
  440. var args = {
  441. path: optObj ? opts.path : expr
  442. };
  443.  
  444. if (!optObj) {
  445. args.json = obj;
  446. } else if ('json' in opts) {
  447. args.json = opts.json;
  448. }
  449.  
  450. var ret = this.evaluate(args);
  451.  
  452. if (!ret || _typeof(ret) !== 'object') {
  453. throw new NewError(ret);
  454. }
  455.  
  456. return ret;
  457. }
  458. } // PUBLIC METHODS
  459.  
  460.  
  461. JSONPath.prototype.evaluate = function (expr, json, callback, otherTypeCallback) {
  462. var _this2 = this;
  463.  
  464. var currParent = this.parent,
  465. currParentProperty = this.parentProperty;
  466. var flatten = this.flatten,
  467. wrap = this.wrap;
  468. this.currResultType = this.resultType;
  469. this.currPreventEval = this.preventEval;
  470. this.currSandbox = this.sandbox;
  471. callback = callback || this.callback;
  472. this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
  473. json = json || this.json;
  474. expr = expr || this.path;
  475.  
  476. if (expr && _typeof(expr) === 'object' && !Array.isArray(expr)) {
  477. if (!expr.path && expr.path !== '') {
  478. throw new TypeError('You must supply a "path" property when providing an object ' + 'argument to JSONPath.evaluate().');
  479. }
  480.  
  481. if (!hasOwnProp.call(expr, 'json')) {
  482. throw new TypeError('You must supply a "json" property when providing an object ' + 'argument to JSONPath.evaluate().');
  483. }
  484.  
  485. var _expr = expr;
  486. json = _expr.json;
  487. flatten = hasOwnProp.call(expr, 'flatten') ? expr.flatten : flatten;
  488. this.currResultType = hasOwnProp.call(expr, 'resultType') ? expr.resultType : this.currResultType;
  489. this.currSandbox = hasOwnProp.call(expr, 'sandbox') ? expr.sandbox : this.currSandbox;
  490. wrap = hasOwnProp.call(expr, 'wrap') ? expr.wrap : wrap;
  491. this.currPreventEval = hasOwnProp.call(expr, 'preventEval') ? expr.preventEval : this.currPreventEval;
  492. callback = hasOwnProp.call(expr, 'callback') ? expr.callback : callback;
  493. this.currOtherTypeCallback = hasOwnProp.call(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback;
  494. currParent = hasOwnProp.call(expr, 'parent') ? expr.parent : currParent;
  495. currParentProperty = hasOwnProp.call(expr, 'parentProperty') ? expr.parentProperty : currParentProperty;
  496. expr = expr.path;
  497. }
  498.  
  499. currParent = currParent || null;
  500. currParentProperty = currParentProperty || null;
  501.  
  502. if (Array.isArray(expr)) {
  503. expr = JSONPath.toPathString(expr);
  504. }
  505.  
  506. if (!expr && expr !== '' || !json) {
  507. return undefined;
  508. }
  509.  
  510. var exprList = JSONPath.toPathArray(expr);
  511.  
  512. if (exprList[0] === '$' && exprList.length > 1) {
  513. exprList.shift();
  514. }
  515.  
  516. this._hasParentSelector = null;
  517.  
  518. var result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback).filter(function (ea) {
  519. return ea && !ea.isParentSelector;
  520. });
  521.  
  522. if (!result.length) {
  523. return wrap ? [] : undefined;
  524. }
  525.  
  526. if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
  527. return this._getPreferredOutput(result[0]);
  528. }
  529.  
  530. return result.reduce(function (rslt, ea) {
  531. var valOrPath = _this2._getPreferredOutput(ea);
  532.  
  533. if (flatten && Array.isArray(valOrPath)) {
  534. rslt = rslt.concat(valOrPath);
  535. } else {
  536. rslt.push(valOrPath);
  537. }
  538.  
  539. return rslt;
  540. }, []);
  541. }; // PRIVATE METHODS
  542.  
  543.  
  544. JSONPath.prototype._getPreferredOutput = function (ea) {
  545. var resultType = this.currResultType;
  546.  
  547. switch (resultType) {
  548. case 'all':
  549. {
  550. var path = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
  551. ea.pointer = JSONPath.toPointer(path);
  552. ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(ea.path);
  553. return ea;
  554. }
  555.  
  556. case 'value':
  557. case 'parent':
  558. case 'parentProperty':
  559. return ea[resultType];
  560.  
  561. case 'path':
  562. return JSONPath.toPathString(ea[resultType]);
  563.  
  564. case 'pointer':
  565. return JSONPath.toPointer(ea.path);
  566.  
  567. default:
  568. throw new TypeError('Unknown result type');
  569. }
  570. };
  571.  
  572. JSONPath.prototype._handleCallback = function (fullRetObj, callback, type) {
  573. if (callback) {
  574. var preferredOutput = this._getPreferredOutput(fullRetObj);
  575.  
  576. fullRetObj.path = typeof fullRetObj.path === 'string' ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path); // eslint-disable-next-line n/callback-return
  577.  
  578. callback(preferredOutput, type, fullRetObj);
  579. }
  580. };
  581. /**
  582. *
  583. * @param {string} expr
  584. * @param {JSONObject} val
  585. * @param {string} path
  586. * @param {PlainObject|GenericArray} parent
  587. * @param {string} parentPropName
  588. * @param {JSONPathCallback} callback
  589. * @param {boolean} hasArrExpr
  590. * @param {boolean} literalPriority
  591. * @returns {ReturnObject|ReturnObject[]}
  592. */
  593.  
  594.  
  595. JSONPath.prototype._trace = function (expr, val, path, parent, parentPropName, callback, hasArrExpr, literalPriority) {
  596. var _this3 = this;
  597.  
  598. // No expr to follow? return path and value as the result of
  599. // this trace branch
  600. var retObj;
  601.  
  602. if (!expr.length) {
  603. retObj = {
  604. path: path,
  605. value: val,
  606. parent: parent,
  607. parentProperty: parentPropName,
  608. hasArrExpr: hasArrExpr
  609. };
  610.  
  611. this._handleCallback(retObj, callback, 'value');
  612.  
  613. return retObj;
  614. }
  615.  
  616. var loc = expr[0],
  617. x = expr.slice(1); // We need to gather the return value of recursive trace calls in order to
  618. // do the parent sel computation.
  619.  
  620. var ret = [];
  621. /**
  622. *
  623. * @param {ReturnObject|ReturnObject[]} elems
  624. * @returns {void}
  625. */
  626.  
  627. function addRet(elems) {
  628. if (Array.isArray(elems)) {
  629. // This was causing excessive stack size in Node (with or
  630. // without Babel) against our performance test:
  631. // `ret.push(...elems);`
  632. elems.forEach(function (t) {
  633. ret.push(t);
  634. });
  635. } else {
  636. ret.push(elems);
  637. }
  638. }
  639.  
  640. if ((typeof loc !== 'string' || literalPriority) && val && hasOwnProp.call(val, loc)) {
  641. // simple case--directly follow property
  642. addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr)); // eslint-disable-next-line unicorn/prefer-switch -- Part of larger `if`
  643. } else if (loc === '*') {
  644. // all child properties
  645. this._walk(val, function (m) {
  646. addRet(_this3._trace(x, val[m], push(path, m), val, m, callback, true, true));
  647. });
  648. } else if (loc === '..') {
  649. // all descendent parent properties
  650. // Check remaining expression with val's immediate children
  651. addRet(this._trace(x, val, path, parent, parentPropName, callback, hasArrExpr));
  652.  
  653. this._walk(val, function (m) {
  654. // We don't join m and x here because we only want parents,
  655. // not scalar values
  656. if (_typeof(val[m]) === 'object') {
  657. // Keep going with recursive descent on val's
  658. // object children
  659. addRet(_this3._trace(expr.slice(), val[m], push(path, m), val, m, callback, true));
  660. }
  661. }); // The parent sel computation is handled in the frame above using the
  662. // ancestor object of val
  663.  
  664. } else if (loc === '^') {
  665. // This is not a final endpoint, so we do not invoke the callback here
  666. this._hasParentSelector = true;
  667. return {
  668. path: path.slice(0, -1),
  669. expr: x,
  670. isParentSelector: true
  671. };
  672. } else if (loc === '~') {
  673. // property name
  674. retObj = {
  675. path: push(path, loc),
  676. value: parentPropName,
  677. parent: parent,
  678. parentProperty: null
  679. };
  680.  
  681. this._handleCallback(retObj, callback, 'property');
  682.  
  683. return retObj;
  684. } else if (loc === '$') {
  685. // root only
  686. addRet(this._trace(x, val, path, null, null, callback, hasArrExpr));
  687. } else if (/^(\x2D?[0-9]*):(\x2D?[0-9]*):?([0-9]*)$/.test(loc)) {
  688. // [start:end:step] Python slice syntax
  689. addRet(this._slice(loc, x, val, path, parent, parentPropName, callback));
  690. } else if (loc.indexOf('?(') === 0) {
  691. // [?(expr)] (filtering)
  692. if (this.currPreventEval) {
  693. throw new Error('Eval [?(expr)] prevented in JSONPath expression.');
  694. }
  695.  
  696. var safeLoc = loc.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/, '$1');
  697.  
  698. this._walk(val, function (m) {
  699. if (_this3._eval(safeLoc, val[m], m, path, parent, parentPropName)) {
  700. addRet(_this3._trace(x, val[m], push(path, m), val, m, callback, true));
  701. }
  702. });
  703. } else if (loc[0] === '(') {
  704. // [(expr)] (dynamic property/index)
  705. if (this.currPreventEval) {
  706. throw new Error('Eval [(expr)] prevented in JSONPath expression.');
  707. } // As this will resolve to a property name (but we don't know it
  708. // yet), property and parent information is relative to the
  709. // parent of the property to which this expression will resolve
  710.  
  711.  
  712. addRet(this._trace(unshift(this._eval(loc, val, path[path.length - 1], path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback, hasArrExpr));
  713. } else if (loc[0] === '@') {
  714. // value type: @boolean(), etc.
  715. var addType = false;
  716. var valueType = loc.slice(1, -2);
  717.  
  718. switch (valueType) {
  719. case 'scalar':
  720. if (!val || !['object', 'function'].includes(_typeof(val))) {
  721. addType = true;
  722. }
  723.  
  724. break;
  725.  
  726. case 'boolean':
  727. case 'string':
  728. case 'undefined':
  729. case 'function':
  730. // eslint-disable-next-line valid-typeof
  731. if (_typeof(val) === valueType) {
  732. addType = true;
  733. }
  734.  
  735. break;
  736.  
  737. case 'integer':
  738. if (Number.isFinite(val) && !(val % 1)) {
  739. addType = true;
  740. }
  741.  
  742. break;
  743.  
  744. case 'number':
  745. if (Number.isFinite(val)) {
  746. addType = true;
  747. }
  748.  
  749. break;
  750.  
  751. case 'nonFinite':
  752. if (typeof val === 'number' && !Number.isFinite(val)) {
  753. addType = true;
  754. }
  755.  
  756. break;
  757.  
  758. case 'object':
  759. // eslint-disable-next-line valid-typeof
  760. if (val && _typeof(val) === valueType) {
  761. addType = true;
  762. }
  763.  
  764. break;
  765.  
  766. case 'array':
  767. if (Array.isArray(val)) {
  768. addType = true;
  769. }
  770.  
  771. break;
  772.  
  773. case 'other':
  774. addType = this.currOtherTypeCallback(val, path, parent, parentPropName);
  775. break;
  776.  
  777. case 'null':
  778. if (val === null) {
  779. addType = true;
  780. }
  781.  
  782. break;
  783.  
  784. /* c8 ignore next 2 */
  785.  
  786. default:
  787. throw new TypeError('Unknown value type ' + valueType);
  788. }
  789.  
  790. if (addType) {
  791. retObj = {
  792. path: path,
  793. value: val,
  794. parent: parent,
  795. parentProperty: parentPropName
  796. };
  797.  
  798. this._handleCallback(retObj, callback, 'value');
  799.  
  800. return retObj;
  801. } // `-escaped property
  802.  
  803. } else if (loc[0] === '`' && val && hasOwnProp.call(val, loc.slice(1))) {
  804. var locProp = loc.slice(1);
  805. addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true));
  806. } else if (loc.includes(',')) {
  807. // [name1,name2,...]
  808. var parts = loc.split(',');
  809.  
  810. var _iterator = _createForOfIteratorHelper(parts),
  811. _step;
  812.  
  813. try {
  814. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  815. var part = _step.value;
  816. addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback, true));
  817. } // simple case--directly follow property
  818.  
  819. } catch (err) {
  820. _iterator.e(err);
  821. } finally {
  822. _iterator.f();
  823. }
  824. } else if (!literalPriority && val && hasOwnProp.call(val, loc)) {
  825. addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr, true));
  826. } // We check the resulting values for parent selections. For parent
  827. // selections we discard the value object and continue the trace with the
  828. // current val object
  829.  
  830.  
  831. if (this._hasParentSelector) {
  832. for (var t = 0; t < ret.length; t++) {
  833. var rett = ret[t];
  834.  
  835. if (rett && rett.isParentSelector) {
  836. var tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
  837.  
  838. if (Array.isArray(tmp)) {
  839. ret[t] = tmp[0];
  840. var tl = tmp.length;
  841.  
  842. for (var tt = 1; tt < tl; tt++) {
  843. t++;
  844. ret.splice(t, 0, tmp[tt]);
  845. }
  846. } else {
  847. ret[t] = tmp;
  848. }
  849. }
  850. }
  851. }
  852.  
  853. return ret;
  854. };
  855.  
  856. JSONPath.prototype._walk = function (val, f) {
  857. if (Array.isArray(val)) {
  858. var n = val.length;
  859.  
  860. for (var i = 0; i < n; i++) {
  861. f(i);
  862. }
  863. } else if (val && _typeof(val) === 'object') {
  864. Object.keys(val).forEach(function (m) {
  865. f(m);
  866. });
  867. }
  868. };
  869.  
  870. JSONPath.prototype._slice = function (loc, expr, val, path, parent, parentPropName, callback) {
  871. if (!Array.isArray(val)) {
  872. return undefined;
  873. }
  874.  
  875. var len = val.length,
  876. parts = loc.split(':'),
  877. step = parts[2] && Number.parseInt(parts[2]) || 1;
  878. var start = parts[0] && Number.parseInt(parts[0]) || 0,
  879. end = parts[1] && Number.parseInt(parts[1]) || len;
  880. start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
  881. end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
  882. var ret = [];
  883.  
  884. for (var i = start; i < end; i += step) {
  885. var tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback, true); // Should only be possible to be an array here since first part of
  886. // ``unshift(i, expr)` passed in above would not be empty, nor `~`,
  887. // nor begin with `@` (as could return objects)
  888. // This was causing excessive stack size in Node (with or
  889. // without Babel) against our performance test: `ret.push(...tmp);`
  890.  
  891.  
  892. tmp.forEach(function (t) {
  893. ret.push(t);
  894. });
  895. }
  896.  
  897. return ret;
  898. };
  899.  
  900. JSONPath.prototype._eval = function (code, _v, _vname, path, parent, parentPropName) {
  901. this.currSandbox._$_parentProperty = parentPropName;
  902. this.currSandbox._$_parent = parent;
  903. this.currSandbox._$_property = _vname;
  904. this.currSandbox._$_root = this.json;
  905. this.currSandbox._$_v = _v;
  906. var containsPath = code.includes('@path');
  907.  
  908. if (containsPath) {
  909. this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname]));
  910. }
  911.  
  912. var scriptCacheKey = 'script:' + code;
  913.  
  914. if (!JSONPath.cache[scriptCacheKey]) {
  915. var script = code.replace(/@parentProperty/g, '_$_parentProperty').replace(/@parent/g, '_$_parent').replace(/@property/g, '_$_property').replace(/@root/g, '_$_root').replace(/@([\t-\r \)\.\[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF])/g, '_$_v$1');
  916.  
  917. if (containsPath) {
  918. script = script.replace(/@path/g, '_$_path');
  919. }
  920.  
  921. JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
  922. }
  923.  
  924. try {
  925. return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
  926. } catch (e) {
  927. throw new Error('jsonPath: ' + e.message + ': ' + code);
  928. }
  929. }; // PUBLIC CLASS PROPERTIES AND METHODS
  930. // Could store the cache object itself
  931.  
  932.  
  933. JSONPath.cache = {};
  934. /**
  935. * @param {string[]} pathArr Array to convert
  936. * @returns {string} The path string
  937. */
  938.  
  939. JSONPath.toPathString = function (pathArr) {
  940. var x = pathArr,
  941. n = x.length;
  942. var p = '$';
  943.  
  944. for (var i = 1; i < n; i++) {
  945. if (!/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(x[i])) {
  946. p += /^[\*0-9]+$/.test(x[i]) ? '[' + x[i] + ']' : "['" + x[i] + "']";
  947. }
  948. }
  949.  
  950. return p;
  951. };
  952. /**
  953. * @param {string} pointer JSON Path
  954. * @returns {string} JSON Pointer
  955. */
  956.  
  957.  
  958. JSONPath.toPointer = function (pointer) {
  959. var x = pointer,
  960. n = x.length;
  961. var p = '';
  962.  
  963. for (var i = 1; i < n; i++) {
  964. if (!/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(x[i])) {
  965. p += '/' + x[i].toString().replace(/~/g, '~0').replace(/\//g, '~1');
  966. }
  967. }
  968.  
  969. return p;
  970. };
  971. /**
  972. * @param {string} expr Expression to convert
  973. * @returns {string[]}
  974. */
  975.  
  976.  
  977. JSONPath.toPathArray = function (expr) {
  978. var cache = JSONPath.cache;
  979.  
  980. if (cache[expr]) {
  981. return cache[expr].concat();
  982. }
  983.  
  984. var subx = [];
  985. var normalized = expr // Properties
  986. .replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g, ';$&;') // Parenthetical evaluations (filtering and otherwise), directly
  987. // within brackets or single quotes
  988. .replace(/['\[](\??\((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\))['\]]/g, function ($0, $1) {
  989. return '[#' + (subx.push($1) - 1) + ']';
  990. }) // Escape periods and tildes within properties
  991. .replace(/\[["']((?:(?!['\]])[\s\S])*)["']\]/g, function ($0, prop) {
  992. return "['" + prop.replace(/\./g, '%@%').replace(/~/g, '%%@@%%') + "']";
  993. }) // Properties operator
  994. .replace(/~/g, ';~;') // Split by property boundaries
  995. .replace(/["']?\.["']?(?!(?:(?!\[)[\s\S])*\])|\[["']?/g, ';') // Reinsert periods within properties
  996. .replace(/%@%/g, '.') // Reinsert tildes within properties
  997. .replace(/%%@@%%/g, '~') // Parent
  998. .replace(/(?:;)?(\^+)(?:;)?/g, function ($0, ups) {
  999. return ';' + ups.split('').join(';') + ';';
  1000. }) // Descendents
  1001. .replace(/;;;|;;/g, ';..;') // Remove trailing
  1002. .replace(/;$|'?\]|'$/g, '');
  1003. var exprList = normalized.split(';').map(function (exp) {
  1004. var match = exp.match(/#([0-9]+)/);
  1005. return !match || !match[1] ? exp : subx[match[1]];
  1006. });
  1007. cache[expr] = exprList;
  1008. return cache[expr].concat();
  1009. };
  1010.  
  1011. /**
  1012. * @typedef {any} ContextItem
  1013. */
  1014.  
  1015. /**
  1016. * @typedef {any} EvaluatedResult
  1017. */
  1018.  
  1019. /**
  1020. * @callback ConditionCallback
  1021. * @param {ContextItem} item
  1022. * @returns {boolean}
  1023. */
  1024.  
  1025. /**
  1026. * Copy items out of one array into another.
  1027. * @param {GenericArray} source Array with items to copy
  1028. * @param {GenericArray} target Array to which to copy
  1029. * @param {ConditionCallback} conditionCb Callback passed the current item;
  1030. * will move item if evaluates to `true`
  1031. * @returns {void}
  1032. */
  1033.  
  1034. var moveToAnotherArray = function moveToAnotherArray(source, target, conditionCb) {
  1035. var il = source.length;
  1036.  
  1037. for (var i = 0; i < il; i++) {
  1038. var item = source[i];
  1039.  
  1040. if (conditionCb(item)) {
  1041. target.push(source.splice(i--, 1)[0]);
  1042. }
  1043. }
  1044. };
  1045. /**
  1046. * In-browser replacement for NodeJS' VM.Script.
  1047. */
  1048.  
  1049.  
  1050. var Script = /*#__PURE__*/function () {
  1051. /**
  1052. * @param {string} expr Expression to evaluate
  1053. */
  1054. function Script(expr) {
  1055. _classCallCheck(this, Script);
  1056.  
  1057. this.code = expr;
  1058. }
  1059. /**
  1060. * @param {PlainObject} context Object whose items will be added
  1061. * to evaluation
  1062. * @returns {EvaluatedResult} Result of evaluated code
  1063. */
  1064.  
  1065.  
  1066. _createClass(Script, [{
  1067. key: "runInNewContext",
  1068. value: function runInNewContext(context) {
  1069. var expr = this.code;
  1070. var keys = Object.keys(context);
  1071. var funcs = [];
  1072. moveToAnotherArray(keys, funcs, function (key) {
  1073. return typeof context[key] === 'function';
  1074. });
  1075. var values = keys.map(function (vr, i) {
  1076. return context[vr];
  1077. });
  1078. var funcString = funcs.reduce(function (s, func) {
  1079. var fString = context[func].toString();
  1080.  
  1081. if (!/function/.test(fString)) {
  1082. fString = 'function ' + fString;
  1083. }
  1084.  
  1085. return 'var ' + func + '=' + fString + ';' + s;
  1086. }, '');
  1087. expr = funcString + expr; // Mitigate http://perfectionkills.com/global-eval-what-are-the-options/#new_function
  1088.  
  1089. if (!/(["'])use strict\1/.test(expr) && !keys.includes('arguments')) {
  1090. expr = 'var arguments = undefined;' + expr;
  1091. } // Remove last semi so `return` will be inserted before
  1092. // the previous one instead, allowing for the return
  1093. // of a bare ending expression
  1094.  
  1095.  
  1096. expr = expr.replace(/;[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*$/, ''); // Insert `return`
  1097.  
  1098. var lastStatementEnd = expr.lastIndexOf(';');
  1099. var code = lastStatementEnd > -1 ? expr.slice(0, lastStatementEnd + 1) + ' return ' + expr.slice(lastStatementEnd + 1) : ' return ' + expr; // eslint-disable-next-line no-new-func
  1100.  
  1101. return _construct(Function, keys.concat([code])).apply(void 0, _toConsumableArray(values));
  1102. }
  1103. }]);
  1104.  
  1105. return Script;
  1106. }();
  1107.  
  1108. JSONPath.prototype.vm = {
  1109. Script: Script
  1110. };
  1111.  
  1112. exports.JSONPath = JSONPath;
  1113.  
  1114. Object.defineProperty(exports, '__esModule', { value: true });
  1115.  
  1116. }));