index.cjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
  4. 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*:/;
  5. const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
  6. function jsonParseTransform(key, value) {
  7. if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
  8. warnKeyDropped(key);
  9. return;
  10. }
  11. return value;
  12. }
  13. function warnKeyDropped(key) {
  14. console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
  15. }
  16. function destr(value, options = {}) {
  17. if (typeof value !== "string") {
  18. return value;
  19. }
  20. if (value[0] === '"' && value[value.length - 1] === '"' && value.indexOf("\\") === -1) {
  21. return value.slice(1, -1);
  22. }
  23. const _value = value.trim();
  24. if (_value.length <= 9) {
  25. switch (_value.toLowerCase()) {
  26. case "true": {
  27. return true;
  28. }
  29. case "false": {
  30. return false;
  31. }
  32. case "undefined": {
  33. return void 0;
  34. }
  35. case "null": {
  36. return null;
  37. }
  38. case "nan": {
  39. return Number.NaN;
  40. }
  41. case "infinity": {
  42. return Number.POSITIVE_INFINITY;
  43. }
  44. case "-infinity": {
  45. return Number.NEGATIVE_INFINITY;
  46. }
  47. }
  48. }
  49. if (!JsonSigRx.test(value)) {
  50. if (options.strict) {
  51. throw new SyntaxError("[destr] Invalid JSON");
  52. }
  53. return value;
  54. }
  55. try {
  56. if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
  57. if (options.strict) {
  58. throw new Error("[destr] Possible prototype pollution");
  59. }
  60. return JSON.parse(value, jsonParseTransform);
  61. }
  62. return JSON.parse(value);
  63. } catch (error) {
  64. if (options.strict) {
  65. throw error;
  66. }
  67. return value;
  68. }
  69. }
  70. function safeDestr(value, options = {}) {
  71. return destr(value, { ...options, strict: true });
  72. }
  73. exports.default = destr;
  74. exports.destr = destr;
  75. exports.safeDestr = safeDestr;