to-json.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getDeepKeys = exports.toJSON = void 0;
  4. const nonJsonTypes = ["function", "symbol", "undefined"];
  5. const protectedProps = ["constructor", "prototype", "__proto__"];
  6. const objectPrototype = Object.getPrototypeOf({});
  7. /**
  8. * Custom JSON serializer for Error objects.
  9. * Returns all built-in error properties, as well as extended properties.
  10. */
  11. function toJSON() {
  12. // HACK: We have to cast the objects to `any` so we can use symbol indexers.
  13. // see https://github.com/Microsoft/TypeScript/issues/1863
  14. let pojo = {};
  15. let error = this;
  16. for (let key of getDeepKeys(error)) {
  17. if (typeof key === "string") {
  18. let value = error[key];
  19. let type = typeof value;
  20. if (!nonJsonTypes.includes(type)) {
  21. pojo[key] = value;
  22. }
  23. }
  24. }
  25. return pojo;
  26. }
  27. exports.toJSON = toJSON;
  28. /**
  29. * Returns own, inherited, enumerable, non-enumerable, string, and symbol keys of `obj`.
  30. * Does NOT return members of the base Object prototype, or the specified omitted keys.
  31. */
  32. function getDeepKeys(obj, omit = []) {
  33. let keys = [];
  34. // Crawl the prototype chain, finding all the string and symbol keys
  35. while (obj && obj !== objectPrototype) {
  36. keys = keys.concat(Object.getOwnPropertyNames(obj), Object.getOwnPropertySymbols(obj));
  37. obj = Object.getPrototypeOf(obj);
  38. }
  39. // De-duplicate the list of keys
  40. let uniqueKeys = new Set(keys);
  41. // Remove any omitted keys
  42. for (let key of omit.concat(protectedProps)) {
  43. uniqueKeys.delete(key);
  44. }
  45. return uniqueKeys;
  46. }
  47. exports.getDeepKeys = getDeepKeys;
  48. //# sourceMappingURL=to-json.js.map