@ingcrea/aumic-sanitizer 0.0.0-stage → 5.4.2
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/LICENSE +10 -0
- package/MANIFEST.es.md +41 -0
- package/MANIFEST.md +11 -0
- package/README.es.md +141 -0
- package/README.md +23 -2
- package/dist/1-atoms/constants.js +18 -0
- package/dist/1-atoms/mojibake-vectors.js +51 -0
- package/dist/1-atoms/types.js +2 -0
- package/dist/2-molecules/LanguageProfiler.js +322 -0
- package/dist/2-molecules/MojibakeEngine.js +57 -0
- package/dist/2-molecules/config.js +41 -0
- package/dist/2-molecules/scanner.js +51 -0
- package/dist/3-cells/HookManager.js +90 -0
- package/dist/3-cells/Sanitizer.js +364 -0
- package/dist/3-cells/worker.js +6 -0
- package/dist/4-organisms/Cli.js +293 -0
- package/dist/5-planets/NativeCompiler.js +32 -0
- package/dist/index.js +8 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 19 November 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
[Full text available at https://www.gnu.org/licenses/agpl-3.0.txt]
|
|
9
|
+
|
|
10
|
+
Copyright (C) 2026 Ingeniería Creativa (ingcrea.com)
|
package/MANIFEST.es.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# AUM-IC SANITIZE: Registro de Decisiones Arquitectónicas (ADR)
|
|
2
|
+
|
|
3
|
+
🌐 Navegación: 🇺🇸 [Read in English](MANIFEST.md) | 🏠 [Volver al Inicio](README.es.md)
|
|
4
|
+
|
|
5
|
+
  
|
|
6
|
+
|
|
7
|
+
Documento formal para el registro del diseño estructural del CLI. Este manifiesto detalla la lógica arquitectónica implementada para garantizar el mantenimiento a largo plazo y la alineación con los estándares operativos de Ingeniería Creativa.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. Registro de Modificaciones (aumic-history.json)
|
|
12
|
+
- **Contexto:** La ejecución de herramientas de modificación de texto sin un log de recuperación es un riesgo crítico en repositorios empresariales.
|
|
13
|
+
- **Decisión:** Implementación de un sistema de instantáneas (snapshot). El CLI almacena el estado previo de los archivos modificados, proveyendo un mecanismo nativo de recuperación (Rollback) por transacción.
|
|
14
|
+
|
|
15
|
+
## 2. Exclusión de Assets Binarios (Short-Circuit)
|
|
16
|
+
- **Contexto:** Procesar archivos compilados o media mediante rutinas de validación de texto resulta en la corrupción del binario y un consumo excesivo de memoria RAM.
|
|
17
|
+
- **Decisión:** Inyección de una barrera de validación en la capa de indexación. Las extensiones de archivos compilados son excluidas antes del acceso al disco.
|
|
18
|
+
|
|
19
|
+
## 3. Optimización de Integración Continua (Delta Scan)
|
|
20
|
+
- **Contexto:** La revisión exhaustiva de un repositorio histórico completo ralentiza el flujo de despliegue local.
|
|
21
|
+
- **Decisión:** Habilitación de un modo diferencial (`--delta`) vinculado al estado de control de versiones de Git, procesando exclusivamente los archivos marcados para commit (Staging).
|
|
22
|
+
|
|
23
|
+
## 4. Clasificador Tecnológico (LanguageProfiler)
|
|
24
|
+
- **Contexto:** Un enfoque genérico para la sanitización genera conflictos sintácticos entre distintos lenguajes de programación.
|
|
25
|
+
- **Decisión:** Creación del módulo `LanguageProfiler.ts` con soporte para 22 perfiles técnicos. Asigna reglas formales de procesamiento según las convenciones de cada extensión (p.ej., desactivando reglas tipográficas en SQL y bases de datos `.csv`).
|
|
26
|
+
|
|
27
|
+
## 5. Arquitectura Multi-Pipeline (AST / StringRegex / Global)
|
|
28
|
+
- **Decisión:**
|
|
29
|
+
- **AST (Babel):** Implementado en el ecosistema JS/TS para manipulación segura de nodos literales mediante `MagicString.overwrite()`.
|
|
30
|
+
- **StringRegex:** Aplicado a lenguajes tradicionales (PHP, C#, Java) enfocando la revisión exclusivamente en cadenas de texto.
|
|
31
|
+
- **Global:** Para formatos declarativos (CSS, YAML, CSV) y texto plano bruto.
|
|
32
|
+
|
|
33
|
+
## 6. Matrices de Resolución de Codificación (MojibakeEngine)
|
|
34
|
+
- **Contexto:** La corrección global de caracteres (Mojibake) provocaba mutaciones no deseadas en formatos que admiten entidades HTML (ej. JSON).
|
|
35
|
+
- **Decisión:** Desarrollo del motor `MojibakeEngine`, el cual categoriza la corrupción en vectores específicos y ejecuta una corrección jerárquica basada en un análisis de densidad (Scoring), restringiendo la resolución de entidades a entornos web (PHP y MARKUP).
|
|
36
|
+
|
|
37
|
+
## 7. Protección de Archivos Minificados
|
|
38
|
+
- **Decisión:** Implementación de heurística técnica (validación de nomenclatura y ratio de caracteres). La confirmación de minificación inactiva políticas invasivas para asegurar la integridad estructural de los bundles.
|
|
39
|
+
|
|
40
|
+
## 8. Escalamiento de Hilos (Worker Threads)
|
|
41
|
+
- **Decisión:** Adopción de la librería `piscina` para la distribución nativa de tareas computacionales en arquitecturas de múltiples núcleos, reduciendo los cuellos de botella por operaciones de I/O masivas.
|
package/MANIFEST.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# AUM-IC SANITIZE: Architecture Decision Record (ADR)
|
|
2
|
+
|
|
3
|
+
🌐 Navigation: 🇲🇽 [Leer en Español](MANIFEST.es.md) | 🏠 [Back to Home](README.md)
|
|
4
|
+
|
|
5
|
+
  
|
|
6
|
+
|
|
7
|
+
Formal document registering the structural design of the CLI. This manifesto details the architectural logic implemented to guarantee long-term maintenance and alignment with the operational standards of Ingeniería Creativa.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
*(Please refer to the Spanish Manifesto for the detailed corporate ADR entries).*
|
package/README.es.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# AUM-IC Sanitizer (Estandarización y Validación de Repositorios)
|
|
2
|
+
|
|
3
|
+
🌐 Navegación: 🇺🇸 [Read in English](README.md) | 📜 [Manifiesto](MANIFEST.es.md)
|
|
4
|
+
|
|
5
|
+
    
|
|
6
|
+
|
|
7
|
+
**AUM-IC Sanitizer** es la herramienta corporativa de **Ingeniería Creativa** para el control de calidad en código fuente. Opera como un CLI y Git Hook especializado en estandarización de codificación (resolución de Mojibake), normalización de saltos de línea (CRLF/LF) y mitigación de inyecciones de código (Trojan Source).
|
|
8
|
+
|
|
9
|
+
Diseñado para integrarse en pipelines CI/CD y despliegues de alto nivel, el sistema evalúa dinámicamente **22 perfiles de lenguaje** para aplicar correcciones con precisión sintáctica, respetando siempre las convenciones estructurales de cada tecnología.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 🛡️ Seguridad Corporativa y Arquitectura Zero-Trust
|
|
14
|
+
|
|
15
|
+
En entornos de producción, la modificación de código mediante heurísticas globales es un riesgo inaceptable. AUM-IC Sanitizer implementa un modelo **Zero-Trust**:
|
|
16
|
+
|
|
17
|
+
1. **Mecanismo de Rollback:** Antes de ejecutar cualquier escritura en disco, el sistema registra el estado previo en `aumic-history.json`. En caso de presentarse un conflicto de integración, el comando `aumic-sanitizer restore` revierte el repositorio a su estado original, asegurando la integridad de los datos.
|
|
18
|
+
2. **Validación Binaria (Short-Circuit):** El motor descarta automáticamente la lectura de binarios compilados y archivos multimedia (`.pdf`, `.docx`, `.xlsx`, `.zip`, `.png`, etc.) en tiempo de indexación, optimizando el rendimiento y eliminando el riesgo de corromper assets.
|
|
19
|
+
3. **Resolución AST (Abstract Syntax Tree):** Para lenguajes críticos (JavaScript, TypeScript, React), la corrección de formato no se basa en expresiones regulares convencionales. Utiliza análisis de árbol sintáctico para limitar los reemplazos exclusivamente a literales y comentarios, protegiendo la lógica del software.
|
|
20
|
+
4. **Dependencias Auditadas:** El CLI opera con **0 vulnerabilidades (0 CVE)** en su árbol de dependencias, garantizando su fiabilidad en infraestructuras corporativas.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 🔬 Matrices de Corrección de Codificación (Mojibake)
|
|
25
|
+
|
|
26
|
+
La herramienta clasifica las anomalías de codificación en 4 vectores estructurales para aplicar correcciones focalizadas:
|
|
27
|
+
|
|
28
|
+
1. **LATIN1**: Discrepancias estándar de ISO-8859-1 a UTF-8.
|
|
29
|
+
2. **DOUBLE_UTF8**: Anomalías generadas por procesos de doble codificación.
|
|
30
|
+
3. **CP1252_PUNCTUATION**: Caracteres tipográficos originados por herramientas ofimáticas (portapapeles de Windows).
|
|
31
|
+
4. **HTML_ENTITIES**: Conversiones directas de codificación a entidades.
|
|
32
|
+
|
|
33
|
+
### Distribución Vectorial por Perfil
|
|
34
|
+
Para prevenir falsos positivos, la habilitación de los vectores depende del perfil del lenguaje:
|
|
35
|
+
|
|
36
|
+
| Perfil de Lenguaje | LATIN1 | CP1252 (Punt) | DOUBLE_UTF8 | HTML_ENTITIES |
|
|
37
|
+
|---|:---:|:---:|:---:|:---:|
|
|
38
|
+
| **PHP** (`.php`, `.phtml`) | ✅ | ✅ | ✅ | ✅ |
|
|
39
|
+
| **MARKUP** (`.html`, `.svg`) | ✅ | ✅ | ✅ | ✅ |
|
|
40
|
+
| **AST** (JS, TS, React, Astro) | ✅ | ✅ | ✅ | ❌ |
|
|
41
|
+
| **DATA** (JSON, YAML, CSV) | ✅ | ✅ | ✅ | ❌ |
|
|
42
|
+
| **Desktop / Mobile / Scripts** | ✅ | ✅ | ✅ | ❌ |
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## Cobertura Estructural de Lenguajes
|
|
47
|
+
|
|
48
|
+
### 🌐 Web
|
|
49
|
+
| Lenguaje / Framework | Pipeline | Observaciones |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| JavaScript / TypeScript / React | AST (Babel) | Corrección habilitada únicamente dentro de strings y comentarios. |
|
|
52
|
+
| Astro | AST (Babel + TS) | Los metadatos (Frontmatter) se procesan como TypeScript. |
|
|
53
|
+
| Vue / Svelte | StringRegex | Análisis limitado a bloques de script y template. |
|
|
54
|
+
| PHP | StringRegex | Manejo específico para literales y sintaxis heredoc. |
|
|
55
|
+
| HTML | StringRegex | Resolución limitada a valores de atributos. |
|
|
56
|
+
| CSS | Global | Los archivos minificados reciben procesamiento restringido. |
|
|
57
|
+
|
|
58
|
+
### 🖥️ Desktop, Backend & Mobile
|
|
59
|
+
| Lenguaje | Pipeline | Observaciones |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| Python / Ruby | StringRegex | Soporte integral para literales multilínea y de interpolación. |
|
|
62
|
+
| Go / Rust / C / C++ | Regex byte-level | Reglas de comillas tipográficas (Smart Quotes) inhabilitadas por sintaxis del lenguaje. |
|
|
63
|
+
| C# / Java / Kotlin / Dart | StringRegex | Soporte para literales estándar y verbatim. |
|
|
64
|
+
| Swift | Regex byte-level | Tratamiento específico para raw strings e interpolaciones. |
|
|
65
|
+
| Shell / Scripts | Regex byte-level | Smart quotes inhabilitadas. |
|
|
66
|
+
| SQL | Regex byte-level | Identificadores estructurales preservados. |
|
|
67
|
+
|
|
68
|
+
### 📄 Infraestructura y Datos (Data Pipelines)
|
|
69
|
+
| Formato | Pipeline | Observaciones |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| **Bases de Datos** (`.csv`, `.tsv`) | Global | Perfil optimizado para la resolución de bases exportadas desde ofimática. |
|
|
72
|
+
| JSON (`.json`) | Regex byte-level | Smart quotes inhabilitadas. |
|
|
73
|
+
| YAML / TOML | Global | Operaciones seguras sobre formato declarativo. |
|
|
74
|
+
| XML / Plist | StringRegex | Limitado a propiedades y valores. |
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Análisis de Minificación
|
|
79
|
+
|
|
80
|
+
El sistema evalúa 4 métricas técnicas por archivo. Si dos o más umbrales coinciden, el archivo se cataloga como **minificado**, inhabilitando automáticamente las reglas invasivas (`smartQuotes` y limpieza de comentarios) para preservar el sourcemap original:
|
|
81
|
+
|
|
82
|
+
- El nombre del archivo incluye `.min.`
|
|
83
|
+
- Total de líneas ≤ 3 con peso superior a 500 caracteres
|
|
84
|
+
- Longitud máxima de una línea > 500 caracteres
|
|
85
|
+
- Ratio de saltos de línea inferior al 0.2% del volumen total
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## ⚙️ Gobernanza y Configuración (Configuration as Code)
|
|
93
|
+
|
|
94
|
+
Para garantizar que todos los desarrolladores y pipelines de CI/CD operen bajo el mismo estándar, la herramienta permite declarar un contrato de infraestructura. Ejecutar `aumic-sanitizer init` genera el archivo `aumic.config.json` en la raíz del proyecto:
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"ignore": [
|
|
99
|
+
"node_modules",
|
|
100
|
+
"dist",
|
|
101
|
+
"build",
|
|
102
|
+
".git",
|
|
103
|
+
"wp-content/uploads"
|
|
104
|
+
],
|
|
105
|
+
"rules": {
|
|
106
|
+
"mojibake": true,
|
|
107
|
+
"zeroWidth": true,
|
|
108
|
+
"crlf": true,
|
|
109
|
+
"eradicator": true,
|
|
110
|
+
"smartQuotes": true
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Este archivo actúa como la **única fuente de verdad**. Permite excluir directorios pesados y desactivar módulos invasivos (por ejemplo, apagar `eradicator` si el proyecto requiere preservar logs en consola por diseño).
|
|
116
|
+
|
|
117
|
+
## Implementación
|
|
118
|
+
|
|
119
|
+
### 1. Panel de Gestión (CLI)
|
|
120
|
+
Interfaz interactiva para administración general:
|
|
121
|
+
```bash
|
|
122
|
+
aumic-sanitizer
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### 2. Procesamiento Directo (Targeting)
|
|
126
|
+
Para integración en scripts de automatización:
|
|
127
|
+
```bash
|
|
128
|
+
aumic-sanitizer scan src/components/
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### 3. Integración Pre-Commit (Delta Scan)
|
|
132
|
+
Evalúa exclusivamente los archivos modificados en el índice de Git:
|
|
133
|
+
```bash
|
|
134
|
+
aumic-sanitizer scan --delta
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### 4. Recuperación de Estado (Rollback)
|
|
138
|
+
Regresa el directorio a la versión previa a la sanitización:
|
|
139
|
+
```bash
|
|
140
|
+
aumic-sanitizer restore
|
|
141
|
+
```
|
package/README.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AUM-IC Sanitizer (Repository Standardization & Validation)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
🌐 Navigation: 🇲🇽 [Leer en Español](README.es.md) | 📜 [Manifesto](MANIFEST.md)
|
|
4
|
+
|
|
5
|
+
    
|
|
6
|
+
|
|
7
|
+
**AUM-IC Sanitizer** is the corporate source code quality control tool developed by **Ingeniería Creativa**. It operates as a specialized CLI and Git Hook for coding standardization (Mojibake resolution), line-ending normalization (CRLF/LF), and Trojan Source mitigation.
|
|
8
|
+
|
|
9
|
+
Designed to integrate seamlessly into CI/CD pipelines and enterprise-level deployments, the system dynamically evaluates **22 language profiles** to apply syntax-accurate corrections, consistently respecting the structural conventions of each technology.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 🛡️ Corporate Security and Zero-Trust Architecture
|
|
14
|
+
|
|
15
|
+
In production environments, modifying code through global heuristics is an unacceptable risk. AUM-IC Sanitizer implements a **Zero-Trust** model:
|
|
16
|
+
|
|
17
|
+
1. **Rollback Mechanism:** Before executing any disk write, the system registers the previous state in `aumic-history.json`. In the event of an integration conflict, the `aumic-sanitizer restore` command reverts the repository to its exact original state, ensuring complete data integrity.
|
|
18
|
+
2. **Binary Validation (Short-Circuit):** The engine automatically discards the reading of compiled binaries and multimedia files (`.pdf`, `.docx`, `.xlsx`, `.zip`, `.png`, etc.) during indexing, optimizing performance and removing the risk of asset corruption.
|
|
19
|
+
3. **AST Resolution (Abstract Syntax Tree):** For critical languages (JavaScript, TypeScript, React), formatting corrections do not rely on conventional regular expressions. The tool utilizes syntax tree analysis to limit replacements strictly to literals and comments, safeguarding software logic.
|
|
20
|
+
4. **Audited Dependencies:** The CLI operates with **0 known vulnerabilities (0 CVE)** in its dependency tree, ensuring reliability within corporate infrastructures.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
*(See the Spanish README or the Manifesto for full technical coverage matrices).*
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EMOJI_PATTERN = void 0;
|
|
4
|
+
exports.reverseEmojiMojibake = reverseEmojiMojibake;
|
|
5
|
+
// Expresión regular para cazar corrupción de emojis
|
|
6
|
+
exports.EMOJI_PATTERN = /ðŸ[^\s"'<>`\n\r]+/g;
|
|
7
|
+
function reverseEmojiMojibake(corrupted) {
|
|
8
|
+
try {
|
|
9
|
+
const buf = Buffer.from(corrupted, 'latin1');
|
|
10
|
+
const decoded = buf.toString('utf8');
|
|
11
|
+
if (decoded.includes('�'))
|
|
12
|
+
return corrupted;
|
|
13
|
+
return decoded;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return corrupted;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.VECTORS = void 0;
|
|
4
|
+
exports.VECTORS = {
|
|
5
|
+
LATIN1: {},
|
|
6
|
+
CP1252_PUNCTUATION: {},
|
|
7
|
+
HTML_ENTITIES: {},
|
|
8
|
+
DOUBLE_UTF8: {}
|
|
9
|
+
};
|
|
10
|
+
const chars = ['á', 'é', 'í', 'ó', 'ú', 'ñ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ', 'ü', 'Ü', '¿', '¡'];
|
|
11
|
+
// Generación Dinámica con Inmunidad Matemática
|
|
12
|
+
for (const char of chars) {
|
|
13
|
+
const mojibake = Buffer.from(char, 'utf8').toString('latin1');
|
|
14
|
+
exports.VECTORS.LATIN1[mojibake] = char;
|
|
15
|
+
const double = Buffer.from(mojibake, 'utf8').toString('latin1');
|
|
16
|
+
exports.VECTORS.DOUBLE_UTF8[double] = char;
|
|
17
|
+
}
|
|
18
|
+
// Sobreescrituras Críticas LATIN1 (Fallo de terminal Windows)
|
|
19
|
+
exports.VECTORS.LATIN1['Ã A'] = 'ÍA';
|
|
20
|
+
exports.VECTORS.LATIN1['Ã'] = 'Í';
|
|
21
|
+
exports.VECTORS.LATIN1['Ü'] = 'Ü';
|
|
22
|
+
// Vector: Entidades HTML (Frecuente en exportaciones SQL -> PHP)
|
|
23
|
+
exports.VECTORS.HTML_ENTITIES = {
|
|
24
|
+
'á': 'á',
|
|
25
|
+
'é': 'é',
|
|
26
|
+
'í': 'í',
|
|
27
|
+
'ó': 'ó',
|
|
28
|
+
'ú': 'ú',
|
|
29
|
+
'ñ': 'ñ',
|
|
30
|
+
'Ã ': 'Á',
|
|
31
|
+
'É': 'É',
|
|
32
|
+
'Ä': 'Í',
|
|
33
|
+
'Ó': 'Ó',
|
|
34
|
+
'Ú': 'Ú',
|
|
35
|
+
'Ñ': 'Ñ',
|
|
36
|
+
'ü': 'ü',
|
|
37
|
+
'Ü': 'Ü',
|
|
38
|
+
'¿': '¿',
|
|
39
|
+
'¡': '¡',
|
|
40
|
+
};
|
|
41
|
+
// Vector: Puntuación Capa 7 (Windows Clipboard)
|
|
42
|
+
exports.VECTORS.CP1252_PUNCTUATION = {
|
|
43
|
+
'“': '“', // Double left quote
|
|
44
|
+
'â€': '”', // Double right quote
|
|
45
|
+
'‑': '‘', // Single left quote
|
|
46
|
+
'‒': '’', // Single right quote
|
|
47
|
+
'‗': '—', // Em dash
|
|
48
|
+
'–': '–', // En dash
|
|
49
|
+
'•': '•', // Bullet
|
|
50
|
+
'…': '…', // Ellipsis
|
|
51
|
+
};
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.detectProfile = detectProfile;
|
|
7
|
+
exports.isBinaryOrIgnored = isBinaryOrIgnored;
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
10
|
+
// MAPA DE EXTENSION → CATEGORIA
|
|
11
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
12
|
+
const EXT_MAP = {
|
|
13
|
+
// JavaScript ecosystem
|
|
14
|
+
'.js': 'JS_AST',
|
|
15
|
+
'.jsx': 'JS_AST',
|
|
16
|
+
'.mjs': 'JS_AST',
|
|
17
|
+
'.cjs': 'JS_AST',
|
|
18
|
+
'.es': 'JS_AST',
|
|
19
|
+
// TypeScript / meta-frameworks
|
|
20
|
+
'.ts': 'TS_AST',
|
|
21
|
+
'.tsx': 'TS_AST',
|
|
22
|
+
'.astro': 'TS_AST',
|
|
23
|
+
// Component frameworks
|
|
24
|
+
'.vue': 'VUE_SVELTE',
|
|
25
|
+
'.svelte': 'VUE_SVELTE',
|
|
26
|
+
// Backend web
|
|
27
|
+
'.php': 'PHP',
|
|
28
|
+
'.phtml': 'PHP',
|
|
29
|
+
// Python
|
|
30
|
+
'.py': 'PYTHON',
|
|
31
|
+
'.pyw': 'PYTHON',
|
|
32
|
+
'.pyi': 'PYTHON',
|
|
33
|
+
// Ruby
|
|
34
|
+
'.rb': 'RUBY',
|
|
35
|
+
'.rake': 'RUBY',
|
|
36
|
+
'.gemspec': 'RUBY',
|
|
37
|
+
'.erb': 'RUBY',
|
|
38
|
+
// Go
|
|
39
|
+
'.go': 'GO',
|
|
40
|
+
// Rust
|
|
41
|
+
'.rs': 'RUST',
|
|
42
|
+
// C# / .NET
|
|
43
|
+
'.cs': 'CSHARP',
|
|
44
|
+
'.csx': 'CSHARP',
|
|
45
|
+
// Java
|
|
46
|
+
'.java': 'JAVA',
|
|
47
|
+
'.groovy': 'JAVA',
|
|
48
|
+
// Kotlin (Android / Server)
|
|
49
|
+
'.kt': 'KOTLIN',
|
|
50
|
+
'.kts': 'KOTLIN',
|
|
51
|
+
// Swift (iOS / macOS)
|
|
52
|
+
'.swift': 'SWIFT',
|
|
53
|
+
// Dart (Flutter)
|
|
54
|
+
'.dart': 'DART',
|
|
55
|
+
// C / C++
|
|
56
|
+
'.c': 'CPP',
|
|
57
|
+
'.h': 'CPP',
|
|
58
|
+
'.cpp': 'CPP',
|
|
59
|
+
'.cc': 'CPP',
|
|
60
|
+
'.cxx': 'CPP',
|
|
61
|
+
'.hpp': 'CPP',
|
|
62
|
+
'.hxx': 'CPP',
|
|
63
|
+
// Markup
|
|
64
|
+
'.html': 'MARKUP',
|
|
65
|
+
'.htm': 'MARKUP',
|
|
66
|
+
'.xml': 'DATA_XML',
|
|
67
|
+
'.svg': 'MARKUP',
|
|
68
|
+
'.xhtml': 'MARKUP',
|
|
69
|
+
'.plist': 'DATA_XML',
|
|
70
|
+
'.xib': 'DATA_XML',
|
|
71
|
+
// Styles
|
|
72
|
+
'.css': 'STYLE',
|
|
73
|
+
'.scss': 'STYLE',
|
|
74
|
+
'.sass': 'STYLE',
|
|
75
|
+
'.less': 'STYLE',
|
|
76
|
+
'.styl': 'STYLE',
|
|
77
|
+
// Data
|
|
78
|
+
'.json': 'DATA_JSON',
|
|
79
|
+
'.jsonc': 'DATA_JSON',
|
|
80
|
+
'.yaml': 'DATA_YAML',
|
|
81
|
+
'.yml': 'DATA_YAML',
|
|
82
|
+
'.toml': 'DATA_TOML',
|
|
83
|
+
// Shell / scripting
|
|
84
|
+
'.sh': 'SHELL',
|
|
85
|
+
'.bash': 'SHELL',
|
|
86
|
+
'.zsh': 'SHELL',
|
|
87
|
+
'.fish': 'SHELL',
|
|
88
|
+
'.ps1': 'SHELL',
|
|
89
|
+
'.bat': 'SHELL',
|
|
90
|
+
'.cmd': 'SHELL',
|
|
91
|
+
// SQL
|
|
92
|
+
'.sql': 'SQL',
|
|
93
|
+
// Plain text
|
|
94
|
+
'.md': 'PLAIN',
|
|
95
|
+
'.mdx': 'PLAIN',
|
|
96
|
+
'.txt': 'PLAIN',
|
|
97
|
+
'.csv': 'PLAIN',
|
|
98
|
+
'.log': 'PLAIN',
|
|
99
|
+
'.rst': 'PLAIN',
|
|
100
|
+
};
|
|
101
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
102
|
+
// PERFILES POR CATEGORIA
|
|
103
|
+
// Define las capacidades de sanitizacion para cada tipo de lenguaje.
|
|
104
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
105
|
+
function buildProfile(cat, isMinified) {
|
|
106
|
+
// Perfil base: conservador y seguro
|
|
107
|
+
const base = {
|
|
108
|
+
category: cat,
|
|
109
|
+
isMinified,
|
|
110
|
+
useAST: false,
|
|
111
|
+
smartQuoteMode: 'disabled',
|
|
112
|
+
allowEradicator: false,
|
|
113
|
+
allowMojibake: true,
|
|
114
|
+
allowZeroWidth: true,
|
|
115
|
+
allowCRLF: true,
|
|
116
|
+
allowNBSP: true,
|
|
117
|
+
allowedMojibakeVectors: ['LATIN1', 'CP1252_PUNCTUATION', 'DOUBLE_UTF8'],
|
|
118
|
+
};
|
|
119
|
+
switch (cat) {
|
|
120
|
+
case 'JS_AST':
|
|
121
|
+
case 'TS_AST':
|
|
122
|
+
return { ...base,
|
|
123
|
+
useAST: !isMinified, // Sin AST en minificados: muy costoso y sin valor
|
|
124
|
+
smartQuoteMode: isMinified ? 'disabled' : 'ast-only',
|
|
125
|
+
allowEradicator: !isMinified, // Nunca borrar console.log en .min.js
|
|
126
|
+
};
|
|
127
|
+
case 'VUE_SVELTE':
|
|
128
|
+
// Bloque <script> se trata como TS_AST, el template como MARKUP.
|
|
129
|
+
// Por ahora usamos string-regex hasta integrar un parser Vue.
|
|
130
|
+
return { ...base,
|
|
131
|
+
smartQuoteMode: isMinified ? 'disabled' : 'string-regex',
|
|
132
|
+
allowEradicator: false,
|
|
133
|
+
};
|
|
134
|
+
case 'PHP':
|
|
135
|
+
return { ...base,
|
|
136
|
+
smartQuoteMode: 'string-regex',
|
|
137
|
+
allowEradicator: false,
|
|
138
|
+
allowNBSP: false,
|
|
139
|
+
allowedMojibakeVectors: ['LATIN1', 'CP1252_PUNCTUATION', 'DOUBLE_UTF8', 'HTML_ENTITIES'],
|
|
140
|
+
};
|
|
141
|
+
case 'PYTHON':
|
|
142
|
+
// Python usa ' " y triple-quotes. string-regex cubre los casos estandar.
|
|
143
|
+
return { ...base,
|
|
144
|
+
smartQuoteMode: 'string-regex',
|
|
145
|
+
allowEradicator: false, // print() puede ser logging legitimo en Python
|
|
146
|
+
};
|
|
147
|
+
case 'RUBY':
|
|
148
|
+
return { ...base,
|
|
149
|
+
smartQuoteMode: 'string-regex',
|
|
150
|
+
allowEradicator: false,
|
|
151
|
+
};
|
|
152
|
+
case 'GO':
|
|
153
|
+
// Go usa backticks para raw strings. Los strings normales usan ".
|
|
154
|
+
// Las comillas simples son rune literals — NUNCA tocar.
|
|
155
|
+
return { ...base,
|
|
156
|
+
smartQuoteMode: 'disabled', // Demasiado riesgo con rune literals
|
|
157
|
+
allowEradicator: false,
|
|
158
|
+
};
|
|
159
|
+
case 'RUST':
|
|
160
|
+
return { ...base,
|
|
161
|
+
smartQuoteMode: 'disabled', // char literals son ' — no tocar
|
|
162
|
+
allowEradicator: false,
|
|
163
|
+
};
|
|
164
|
+
case 'CSHARP':
|
|
165
|
+
// C# tiene verbatim strings @"..." y string interpolation $"..."
|
|
166
|
+
return { ...base,
|
|
167
|
+
smartQuoteMode: 'string-regex',
|
|
168
|
+
allowEradicator: false,
|
|
169
|
+
};
|
|
170
|
+
case 'JAVA':
|
|
171
|
+
case 'KOTLIN':
|
|
172
|
+
return { ...base,
|
|
173
|
+
smartQuoteMode: 'string-regex',
|
|
174
|
+
allowEradicator: false,
|
|
175
|
+
};
|
|
176
|
+
case 'SWIFT':
|
|
177
|
+
// Swift tiene interpolacion avanzada y raw strings #"..."#
|
|
178
|
+
return { ...base,
|
|
179
|
+
smartQuoteMode: 'disabled',
|
|
180
|
+
allowEradicator: false,
|
|
181
|
+
};
|
|
182
|
+
case 'DART':
|
|
183
|
+
return { ...base,
|
|
184
|
+
smartQuoteMode: 'string-regex',
|
|
185
|
+
allowEradicator: false,
|
|
186
|
+
};
|
|
187
|
+
case 'CPP':
|
|
188
|
+
// C/C++ tiene char literals (') y raw strings R"(...)". Demasiado riesgo.
|
|
189
|
+
return { ...base,
|
|
190
|
+
smartQuoteMode: 'disabled',
|
|
191
|
+
allowEradicator: false,
|
|
192
|
+
};
|
|
193
|
+
case 'MARKUP':
|
|
194
|
+
return { ...base,
|
|
195
|
+
smartQuoteMode: 'string-regex',
|
|
196
|
+
allowEradicator: false,
|
|
197
|
+
allowCRLF: false,
|
|
198
|
+
allowedMojibakeVectors: ['LATIN1', 'CP1252_PUNCTUATION', 'DOUBLE_UTF8', 'HTML_ENTITIES'],
|
|
199
|
+
};
|
|
200
|
+
case 'STYLE':
|
|
201
|
+
// CSS/SCSS: strings solo en url() y content. Global es seguro.
|
|
202
|
+
return { ...base,
|
|
203
|
+
smartQuoteMode: isMinified ? 'disabled' : 'global',
|
|
204
|
+
allowEradicator: false,
|
|
205
|
+
};
|
|
206
|
+
case 'DATA_JSON':
|
|
207
|
+
// JSON ESTRICTO: las comillas simples son INVALIDAS. NUNCA reemplazar.
|
|
208
|
+
return { ...base,
|
|
209
|
+
smartQuoteMode: 'disabled', // No existe ' valido en JSON
|
|
210
|
+
allowEradicator: false,
|
|
211
|
+
allowNBSP: false,
|
|
212
|
+
};
|
|
213
|
+
case 'DATA_YAML':
|
|
214
|
+
case 'DATA_TOML':
|
|
215
|
+
return { ...base,
|
|
216
|
+
smartQuoteMode: 'global', // Strings son de texto — global seguro
|
|
217
|
+
allowEradicator: false,
|
|
218
|
+
};
|
|
219
|
+
case 'DATA_XML':
|
|
220
|
+
return { ...base,
|
|
221
|
+
smartQuoteMode: 'string-regex',
|
|
222
|
+
allowEradicator: false,
|
|
223
|
+
allowNBSP: false,
|
|
224
|
+
};
|
|
225
|
+
case 'SHELL':
|
|
226
|
+
// Scripts shell: ' y " tienen semantica diferente (expansión vs literal)
|
|
227
|
+
return { ...base,
|
|
228
|
+
smartQuoteMode: 'disabled',
|
|
229
|
+
allowEradicator: false,
|
|
230
|
+
};
|
|
231
|
+
case 'SQL':
|
|
232
|
+
// SQL usa ' para strings. Las comillas dobles son identificadores.
|
|
233
|
+
return { ...base,
|
|
234
|
+
smartQuoteMode: 'disabled', // Cambiar ' a ' en SQL rompe la sintaxis
|
|
235
|
+
allowEradicator: false,
|
|
236
|
+
};
|
|
237
|
+
case 'ENV':
|
|
238
|
+
return { ...base,
|
|
239
|
+
smartQuoteMode: 'global',
|
|
240
|
+
allowEradicator: false,
|
|
241
|
+
allowCRLF: true,
|
|
242
|
+
};
|
|
243
|
+
case 'PLAIN':
|
|
244
|
+
default:
|
|
245
|
+
return { ...base,
|
|
246
|
+
smartQuoteMode: 'global',
|
|
247
|
+
allowEradicator: false,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
252
|
+
// DETECTOR DE MINIFICACION
|
|
253
|
+
// Un archivo esta minificado si cumple al menos 2 de estas condiciones.
|
|
254
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
255
|
+
function detectMinification(filepath, content) {
|
|
256
|
+
let signals = 0;
|
|
257
|
+
// 1. El nombre del archivo contiene .min.
|
|
258
|
+
if (path_1.default.basename(filepath).includes('.min.'))
|
|
259
|
+
signals++;
|
|
260
|
+
// 2. El archivo es practicamente una sola linea larga
|
|
261
|
+
const lines = content.split('\n');
|
|
262
|
+
if (lines.length <= 3 && content.length > 500)
|
|
263
|
+
signals++;
|
|
264
|
+
// 3. La linea mas larga supera 500 caracteres (threshold heuristico)
|
|
265
|
+
const maxLineLen = Math.max(...lines.map((l) => l.length));
|
|
266
|
+
if (maxLineLen > 500)
|
|
267
|
+
signals++;
|
|
268
|
+
// 4. Ratio de saltos de linea muy bajo (densidad de codigo alta)
|
|
269
|
+
const nlRatio = (content.match(/\n/g) || []).length / content.length;
|
|
270
|
+
if (nlRatio < 0.002 && content.length > 1000)
|
|
271
|
+
signals++;
|
|
272
|
+
return signals >= 2;
|
|
273
|
+
}
|
|
274
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
275
|
+
// API PUBLICA
|
|
276
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
277
|
+
/**
|
|
278
|
+
* Detecta el perfil de lenguaje de un archivo.
|
|
279
|
+
* Combina extension, nombre de archivo y analisis heuristico del contenido.
|
|
280
|
+
*/
|
|
281
|
+
function detectProfile(filepath, content) {
|
|
282
|
+
const ext = path_1.default.extname(filepath).toLowerCase();
|
|
283
|
+
const basename = path_1.default.basename(filepath).toLowerCase();
|
|
284
|
+
// Deteccion especial por nombre de archivo (sin extension)
|
|
285
|
+
let category = EXT_MAP[ext] ?? 'UNKNOWN';
|
|
286
|
+
if (category === 'UNKNOWN') {
|
|
287
|
+
if (basename === '.env' || basename.startsWith('.env.'))
|
|
288
|
+
category = 'ENV';
|
|
289
|
+
else if (basename === 'makefile' || basename === 'dockerfile')
|
|
290
|
+
category = 'SHELL';
|
|
291
|
+
else if (basename === 'gemfile' || basename === 'rakefile')
|
|
292
|
+
category = 'RUBY';
|
|
293
|
+
else if (basename === 'podfile' || basename === 'fastfile')
|
|
294
|
+
category = 'RUBY';
|
|
295
|
+
else if (basename.endsWith('.gradle'))
|
|
296
|
+
category = 'KOTLIN';
|
|
297
|
+
}
|
|
298
|
+
const isMinified = detectMinification(filepath, content);
|
|
299
|
+
return buildProfile(category, isMinified);
|
|
300
|
+
}
|
|
301
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
302
|
+
// LISTA NEGRA DE BINARIOS Y DOCUMENTOS COMPILADOS
|
|
303
|
+
// El motor ignorará estos archivos instantáneamente antes de la lectura en disco.
|
|
304
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
305
|
+
const BINARY_EXTENSIONS = new Set([
|
|
306
|
+
// Documentos compilados
|
|
307
|
+
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
|
|
308
|
+
// Imágenes (Nota: .svg se ignora aquí porque ES texto y ya está en MARKUP)
|
|
309
|
+
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.ico', '.tiff',
|
|
310
|
+
// Fuentes
|
|
311
|
+
'.ttf', '.woff', '.woff2', '.eot', '.otf',
|
|
312
|
+
// Comprimidos
|
|
313
|
+
'.zip', '.tar', '.gz', '.7z', '.rar',
|
|
314
|
+
// Binarios y ejecutables
|
|
315
|
+
'.exe', '.dll', '.so', '.dylib', '.bin', '.dat',
|
|
316
|
+
// Audio / Video
|
|
317
|
+
'.mp3', '.mp4', '.avi', '.mov', '.mkv', '.wav'
|
|
318
|
+
]);
|
|
319
|
+
function isBinaryOrIgnored(filepath) {
|
|
320
|
+
const ext = path_1.default.extname(filepath).toLowerCase();
|
|
321
|
+
return BINARY_EXTENSIONS.has(ext);
|
|
322
|
+
}
|