Browse Source

refactor: rollback

e22m4u 3 days ago
parent
commit
26eaa02516

+ 4 - 0
.mocharc.cjs

@@ -0,0 +1,4 @@
+module.exports = {
+  extension: ['js'],
+  spec: 'src/**/*.spec.js',
+}

+ 0 - 4
.mocharc.json

@@ -1,4 +0,0 @@
-{
-  "extension": ["js"],
-  "spec": "src/**/*.spec.js"
-}

+ 58 - 57
dist/cjs/index.cjs

@@ -60,8 +60,65 @@ function generateRandomHex(length = 4) {
 }
 __name(generateRandomHex, "generateRandomHex");
 
+// src/debuggable.js
+var _Debuggable = class _Debuggable {
+  /**
+   * Debug.
+   *
+   * @type {*}
+   */
+  debug;
+  /**
+   * Ctor Debug.
+   *
+   * @type {Function}
+   */
+  ctorDebug;
+  /**
+   * Возвращает функцию-отладчик с сегментом пространства имен
+   * указанного в параметре метода.
+   *
+   * @param {Function} method
+   * @returns {Function}
+   */
+  getDebuggerFor(method) {
+    const name = method.name || "anonymous";
+    return this.debug.withHash().withNs(name);
+  }
+  /**
+   * Constructor.
+   *
+   * @param {DebuggableOptions|undefined} options
+   */
+  constructor(options = void 0) {
+    const className = toCamelCase(this.constructor.name);
+    options = typeof options === "object" && options || {};
+    const namespace = options.namespace && String(options.namespace) || void 0;
+    if (namespace) {
+      this.debug = createDebugger(namespace, className);
+    } else {
+      this.debug = createDebugger(className);
+    }
+    const noEnvironmentNamespace = Boolean(options.noEnvironmentNamespace);
+    if (noEnvironmentNamespace) this.debug = this.debug.withoutEnvNs();
+    this.ctorDebug = this.debug.withNs("constructor").withHash();
+    const noInstantiationMessage = Boolean(options.noInstantiationMessage);
+    if (!noInstantiationMessage)
+      this.ctorDebug(_Debuggable.INSTANTIATION_MESSAGE);
+  }
+};
+__name(_Debuggable, "Debuggable");
+/**
+ * Instantiation message.
+ *
+ * @type {string}
+ */
+__publicField(_Debuggable, "INSTANTIATION_MESSAGE", "Instantiated.");
+var Debuggable = _Debuggable;
+
 // src/create-debugger.js
 var import_js_format = require("@e22m4u/js-format");
+var import_js_format2 = require("@e22m4u/js-format");
 
 // src/create-colorized-dump.js
 var import_util = require("util");
@@ -267,7 +324,7 @@ function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
   function debugFn(messageOrData, ...args) {
     if (!isDebuggerEnabled()) return;
     const prefix = getPrefix();
-    const multiString = (0, import_js_format.format)(messageOrData, ...args);
+    const multiString = (0, import_js_format2.format)(messageOrData, ...args);
     const rows = multiString.split("\n");
     rows.forEach((message) => {
       prefix ? console.log(`${prefix} ${message}`) : console.log(message);
@@ -335,62 +392,6 @@ function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
   return debugFn;
 }
 __name(createDebugger, "createDebugger");
-
-// src/debuggable.js
-var _Debuggable = class _Debuggable {
-  /**
-   * Debug.
-   *
-   * @type {*}
-   */
-  debug;
-  /**
-   * Ctor Debug.
-   *
-   * @type {Function}
-   */
-  ctorDebug;
-  /**
-   * Возвращает функцию-отладчик с сегментом пространства имен
-   * указанного в параметре метода.
-   *
-   * @param {Function} method
-   * @returns {Function}
-   */
-  getDebuggerFor(method) {
-    const name = method.name || "anonymous";
-    return this.debug.withHash().withNs(name);
-  }
-  /**
-   * Constructor.
-   *
-   * @param {DebuggableOptions|undefined} options
-   */
-  constructor(options = void 0) {
-    const className = toCamelCase(this.constructor.name);
-    options = typeof options === "object" && options || {};
-    const namespace = options.namespace && String(options.namespace) || void 0;
-    if (namespace) {
-      this.debug = createDebugger(namespace, className);
-    } else {
-      this.debug = createDebugger(className);
-    }
-    const noEnvironmentNamespace = Boolean(options.noEnvironmentNamespace);
-    if (noEnvironmentNamespace) this.debug = this.debug.withoutEnvNs();
-    this.ctorDebug = this.debug.withNs("constructor").withHash();
-    const noInstantiationMessage = Boolean(options.noInstantiationMessage);
-    if (!noInstantiationMessage)
-      this.ctorDebug(_Debuggable.INSTANTIATION_MESSAGE);
-  }
-};
-__name(_Debuggable, "Debuggable");
-/**
- * Instantiation message.
- *
- * @type {string}
- */
-__publicField(_Debuggable, "INSTANTIATION_MESSAGE", "Instantiated.");
-var Debuggable = _Debuggable;
 // Annotate the CommonJS export names for ESM import in node:
 0 && (module.exports = {
   DEFAULT_OFFSET_STEP_SPACES,

+ 1 - 13
eslint.config.js

@@ -1,8 +1,6 @@
 import globals from 'globals';
 import eslintJs from '@eslint/js';
-import eslintJsdocPlugin from 'eslint-plugin-jsdoc';
 import eslintMochaPlugin from 'eslint-plugin-mocha';
-import eslintImportPlugin from 'eslint-plugin-import';
 import eslintPrettierConfig from 'eslint-config-prettier';
 import eslintChaiExpectPlugin from 'eslint-plugin-chai-expect';
 
@@ -16,25 +14,15 @@ export default [{
     },
   },
   plugins: {
-    'jsdoc': eslintJsdocPlugin,
     'mocha': eslintMochaPlugin,
-    'import': eslintImportPlugin,
     'chai-expect': eslintChaiExpectPlugin,
   },
   rules: {
     ...eslintJs.configs.recommended.rules,
     ...eslintPrettierConfig.rules,
-    ...eslintImportPlugin.flatConfigs.recommended.rules,
     ...eslintMochaPlugin.configs.recommended.rules,
     ...eslintChaiExpectPlugin.configs['recommended-flat'].rules,
-    ...eslintJsdocPlugin.configs['flat/recommended-error'].rules,
-    'no-duplicate-imports': 'error',
-    'jsdoc/reject-any-type': 0,
-    'jsdoc/reject-function-type': 0,
-    'jsdoc/require-param-description': 0,
-    'jsdoc/require-returns-description': 0,
-    'jsdoc/require-property-description': 0,
-    'jsdoc/tag-lines': ['error', 'any', {startLines: 1}],
+    "no-unused-vars": ["error", {caughtErrors: "none"}],
   },
   files: ['src/**/*.js'],
 }];

+ 0 - 7
jsconfig.json

@@ -1,7 +0,0 @@
-{
-  "compilerOptions": {
-    "target": "es2022",
-    "module": "NodeNext",
-    "moduleResolution": "NodeNext"
-  }
-}

+ 12 - 10
package.json

@@ -1,6 +1,6 @@
 {
   "name": "@e22m4u/js-debug",
-  "version": "0.4.0",
+  "version": "0.3.3",
   "description": "Утилита вывода сообщений отладки для JavaScript",
   "author": "Mikhail Evstropov <e22m4u@yandex.ru>",
   "license": "MIT",
@@ -11,15 +11,17 @@
     "debugger",
     "interpolation"
   ],
-  "homepage": "https://gitrepos.ru/e22m4u/js-debug",
+  "homepage": "https://github.com/e22m4u/js-debug",
   "repository": {
     "type": "git",
-    "url": "git+https://gitrepos.ru/e22m4u/js-debug.git"
+    "url": "git+https://github.com/e22m4u/js-debug.git"
   },
   "type": "module",
+  "types": "./src/index.d.ts",
   "module": "./src/index.js",
   "main": "./dist/cjs/index.cjs",
   "exports": {
+    "types": "./src/index.d.ts",
     "import": "./src/index.js",
     "require": "./dist/cjs/index.cjs"
   },
@@ -27,12 +29,12 @@
     "node": ">=12"
   },
   "scripts": {
-    "lint": "eslint ./src",
-    "lint:fix": "eslint ./src --fix",
+    "lint": "tsc && eslint ./src",
+    "lint:fix": "tsc && eslint ./src --fix",
     "format": "prettier --write \"./src/**/*.js\"",
     "test": "npm run lint && c8 --reporter=text-summary mocha --bail",
     "test:coverage": "npm run lint && c8 --reporter=text mocha --bail",
-    "build:cjs": "rimraf ./dist/cjs && node build-cjs.js",
+    "build:cjs": "rimraf ./dist/cjs && node --no-warnings=ExperimentalWarning build-cjs.js",
     "prepare": "husky"
   },
   "dependencies": {
@@ -44,19 +46,19 @@
     "@commitlint/config-conventional": "~20.0.0",
     "@e22m4u/js-spy": "~0.2.0",
     "@eslint/js": "~9.39.1",
+    "@types/mocha": "~10.0.10",
     "c8": "~10.1.3",
     "chai": "~6.2.1",
     "esbuild": "~0.27.0",
     "eslint": "~9.39.1",
     "eslint-config-prettier": "~10.1.8",
     "eslint-plugin-chai-expect": "~3.1.0",
-    "eslint-plugin-import": "~2.32.0",
-    "eslint-plugin-jsdoc": "~61.4.1",
     "eslint-plugin-mocha": "~11.2.0",
     "globals": "~16.5.0",
     "husky": "~9.1.7",
     "mocha": "~11.7.5",
-    "prettier": "~3.7.3",
-    "rimraf": "~6.1.2"
+    "prettier": "~3.7.2",
+    "rimraf": "~6.1.2",
+    "typescript": "~5.9.3"
   }
 }

+ 6 - 0
src/create-colorized-dump.d.ts

@@ -0,0 +1,6 @@
+/**
+ * Create colorized dump.
+ *
+ * @param value
+ */
+export declare function createColorizedDump(value: unknown): string;

+ 134 - 0
src/create-debugger.d.ts

@@ -0,0 +1,134 @@
+/**
+ * Стандартное количество пробелов в одном шаге смещения.
+ */
+export const DEFAULT_OFFSET_STEP_SPACES: number;
+
+/**
+ * Объект конфигурации, который хранит все настройки
+ * для конкретного экземпляра отладчика.
+ */
+export type DebuggerState = {
+  /**
+   * Массив строк, содержащий сегменты пространства имен,
+   * полученные из переменной окружения DEBUGGER_NAMESPACE.
+   */
+  envNsSegments: string[];
+  /**
+   * Массив строк, содержащий сегменты пространства имен,
+   * переданные в качестве аргументов при создании отладчика.
+   */
+  nsSegments: string[];
+  /**
+   * Строка, используемая в качестве шаблона для определения,
+   * активен ли данный отладчик. Она получается из переменной
+   * окружения DEBUG или из localStorage.
+   */
+  pattern: string;
+  /**
+   * Строка, содержащая случайный шестнадцатеричный хэш,
+   * который может быть добавлен к префиксу вывода отладки.
+   */
+  hash: string;
+  /**
+   * Число, определяющее размер смещения (отступа) для сообщений
+   * отладки.
+   */
+  offsetSize: number;
+  /**
+   * Строка, представляющая собой один шаг смещения
+   * (например, два пробела).
+   */
+  offsetStep: string;
+  /**
+   * Строка, используемая в качестве разделителя между
+   * сегментами пространства имен.
+   */
+  delimiter: string;
+};
+
+/**
+ * Представляет функцию отладчика, которая также может быть расширена
+ * пространствами имен, хэшами или отступами.
+ */
+export interface Debugger {
+  /**
+   * Вывод отладочного сообщения.
+   *
+   * @param messageOrData Строка сообщения (с опциональными
+   *   спецификаторами формата).
+   * @param args Дополнительные аргументы для интерполяции.
+   */
+  (message: unknown, ...args: any[]): void;
+
+  /**
+   * Объект конфигурации, который хранит все настройки
+   * для конкретного экземпляра отладчика.
+   */
+  state: DebuggerState;
+
+  /**
+   * Создание нового экземпляра отладчика с добавленным сегментом
+   * пространства имен.
+   *
+   * @param namespace Сегмент пространства имен для добавления.
+   * @param args Дополнительные сегменты пространства имен для
+   *   добавления.
+   * @returns Новый экземпляр Debugger.
+   * @throws {Error} Если пространство имен не является непустой
+   *   строкой.
+   */
+  withNs(namespace: string, ...args: string[]): Debugger;
+
+  /**
+   * Создание нового экземпляра отладчика со статическим случайным хэшем,
+   * добавляемым к префиксу.
+   *
+   * @param hashLength Желаемая длина шестнадцатеричного хэша
+   *   (по умолчанию: 4).
+   * @returns Новый экземпляр Debugger.
+   * @throws {Error} Если длина хэша не является положительным
+   *   числом.
+   */
+  withHash(hashLength?: number): Debugger;
+
+  /**
+   * Создание нового экземпляра отладчика с отступом для его сообщений.
+   *
+   * @param offsetSize Количество шагов отступа (положительное
+   *   целое число).
+   * @returns Новый экземпляр Debugger.
+   * @throws {Error} Если размер отступа не является положительным
+   *   числом.
+   */
+  withOffset(offsetSize: number): Debugger;
+
+  /**
+   * Создание нового экземпляра отладчика без пространства имен
+   * из переменной окружения DEBUGGER_NAMESPACE.
+   *
+   * @returns Новый экземпляр Debugger.
+   */
+  withoutEnvNs(): Debugger;
+
+  /**
+   * Вывод дампа первого аргумента. Если передано два аргумента,
+   * то первый будет являться описанием для второго.
+   * 
+   * @param dataOrDescription Данные отладки или описание для второго аргумента.
+   * @param args Данные отладки (при наличии описания).
+   */
+  inspect(dataOrDescription: unknown, ...args: any[]): void;
+}
+
+/**
+ * Create debugger.
+ *
+ * @param namespace Сегмент пространства имен.
+ * @param namespaceSegments Дополнительные сегменты пространства имен для
+ *   добавления.
+ * @returns Новый экземпляр Debugger.
+ */
+export declare function createDebugger(
+  namespace?: string,
+  ...namespaceSegments: string[],
+): Debugger;

+ 4 - 7
src/create-debugger.js

@@ -1,6 +1,8 @@
-import {Errorf, format} from '@e22m4u/js-format';
+import {Errorf} from '@e22m4u/js-format';
+import {format} from '@e22m4u/js-format';
+import {isNonArrayObject} from './utils/index.js';
+import {generateRandomHex} from './utils/index.js';
 import {createColorizedDump} from './create-colorized-dump.js';
-import {isNonArrayObject, generateRandomHex} from './utils/index.js';
 
 /**
  * Доступные цвета.
@@ -224,11 +226,6 @@ export function createDebugger(
   };
   // формирование функции вывода
   // сообщений отладки
-  /**
-   * @param {*} messageOrData
-   * @param  {...*} args
-   * @returns {undefined}
-   */
   function debugFn(messageOrData, ...args) {
     if (!isDebuggerEnabled()) return;
     const prefix = getPrefix();

+ 2 - 1
src/create-debugger.spec.js

@@ -1,7 +1,8 @@
 import {expect} from 'chai';
 import {createSpy} from '@e22m4u/js-spy';
 import {stripAnsi} from './utils/strip-ansi.js';
-import {createDebugger, DEFAULT_OFFSET_STEP_SPACES} from './create-debugger.js';
+import {createDebugger} from './create-debugger.js';
+import {DEFAULT_OFFSET_STEP_SPACES} from './create-debugger.js';
 
 describe('createDebugger', function () {
   let consoleLogSpy;

+ 48 - 0
src/debuggable.d.ts

@@ -0,0 +1,48 @@
+import {Callable} from './types.js';
+import {Debugger} from './create-debugger.js';
+
+/**
+ * Debuggable options.
+ */
+export type DebuggableOptions = {
+  namespace?: string,
+  noEnvironmentNamespace?: boolean,
+  noInstantiationMessage?: boolean,
+}
+
+/**
+ * Debuggable.
+ */
+export class Debuggable {
+  /**
+   * Instantiation message.
+   */
+  static INSTANTIATION_MESSAGE: string;
+
+  /**
+   * Debug.
+   */
+  debug: Debugger;
+
+  /**
+   * Debug.
+   */
+  ctorDebug: Debugger;
+
+  /**
+   * Возвращает функцию-отладчик с сегментом пространства имен
+   * указанного в параметре метода.
+   *
+   * @param method
+   * @protected
+   */
+  protected getDebuggerFor(method: Callable): Debugger;
+
+  /**
+   * Constructor.
+   *
+   * @param container
+   * @param options
+   */
+  constructor(options?: DebuggableOptions);
+}

+ 6 - 5
src/debuggable.js

@@ -1,11 +1,12 @@
 import {toCamelCase} from './utils/index.js';
-import {createDebugger} from './create-debugger.js';
+import {createDebugger} from '@e22m4u/js-debug';
 
 /**
- * @typedef {object} DebuggableOptions
- * @property {string} [namespace]
- * @property {boolean} [noEnvironmentNamespace]
- * @property {boolean} [noInstantiationMessage]
+ * @typedef {{
+ *   namespace?: string,
+ *   noEnvironmentNamespace?: boolean,
+ *   noInstantiationMessage?: boolean,
+ * }} DebuggableOptions
  */
 
 /**

+ 2 - 1
src/debuggable.spec.js

@@ -1,7 +1,8 @@
 import {expect} from 'chai';
 import {createSpy} from '@e22m4u/js-spy';
 import {Debuggable} from './debuggable.js';
-import {stripAnsi, escapeRegexp} from './utils/index.js';
+import {stripAnsi} from './utils/index.js';
+import {escapeRegexp} from './utils/index.js';
 
 describe('Debuggable', function () {
   let consoleLogSpy;

+ 3 - 0
src/index.d.ts

@@ -0,0 +1,3 @@
+export * from './debuggable.js';
+export * from './create-debugger.js';
+export * from './create-colorized-dump.js';

+ 5 - 0
src/types.d.ts

@@ -0,0 +1,5 @@
+/**
+ * A function type without class and constructor.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type Callable<T = unknown> = (...args: any[]) => T;

+ 1 - 0
src/types.js

@@ -0,0 +1 @@
+export {};

+ 1 - 2
src/utils/is-non-array-object.js

@@ -1,8 +1,7 @@
 /**
  * Is non-array object.
  *
- * @param {*} input
- * @returns {boolean}
+ * @param input
  */
 export function isNonArrayObject(input) {
   return Boolean(input && typeof input === 'object' && !Array.isArray(input));

+ 1 - 2
src/utils/to-camel-case.js

@@ -1,8 +1,7 @@
 /**
  * To camel case.
  *
- * @param {string} input
- * @returns {string}
+ * @param input
  */
 export function toCamelCase(input) {
   return input

+ 14 - 0
tsconfig.json

@@ -0,0 +1,14 @@
+{
+  "compilerOptions": {
+    "noEmit": true,
+    "target": "es2022",
+    "module": "NodeNext",
+    "moduleResolution": "NodeNext",
+    "allowJs": true,
+    "checkJs": true
+  },
+  "include": [
+    "./src/**/*.ts",
+    "./src/**/*.js"
+  ]
+}