debug-web 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## [1.0.0] - 2026-01-04
4
+ - Initial release of debug-web library
5
+ - Console logging with CSS styling, global data storage, and TypeScript support
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Karlen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.de.md ADDED
@@ -0,0 +1,182 @@
1
+ # Debug Web
2
+ Leichtgewichtige Bibliothek für Browser-Debugging.
3
+
4
+ **Vorteile**:
5
+ - 🚀 **Keine Abhängigkeiten** — nur reines TypeScript;
6
+ - 📦 **Größe ~3.0 kB** — minimaler Einfluss auf das Bundle;
7
+ - 🎨 **Konsole-Ausgabe-Styling** — farbige Formatierung für schnelle Identifizierung;
8
+ - 💾 **Globale Speicherung** — Zugriff auf Debug-Daten über `window`.
9
+
10
+ ---
11
+
12
+ ## Inhaltsverzeichnis 📑
13
+
14
+ - [Installation](#installation-)
15
+ - [Log-Level](#log-level-)
16
+ - [Optionen](#optionen-)
17
+ - [Standardstile](#standardstile-)
18
+ - [Verwendung](#verwendung-)
19
+ - [Stilanpassung](#stilanpassung-)
20
+ - [API](#api-)
21
+ - [Erweiterung der Funktionalität](#erweiterung-der-funktionalität)
22
+
23
+ ## Andere Sprachversionen
24
+
25
+ [English](README.md), [Español](README.es.md), [Deutsch](README.de.md), [中文](README.zh.md), [Русский](README.ru.md)
26
+
27
+ ---
28
+
29
+ ## Installation 📦
30
+
31
+ ```bash
32
+ npm install debug-web
33
+ ```
34
+ ```bash
35
+ yarn add debug-web
36
+ ```
37
+
38
+ ## Log-Level 🔧
39
+
40
+ Priorität (niedrig nach hoch):
41
+
42
+ 1. `debug` (0) — Debug-Informationen (`console.debug`);
43
+ 2. `log` (1) — Grundlegende Nachrichten (`console.log`);
44
+ 3. `info` (2) — Informationelle Nachrichten (`console.info`);
45
+ 4. `warn` (3) — Warnungen (`console.warn`);
46
+ 5. `error` (4) — Fehler (`console.error`).
47
+
48
+ ℹ️ Benutzerdefinierte Level: Jeder Zeichenkettenwert (einschließlich `success`) wird als `info`-Level behandelt.
49
+
50
+ ## Optionen ⚙️
51
+
52
+ | Parameter | Typ | Standardwert | Beschreibung |
53
+ |-----------|---------------------------------|--------------------------------|--------------------------------------------------------------------------|
54
+ | `app` | `string` \| `null` | `'__web_debug__'` | Eindeutiger App-Name zur Trennung von Daten verschiedener Anwendungen |
55
+ | `level` | `DebugLogLevel` | `'log'` | Minimales Log-Level (Nachrichten darunter werden nicht ausgegeben) |
56
+ | `prop` | `string` \| `null` | `'info'` | NName der globalen Variable für Datenzugriff über `window[prop]` |
57
+ | `data` | `Record<string, unknown>` | — | Initiale Debug-Daten, die sofort nach Initialisierung gespeichert werden |
58
+ | `style` | `Record<DebugLogLevel, string>` | siehe [unten](#standardstile-) | Benutzerdefinierte CSS-Stile für Nachrichten verschiedener Level |
59
+
60
+ ```typescript
61
+ type DebugLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
62
+ ```
63
+
64
+ ### Standardstile 🎨
65
+
66
+ | Level | Stil (CSS) |
67
+ |-----------|----------------------------------------------------------------------------|
68
+ | `info` | `background-color: #155adc; color: #fff; padding: 2px; border-radius: 3px` |
69
+ | `success` | `background-color: #13a10e; color: #fff; padding: 2px; border-radius: 3px` |
70
+ | `warn` | `background-color: #ffa500; color: #fff; padding: 2px; border-radius: 3px` |
71
+ | `error` | `background-color: #dc143c; color: #fff; padding: 2px; border-radius: 3px` |
72
+
73
+ ## Verwendung 💡
74
+
75
+ ### Initialisierung
76
+
77
+ Einmalig am Einstiegspunkt der Anwendung aufrufen (`main.js` / `app.js`):
78
+
79
+ ```javascript
80
+ import { debugInit } from 'debug-web';
81
+
82
+ debugInit({
83
+ level: isDev ? 'debug' : 'error',
84
+ data: { version: env.VERSION, buildTime: env.BUILD_TIMESTAMP }
85
+ });
86
+ ```
87
+
88
+ ### Protokollierung
89
+
90
+ Überall in der Anwendung verwenden, um Nachrichten auszugeben:
91
+
92
+ ```javascript
93
+ import { debug, log, info, success, warn, error } from 'debug-web';
94
+
95
+ debug('Debug-Nachricht');
96
+ log('Reguläre Nachricht');
97
+ info('Informationelle Nachricht');
98
+ success('Erfolg!');
99
+ warn('Warnung!');
100
+ error(new Error());
101
+ ```
102
+
103
+ ### Debug-Daten
104
+
105
+ Debug-Daten speichern, die über eine globale Variable zugänglich sind:
106
+
107
+ ```javascript
108
+ import { debugData } from 'debug-web';
109
+
110
+ debugData({ lastError: null, prevRoute: '/home', bus: ['ui:modal-opened'] });
111
+ ```
112
+ 💡 Tipp: Gib in DevTools `info` (oder einen anderen `prop`-Wert) ein, um alle gespeicherten Daten zu erhalten.
113
+
114
+ ## Stilanpassung 🖌️
115
+
116
+ ```javascript
117
+ import { debugSetStyle } from 'debug-web';
118
+
119
+ // Stil für bestimmtes Level ändern
120
+ debugSetStyle('info', 'color: purple; font-weight: bold;');
121
+
122
+ // Oder mehrere Level gleichzeitig ändern
123
+ debugSetStyle({ info: 'color: #9b59b6;', success: 'color: #27ae60;' });
124
+ ```
125
+
126
+ ## API 📚
127
+
128
+ ### Protokollierungsmethoden
129
+
130
+ Alle wichtigen `console`-Methoden werden unterstützt:
131
+
132
+ - `debug`, `log`, `info`, `warn`, `error`;
133
+ - `group` (`groupCollapsed`), `groupEnd`;
134
+ - `trace`, `count`, `countReset`;
135
+ - `time`, `timeLog`, `timeEnd`;
136
+ - `dir`, `dirxml`, `table`.
137
+
138
+ ### Hilfsmethoden
139
+
140
+ - `debugData` — Hinzufügen von Debug-Daten (mit vorhandenen zusammengeführt);
141
+ - `debugSetStyle` — Ändern von CSS-Stilen für Log-Level;
142
+ - `debugGetStyle` — Abrufen aktueller Stileinstellungen;
143
+ - `debugReset`.
144
+
145
+ ## Erweiterung der Funktionalität
146
+
147
+ Sie können eine eigene Klasse erstellen, um benutzerdefinierte Protokollierungsmethoden hinzuzufügen:
148
+
149
+ ```ts
150
+ export class CustomDebug extends WebDebug {
151
+ static {
152
+ // Neuen Stil für benutzerdefiniertes Level hinzufügen
153
+ CustomDebug.setStyle({ ...WebDebug._style, 'customEvent': 'color: #00ff00' });
154
+ }
155
+
156
+ // Neue Protokollierungsmethode erstellen
157
+ static customEvent(...attrs: unknown[]) {
158
+ // Prüfen, ob 'info'-Level (dem benutzerdefinierte Level gleichgesetzt werden) erlaubt ist
159
+ if (!CustomDebug.can('info')) return;
160
+
161
+ // Interne Methode für Formatierung und Ausgabe verwenden
162
+ CustomDebug.print('info', 'customEvent', attrs);
163
+ }
164
+ }
165
+ ```
166
+
167
+ ## Unterstützung
168
+
169
+ Wenn Sie diese Bibliothek nützlich finden, erwägen Sie eine Unterstützung der Entwicklung:
170
+
171
+ - [Patreon](https://www.patreon.com/collection/1924882)
172
+ - [Boosty](https://boosty.to/karlen/donate)
173
+
174
+ ## Lizenz
175
+
176
+ MIT © [Karlen Pireverdiev](https://github.com/Karlen-ll)
177
+
178
+ ## Links
179
+ - [📝 Änderungsprotokoll](CHANGELOG.md)
180
+ - [💻 Quellcode](https://github.com/Karlen-ll/debug-web)
181
+ - [🐛 Fehlermeldungen](https://github.com/Karlen-ll/debug-web/issues)
182
+ - [📦 NPM-Paket](https://www.npmjs.com/package/debug-web)
package/README.es.md ADDED
@@ -0,0 +1,183 @@
1
+ # Debug Web
2
+ Librería ligera para depuración en el navegador.
3
+
4
+ **Ventajas**:
5
+ - 🚀 **Sin dependencias** — solo TypeScript puro;
6
+ - 📦 **Peso ~3.0 kB** — impacto mínimo en el bundle;
7
+ - 🎨 **Estilización de salida de consola** — formato coloreado para identificación rápida;
8
+ - 💾 **Almacenamiento global** — accede a datos de depuración mediante `window`.
9
+
10
+ ---
11
+
12
+ ## Tabla de Contenidos 📑
13
+
14
+ - [Instalación](#instalación-)
15
+ - [Niveles de Registro](#niveles-de-registro-)
16
+ - [Opciones](#opciones-)
17
+ - [Estilos por Defecto](#estilos-por-defecto-)
18
+ - [Cómo Usar](#cómo-usar-)
19
+ - [Personalización de Estilos](#personalización-de-estilos-)
20
+ - [API](#api-)
21
+ - [Extensión de Funcionalidad](#extensión-de-funcionalidad)
22
+
23
+ ## Otras Traducciones
24
+
25
+ [English](README.md), [Español](README.es.md), [Deutsch](README.de.md), [中文](README.zh.md), [Русский](README.ru.md)
26
+
27
+ ---
28
+
29
+ ## Instalación 📦
30
+
31
+ ```bash
32
+ npm install debug-web
33
+ ```
34
+ ```bash
35
+ yarn add debug-web
36
+ ```
37
+
38
+ ## Niveles de Registro 🔧
39
+
40
+ Prioridad (de menor a mayor):
41
+
42
+ 1. `debug` (0) — información de depuración (`console.debug`);
43
+ 2. `log` (1) — mensajes básicos (`console.log`)
44
+ 3. `info` (2) — mensajes informativos (`console.info`)
45
+ 4. `warn` (3) — advertencias (`console.warn`)
46
+ 5. `error` (4) — errores (`console.error`)
47
+
48
+ ℹ️ Niveles personalizados: cualquier valor de cadena (incluyendo `success`) se tratará como nivel `info`.
49
+
50
+ ## Opciones ⚙️
51
+
52
+ | Parámetro | Tipo | Por Defecto | Descripción |
53
+ |-----------|---------------------------------|------------------------------------|---------------------------------------------------------------------------|
54
+ | `app` | `string` \| `null` | `'__web_debug__'` | Nombre único de la app para separar datos de diferentes aplicaciones |
55
+ | `level` | `DebugLogLevel` | `'log'` | Nivel mínimo de registro (mensajes por debajo no se imprimen) |
56
+ | `prop` | `string` \| `null` | `'info'` | Nombre de la variable global para acceder a datos mediante `window[prop]` |
57
+ | `data` | `Record<string, unknown>` | — | Datos de depuración iniciales guardados tras la inicialización |
58
+ | `style` | `Record<DebugLogLevel, string>` | ver [abajo](#estilos-por-defecto-) | Estilos CSS personalizados para mensajes de diferentes niveles |
59
+
60
+ ```typescript
61
+ type DebugLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
62
+ ```
63
+
64
+ ### Estilos por Defecto 🎨
65
+
66
+ | Nivel | Estilo (CSS) |
67
+ |-----------|----------------------------------------------------------------------------|
68
+ | `info` | `background-color: #155adc; color: #fff; padding: 2px; border-radius: 3px` |
69
+ | `success` | `background-color: #13a10e; color: #fff; padding: 2px; border-radius: 3px` |
70
+ | `warn` | `background-color: #ffa500; color: #fff; padding: 2px; border-radius: 3px` |
71
+ | `error` | `background-color: #dc143c; color: #fff; padding: 2px; border-radius: 3px` |
72
+
73
+ ## Cómo Usar 💡
74
+
75
+ ### Inicialización
76
+
77
+ Se llama una vez en el punto de entrada de la aplicación (`main.js` / `app.js`):
78
+
79
+ ```javascript
80
+ import { debugInit } from 'debug-web';
81
+
82
+ debugInit({
83
+ level: isDev ? 'debug' : 'error',
84
+ data: { version: env.VERSION, buildTime: env.BUILD_TIMESTAMP }
85
+ });
86
+ ```
87
+
88
+ ### Registro
89
+
90
+ Usa en cualquier parte de la aplicación para mostrar mensajes:
91
+
92
+ ```javascript
93
+ import { debug, log, info, success, warn, error } from 'debug-web';
94
+
95
+ debug('Mensaje de depuración');
96
+ log('Mensaje regular');
97
+ info('Mensaje informativo');
98
+ success('¡Éxito!');
99
+ warn('¡Advertencia!');
100
+ error(new Error());
101
+ ```
102
+
103
+ ### Datos de Depuración
104
+
105
+ Guarda datos de depuración que serán accesibles mediante una variable global:
106
+
107
+ ```javascript
108
+ import { debugData } from 'debug-web';
109
+
110
+ debugData({ lastError: null, prevRoute: '/home', bus: ['ui:modal-opened'] });
111
+ ```
112
+
113
+ 💡 Consejo: En DevTools, escribe `info` (u otro valor de `prop`) para obtener todos los datos guardados.
114
+
115
+ ## Personalización de Estilos 🖌️
116
+
117
+ ```javascript
118
+ import { debugSetStyle } from 'debug-web';
119
+
120
+ // Cambiar estilo para un nivel específico
121
+ debugSetStyle('info', 'color: purple; font-weight: bold;');
122
+
123
+ // O cambiar varios niveles a la vez
124
+ debugSetStyle({ info: 'color: #9b59b6;', success: 'color: #27ae60;' });
125
+ ```
126
+
127
+ ## API 📚
128
+
129
+ ### Métodos de Registro
130
+
131
+ Se soportan todos los métodos principales de `console`:
132
+
133
+ - `debug`, `log`, `info`, `warn`, `error`;
134
+ - `group` (`groupCollapsed`), `groupEnd`;
135
+ - `trace`, `count`, `countReset`;
136
+ - `time`, `timeLog`, `timeEnd`;
137
+ - `dir`, `dirxml`, `table`.
138
+
139
+ ### Métodos Auxiliares
140
+
141
+ - `debugData` — Agregar datos de depuración (se fusiona con los existentes);
142
+ - `debugSetStyle` — Cambiar estilos CSS para niveles de registro;
143
+ - `debugGetStyle` — Obtener configuración actual de estilos;
144
+ - `debugReset`.
145
+
146
+ ## Extensión de Funcionalidad
147
+
148
+ Puedes crear tu propia clase para agregar métodos de registro personalizados:
149
+
150
+ ```ts
151
+ export class CustomDebug extends WebDebug {
152
+ static {
153
+ // Agregar nuevo estilo para nivel personalizado
154
+ CustomDebug.setStyle({ ...WebDebug._style, 'customEvent': 'color: #00ff00' });
155
+ }
156
+
157
+ // Crear un nuevo método de registro
158
+ static customEvent(...attrs: unknown[]) {
159
+ // Verificar si el nivel 'info' (al que se equiparan niveles personalizados) está permitido
160
+ if (!CustomDebug.can('info')) return;
161
+
162
+ // Usar método interno para formatear y mostrar
163
+ CustomDebug.print('info', 'customEvent', attrs);
164
+ }
165
+ }
166
+ ```
167
+
168
+ ## Apoyo
169
+
170
+ Si encuentras útil esta librería, considera apoyar su desarrollo:
171
+
172
+ - [Patreon](https://www.patreon.com/collection/1924882)
173
+ - [Boosty](https://boosty.to/karlen/donate)
174
+
175
+ ## Licencia
176
+
177
+ MIT © [Karlen Pireverdiev](https://github.com/Karlen-ll)
178
+
179
+ ## Enlaces
180
+ - [📝 Historial de Cambios](CHANGELOG.md)
181
+ - [💻 Código Fuente](https://github.com/Karlen-ll/debug-web)
182
+ - [🐛 Reportar Errores](https://github.com/Karlen-ll/debug-web/issues)
183
+ - [📦 Paquete NPM](https://www.npmjs.com/package/debug-web)
package/README.md ADDED
@@ -0,0 +1,183 @@
1
+ # Debug Web
2
+ Lightweight browser debugging library.
3
+
4
+ **Advantages**:
5
+ - 🚀 **No dependencies** — pure TypeScript only;
6
+ - 📦 **Size ~3.0 kB** — minimal bundle impact;
7
+ - 🎨 **Console output styling** — colored formatting for quick identification;
8
+ - 💾 **Global storage** — access debug data via `window`.
9
+
10
+ ---
11
+
12
+ ## Table of Contents 📑
13
+
14
+ - [Installation](#installation-)
15
+ - [Log Levels](#log-levels-)
16
+ - [Options](#options-)
17
+ - [Default Styles](#default-styles-)
18
+ - [How to Use](#how-to-use-)
19
+ - [Style Customization](#style-customization-)
20
+ - [API](#api-)
21
+ - [Extending Functionality](#extending-functionality)
22
+
23
+ ## Other Language Versions
24
+
25
+ [English](README.md), [Español](README.es.md), [Deutsch](README.de.md), [中文](README.zh.md), [Русский](README.ru.md)
26
+
27
+ ---
28
+
29
+ ## Installation 📦
30
+
31
+ ```bash
32
+ npm install debug-web
33
+ ```
34
+ ```bash
35
+ yarn add debug-web
36
+ ```
37
+
38
+ ## Log Levels 🔧
39
+
40
+ Priority (lowest to highest):
41
+
42
+ 1. `debug` (0) — debug information (`console.debug`);
43
+ 2. `log` (1) — basic messages (`console.log`)
44
+ 3. `info` (2) — informational messages (`console.info`)
45
+ 4. `warn` (3) — warnings (`console.warn`)
46
+ 5. `error` (4) — errors (`console.error`)
47
+
48
+ ℹ️ Custom levels: any string values (including `success`) will be treated as `info` level.
49
+
50
+ ## Options ⚙️
51
+
52
+ | Parameter | Type | Default | Description |
53
+ |-----------|---------------------------------|-------------------------------|---------------------------------------------------------------|
54
+ | `app` | `string` \| `null` | `'__web_debug__'` | Unique app name to separate data from different applications |
55
+ | `level` | `DebugLogLevel` | `'log'` | Minimum log level (messages below this level are not printed) |
56
+ | `prop` | `string` \| `null` | `'info'` | Name of global variable to access data via `window[prop]` |
57
+ | `data` | `Record<string, unknown>` | — | Initial debug data saved immediately after initialization |
58
+ | `style` | `Record<DebugLogLevel, string>` | see [below](#default-styles-) | Custom CSS styles for messages of different levels |
59
+
60
+ ```typescript
61
+ type DebugLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
62
+ ```
63
+
64
+ ### Default Styles 🎨
65
+
66
+ | Level | Style (CSS) |
67
+ |-----------|----------------------------------------------------------------------------|
68
+ | `info` | `background-color: #155adc; color: #fff; padding: 2px; border-radius: 3px` |
69
+ | `success` | `background-color: #13a10e; color: #fff; padding: 2px; border-radius: 3px` |
70
+ | `warn` | `background-color: #ffa500; color: #fff; padding: 2px; border-radius: 3px` |
71
+ | `error` | `background-color: #dc143c; color: #fff; padding: 2px; border-radius: 3px` |
72
+
73
+ ## How to Use 💡
74
+
75
+ ### Initialization
76
+
77
+ Called once at the application entry point (`main.js` / `app.js`):
78
+
79
+ ```javascript
80
+ import { debugInit } from 'debug-web';
81
+
82
+ debugInit({
83
+ level: isDev ? 'debug' : 'error',
84
+ data: { version: env.VERSION, buildTime: env.BUILD_TIMESTAMP }
85
+ });
86
+ ```
87
+
88
+ ### Logging
89
+
90
+ Use anywhere in the application to output messages:
91
+
92
+ ```javascript
93
+ import { debug, log, info, success, warn, error } from 'debug-web';
94
+
95
+ debug('Debug message');
96
+ log('Regular message');
97
+ info('Informational message');
98
+ success('Success!');
99
+ warn('Warning!');
100
+ error(new Error());
101
+ ```
102
+
103
+ ### Debug Data
104
+
105
+ Save debug data that will be accessible via a global variable:
106
+
107
+ ```javascript
108
+ import { debugData } from 'debug-web';
109
+
110
+ debugData({ lastError: null, prevRoute: '/home', bus: ['ui:modal-opened'] });
111
+ ```
112
+
113
+ 💡 Tip: In DevTools, type `info` (or another `prop` value) to get all saved data.
114
+
115
+ ## Style Customization 🖌️
116
+
117
+ ```javascript
118
+ import { debugSetStyle } from 'debug-web';
119
+
120
+ // Change style for a specific level
121
+ debugSetStyle('info', 'color: purple; font-weight: bold;');
122
+
123
+ // Or change multiple levels at once
124
+ debugSetStyle({ info: 'color: #9b59b6;', success: 'color: #27ae60;' });
125
+ ```
126
+
127
+ ## API 📚
128
+
129
+ ### Logging Methods
130
+
131
+ All major `console` methods are supported:
132
+
133
+ - `debug`, `log`, `info`, `warn`, `error`;
134
+ - `group` (`groupCollapsed`), `groupEnd`;
135
+ - `trace`, `count`, `countReset`;
136
+ - `time`, `timeLog`, `timeEnd`;
137
+ - `dir`, `dirxml`, `table`.
138
+
139
+ ### Helper Methods
140
+
141
+ - `debugData` — Adding debug data (merged with existing);
142
+ - `debugSetStyle` — Changing CSS styles for log levels;
143
+ - `debugGetStyle` — Getting current style settings;
144
+ - `debugReset`.
145
+
146
+ ## Extending Functionality
147
+
148
+ You can create your own class to add custom logging methods:
149
+
150
+ ```ts
151
+ export class CustomDebug extends WebDebug {
152
+ static {
153
+ // Add new style for custom level
154
+ CustomDebug.setStyle({ ...WebDebug._style, 'customEvent': 'color: #00ff00' });
155
+ }
156
+
157
+ // Create a new logging method
158
+ static customEvent(...attrs: unknown[]) {
159
+ // Check if 'info' level (to which custom levels are equated) is allowed
160
+ if (!CustomDebug.can('info')) return;
161
+
162
+ // Use internal method for formatting and output
163
+ CustomDebug.print('info', 'customEvent', attrs);
164
+ }
165
+ }
166
+ ```
167
+
168
+ ## Support
169
+
170
+ If you find this library useful, consider supporting its development:
171
+
172
+ - [Patreon](https://www.patreon.com/collection/1924882)
173
+ - [Boosty](https://boosty.to/karlen/donate)
174
+
175
+ ## License
176
+
177
+ MIT © [Karlen Pireverdiev](https://github.com/Karlen-ll)
178
+
179
+ ## Ссылки
180
+ - [📝 Changelog](CHANGELOG.md)
181
+ - [💻 Source Code](https://github.com/Karlen-ll/debug-web)
182
+ - [🐛 Bug Reports](https://github.com/Karlen-ll/debug-web/issues)
183
+ - [📦 NPM Package](https://www.npmjs.com/package/debug-web)
package/README.ru.md ADDED
@@ -0,0 +1,183 @@
1
+ # Debug Web
2
+ Легковесная библиотека для отладки в браузере.
3
+
4
+ **Преимущества**:
5
+ - 🚀 **Нет зависимостей** — только чистый TypeScript;
6
+ - 📦 **Вес ~3.0 kB** — минимальное влияние на бандл;
7
+ - 🎨 **Стилизация console-выводов** — цветное форматирование для быстрой идентификации;
8
+ - 💾 **Глобальное хранилище** — доступ к отладочным данным через `window`.
9
+
10
+ ---
11
+
12
+ ## Оглавление 📑
13
+
14
+ - [Установка](#установка-)
15
+ - [Уровни логирования](#уровни-логирования-)
16
+ - [Опции](#опции-)
17
+ - [Стили по умолчанию](#стили-по-умолчанию-)
18
+ - [Как использовать](#как-использовать-)
19
+ - [Кастомизация стилей](#кастомизация-стилей-)
20
+ - [API](#api-)
21
+ - [Расширение функциональности](#расширение-функциональности)
22
+
23
+ ## Другие языковые версии
24
+
25
+ [English](README.md), [Español](README.es.md), [Deutsch](README.de.md), [中文](README.zh.md), [Русский](README.ru.md)
26
+
27
+ ---
28
+
29
+ ## Установка 📦
30
+
31
+ ```bash
32
+ npm install debug-web
33
+ ```
34
+ ```bash
35
+ yarn add debug-web
36
+ ```
37
+
38
+ ## Уровни логирования 🔧
39
+
40
+ Приоритет (от низкого к высокому):
41
+
42
+ 1. `debug` (0) — отладочная информация (`console.debug`);
43
+ 2. `log` (1) — базовые сообщения (`console.log`)
44
+ 3. `info` (2) — информационные сообщения (`console.info`)
45
+ 4. `warn` (3) — предупреждения (`console.warn`)
46
+ 5. `error` (4) — ошибки (`console.error`)
47
+
48
+ ℹ️ Кастомные уровни: любые строковые значения (включая `success`) будут обработаны как уровень `info`.
49
+
50
+ ## Опции ⚙️
51
+
52
+ | Параметр | Тип | По умолчанию | Описание |
53
+ |----------|---------------------------------|----------------------------------|----------------------------------------------------------------------------|
54
+ | `app` | `string` \| `null` | `'__web_debug__'` | Уникальное имя приложения для разделения данных разных приложений |
55
+ | `level` | `DebugLogLevel` | `'log'` | Минимальный уровень логирования (сообщения ниже этого уровня не выводятся) |
56
+ | `prop` | `string` \| `null` | `'info'` | Имя глобальной переменной для доступа к данным через `window[prop]` |
57
+ | `data` | `Record<string, unknown>` | — | Начальные отладочные данные, сохраняемые сразу после инициализации |
58
+ | `style` | `Record<DebugLogLevel, string>` | см. [ниже](#стили-по-умолчанию-) | Кастомизация CSS-стилей для сообщений разных уровней |
59
+
60
+ ```typescript
61
+ type DebugLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
62
+ ```
63
+
64
+ ### Стили по умолчанию 🎨
65
+
66
+ | Уровень | Стиль (CSS) |
67
+ |-----------|----------------------------------------------------------------------------|
68
+ | `info` | `background-color: #155adc; color: #fff; padding: 2px; border-radius: 3px` |
69
+ | `success` | `background-color: #13a10e; color: #fff; padding: 2px; border-radius: 3px` |
70
+ | `warn` | `background-color: #ffa500; color: #fff; padding: 2px; border-radius: 3px` |
71
+ | `error` | `background-color: #dc143c; color: #fff; padding: 2px; border-radius: 3px` |
72
+
73
+ ## Как использовать 💡
74
+
75
+ ### Инициализация
76
+
77
+ Вызывается один раз в точке входа приложения (`main.js` / `app.js`):
78
+
79
+ ```javascript
80
+ import { debugInit } from 'debug-web';
81
+
82
+ debugInit({
83
+ level: isDev ? 'debug' : 'error',
84
+ data: { version: env.VERSION, buildTime: env.BUILD_TIMESTAMP }
85
+ });
86
+ ```
87
+
88
+ ### Логирование
89
+
90
+ Используйте в любом месте приложения для вывода сообщений:
91
+
92
+ ```javascript
93
+ import { debug, log, info, success, warn, error } from 'debug-web';
94
+
95
+ debug('Отладочное сообщение');
96
+ log('Обычное сообщение');
97
+ info('Информационное сообщение');
98
+ success('Успешно!');
99
+ warn('Внимание!');
100
+ error(new Error());
101
+ ```
102
+
103
+ ### Отладочные данные
104
+
105
+ Сохраняйте данные для отладки, которые будут доступны через глобальную переменную:
106
+
107
+ ```javascript
108
+ import { debugData } from 'debug-web';
109
+
110
+ debugData({ lastError: null, prevRoute: '/home', bus: ['ui:modal-opened'] });
111
+ ```
112
+
113
+ 💡 Совет: В DevTools введите `info` (или другое значение `prop`) чтобы получить все сохранённые данные.
114
+
115
+ ## Кастомизация стилей 🖌️
116
+
117
+ ```javascript
118
+ import { debugSetStyle } from 'debug-web';
119
+
120
+ // Изменить стиль для конкретного уровня
121
+ debugSetStyle('info', 'color: purple; font-weight: bold;');
122
+
123
+ // Или изменить несколько уровней сразу
124
+ debugSetStyle({ info: 'color: #9b59b6;', success: 'color: #27ae60;' });
125
+ ```
126
+
127
+ ## API 📚
128
+
129
+ ### Методы логирования
130
+
131
+ Поддерживаются все основные методы `console`:
132
+
133
+ - `debug`, `log`, `info`, `warn`, `error`;
134
+ - `group` (`groupCollapsed`), `groupEnd`;
135
+ - `trace`, `count`, `countReset`;
136
+ - `time`, `timeLog`, `timeEnd`;
137
+ - `dir`, `dirxml`, `table`.
138
+
139
+ ### Вспомогательные методы
140
+
141
+ - `debugData` — Добавление отладочных данных (объединяется с существующими);
142
+ - `debugSetStyle` — Изменение CSS-стилей для уровней логирования;
143
+ - `debugGetStyle` — Получение текущих настроек стилей;
144
+ - `debugReset`.
145
+
146
+ ## Расширение функциональности
147
+
148
+ Вы можете создать собственный класс для добавления кастомных методов логирования:
149
+
150
+ ```ts
151
+ export class CustomDebug extends WebDebug {
152
+ static {
153
+ // Добавляем новый стиль для кастомного уровня
154
+ CustomDebug.setStyle({ ...WebDebug._style, 'customEvent': 'color: #00ff00' });
155
+ }
156
+
157
+ // Создаём новый метод логирования
158
+ static customEvent(...attrs: unknown[]) {
159
+ // Проверяем, разрешён ли уровень 'info' (к которому приравниваются кастомные уровни)
160
+ if (!CustomDebug.can('info')) return;
161
+
162
+ // Используем внутренний метод для форматирования и вывода
163
+ CustomDebug.print('info', 'customEvent', attrs);
164
+ }
165
+ }
166
+ ```
167
+
168
+ ## Поддержка
169
+
170
+ Если эта библиотека полезна для вас, рассмотрите возможность поддержать её разработку:
171
+
172
+ - [Patreon](https://www.patreon.com/collection/1924882)
173
+ - [Boosty](https://boosty.to/karlen/donate)
174
+
175
+ ## Лицензия
176
+
177
+ MIT © [Karlen Pireverdiev](https://github.com/Karlen-ll)
178
+
179
+ ## Ссылки
180
+ - [📝 История изменений](CHANGELOG.md)
181
+ - [💻 Исходный код](https://github.com/Karlen-ll/debug-web)
182
+ - [🐛 Отчеты об ошибках](https://github.com/Karlen-ll/debug-web/issues)
183
+ - [📦 NPM пакет](https://www.npmjs.com/package/debug-web)
package/README.zh.md ADDED
@@ -0,0 +1,183 @@
1
+ # Debug Web
2
+ 轻量级浏览器调试库。
3
+
4
+ **优点**:
5
+ - 🚀 **无依赖** — 仅使用纯 TypeScript;
6
+ - 📦 **大小约 3.0 kB** — 对打包体积影响极小;
7
+ - 🎨 **控制台输出样式** — 彩色格式化,便于快速识别;
8
+ - 💾 **全局存储** — 通过 `window` 访问调试数据。
9
+
10
+ ---
11
+
12
+ ## 目录 📑
13
+
14
+ - [安装](#安装-)
15
+ - [日志级别](#日志级别-)
16
+ - [选项](#选项-)
17
+ - [默认样式](#默认样式-)
18
+ - [使用方法](#使用方法-)
19
+ - [样式自定义](#样式自定义-)
20
+ - [API](#api-)
21
+ - [扩展功能](#扩展功能)
22
+
23
+ ## 其他语言版本
24
+
25
+ [English](README.md), [Español](README.es.md), [Deutsch](README.de.md), [中文](README.zh.md), [Русский](README.ru.md)
26
+
27
+ ---
28
+
29
+ ## 安装 📦
30
+
31
+ ```bash
32
+ npm install debug-web
33
+ ```
34
+ ```bash
35
+ yarn add debug-web
36
+ ```
37
+
38
+ ## 日志级别 🔧
39
+
40
+ 优先级(从低到高):
41
+
42
+ 1. `debug` (0) — 调试信息 (`console.debug`);
43
+ 2. `log` (1) — 基本消息 (`console.log`)
44
+ 3. `info` (2) — 信息性消息 (`console.info`)
45
+ 4. `warn` (3) — 警告 (`console.warn`)
46
+ 5. `error` (4) — 错误 (`console.error`)
47
+
48
+ ℹ️ 自定义级别: 任何字符串值(包括 `success`)都将被视为 `info` 级别。
49
+
50
+ ## 选项 ⚙️
51
+
52
+ | 参数 | 类型 | 默认值 | 描述 |
53
+ |---------|---------------------------------|-------------------|-----------------------------------------|
54
+ | `app` | `string` \| `null` | `'__web_debug__'` | 用于区分不同应用数据的唯一应用名称 |
55
+ | `level` | `DebugLogLevel` | `'log'` | 最低日志级别(低于此级别的消息不会打印) |
56
+ | `prop` | `string` \| `null` | `'info'` | 用于通过 `window[prop]` 访问数据的全局变量名 |
57
+ | `data` | `Record<string, unknown>` | — | 初始化后立即保存的初始调试数据 |
58
+ | `style` | `Record<DebugLogLevel, string>` | 参见 [下方](#默认样式-) | 为不同级别的消息自定义 CSS 样式 |
59
+
60
+ ```typescript
61
+ type DebugLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
62
+ ```
63
+
64
+ ### 默认样式 🎨
65
+
66
+ | 级别 | 样式 (CSS) |
67
+ |-----------|----------------------------------------------------------------------------|
68
+ | `info` | `background-color: #155adc; color: #fff; padding: 2px; border-radius: 3px` |
69
+ | `success` | `background-color: #13a10e; color: #fff; padding: 2px; border-radius: 3px` |
70
+ | `warn` | `background-color: #ffa500; color: #fff; padding: 2px; border-radius: 3px` |
71
+ | `error` | `background-color: #dc143c; color: #fff; padding: 2px; border-radius: 3px` |
72
+
73
+ ## 使用方法 💡
74
+
75
+ ### 初始化
76
+
77
+ 在应用程序入口点(`main.js` / `app.js`)调用一次:
78
+
79
+ ```javascript
80
+ import { debugInit } from 'debug-web';
81
+
82
+ debugInit({
83
+ level: isDev ? 'debug' : 'error',
84
+ data: { version: env.VERSION, buildTime: env.BUILD_TIMESTAMP }
85
+ });
86
+ ```
87
+
88
+ ### 日志记录
89
+
90
+ 在应用程序的任何位置使用以输出消息:
91
+
92
+ ```javascript
93
+ import { debug, log, info, success, warn, error } from 'debug-web';
94
+
95
+ debug('调试消息');
96
+ log('常规消息');
97
+ info('信息性消息');
98
+ success('成功!');
99
+ warn('警告!');
100
+ error(new Error());
101
+ ```
102
+
103
+ ### 调试数据
104
+
105
+ 保存调试数据,可通过全局变量访问:
106
+
107
+ ```javascript
108
+ import { debugData } from 'debug-web';
109
+
110
+ debugData({ lastError: null, prevRoute: '/home', bus: ['ui:modal-opened'] });
111
+ ```
112
+
113
+ 💡 提示: 在 DevTools 中输入 `info`(或其他 `prop` 值)以获取所有保存的数据。
114
+
115
+ ## 样式自定义 🖌️
116
+
117
+ ```javascript
118
+ import { debugSetStyle } from 'debug-web';
119
+
120
+ // 更改特定级别的样式
121
+ debugSetStyle('info', 'color: purple; font-weight: bold;');
122
+
123
+ // 或同时更改多个级别
124
+ debugSetStyle({ info: 'color: #9b59b6;', success: 'color: #27ae60;' });
125
+ ```
126
+
127
+ ## API 📚
128
+
129
+ ### 日志方法
130
+
131
+ 支持所有主要的 `console` 方法:
132
+
133
+ - `debug`, `log`, `info`, `warn`, `error`;
134
+ - `group` (`groupCollapsed`), `groupEnd`;
135
+ - `trace`, `count`, `countReset`;
136
+ - `time`, `timeLog`, `timeEnd`;
137
+ - `dir`, `dirxml`, `table`.
138
+
139
+ ### 辅助方法
140
+
141
+ - `debugData` — 添加调试数据(与现有数据合并);
142
+ - `debugSetStyle` — 更改日志级别的 CSS 样式;
143
+ - `debugGetStyle` — 获取当前样式设置;
144
+ - `debugReset`.
145
+
146
+ ## 扩展功能
147
+
148
+ 您可以创建自己的类以添加自定义日志方法:
149
+
150
+ ```ts
151
+ export class CustomDebug extends WebDebug {
152
+ static {
153
+ // 为自定义级别添加新样式
154
+ CustomDebug.setStyle({ ...WebDebug._style, 'customEvent': 'color: #00ff00' });
155
+ }
156
+
157
+ // 创建新的日志方法
158
+ static customEvent(...attrs: unknown[]) {
159
+ // 检查是否允许 'info' 级别(自定义级别等同于该级别)
160
+ if (!CustomDebug.can('info')) return;
161
+
162
+ // 使用内部方法进行格式化和输出
163
+ CustomDebug.print('info', 'customEvent', attrs);
164
+ }
165
+ }
166
+ ```
167
+
168
+ ## 支持
169
+
170
+ 如果您觉得这个库有用,请考虑支持其开发:
171
+
172
+ - [Patreon](https://www.patreon.com/collection/1924882)
173
+ - [Boosty](https://boosty.to/karlen/donate)
174
+
175
+ ## 许可证
176
+
177
+ MIT © [Karlen Pireverdiev](https://github.com/Karlen-ll)
178
+
179
+ ## 链接
180
+ - [📝 更新日志](CHANGELOG.md)
181
+ - [💻 源代码](https://github.com/Karlen-ll/debug-web)
182
+ - [🐛 问题反馈](https://github.com/Karlen-ll/debug-web/issues)
183
+ - [📦 NPM 包](https://www.npmjs.com/package/debug-web)
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";const e=(e,t="#fff")=>`background-color: ${e}; color: ${t}; padding: 2px; border-radius: 3px;`,t={info:e("#155adc"),success:e("#13a10e"),warn:e("#ffa500"),error:e("#dc143c")},o=e=>void 0!==e,s=(e,t=!1)=>t?Symbol.for(e):e,r="__web_debug__",c="info";class n{static _level=0;static _app=r;static _prop=c;static _style=t;static _levelMap={debug:0,log:1,info:2,warn:3,error:4};constructor(){}static init(e){e&&(e.app?.trim()&&(n._app=e.app),o(e.level)&&(n._level=n.getLevel(e.level)),o(e.prop)&&(n._prop=e.prop),e.style&&n.setStyle(e.style),e.data&&n.set(e.data)),n.attach()}static attach(){n._prop&&o(window)&&Object.defineProperty(window,n._prop,{get:()=>n.get(),configurable:!0})}static log(...e){n.can()&&n.print("log","log",e)}static info(...e){n.can("info")&&n.print("info","info",e)}static success(...e){n.can("success")&&n.print("info","success",e)}static warn(...e){n.can("warn")&&console.warn(...e)}static error(e,...t){n.can("error")&&(e instanceof Error?n._level<4&&e.stack?console.error(e.message,e.stack,...t):console.error(e.message,...t):console.error(e,...t))}static debug(e,...t){n.can("debug")&&console.debug(e,...t)}static group(e,t="log",...o){n.can()&&n.print(e?"groupCollapsed":"group",t,o)}static groupEnd(){n.can()&&console.groupEnd()}static dir(e,t){n.can()&&console.dir(e,t)}static dirxml(...e){n.can()&&console.dirxml(...e)}static count(e){n.can()&&console.count(e)}static countReset(e){n.can()&&console.countReset(e)}static table(e,t){n.can("info")&&console.table(e,t)}static time(e){n.can("info")&&console.time(e)}static timeLog(e,...t){n.can("info")&&console.timeLog(e,...t)}static timeEnd(e){n.can("info")&&console.timeEnd(e)}static trace(e,...t){n.can()&&console.trace(e,...t)}static set(e){if(!o(window))return;const t=s(n._app,!0);Object.defineProperty(window,t,{value:Object.assign(window[t]||{},e),writable:!0,enumerable:!1,configurable:!0})}static get(){return o(window)?window[s(n._app,!0)]:void 0}static setStyle(e,t){"string"==typeof e?n._style[e]=t:Object.assign(n._style,e)}static getStyle(){return n._style}static reset(){o(window)&&(delete window[s(n._app,!0)],delete window[s(n._prop)]),n._level=0,n._app=r,n._prop=c}static can(e="log"){return n.getLevel(e)>=n._level}static getLevel(e){return n._levelMap[e]??2}static print(e,t,o){console[e](...((e,t)=>{return t&&e?.length?[...(o=e[0],s=t,[s.includes("background")?`%c ${o} `:`%c${o}`,s]),...e.slice(1)]:e;var o,s})(o,n._style[t]))}}const a=n.log,i=n.info,l=n.success,p=n.warn,d=n.error,g=n.debug,u=n.group,b=n.groupEnd,w=n.dir,x=n.dirxml,_=n.table,f=n.count,m=n.countReset,y=n.time,v=n.timeLog,E=n.timeEnd,S=n.trace,L=n.set,R=n.init,j=n.reset,k=n.getStyle,O=n.setStyle;exports.DebugWeb=n,exports.count=f,exports.countReset=m,exports.debug=g,exports.debugData=L,exports.debugGetStyle=k,exports.debugInit=R,exports.debugReset=j,exports.debugSetStyle=O,exports.dir=w,exports.dirxml=x,exports.error=d,exports.group=u,exports.groupEnd=b,exports.info=i,exports.log=a,exports.success=l,exports.table=_,exports.time=y,exports.timeEnd=E,exports.timeLog=v,exports.trace=S,exports.warn=p;
@@ -0,0 +1,143 @@
1
+ type ConsoleMethod = 'debug' | 'log' | 'info' | 'warn' | 'error' | 'group' | 'groupCollapsed';
2
+ type DebugWebLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
3
+ type DebugWebData = Record<string, unknown>;
4
+ type DebugWebStyle = Partial<Record<DebugWebLogLevel, string | null>>;
5
+ interface DebugWebOptions {
6
+ /** Unique application name
7
+ * @desc Required to separate data of different applications in the same environment */
8
+ app?: string | null;
9
+ /** Allowed logging level
10
+ * @desc Custom values will default to 'info' */
11
+ level?: DebugWebLogLevel;
12
+ /** Variable name in window (if null, do not create)
13
+ * @default 'info' */
14
+ prop?: string | null;
15
+ /** Important debugging data */
16
+ data?: DebugWebData;
17
+ /** Styles map for different logging levels */
18
+ style?: DebugWebStyle;
19
+ }
20
+ /**
21
+ * Class for centralized collection and output of debugging information
22
+ * @singleton
23
+ */
24
+ declare class DebugWeb {
25
+ protected static _level: number;
26
+ protected static _app: string;
27
+ protected static _prop: string | null;
28
+ protected static _style: DebugWebStyle;
29
+ protected static _levelMap: Partial<Record<DebugWebLogLevel, number>>;
30
+ protected constructor();
31
+ /**
32
+ * Creates a Debug instance
33
+ * @desc Called once at the application entry point
34
+ * @example WebDebug.init({ level: 'error' })
35
+ */
36
+ static init(options?: DebugWebOptions): void;
37
+ /** Create window.info property for data access */
38
+ static attach(): void;
39
+ /** Output message to Web console
40
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/log_static console.log} */
41
+ static log(...attrs: unknown[]): void;
42
+ /** Output informational message
43
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/info_static console.info} */
44
+ static info(...attrs: unknown[]): void;
45
+ /** Output success message
46
+ * @desc Uses the `console.info` */
47
+ static success(...attrs: unknown[]): void;
48
+ /** Output warning message
49
+ * @desc Method is not styled
50
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/warn_static console.warn} */
51
+ static warn(...attrs: unknown[]): void;
52
+ /** Output error message
53
+ * @desc Method is not styled
54
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/error_static console.error} */
55
+ static error(error: Error | string, ...attrs: unknown[]): void;
56
+ /** Output debug message with low priority
57
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/debug_static console.debug} */
58
+ static debug(message?: unknown, ...attrs: unknown[]): void;
59
+ /** Open a group (level: log)
60
+ * @desc level — only for styling, does not affect logging
61
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/group_static console.group} */
62
+ static group(collapsed?: boolean, level?: DebugWebLogLevel, ...attrs: unknown[]): void;
63
+ /** Close the group (level: log)
64
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/groupEnd_static console.groupEnd} */
65
+ static groupEnd(): void;
66
+ /** Output an object (level: log)
67
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/dir_static console.dir} */
68
+ static dir(value: unknown, options?: Parameters<typeof console.dir>[1]): void;
69
+ /** Output XML/HTML tree of elements (level: log)
70
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/dirxml_static console.dirxml} */
71
+ static dirxml(...attrs: unknown[]): void;
72
+ /** Log number of times called with given label (level: log)
73
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/count_static console.count} */
74
+ static count(label?: string): void;
75
+ /** Reset counter for the given label (level: log)
76
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/countReset_static console.countReset} */
77
+ static countReset(label?: string): void;
78
+ /** Output a table (level: info)
79
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/table_static console.table} */
80
+ static table(data: unknown, properties?: Parameters<typeof console.table>[1]): void;
81
+ /** Start timer for execution time measurement (level: info)
82
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/time_static console.time} */
83
+ static time(label?: string): void;
84
+ /** Output current timer value (level: info)
85
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/timeLog_static console.timeLog} */
86
+ static timeLog(label?: string, ...attrs: unknown[]): void;
87
+ /** Finish execution time measurement (level: info)
88
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd_static console.timeEnd} */
89
+ static timeEnd(label?: string): void;
90
+ /** Output stack trace (level: log)
91
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/trace_static console.trace} */
92
+ static trace(message?: unknown, ...attrs: unknown[]): void;
93
+ /**
94
+ * Update debugging data
95
+ * @desc Data is stored in the window object
96
+ * @example WebDebug.add({ mode })
97
+ */
98
+ static set(data: DebugWebData): void;
99
+ /** Get all collected debugging data */
100
+ static get(): any;
101
+ /**
102
+ * Update styles map by logging level or entirely
103
+ * @example WebDebug.setStyle('info', 'color: #155adc')
104
+ * @example WebDebug.setStyle({ info: 'color: #155adc', warn: 'color: #ffa500' })
105
+ */
106
+ static setStyle(levelOrMap: DebugWebLogLevel | DebugWebStyle, style?: string | null): void;
107
+ /** Get styles map by logging level */
108
+ static getStyle(): DebugWebStyle;
109
+ /** Clear all debugging data and remove global references */
110
+ static reset(): void;
111
+ /** Check if logging level is enabled */
112
+ protected static can(level?: DebugWebLogLevel): boolean;
113
+ /** Get logging level priority number */
114
+ protected static getLevel(level: DebugWebLogLevel): number;
115
+ /** Format and output data using specified console method and level styling */
116
+ protected static print(method: ConsoleMethod, level: DebugWebLogLevel, attrs: unknown[]): void;
117
+ }
118
+
119
+ declare const log: typeof DebugWeb.log;
120
+ declare const info: typeof DebugWeb.info;
121
+ declare const success: typeof DebugWeb.success;
122
+ declare const warn: typeof DebugWeb.warn;
123
+ declare const error: typeof DebugWeb.error;
124
+ declare const debug: typeof DebugWeb.debug;
125
+ declare const group: typeof DebugWeb.group;
126
+ declare const groupEnd: typeof DebugWeb.groupEnd;
127
+ declare const dir: typeof DebugWeb.dir;
128
+ declare const dirxml: typeof DebugWeb.dirxml;
129
+ declare const table: typeof DebugWeb.table;
130
+ declare const count: typeof DebugWeb.count;
131
+ declare const countReset: typeof DebugWeb.countReset;
132
+ declare const time: typeof DebugWeb.time;
133
+ declare const timeLog: typeof DebugWeb.timeLog;
134
+ declare const timeEnd: typeof DebugWeb.timeEnd;
135
+ declare const trace: typeof DebugWeb.trace;
136
+ declare const debugData: typeof DebugWeb.set;
137
+ declare const debugInit: typeof DebugWeb.init;
138
+ declare const debugReset: typeof DebugWeb.reset;
139
+ declare const debugGetStyle: typeof DebugWeb.getStyle;
140
+ declare const debugSetStyle: typeof DebugWeb.setStyle;
141
+
142
+ export { DebugWeb, count, countReset, debug, debugData, debugGetStyle, debugInit, debugReset, debugSetStyle, dir, dirxml, error, group, groupEnd, info, log, success, table, time, timeEnd, timeLog, trace, warn };
143
+ export type { DebugWebData, DebugWebLogLevel, DebugWebOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ const t=(t,e="#fff")=>`background-color: ${t}; color: ${e}; padding: 2px; border-radius: 3px;`,e={info:t("#155adc"),success:t("#13a10e"),warn:t("#ffa500"),error:t("#dc143c")},o=t=>void 0!==t,c=(t,e=!1)=>e?Symbol.for(t):t,n="__web_debug__",s="info";class a{static _level=0;static _app=n;static _prop=s;static _style=e;static _levelMap={debug:0,log:1,info:2,warn:3,error:4};constructor(){}static init(t){t&&(t.app?.trim()&&(a._app=t.app),o(t.level)&&(a._level=a.getLevel(t.level)),o(t.prop)&&(a._prop=t.prop),t.style&&a.setStyle(t.style),t.data&&a.set(t.data)),a.attach()}static attach(){a._prop&&o(window)&&Object.defineProperty(window,a._prop,{get:()=>a.get(),configurable:!0})}static log(...t){a.can()&&a.print("log","log",t)}static info(...t){a.can("info")&&a.print("info","info",t)}static success(...t){a.can("success")&&a.print("info","success",t)}static warn(...t){a.can("warn")&&console.warn(...t)}static error(t,...e){a.can("error")&&(t instanceof Error?a._level<4&&t.stack?console.error(t.message,t.stack,...e):console.error(t.message,...e):console.error(t,...e))}static debug(t,...e){a.can("debug")&&console.debug(t,...e)}static group(t,e="log",...o){a.can()&&a.print(t?"groupCollapsed":"group",e,o)}static groupEnd(){a.can()&&console.groupEnd()}static dir(t,e){a.can()&&console.dir(t,e)}static dirxml(...t){a.can()&&console.dirxml(...t)}static count(t){a.can()&&console.count(t)}static countReset(t){a.can()&&console.countReset(t)}static table(t,e){a.can("info")&&console.table(t,e)}static time(t){a.can("info")&&console.time(t)}static timeLog(t,...e){a.can("info")&&console.timeLog(t,...e)}static timeEnd(t){a.can("info")&&console.timeEnd(t)}static trace(t,...e){a.can()&&console.trace(t,...e)}static set(t){if(!o(window))return;const e=c(a._app,!0);Object.defineProperty(window,e,{value:Object.assign(window[e]||{},t),writable:!0,enumerable:!1,configurable:!0})}static get(){return o(window)?window[c(a._app,!0)]:void 0}static setStyle(t,e){"string"==typeof t?a._style[t]=e:Object.assign(a._style,t)}static getStyle(){return a._style}static reset(){o(window)&&(delete window[c(a._app,!0)],delete window[c(a._prop)]),a._level=0,a._app=n,a._prop=s}static can(t="log"){return a.getLevel(t)>=a._level}static getLevel(t){return a._levelMap[t]??2}static print(t,e,o){console[t](...((t,e)=>{return e&&t?.length?[...(o=t[0],c=e,[c.includes("background")?`%c ${o} `:`%c${o}`,c]),...t.slice(1)]:t;var o,c})(o,a._style[e]))}}const r=a.log,i=a.info,l=a.success,p=a.warn,d=a.error,g=a.debug,u=a.group,_=a.groupEnd,w=a.dir,f=a.dirxml,b=a.table,m=a.count,v=a.countReset,y=a.time,E=a.timeLog,x=a.timeEnd,L=a.trace,S=a.set,j=a.init,k=a.reset,O=a.getStyle,$=a.setStyle;export{a as DebugWeb,m as count,v as countReset,g as debug,S as debugData,O as debugGetStyle,j as debugInit,k as debugReset,$ as debugSetStyle,w as dir,f as dirxml,d as error,u as group,_ as groupEnd,i as info,r as log,l as success,b as table,y as time,x as timeEnd,E as timeLog,L as trace,p as warn};
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "debug-web",
3
+ "version": "1.0.1",
4
+ "description": "Browser debug utility",
5
+ "keywords": [
6
+ "browser",
7
+ "debug",
8
+ "web",
9
+ "log"
10
+ ],
11
+ "type": "module",
12
+ "main": "./dist/index.cjs",
13
+ "module": "./dist/index.mjs",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.mjs",
18
+ "require": "./dist/index.cjs"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "README.es.md",
25
+ "README.de.md",
26
+ "README.zh.md",
27
+ "README.ru.md",
28
+ "CHANGELOG.md",
29
+ "LICENSE"
30
+ ],
31
+ "scripts": {
32
+ "build": "rollup -c --configPlugin @rollup/plugin-typescript",
33
+ "build:pack": "npm run build && npm pack",
34
+ "lint": "eslint src",
35
+ "lint:fix": "eslint src --fix",
36
+ "test": "vitest run",
37
+ "test:watch": "vitest --watch",
38
+ "test:coverage": "vitest run --coverage"
39
+ },
40
+ "devDependencies": {
41
+ "@eslint/js": "^9.39.2",
42
+ "@rollup/plugin-terser": "^0.4.4",
43
+ "@rollup/plugin-typescript": "^11.0.0",
44
+ "@types/node": "^20.19.27",
45
+ "@vitest/coverage-istanbul": "^4.0.15",
46
+ "eslint": "^9.39.2",
47
+ "globals": "^16.5.0",
48
+ "happy-dom": "^20.0.11",
49
+ "jiti": "^2.6.1",
50
+ "rollup": "^3.0.0",
51
+ "rollup-plugin-dts": "6.3.0",
52
+ "ts-node": "^10.9.1",
53
+ "tslib": "^2.8.1",
54
+ "typescript": "^5.0.0",
55
+ "typescript-eslint": "^8.49.0",
56
+ "vitest": "^4.0.15"
57
+ },
58
+ "repository": {
59
+ "type": "git",
60
+ "url": "git+https://github.com/Karlen-ll/debug-web.git"
61
+ },
62
+ "author": {
63
+ "name": "Karlen",
64
+ "email": "ll.karlen@gmail.com"
65
+ },
66
+ "license": "MIT",
67
+ "bugs": {
68
+ "url": "https://github.com/Karlen-ll/debug-web/issues"
69
+ },
70
+ "homepage": "https://github.com/Karlen-ll/debug-web#readme"
71
+ }