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

refactor: removes type definitions

e22m4u 4 дней назад
Родитель
Сommit
9df214ee23

+ 57 - 58
dist/cjs/index.cjs

@@ -60,65 +60,8 @@ 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");
@@ -324,7 +267,7 @@ function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
   function debugFn(messageOrData, ...args) {
     if (!isDebuggerEnabled()) return;
     const prefix = getPrefix();
-    const multiString = (0, import_js_format2.format)(messageOrData, ...args);
+    const multiString = (0, import_js_format.format)(messageOrData, ...args);
     const rows = multiString.split("\n");
     rows.forEach((message) => {
       prefix ? console.log(`${prefix} ${message}`) : console.log(message);
@@ -392,6 +335,62 @@ 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,

+ 13 - 1
eslint.config.js

@@ -1,6 +1,8 @@
 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';
 
@@ -14,15 +16,25 @@ 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,
-    "no-unused-vars": ["error", {caughtErrors: "none"}],
+    ...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}],
   },
   files: ['src/**/*.js'],
 }];

+ 7 - 0
jsconfig.json

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

+ 8 - 10
package.json

@@ -11,17 +11,15 @@
     "debugger",
     "interpolation"
   ],
-  "homepage": "https://github.com/e22m4u/js-debug",
+  "homepage": "https://gitrepos.ru/e22m4u/js-debug",
   "repository": {
     "type": "git",
-    "url": "git+https://github.com/e22m4u/js-debug.git"
+    "url": "git+https://gitrepos.ru/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"
   },
@@ -29,8 +27,8 @@
     "node": ">=12"
   },
   "scripts": {
-    "lint": "tsc && eslint ./src",
-    "lint:fix": "tsc && eslint ./src --fix",
+    "lint": "eslint ./src",
+    "lint:fix": "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",
@@ -46,19 +44,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.2",
-    "rimraf": "~6.1.2",
-    "typescript": "~5.9.3"
+    "prettier": "~3.7.3",
+    "rimraf": "~6.1.2"
   }
 }

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

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

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

@@ -1,134 +0,0 @@
-/**
- * Стандартное количество пробелов в одном шаге смещения.
- */
-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;

+ 7 - 4
src/create-debugger.js

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

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

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

+ 0 - 48
src/debuggable.d.ts

@@ -1,48 +0,0 @@
-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);
-}

+ 5 - 6
src/debuggable.js

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

+ 1 - 2
src/debuggable.spec.js

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

+ 0 - 3
src/index.d.ts

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

+ 0 - 5
src/types.d.ts

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

+ 0 - 1
src/types.js

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

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

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

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

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

+ 0 - 14
tsconfig.json

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