Просмотр исходного кода

chore: adds extra offset to dump with heading messages

e22m4u 7 месяцев назад
Родитель
Сommit
205b63bd86
3 измененных файлов с 130 добавлено и 20 удалено
  1. 17 4
      dist/cjs/index.cjs
  2. 28 5
      src/create-debugger.js
  3. 85 11
      src/create-debugger.spec.js

+ 17 - 4
dist/cjs/index.cjs

@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
 // src/index.js
 var index_exports = {};
 __export(index_exports, {
+  DEFAULT_OFFSET_STEP_SPACES: () => DEFAULT_OFFSET_STEP_SPACES,
   INSPECT_OPTIONS: () => INSPECT_OPTIONS,
   createColorizedDump: () => createColorizedDump,
   createDebugger: () => createDebugger
@@ -146,6 +147,7 @@ var AVAILABLE_COLORS = [
   220,
   221
 ];
+var DEFAULT_OFFSET_STEP_SPACES = 2;
 function pickColorCode(input) {
   if (typeof input !== "string")
     throw new import_js_format.Errorf(
@@ -204,7 +206,7 @@ function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
   state.pattern = typeof state.pattern === "string" ? state.pattern : "";
   state.hash = typeof state.hash === "string" ? state.hash : "";
   state.offsetSize = typeof state.offsetSize === "number" ? state.offsetSize : 0;
-  state.offsetStep = typeof state.offsetStep === "string" ? state.offsetStep : "   ";
+  state.offsetStep = typeof state.offsetStep !== "string" ? " ".repeat(DEFAULT_OFFSET_STEP_SPACES) : state.offsetStep;
   state.delimiter = state.delimiter && typeof state.delimiter === "string" ? state.delimiter : ":";
   if (!withCustomState) {
     if (typeof process !== "undefined" && process.env && process.env["DEBUGGER_NAMESPACE"]) {
@@ -264,9 +266,19 @@ function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
     }
     const multiString = createColorizedDump(messageOrData);
     const rows = multiString.split("\n");
-    [...args, ...rows].forEach((message) => {
-      prefix ? console.log(`${prefix} ${message}`) : console.log(message);
-    });
+    if (args.length) {
+      args.forEach((message) => {
+        prefix ? console.log(`${prefix} ${message}`) : console.log(message);
+      });
+      rows.forEach((message) => {
+        message = `${state.offsetStep}${message}`;
+        prefix ? console.log(`${prefix} ${message}`) : console.log(message);
+      });
+    } else {
+      rows.forEach((message) => {
+        prefix ? console.log(`${prefix} ${message}`) : console.log(message);
+      });
+    }
   }
   __name(debugFn, "debugFn");
   debugFn.withNs = function(namespace, ...args) {
@@ -308,6 +320,7 @@ function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
 __name(createDebugger, "createDebugger");
 // Annotate the CommonJS export names for ESM import in node:
 0 && (module.exports = {
+  DEFAULT_OFFSET_STEP_SPACES,
   INSPECT_OPTIONS,
   createColorizedDump,
   createDebugger

+ 28 - 5
src/create-debugger.js

@@ -17,6 +17,13 @@ const AVAILABLE_COLORS = [
   205, 206, 207, 208, 209, 214, 215, 220, 221,
 ];
 
+/**
+ * Стандартное количество пробелов в одном шаге смещения.
+ *
+ * @type {number}
+ */
+export const DEFAULT_OFFSET_STEP_SPACES = 2;
+
 /**
  * Подбор цвета для строки.
  *
@@ -101,7 +108,7 @@ function matchPattern(pattern, input) {
  * Create debugger.
  *
  * @param {string} namespaceOrOptions
- * @param {string[]} namespaceSegments
+ * @param {string} namespaceSegments
  * @returns {Function}
  */
 export function createDebugger(
@@ -131,7 +138,9 @@ export function createDebugger(
   state.offsetSize =
     typeof state.offsetSize === 'number' ? state.offsetSize : 0;
   state.offsetStep =
-    typeof state.offsetStep === 'string' ? state.offsetStep : '   ';
+    typeof state.offsetStep !== 'string'
+      ? ' '.repeat(DEFAULT_OFFSET_STEP_SPACES)
+      : state.offsetStep;
   state.delimiter =
     state.delimiter && typeof state.delimiter === 'string'
       ? state.delimiter
@@ -223,9 +232,23 @@ export function createDebugger(
     }
     const multiString = createColorizedDump(messageOrData);
     const rows = multiString.split('\n');
-    [...args, ...rows].forEach(message => {
-      prefix ? console.log(`${prefix} ${message}`) : console.log(message);
-    });
+    // если дамп объекта имеет заголовочные сообщения передаваемые
+    // в аргументах данной функции, то после вывода этих сообщений
+    // к дампу добавляется один шаг смещения, чтобы визуально связать
+    // дамп с заголовочными сообщениями
+    if (args.length) {
+      args.forEach(message => {
+        prefix ? console.log(`${prefix} ${message}`) : console.log(message);
+      });
+      rows.forEach(message => {
+        message = `${state.offsetStep}${message}`;
+        prefix ? console.log(`${prefix} ${message}`) : console.log(message);
+      });
+    } else {
+      rows.forEach(message => {
+        prefix ? console.log(`${prefix} ${message}`) : console.log(message);
+      });
+    }
   }
   // создание новой функции логирования
   // с дополнительным пространством имен

+ 85 - 11
src/create-debugger.spec.js

@@ -1,7 +1,7 @@
 import sinon from 'sinon';
 import {expect} from 'chai';
 import {inspect} from 'util';
-import {createDebugger} from './create-debugger.js';
+import {createDebugger, DEFAULT_OFFSET_STEP_SPACES} from './create-debugger.js';
 
 // вспомогательная функция для удаления ANSI escape-кодов (цветов)
 // eslint-disable-next-line no-control-regex
@@ -308,6 +308,41 @@ describe('createDebugger', function () {
       );
     });
 
+    it('should add extra offset to dump if it has heading messages', function () {
+      process.env.DEBUG = 'app:service';
+      const debug = createDebugger('app', 'service');
+      const dummyData = {foo: 'bar', baz: 'qux'};
+      debug(dummyData, 'Data:');
+      expect(consoleLogSpy.callCount).to.be.eq(5);
+      expect(stripAnsi(consoleLogSpy.getCall(0).args[0])).to.be.eq(
+        'app:service Data:',
+      );
+      expect(stripAnsi(consoleLogSpy.getCall(1).args[0])).to.match(
+        new RegExp(
+          '^app:service\\s{' + (DEFAULT_OFFSET_STEP_SPACES + 1) + '}\\{',
+        ),
+      );
+      expect(stripAnsi(consoleLogSpy.getCall(2).args[0])).to.match(
+        new RegExp(
+          '^app:service\\s{' +
+            (DEFAULT_OFFSET_STEP_SPACES + 1) +
+            "}  foo: 'bar',",
+        ),
+      );
+      expect(stripAnsi(consoleLogSpy.getCall(3).args[0])).to.match(
+        new RegExp(
+          '^app:service\\s{' +
+            (DEFAULT_OFFSET_STEP_SPACES + 1) +
+            "}  baz: 'qux'",
+        ),
+      );
+      expect(stripAnsi(consoleLogSpy.getCall(4).args[0])).to.match(
+        new RegExp(
+          '^app:service\\s{' + (DEFAULT_OFFSET_STEP_SPACES + 1) + '}\\}',
+        ),
+      );
+    });
+
     it('should throw error if createDebugger is called with invalid subsequent segment type', function () {
       expect(() => createDebugger('app', 'valid', 123)).to.throw(
         /Namespace segment must be a non-empty String/,
@@ -526,11 +561,15 @@ describe('createDebugger', function () {
       debug1('message1');
       debug2('message2');
       expect(consoleLogSpy.calledTwice).to.be.true;
-      expect(stripAnsi(consoleLogSpy.getCall(0).args[0])).to.equal(
-        'offset    message1',
+      expect(stripAnsi(consoleLogSpy.getCall(0).args[0])).to.match(
+        new RegExp(
+          '^offset\\s{' + (DEFAULT_OFFSET_STEP_SPACES + 1) + '}message1$',
+        ),
       );
-      expect(stripAnsi(consoleLogSpy.getCall(1).args[0])).to.equal(
-        'offset       message2',
+      expect(stripAnsi(consoleLogSpy.getCall(1).args[0])).to.match(
+        new RegExp(
+          '^offset\\s{' + (DEFAULT_OFFSET_STEP_SPACES * 2 + 1) + '}message2$',
+        ),
       );
     });
 
@@ -549,7 +588,7 @@ describe('createDebugger', function () {
       expectedLines.forEach((line, index) => {
         // предполагая, что offsetStep = '   '
         expect(stripAnsi(consoleLogSpy.getCall(index).args[0])).to.match(
-          /^offsetobj\s{4}/,
+          new RegExp('^offsetobj\\s{' + (DEFAULT_OFFSET_STEP_SPACES + 1) + '}'),
         );
         expect(stripAnsi(consoleLogSpy.getCall(index).args[0])).to.contain(
           stripAnsi(line),
@@ -577,8 +616,31 @@ describe('createDebugger', function () {
       debugOffset('message');
       expect(consoleLogSpy.calledOnce).to.be.true;
       // предполагая, что offsetStep = '   '
-      expect(stripAnsi(consoleLogSpy.firstCall.args[0])).to.equal(
-        'envNs    message',
+      expect(stripAnsi(consoleLogSpy.firstCall.args[0])).to.match(
+        new RegExp(
+          '^envNs\\s{' + (DEFAULT_OFFSET_STEP_SPACES + 1) + '}message$',
+        ),
+      );
+    });
+
+    it('should add extra offset to dump if it has heading messages', function () {
+      process.env.DEBUG = '*';
+      const debug = createDebugger();
+      const dummyData = {foo: 'bar', baz: 'qux'};
+      debug(dummyData, 'Data:');
+      expect(consoleLogSpy.callCount).to.be.eq(5);
+      expect(stripAnsi(consoleLogSpy.getCall(0).args[0])).to.be.eq('Data:');
+      expect(stripAnsi(consoleLogSpy.getCall(1).args[0])).to.match(
+        new RegExp('^\\s{' + DEFAULT_OFFSET_STEP_SPACES + '}\\{'),
+      );
+      expect(stripAnsi(consoleLogSpy.getCall(2).args[0])).to.match(
+        new RegExp('^\\s{' + DEFAULT_OFFSET_STEP_SPACES + "}  foo: 'bar',"),
+      );
+      expect(stripAnsi(consoleLogSpy.getCall(3).args[0])).to.match(
+        new RegExp('^\\s{' + DEFAULT_OFFSET_STEP_SPACES + "}  baz: 'qux'"),
+      );
+      expect(stripAnsi(consoleLogSpy.getCall(4).args[0])).to.match(
+        new RegExp('^\\s{' + DEFAULT_OFFSET_STEP_SPACES + '}\\}'),
       );
     });
   });
@@ -594,7 +656,11 @@ describe('createDebugger', function () {
       expect(consoleLogSpy.calledOnce).to.be.true;
       // предполагая, что offsetStep = '   '
       expect(stripAnsi(consoleLogSpy.firstCall.args[0])).to.match(
-        /^app:svc:[a-f0-9]{5}\s{4}combined message$/,
+        new RegExp(
+          '^app:svc:[a-f0-9]{5}\\s{' +
+            (DEFAULT_OFFSET_STEP_SPACES + 1) +
+            '}combined message$',
+        ),
       );
     });
 
@@ -617,13 +683,21 @@ describe('createDebugger', function () {
       expect(consoleLogSpy.callCount).to.equal(totalExpectedCalls);
       // предполагая, что offsetStep = '   '
       expect(stripAnsi(consoleLogSpy.getCall(0).args[0])).to.match(
-        /^app:svc:[a-f0-9]{3}\s{4}Data:$/,
+        new RegExp(
+          '^app:svc:[a-f0-9]{3}\\s{' +
+            (DEFAULT_OFFSET_STEP_SPACES + 1) +
+            '}Data:$',
+        ),
       );
       expectedLines.forEach((line, index) => {
         const callIndex = index + 1;
         const logLine = stripAnsi(consoleLogSpy.getCall(callIndex).args[0]);
         // предполагая, что offsetStep = '   '
-        expect(logLine).to.match(/^app:svc:[a-f0-9]{3}\s{4}/);
+        expect(logLine).to.match(
+          new RegExp(
+            '^app:svc:[a-f0-9]{3}\\s{' + (DEFAULT_OFFSET_STEP_SPACES + 1) + '}',
+          ),
+        );
         expect(logLine).to.contain(stripAnsi(line));
       });
     });