index.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
  2. 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*:/;
  3. const JsonSigRx = /^["{[]|^-?[0-9][0-9.]{0,14}$/;
  4. function jsonParseTransform(key, value) {
  5. if (key === "__proto__" || key === "constructor") {
  6. return;
  7. }
  8. return value;
  9. }
  10. function destr(val) {
  11. if (typeof val !== "string") {
  12. return val;
  13. }
  14. const _lval = val.toLowerCase();
  15. if (_lval === "true") {
  16. return true;
  17. }
  18. if (_lval === "false") {
  19. return false;
  20. }
  21. if (_lval === "null") {
  22. return null;
  23. }
  24. if (_lval === "nan") {
  25. return NaN;
  26. }
  27. if (_lval === "infinity") {
  28. return Infinity;
  29. }
  30. if (_lval === "undefined") {
  31. return void 0;
  32. }
  33. if (!JsonSigRx.test(val)) {
  34. return val;
  35. }
  36. try {
  37. if (suspectProtoRx.test(val) || suspectConstructorRx.test(val)) {
  38. return JSON.parse(val, jsonParseTransform);
  39. }
  40. return JSON.parse(val);
  41. } catch (_e) {
  42. return val;
  43. }
  44. }
  45. export { destr as default };