debug.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.genRedactedString = exports.getStringValue = exports.MAX_ARGUMENT_LENGTH = void 0;
  4. const debug_1 = require("debug");
  5. const MAX_ARGUMENT_LENGTH = 200;
  6. exports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH;
  7. const NAMESPACE_PREFIX = "ioredis";
  8. /**
  9. * helper function that tried to get a string value for
  10. * arbitrary "debug" arg
  11. */
  12. function getStringValue(v) {
  13. if (v === null) {
  14. return;
  15. }
  16. switch (typeof v) {
  17. case "boolean":
  18. return;
  19. case "number":
  20. return;
  21. case "object":
  22. if (Buffer.isBuffer(v)) {
  23. return v.toString("hex");
  24. }
  25. if (Array.isArray(v)) {
  26. return v.join(",");
  27. }
  28. try {
  29. return JSON.stringify(v);
  30. }
  31. catch (e) {
  32. return;
  33. }
  34. case "string":
  35. return v;
  36. }
  37. }
  38. exports.getStringValue = getStringValue;
  39. /**
  40. * helper function that redacts a string representation of a "debug" arg
  41. */
  42. function genRedactedString(str, maxLen) {
  43. const { length } = str;
  44. return length <= maxLen
  45. ? str
  46. : str.slice(0, maxLen) + ' ... <REDACTED full-length="' + length + '">';
  47. }
  48. exports.genRedactedString = genRedactedString;
  49. /**
  50. * a wrapper for the `debug` module, used to generate
  51. * "debug functions" that trim the values in their output
  52. */
  53. function genDebugFunction(namespace) {
  54. const fn = (0, debug_1.default)(`${NAMESPACE_PREFIX}:${namespace}`);
  55. function wrappedDebug(...args) {
  56. if (!fn.enabled) {
  57. return; // no-op
  58. }
  59. // we skip the first arg because that is the message
  60. for (let i = 1; i < args.length; i++) {
  61. const str = getStringValue(args[i]);
  62. if (typeof str === "string" && str.length > MAX_ARGUMENT_LENGTH) {
  63. args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH);
  64. }
  65. }
  66. return fn.apply(null, args);
  67. }
  68. Object.defineProperties(wrappedDebug, {
  69. namespace: {
  70. get() {
  71. return fn.namespace;
  72. },
  73. },
  74. enabled: {
  75. get() {
  76. return fn.enabled;
  77. },
  78. },
  79. destroy: {
  80. get() {
  81. return fn.destroy;
  82. },
  83. },
  84. log: {
  85. get() {
  86. return fn.log;
  87. },
  88. set(l) {
  89. fn.log = l;
  90. },
  91. },
  92. });
  93. return wrappedDebug;
  94. }
  95. exports.default = genDebugFunction;