textoneitor 0.0.0-stage → 1.2.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.
Files changed (77) hide show
  1. package/LICENSE +101 -0
  2. package/LICENSE-AGPL-3.0 +661 -0
  3. package/README.md +69 -2
  4. package/dist/api/index.d.ts +34 -0
  5. package/dist/api/index.js +98 -0
  6. package/dist/baseline/index.d.ts +20 -0
  7. package/dist/baseline/index.js +81 -0
  8. package/dist/bundle/dist/cli.mjs +29893 -0
  9. package/dist/bundle/package.json +6 -0
  10. package/dist/bundle/rulepack/rulepack.json +1496 -0
  11. package/dist/bundle/rules/situaciones.yml +27 -0
  12. package/dist/cli/benchmark.d.ts +89 -0
  13. package/dist/cli/benchmark.js +185 -0
  14. package/dist/cli/main.d.ts +2 -0
  15. package/dist/cli/main.js +377 -0
  16. package/dist/config/core.d.ts +55 -0
  17. package/dist/config/core.js +244 -0
  18. package/dist/config/glob.d.ts +2 -0
  19. package/dist/config/glob.js +72 -0
  20. package/dist/config/index.d.ts +8 -0
  21. package/dist/config/index.js +38 -0
  22. package/dist/config/situaciones.d.ts +17 -0
  23. package/dist/config/situaciones.js +43 -0
  24. package/dist/contracts/index.d.ts +238 -0
  25. package/dist/contracts/index.js +4 -0
  26. package/dist/document/index.d.ts +10 -0
  27. package/dist/document/index.js +70 -0
  28. package/dist/document/text.d.ts +22 -0
  29. package/dist/document/text.js +91 -0
  30. package/dist/document/tokenize.d.ts +4 -0
  31. package/dist/document/tokenize.js +59 -0
  32. package/dist/markdown/index.d.ts +7 -0
  33. package/dist/markdown/index.js +178 -0
  34. package/dist/paths.d.ts +4 -0
  35. package/dist/paths.js +14 -0
  36. package/dist/reporters/index.d.ts +29 -0
  37. package/dist/reporters/index.js +182 -0
  38. package/dist/rules/compiler/build.d.ts +1 -0
  39. package/dist/rules/compiler/build.js +46 -0
  40. package/dist/rules/compiler/index.d.ts +40 -0
  41. package/dist/rules/compiler/index.js +343 -0
  42. package/dist/rules/compiler/safety.d.ts +16 -0
  43. package/dist/rules/compiler/safety.js +124 -0
  44. package/dist/rules/detectors/index.d.ts +4 -0
  45. package/dist/rules/detectors/index.js +651 -0
  46. package/dist/rules/detectors/shared.d.ts +30 -0
  47. package/dist/rules/detectors/shared.js +87 -0
  48. package/dist/rules/runtime/index.d.ts +17 -0
  49. package/dist/rules/runtime/index.js +74 -0
  50. package/dist/runner/index.d.ts +18 -0
  51. package/dist/runner/index.js +176 -0
  52. package/dist/runner/lint-text.d.ts +19 -0
  53. package/dist/runner/lint-text.js +20 -0
  54. package/dist/scoring/index.d.ts +16 -0
  55. package/dist/scoring/index.js +41 -0
  56. package/dist/suppressions/index.d.ts +23 -0
  57. package/dist/suppressions/index.js +86 -0
  58. package/dist/web/engine.meta.json +1 -0
  59. package/dist/web/engine.mjs +11029 -0
  60. package/dist/web/index.d.ts +39 -0
  61. package/dist/web/index.js +37 -0
  62. package/dist/web/node-crypto-shim.d.ts +9 -0
  63. package/dist/web/node-crypto-shim.js +24 -0
  64. package/dist/web/sha256.d.ts +11 -0
  65. package/dist/web/sha256.js +89 -0
  66. package/package.json +88 -4
  67. package/rulepack/rulepack.json +1496 -0
  68. package/rules/profiles/academico.yml +4 -0
  69. package/rules/profiles/chat.yml +4 -0
  70. package/rules/profiles/correo.yml +3 -0
  71. package/rules/profiles/general.yml +2 -0
  72. package/rules/profiles/marketing.yml +4 -0
  73. package/rules/profiles/readme.yml +5 -0
  74. package/rules/profiles/redes.yml +6 -0
  75. package/rules/profiles/tecnico.yml +4 -0
  76. package/rules/situaciones.yml +27 -0
  77. package/schemas/rule.schema.json +90 -0
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # TEXTOneitor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Revisor de textos en español que marca lo que suena a IA: muletillas de redacción, rayas de inciso a la inglesa, tríadas por costumbre, cierres de arenga, frases todas del mismo largo. Se ejecuta en tu ordenador, no usa IA y no sale a la red.
4
+
5
+ ```
6
+ npm i -D textoneitor
7
+ npx textoneitor lint docs README.md
8
+ ```
9
+
10
+ ```
11
+ README.md índice 34/100
12
+ 12:1 warning Muletilla de redacción generada: «En este artículo exploraremos». lexico/muletillas-ia
13
+ 18:40 warning 4 rayas con espacios a ambos lados (uso inglés del em dash). formato/raya-espaciada
14
+ 24:1 warning Cierre formulario: «En definitiva» al inicio del último párrafo. estructura/cierre-formulario
15
+ ```
16
+
17
+ El índice va de 0 a 100 y mide patrones de escritura. No dice quién ha escrito un texto y no sirve para acusar a nadie.
18
+
19
+ ## Comandos
20
+
21
+ ```
22
+ textoneitor lint [rutas...] # --format terminal|json|sarif, --profile, --fail-on, --max-index, --stdin
23
+ textoneitor rules list # --json, --status stable|candidate
24
+ textoneitor rules explain <id> # qué mide, ejemplo, falsos positivos conocidos
25
+ textoneitor config validate # comprueba textoneitor.yml
26
+ textoneitor config explain <archivo>
27
+ textoneitor baseline create # congela lo que ya está escrito
28
+ textoneitor baseline update
29
+ ```
30
+
31
+ ## Perfiles
32
+
33
+ `chat`, `correo`, `readme`, `redes` para lo cotidiano; `general`, `tecnico`, `academico`, `marketing` para prosa editada. Cambian qué reglas están activas, porque una raya de inciso es normal en un artículo y rara en un mensaje.
34
+
35
+ ## Configuración
36
+
37
+ `textoneitor.yml` en la raíz:
38
+
39
+ ```yaml
40
+ profile: readme
41
+ fail_on: warning
42
+ max_index: 40
43
+ rules:
44
+ formato/raya-espaciada: off
45
+ overrides:
46
+ - files: ["blog/**"]
47
+ rules:
48
+ "lexico/*": info
49
+ ```
50
+
51
+ Supresiones en el propio texto:
52
+
53
+ ```markdown
54
+ <!-- textoneitor-disable-next-line retorica/triada -->
55
+ ```
56
+
57
+ ## API
58
+
59
+ ```js
60
+ import { lintText, lintFile, lintProject, loadConfig, loadRulePack } from "textoneitor";
61
+
62
+ const r = lintText(texto, { config: { profile: "chat" }, format: "text" });
63
+ console.log(r.score.index, r.findings.map((f) => f.rule));
64
+ ```
65
+
66
+ ## Lo demás
67
+
68
+ El código, la guía de estilo para escribir en español que no suene a IA, el informe del benchmark y los adaptadores de pre-commit, GitHub Actions y Claude Code están en https://github.com/Josulo72/textoneitor
69
+
70
+ Business Source License 1.1: puedes usarlo, también en tu empresa y para tus clientes, pero no venderlo ni montar un servicio de pago con él. El 17 de septiembre de 2030 pasa a AGPL-3.0. Textos completos en `LICENSE` y `LICENSE-AGPL-3.0`.
@@ -0,0 +1,34 @@
1
+ import type { CompiledRule, Config, FileResult, RulePack, ScanResult } from "../contracts/index.js";
2
+ import { type LoadedConfig } from "../config/index.js";
3
+ import { type RunnerContext, type ScanOptions } from "../runner/index.js";
4
+ export type * from "../contracts/index.js";
5
+ export { SCHEMA_VERSION } from "../contracts/index.js";
6
+ export { defaultConfig, loadConfig, validateConfigObject, explainConfig, resolveEffectiveRules } from "../config/index.js";
7
+ export { reportJson, reportSarif, reportTerminal, render } from "../reporters/index.js";
8
+ export { createBaseline, readBaseline, writeBaseline, updateBaseline, applyBaseline } from "../baseline/index.js";
9
+ export { buildDocument } from "../document/index.js";
10
+ export { runRules } from "../rules/runtime/index.js";
11
+ export { computeScore } from "../scoring/index.js";
12
+ export { evaluatePolicy, discoverFiles } from "../runner/index.js";
13
+ export declare function toolVersion(): string;
14
+ /** Carga el Rule Pack oficial compilado (o uno alternativo). */
15
+ export declare function loadRulePack(file?: string): RulePack;
16
+ export interface ContextOptions {
17
+ /** Configuración ya cargada, objeto parcial, o ruta a archivo. Si se omite se busca desde `cwd`. */
18
+ config?: LoadedConfig | Partial<Config> | string;
19
+ cwd?: string;
20
+ rulepack?: string;
21
+ }
22
+ export declare function createContext(opts?: ContextOptions): RunnerContext;
23
+ /** Analiza un texto en memoria. */
24
+ export declare function lintText(text: string, opts?: ContextOptions & {
25
+ format?: "text" | "markdown";
26
+ path?: string;
27
+ }): FileResult;
28
+ /** Analiza un archivo del disco (respeta overrides por ruta). */
29
+ export declare function lintFile(file: string, opts?: ContextOptions): FileResult;
30
+ /** Analiza un proyecto completo (descubrimiento, gitignore, caché, baseline y política). */
31
+ export declare function lintProject(opts?: ContextOptions & ScanOptions): ScanResult;
32
+ /** Devuelve la regla compilada y su documentación. */
33
+ export declare function explainRule(id: string, rulepack?: string): CompiledRule | null;
34
+ export declare function listRules(rulepack?: string): CompiledRule[];
@@ -0,0 +1,98 @@
1
+ /**
2
+ * API programática. Mismo motor, misma configuración y misma puntuación que la CLI.
3
+ */
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { SCHEMA_VERSION } from "../contracts/index.js";
7
+ import { defaultConfig, loadConfig, mergeConfig, validateConfigObject } from "../config/index.js";
8
+ import { lintDocumentText, scanProject } from "../runner/index.js";
9
+ import { packageRoot, rulepackPath } from "../paths.js";
10
+ export { SCHEMA_VERSION } from "../contracts/index.js";
11
+ export { defaultConfig, loadConfig, validateConfigObject, explainConfig, resolveEffectiveRules } from "../config/index.js";
12
+ export { reportJson, reportSarif, reportTerminal, render } from "../reporters/index.js";
13
+ export { createBaseline, readBaseline, writeBaseline, updateBaseline, applyBaseline } from "../baseline/index.js";
14
+ export { buildDocument } from "../document/index.js";
15
+ export { runRules } from "../rules/runtime/index.js";
16
+ export { computeScore } from "../scoring/index.js";
17
+ export { evaluatePolicy, discoverFiles } from "../runner/index.js";
18
+ let cachedPack = null;
19
+ export function toolVersion() {
20
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot(), "package.json"), "utf8"));
21
+ return pkg.version;
22
+ }
23
+ /** Carga el Rule Pack oficial compilado (o uno alternativo). */
24
+ export function loadRulePack(file) {
25
+ if (!file && cachedPack)
26
+ return cachedPack;
27
+ const p = file ?? rulepackPath();
28
+ if (!fs.existsSync(p)) {
29
+ throw new Error(`No se encuentra el Rule Pack en ${p}. Ejecuta el build del paquete.`);
30
+ }
31
+ const pack = JSON.parse(fs.readFileSync(p, "utf8"));
32
+ if (pack.schema_version !== SCHEMA_VERSION)
33
+ throw new Error(`Rule Pack con schema_version ${pack.schema_version}; se esperaba ${SCHEMA_VERSION}`);
34
+ if (!file)
35
+ cachedPack = pack;
36
+ return pack;
37
+ }
38
+ export function createContext(opts = {}) {
39
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
40
+ let loaded;
41
+ if (opts.config && typeof opts.config === "object" && "config" in opts.config && "root" in opts.config) {
42
+ loaded = opts.config;
43
+ }
44
+ else if (typeof opts.config === "string") {
45
+ loaded = loadConfig({ cwd, file: opts.config });
46
+ }
47
+ else if (opts.config && typeof opts.config === "object") {
48
+ const issues = validateConfigObject(opts.config);
49
+ if (issues.length)
50
+ throw new Error(`Configuración inválida: ${issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
51
+ loaded = { config: mergeConfig(defaultConfig(), opts.config), file: null, root: cwd, issues: [] };
52
+ }
53
+ else {
54
+ loaded = loadConfig({ cwd });
55
+ }
56
+ if (loaded.issues.length)
57
+ throw new Error(`Configuración inválida en ${loaded.file}: ${loaded.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
58
+ return { config: loaded.config, root: loaded.root, pack: loadRulePack(opts.rulepack), toolVersion: toolVersion() };
59
+ }
60
+ /**
61
+ * Una opción desconocida se ignoraría sin avisar y el análisis saldría con la configuración del proyecto:
62
+ * `lintText(t, { profile: "chat" })` no aplica el perfil. Mejor fallar diciendo dónde va.
63
+ */
64
+ function checkOptions(opts, allowed) {
65
+ for (const k of Object.keys(opts)) {
66
+ if (allowed.includes(k))
67
+ continue;
68
+ const hint = k in defaultConfig() ? `; va dentro de config: { ${k}: … }` : "";
69
+ throw new Error(`Opción desconocida «${k}»${hint}`);
70
+ }
71
+ }
72
+ /** Analiza un texto en memoria. */
73
+ export function lintText(text, opts = {}) {
74
+ checkOptions(opts, ["config", "cwd", "rulepack", "format", "path"]);
75
+ const ctx = createContext(opts);
76
+ return lintDocumentText(text, ctx, { relPath: opts.path, format: opts.format ?? (opts.path ? undefined : "text") });
77
+ }
78
+ /** Analiza un archivo del disco (respeta overrides por ruta). */
79
+ export function lintFile(file, opts = {}) {
80
+ checkOptions(opts, ["config", "cwd", "rulepack"]);
81
+ const ctx = createContext(opts);
82
+ const abs = path.resolve(ctx.root, file);
83
+ const rel = path.relative(ctx.root, abs).replace(/\\/g, "/");
84
+ return lintDocumentText(fs.readFileSync(abs, "utf8"), ctx, { relPath: rel });
85
+ }
86
+ /** Analiza un proyecto completo (descubrimiento, gitignore, caché, baseline y política). */
87
+ export function lintProject(opts = {}) {
88
+ checkOptions(opts, ["config", "cwd", "rulepack", "targets", "noCache", "baseline"]);
89
+ const ctx = createContext(opts);
90
+ return scanProject(ctx, { targets: opts.targets, noCache: opts.noCache, baseline: opts.baseline });
91
+ }
92
+ /** Devuelve la regla compilada y su documentación. */
93
+ export function explainRule(id, rulepack) {
94
+ return loadRulePack(rulepack).rules.find((r) => r.id === id) ?? null;
95
+ }
96
+ export function listRules(rulepack) {
97
+ return loadRulePack(rulepack).rules;
98
+ }
@@ -0,0 +1,20 @@
1
+ import type { BaselineEntry, BaselineFile, FileResult } from "../contracts/index.js";
2
+ export declare function readBaseline(file: string): BaselineFile;
3
+ export declare function writeBaseline(file: string, data: BaselineFile): void;
4
+ /** Construye entradas de baseline a partir de resultados (solo hallazgos no suprimidos inline). */
5
+ export declare function entriesFromResults(files: FileResult[], reason?: string): BaselineEntry[];
6
+ export declare function createBaseline(files: FileResult[], reason?: string, now?: Date): BaselineFile;
7
+ /**
8
+ * Marca como suprimidos por baseline los hallazgos cuya huella está en la baseline.
9
+ * Devuelve estadísticas: coincidencias y entradas obsoletas (ya no aparecen).
10
+ */
11
+ export declare function applyBaseline(files: FileResult[], baseline: BaselineFile): {
12
+ matched: number;
13
+ stale: BaselineEntry[];
14
+ };
15
+ /** Actualiza una baseline: elimina obsoletas de los archivos escaneados y conserva el resto; no añade hallazgos nuevos salvo que se indique. */
16
+ export declare function updateBaseline(existing: BaselineFile, files: FileResult[], opts: {
17
+ addNew: boolean;
18
+ reason?: string;
19
+ now?: Date;
20
+ }): BaselineFile;
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { SCHEMA_VERSION } from "../contracts/index.js";
4
+ export function readBaseline(file) {
5
+ const raw = JSON.parse(fs.readFileSync(file, "utf8"));
6
+ if (raw.schema_version !== SCHEMA_VERSION)
7
+ throw new Error(`baseline: schema_version ${raw.schema_version} no soportada`);
8
+ if (!Array.isArray(raw.entries))
9
+ throw new Error("baseline: falta entries");
10
+ return raw;
11
+ }
12
+ export function writeBaseline(file, data) {
13
+ fs.mkdirSync(path.dirname(file), { recursive: true });
14
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n", "utf8");
15
+ }
16
+ /** Construye entradas de baseline a partir de resultados (solo hallazgos no suprimidos inline). */
17
+ export function entriesFromResults(files, reason) {
18
+ const entries = [];
19
+ for (const f of files) {
20
+ for (const x of f.findings) {
21
+ if (x.suppressed?.by === "inline")
22
+ continue;
23
+ const e = { rule: x.rule, path: f.path.replace(/\\/g, "/"), fingerprint: x.fingerprint };
24
+ if (reason)
25
+ e.reason = reason;
26
+ entries.push(e);
27
+ }
28
+ }
29
+ entries.sort((a, b) => a.path.localeCompare(b.path, "en") || a.rule.localeCompare(b.rule, "en") || a.fingerprint.localeCompare(b.fingerprint, "en"));
30
+ return entries;
31
+ }
32
+ export function createBaseline(files, reason, now = new Date()) {
33
+ return { schema_version: SCHEMA_VERSION, created: now.toISOString(), entries: entriesFromResults(files, reason) };
34
+ }
35
+ /**
36
+ * Marca como suprimidos por baseline los hallazgos cuya huella está en la baseline.
37
+ * Devuelve estadísticas: coincidencias y entradas obsoletas (ya no aparecen).
38
+ */
39
+ export function applyBaseline(files, baseline) {
40
+ const index = new Map();
41
+ for (const e of baseline.entries)
42
+ index.set(`${e.path}\0${e.fingerprint}`, e);
43
+ const seen = new Set();
44
+ let matched = 0;
45
+ for (const f of files) {
46
+ const p = f.path.replace(/\\/g, "/");
47
+ for (const x of f.findings) {
48
+ if (x.suppressed)
49
+ continue;
50
+ const key = `${p}\0${x.fingerprint}`;
51
+ const e = index.get(key);
52
+ if (e) {
53
+ x.suppressed = { by: "baseline", reason: e.reason };
54
+ seen.add(key);
55
+ matched++;
56
+ }
57
+ }
58
+ }
59
+ const scanned = new Set(files.map((f) => f.path.replace(/\\/g, "/")));
60
+ const stale = baseline.entries.filter((e) => scanned.has(e.path) && !seen.has(`${e.path}\0${e.fingerprint}`));
61
+ return { matched, stale };
62
+ }
63
+ /** Actualiza una baseline: elimina obsoletas de los archivos escaneados y conserva el resto; no añade hallazgos nuevos salvo que se indique. */
64
+ export function updateBaseline(existing, files, opts) {
65
+ const scanned = new Set(files.map((f) => f.path.replace(/\\/g, "/")));
66
+ const current = new Set(entriesFromResults(files).map((e) => `${e.path}\0${e.fingerprint}`));
67
+ const kept = existing.entries.filter((e) => !scanned.has(e.path) || current.has(`${e.path}\0${e.fingerprint}`));
68
+ const entries = [...kept];
69
+ if (opts.addNew) {
70
+ const have = new Set(kept.map((e) => `${e.path}\0${e.fingerprint}`));
71
+ for (const e of entriesFromResults(files, opts.reason)) {
72
+ const k = `${e.path}\0${e.fingerprint}`;
73
+ if (!have.has(k)) {
74
+ entries.push(e);
75
+ have.add(k);
76
+ }
77
+ }
78
+ }
79
+ entries.sort((a, b) => a.path.localeCompare(b.path, "en") || a.rule.localeCompare(b.rule, "en") || a.fingerprint.localeCompare(b.fingerprint, "en"));
80
+ return { schema_version: SCHEMA_VERSION, created: (opts.now ?? new Date()).toISOString(), entries };
81
+ }