index.cjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
  3. const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
  4. const JsonSigRx = /^["{[]|^-?[0-9][0-9.]{0,14}$/;
  5. function jsonParseTransform(key, value) {
  6. if (key === "__proto__" || key === "constructor") {
  7. return;
  8. }
  9. return value;
  10. }
  11. function destr(val, options = {}) {
  12. if (typeof val !== "string") {
  13. return val;
  14. }
  15. const _lval = val.toLowerCase();
  16. if (_lval === "true") {
  17. return true;
  18. }
  19. if (_lval === "false") {
  20. return false;
  21. }
  22. if (_lval === "null") {
  23. return null;
  24. }
  25. if (_lval === "nan") {
  26. return NaN;
  27. }
  28. if (_lval === "infinity") {
  29. return Infinity;
  30. }
  31. if (_lval === "undefined") {
  32. return void 0;
  33. }
  34. if (!JsonSigRx.test(val)) {
  35. if (options.strict) {
  36. throw new SyntaxError("Invalid JSON");
  37. }
  38. return val;
  39. }
  40. try {
  41. if (suspectProtoRx.test(val) || suspectConstructorRx.test(val)) {
  42. return JSON.parse(val, jsonParseTransform);
  43. }
  44. return JSON.parse(val);
  45. } catch (error) {
  46. if (options.strict) {
  47. throw error;
  48. }
  49. return val;
  50. }
  51. }
  52. module.exports = destr;