textoneitor 0.0.0-stage → 1.2.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.
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 +29861 -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 +357 -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 +68 -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 +636 -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 +16 -0
  51. package/dist/runner/index.js +171 -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 +11018 -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
@@ -0,0 +1,4 @@
1
+ /** Raíz del paquete (packages/linter), tanto desde src/ (tests) como desde dist/. */
2
+ export declare function packageRoot(): string;
3
+ export declare function rulesDir(): string;
4
+ export declare function rulepackPath(): string;
package/dist/paths.js ADDED
@@ -0,0 +1,14 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ /** Raíz del paquete (packages/linter), tanto desde src/ (tests) como desde dist/. */
4
+ export function packageRoot() {
5
+ const here = path.dirname(fileURLToPath(import.meta.url));
6
+ // src/paths.ts o dist/paths.js -> un nivel arriba.
7
+ return path.resolve(here, "..");
8
+ }
9
+ export function rulesDir() {
10
+ return path.join(packageRoot(), "rules");
11
+ }
12
+ export function rulepackPath() {
13
+ return path.join(packageRoot(), "rulepack", "rulepack.json");
14
+ }
@@ -0,0 +1,29 @@
1
+ import type { CompiledRule, ScanResult } from "../contracts/index.js";
2
+ export type ReporterName = "terminal" | "json" | "sarif" | "revision";
3
+ /** JSON determinista: mismas claves, mismo orden, sin tiempos. */
4
+ export declare function reportJson(result: ScanResult, opts?: {
5
+ pretty?: boolean;
6
+ includeTimings?: boolean;
7
+ }): string;
8
+ export declare function reportTerminal(result: ScanResult, opts?: {
9
+ color?: boolean;
10
+ verbose?: boolean;
11
+ }): string;
12
+ export declare function reportSarif(result: ScanResult, rules: CompiledRule[], opts?: {
13
+ uriBase?: string;
14
+ }): string;
15
+ /**
16
+ * Orientación para quien vaya a reescribir el texto (el asistente, desde los hooks o /revisar). Es orientación y no una
17
+ * lista de órdenes: quien reescribe decide qué hallazgos acepta, cuáles ignora y cómo los adapta al contexto.
18
+ * Agrupa por regla para no repetir la orientación en cada hallazgo: qué busca la regla, la orientación (`rewrite_guidance`)
19
+ * y dónde está cada caso. Texto plano, sin color y determinista. Sin --verbose lleva error y warning; con --verbose
20
+ * también los info. Los suprimidos no salen nunca.
21
+ */
22
+ export declare function reportRevision(result: ScanResult, rules: CompiledRule[], opts?: {
23
+ verbose?: boolean;
24
+ }): string;
25
+ export declare function render(name: ReporterName, result: ScanResult, rules: CompiledRule[], opts?: {
26
+ color?: boolean;
27
+ verbose?: boolean;
28
+ uriBase?: string;
29
+ }): string;
@@ -0,0 +1,182 @@
1
+ /* ---------------- JSON ---------------- */
2
+ /** JSON determinista: mismas claves, mismo orden, sin tiempos. */
3
+ export function reportJson(result, opts = {}) {
4
+ const clean = {
5
+ ...result,
6
+ durationMs: opts.includeTimings ? result.durationMs : 0,
7
+ files: result.files.map((f) => {
8
+ const { fromCache: _fc, ...rest } = f;
9
+ return { ...rest, durationMs: opts.includeTimings ? f.durationMs : 0 };
10
+ }),
11
+ };
12
+ return JSON.stringify(clean, null, opts.pretty === false ? undefined : 2) + "\n";
13
+ }
14
+ /* ---------------- Terminal ---------------- */
15
+ const COLORS = {
16
+ reset: "\x1b[0m",
17
+ dim: "\x1b[2m",
18
+ bold: "\x1b[1m",
19
+ red: "\x1b[31m",
20
+ yellow: "\x1b[33m",
21
+ cyan: "\x1b[36m",
22
+ green: "\x1b[32m",
23
+ };
24
+ export function reportTerminal(result, opts = {}) {
25
+ const c = (code, s) => (opts.color ? `${COLORS[code]}${s}${COLORS.reset}` : s);
26
+ const lines = [];
27
+ const levelTag = (f) => f.level === "error" ? c("red", "error ") : f.level === "warning" ? c("yellow", "warning") : c("cyan", "info ");
28
+ for (const file of result.files) {
29
+ const active = file.findings.filter((f) => !f.suppressed);
30
+ const suppressed = file.findings.length - active.length;
31
+ if (active.length === 0 && !opts.verbose)
32
+ continue;
33
+ const idx = file.score.index === null ? c("dim", `índice: n/d (${file.score.eligibleWords} palabras, mínimo ${file.score.minWords})`) : `índice ${c("bold", String(file.score.index))}/100`;
34
+ lines.push(`${c("bold", file.path)} ${idx}${suppressed ? c("dim", ` (${suppressed} suprimidos)`) : ""}`);
35
+ for (const f of active) {
36
+ const pos = `${f.range.start.line}:${f.range.start.column}`;
37
+ lines.push(` ${pos.padEnd(8)} ${levelTag(f)} ${f.message} ${c("dim", f.rule)}`);
38
+ if (f.snippet && opts.verbose)
39
+ lines.push(` ${c("dim", `«${f.snippet}»`)}`);
40
+ }
41
+ if (file.score.contributors.length && opts.verbose) {
42
+ lines.push(` ${c("dim", "contribuyentes: " + file.score.contributors.slice(0, 5).map((x) => `${x.rule} (${x.findings})`).join(", "))}`);
43
+ }
44
+ lines.push("");
45
+ }
46
+ const { counts } = result.policy;
47
+ const total = counts.error + counts.warning + counts.info;
48
+ const summary = `${result.files.length} archivo(s), ${total} hallazgo(s): ${counts.error} error, ${counts.warning} warning, ${counts.info} info` + (counts.suppressed ? `, ${counts.suppressed} suprimido(s)` : "");
49
+ lines.push(summary);
50
+ if (result.baseline)
51
+ lines.push(c("dim", `baseline ${result.baseline.path}: ${result.baseline.matched} coincidencias, ${result.baseline.stale} obsoletas`));
52
+ if (result.policy.ok)
53
+ lines.push(c("green", "OK") + c("dim", ` (fail_on: ${result.policy.failOn})`));
54
+ else {
55
+ lines.push(c("red", "FALLO"));
56
+ for (const r of result.policy.reasons)
57
+ lines.push(` - ${r}`);
58
+ }
59
+ return lines.join("\n") + "\n";
60
+ }
61
+ /* ---------------- SARIF 2.1.0 ---------------- */
62
+ export function reportSarif(result, rules, opts = {}) {
63
+ const used = new Set(result.files.flatMap((f) => f.findings.map((x) => x.rule)));
64
+ const ruleList = rules.filter((r) => used.has(r.id)).sort((a, b) => a.id.localeCompare(b.id, "en"));
65
+ const ruleIndex = new Map(ruleList.map((r, i) => [r.id, i]));
66
+ const sarif = {
67
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
68
+ version: "2.1.0",
69
+ runs: [
70
+ {
71
+ tool: {
72
+ driver: {
73
+ name: result.tool.name,
74
+ version: result.tool.version,
75
+ informationUri: "https://github.com/Josulo72/textoneitor",
76
+ rules: ruleList.map((r) => ({
77
+ id: r.id,
78
+ name: r.title,
79
+ shortDescription: { text: r.summary },
80
+ fullDescription: { text: r.explanation },
81
+ help: { text: r.rewrite_guidance },
82
+ defaultConfiguration: { level: sarifLevel(r.default_level) },
83
+ properties: { category: r.category, status: r.status, revision: r.revision },
84
+ })),
85
+ },
86
+ },
87
+ originalUriBaseIds: { PROJECTROOT: { uri: opts.uriBase ?? "file:///" } },
88
+ results: result.files.flatMap((f) => f.findings.map((x) => ({
89
+ ruleId: x.rule,
90
+ ruleIndex: ruleIndex.get(x.rule) ?? -1,
91
+ level: sarifLevel(x.level),
92
+ message: { text: x.message },
93
+ locations: [
94
+ {
95
+ physicalLocation: {
96
+ // SARIF pide una referencia URI válida: espacios, «ñ» o «<texto>» van codificados por segmento.
97
+ artifactLocation: { uri: f.path.replace(/\\/g, "/").split("/").map(encodeURIComponent).join("/"), uriBaseId: "PROJECTROOT" },
98
+ region: {
99
+ startLine: x.range.start.line,
100
+ startColumn: x.range.start.column,
101
+ endLine: x.range.end.line,
102
+ endColumn: x.range.end.column,
103
+ ...(x.snippet ? { snippet: { text: x.snippet } } : {}),
104
+ },
105
+ },
106
+ },
107
+ ],
108
+ partialFingerprints: { "textoneitor/v1": x.fingerprint },
109
+ ...(x.suppressed ? { suppressions: [{ kind: x.suppressed.by === "inline" ? "inSource" : "external", ...(x.suppressed.reason ? { justification: x.suppressed.reason } : {}) }] } : {}),
110
+ }))),
111
+ properties: {
112
+ policy: result.policy,
113
+ scores: Object.fromEntries(result.files.map((f) => [f.path, f.score.index])),
114
+ },
115
+ },
116
+ ],
117
+ };
118
+ return JSON.stringify(sarif, null, 2) + "\n";
119
+ }
120
+ function sarifLevel(l) {
121
+ return l === "error" ? "error" : l === "warning" ? "warning" : l === "info" ? "note" : "none";
122
+ }
123
+ /* ---------------- Revisión ---------------- */
124
+ /**
125
+ * Orientación para quien vaya a reescribir el texto (el asistente, desde los hooks o /revisar). Es orientación y no una
126
+ * lista de órdenes: quien reescribe decide qué hallazgos acepta, cuáles ignora y cómo los adapta al contexto.
127
+ * Agrupa por regla para no repetir la orientación en cada hallazgo: qué busca la regla, la orientación (`rewrite_guidance`)
128
+ * y dónde está cada caso. Texto plano, sin color y determinista. Sin --verbose lleva error y warning; con --verbose
129
+ * también los info. Los suprimidos no salen nunca.
130
+ */
131
+ export function reportRevision(result, rules, opts = {}) {
132
+ const byId = new Map(rules.map((r) => [r.id, r]));
133
+ const out = [];
134
+ const cabecera = [
135
+ "Orientación para revisar el texto. Cada hallazgo es una señal, no una orden: acéptalo, ignóralo o reinterprétalo según el contexto.",
136
+ "",
137
+ ];
138
+ for (const file of result.files) {
139
+ const active = file.findings.filter((f) => !f.suppressed && (opts.verbose || f.level !== "info"));
140
+ if (!active.length)
141
+ continue;
142
+ const idx = file.score.index === null ? "sin índice (texto corto)" : `índice ${file.score.index}/100`;
143
+ out.push(`${file.path} (${idx})`, "");
144
+ const groups = new Map();
145
+ for (const f of active) {
146
+ const g = groups.get(f.rule);
147
+ if (g)
148
+ g.push(f);
149
+ else
150
+ groups.set(f.rule, [f]);
151
+ }
152
+ for (const [id, fs] of groups) {
153
+ const r = byId.get(id);
154
+ out.push(`${id}${r ? `: ${r.title}` : ""}`);
155
+ if (r)
156
+ out.push(` Qué busca: ${r.summary}`, ` Orientación: ${r.rewrite_guidance}`);
157
+ // Las reglas que miden la estructura del texto entero (longitud de frase) no señalan un sitio: su «fragmento» es solo el principio.
158
+ const wholeText = r?.scope === "document" && r.detector === "structure";
159
+ for (const f of fs) {
160
+ const pos = `${f.range.start.line}:${f.range.start.column}`;
161
+ const where = wholeText ? " Afecta a todo el texto." : f.snippet ? ` Fragmento: "${f.snippet.replace(/\s+/g, " ")}"` : "";
162
+ out.push(` - ${wholeText ? "" : `${pos} `}${f.message}${where}`);
163
+ }
164
+ out.push("");
165
+ }
166
+ }
167
+ if (!out.length)
168
+ return "Nada que revisar.\n";
169
+ return [...cabecera, ...out].join("\n");
170
+ }
171
+ export function render(name, result, rules, opts = {}) {
172
+ switch (name) {
173
+ case "json":
174
+ return reportJson(result);
175
+ case "sarif":
176
+ return reportSarif(result, rules, { uriBase: opts.uriBase });
177
+ case "revision":
178
+ return reportRevision(result, rules, { verbose: opts.verbose });
179
+ default:
180
+ return reportTerminal(result, { color: opts.color, verbose: opts.verbose });
181
+ }
182
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Entrada de build: compila las reglas oficiales y escribe el Rule Pack y la documentación de reglas.
3
+ * Uso: node dist/rules/compiler/build.js
4
+ */
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { parse as parseYaml } from "yaml";
8
+ import { compileRules, renderRulesDoc } from "./index.js";
9
+ import { packageRoot, rulepackPath, rulesDir } from "../../paths.js";
10
+ const root = packageRoot();
11
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
12
+ const policyFile = path.resolve(root, "..", "..", "quality-policy.yml");
13
+ const policy = fs.existsSync(policyFile)
14
+ ? parseYaml(fs.readFileSync(policyFile, "utf8"))
15
+ : {};
16
+ const result = compileRules({
17
+ rulesDir: rulesDir(),
18
+ version: pkg.version,
19
+ minPositive: policy.rules?.min_positive_examples,
20
+ minNegative: policy.rules?.min_negative_examples,
21
+ minReviewers: policy.rules?.min_reviewers,
22
+ maxMsPerRule: policy.regex_safety?.max_ms_per_rule_on_1mb,
23
+ adversarialBytes: 1_000_000,
24
+ });
25
+ for (const i of result.issues)
26
+ console.error(`[${i.severity}] ${i.rule}: ${i.message}`);
27
+ const errors = result.issues.filter((i) => i.severity === "error");
28
+ if (errors.length) {
29
+ console.error(`\nCompilación fallida: ${errors.length} error(es).`);
30
+ process.exit(1);
31
+ }
32
+ const stable = result.pack.rules.filter((r) => r.status === "stable").length;
33
+ const min = policy.rules?.stable_min ?? 0;
34
+ const max = policy.rules?.stable_max ?? Infinity;
35
+ if (stable < min || stable > max) {
36
+ console.error(`Reglas stable: ${stable}; la política exige entre ${min} y ${max}.`);
37
+ process.exit(1);
38
+ }
39
+ const out = rulepackPath();
40
+ fs.mkdirSync(path.dirname(out), { recursive: true });
41
+ fs.writeFileSync(out, JSON.stringify(result.pack, null, 2) + "\n", "utf8");
42
+ const docOut = path.resolve(root, "..", "..", "docs", "rules.md");
43
+ fs.writeFileSync(docOut, renderRulesDoc(result.definitions, result.pack) + "\n", "utf8");
44
+ const slowest = Object.entries(result.timings).sort((a, b) => b[1] - a[1]).slice(0, 3);
45
+ console.log(`Rule Pack: ${result.pack.rules.length} reglas (${stable} stable) -> ${path.relative(process.cwd(), out)}`);
46
+ console.log(`Más lentas (1 MB adversarial): ${slowest.map(([id, ms]) => `${id} ${ms} ms`).join(", ")}`);
@@ -0,0 +1,40 @@
1
+ import type { CompiledRule, Level, ProfileName, RuleDefinition, RulePack } from "../../contracts/index.js";
2
+ import { type SafetyPolicy } from "./safety.js";
3
+ export interface CompileIssue {
4
+ rule: string;
5
+ severity: "error" | "warning";
6
+ message: string;
7
+ }
8
+ export interface CompileOptions {
9
+ rulesDir: string;
10
+ version: string;
11
+ safety?: SafetyPolicy;
12
+ /** Bytes del texto adversarial para la prueba de tiempo por regla. */
13
+ adversarialBytes?: number;
14
+ maxMsPerRule?: number;
15
+ /** Requisitos mínimos de fixtures. */
16
+ minPositive?: number;
17
+ minNegative?: number;
18
+ minReviewers?: number;
19
+ }
20
+ export interface CompileResult {
21
+ pack: RulePack;
22
+ issues: CompileIssue[];
23
+ definitions: RuleDefinition[];
24
+ timings: Record<string, number>;
25
+ }
26
+ export declare function loadLexicons(dir: string): Map<string, string[]>;
27
+ export declare function loadProfiles(dir: string): Map<ProfileName, Record<string, Level>>;
28
+ export declare function loadDefinitions(dir: string): {
29
+ defs: RuleDefinition[];
30
+ files: Map<string, string>;
31
+ };
32
+ /** Traduce `conditions` del YAML a `params` del detector con léxicos resueltos. Devuelve también los patrones a auditar. */
33
+ export declare function resolveConditions(def: RuleDefinition, lexicons: Map<string, string[]>): {
34
+ params: Record<string, unknown>;
35
+ patterns: string[];
36
+ };
37
+ export declare function compileRules(opts: CompileOptions): CompileResult;
38
+ export declare function runFixtures(rule: CompiledRule, def: Pick<RuleDefinition, "examples">): string[];
39
+ /** Documentación de reglas en Markdown, generada del pack. */
40
+ export declare function renderRulesDoc(defs: RuleDefinition[], pack: RulePack): string;
@@ -0,0 +1,343 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { parse as parseYaml } from "yaml";
4
+ import { Ajv } from "ajv";
5
+ import { SCHEMA_VERSION } from "../../contracts/index.js";
6
+ import { buildDocument } from "../../document/index.js";
7
+ import { runRules } from "../runtime/index.js";
8
+ import { adversarialText, checkPattern, DEFAULT_SAFETY } from "./safety.js";
9
+ import { packageRoot } from "../../paths.js";
10
+ const PROFILE_NAMES = ["general", "tecnico", "academico", "marketing", "chat", "correo", "readme", "redes"];
11
+ export function loadLexicons(dir) {
12
+ const out = new Map();
13
+ if (!fs.existsSync(dir))
14
+ return out;
15
+ for (const f of fs.readdirSync(dir).filter((x) => /\.ya?ml$/.test(x)).sort()) {
16
+ const raw = parseYaml(fs.readFileSync(path.join(dir, f), "utf8"));
17
+ const name = raw?.name ?? f.replace(/\.ya?ml$/, "");
18
+ if (!Array.isArray(raw?.terms))
19
+ throw new Error(`léxico ${f}: falta terms`);
20
+ const terms = raw.terms.map((t) => String(t).trim()).filter(Boolean);
21
+ out.set(name, [...new Set(terms)]);
22
+ }
23
+ return out;
24
+ }
25
+ export function loadProfiles(dir) {
26
+ const out = new Map();
27
+ if (!fs.existsSync(dir))
28
+ return out;
29
+ for (const name of PROFILE_NAMES) {
30
+ const f = path.join(dir, `${name}.yml`);
31
+ if (!fs.existsSync(f))
32
+ continue;
33
+ const raw = parseYaml(fs.readFileSync(f, "utf8"));
34
+ out.set(name, raw?.rules ?? {});
35
+ }
36
+ return out;
37
+ }
38
+ export function loadDefinitions(dir) {
39
+ const defs = [];
40
+ const files = new Map();
41
+ for (const f of fs.readdirSync(dir).filter((x) => /\.ya?ml$/.test(x)).sort()) {
42
+ const full = path.join(dir, f);
43
+ const raw = parseYaml(fs.readFileSync(full, "utf8"));
44
+ defs.push(raw);
45
+ files.set(raw?.id ?? f, full);
46
+ }
47
+ return { defs, files };
48
+ }
49
+ function schemaValidator() {
50
+ const schemaPath = path.join(packageRoot(), "schemas", "rule.schema.json");
51
+ const schema = JSON.parse(fs.readFileSync(schemaPath, "utf8"));
52
+ const ajv = new Ajv({ allErrors: true, strict: false });
53
+ return ajv.compile(schema);
54
+ }
55
+ function resolveTerms(c, lexicons, where) {
56
+ const out = [];
57
+ if (typeof c.lexicon === "string") {
58
+ const l = lexicons.get(c.lexicon);
59
+ if (!l)
60
+ throw new Error(`${where}: léxico desconocido "${c.lexicon}"`);
61
+ out.push(...l);
62
+ }
63
+ if (Array.isArray(c.lexicons)) {
64
+ for (const n of c.lexicons) {
65
+ const l = lexicons.get(n);
66
+ if (!l)
67
+ throw new Error(`${where}: léxico desconocido "${n}"`);
68
+ out.push(...l);
69
+ }
70
+ }
71
+ if (Array.isArray(c.terms))
72
+ out.push(...c.terms.map(String));
73
+ if (out.length === 0)
74
+ throw new Error(`${where}: sin términos (lexicon/terms)`);
75
+ return [...new Set(out)];
76
+ }
77
+ /** Traduce `conditions` del YAML a `params` del detector con léxicos resueltos. Devuelve también los patrones a auditar. */
78
+ export function resolveConditions(def, lexicons) {
79
+ const c = def.conditions;
80
+ const patterns = [];
81
+ const auditTerms = (terms) => {
82
+ for (const t of terms) {
83
+ if (t.startsWith("re:"))
84
+ patterns.push(t.slice(3));
85
+ else if (t.startsWith("raw:"))
86
+ patterns.push(t.slice(4));
87
+ }
88
+ };
89
+ switch (def.detector) {
90
+ case "regex": {
91
+ if (!Array.isArray(c.patterns) || c.patterns.length === 0)
92
+ throw new Error(`${def.id}: regex requiere patterns`);
93
+ const ps = c.patterns.map(String);
94
+ patterns.push(...ps);
95
+ return { params: { patterns: ps, flags: c.flags ?? "giu", anchor: c.anchor, kinds: c.kinds }, patterns };
96
+ }
97
+ case "lexicon": {
98
+ const terms = resolveTerms(c, lexicons, def.id);
99
+ auditTerms(terms);
100
+ return { params: { terms, kinds: c.kinds }, patterns };
101
+ }
102
+ case "sequence": {
103
+ if (!Array.isArray(c.steps) || c.steps.length < 2)
104
+ throw new Error(`${def.id}: sequence requiere al menos 2 steps`);
105
+ const steps = c.steps.map((s, i) => resolveTerms(s, lexicons, `${def.id}.steps[${i}]`));
106
+ steps.forEach(auditTerms);
107
+ return { params: { steps, max_gap: Number(c.max_gap ?? 8) }, patterns };
108
+ }
109
+ case "density": {
110
+ const terms = resolveTerms(c, lexicons, def.id);
111
+ auditTerms(terms);
112
+ if (typeof c.min_count !== "number")
113
+ throw new Error(`${def.id}: density requiere min_count`);
114
+ return {
115
+ params: {
116
+ terms,
117
+ window: c.window ?? "document",
118
+ unit: c.unit ?? "match",
119
+ min_count: c.min_count,
120
+ per_1000: c.per_1000,
121
+ ratio: c.ratio,
122
+ min_words: c.min_words,
123
+ kinds: c.kinds,
124
+ },
125
+ patterns,
126
+ };
127
+ }
128
+ case "repetition": {
129
+ if (!["sentence_start", "block_start", "ngram"].includes(String(c.unit)))
130
+ throw new Error(`${def.id}: repetition.unit inválido`);
131
+ return { params: { unit: c.unit, n: Number(c.n ?? 2), min_repeats: Number(c.min_repeats ?? 3), consecutive: c.consecutive }, patterns };
132
+ }
133
+ case "structure": {
134
+ if (typeof c.kind !== "string")
135
+ throw new Error(`${def.id}: structure requiere kind`);
136
+ return { params: { ...c }, patterns };
137
+ }
138
+ case "cooccurrence": {
139
+ if (!Array.isArray(c.groups) || c.groups.length < 2)
140
+ throw new Error(`${def.id}: cooccurrence requiere al menos 2 groups`);
141
+ const groups = c.groups.map((g, i) => resolveTerms(g, lexicons, `${def.id}.groups[${i}]`));
142
+ groups.forEach(auditTerms);
143
+ return { params: { groups, window: c.window ?? "sentence", ordered: c.ordered ?? true, anchor: c.anchor }, patterns };
144
+ }
145
+ }
146
+ }
147
+ export function compileRules(opts) {
148
+ const issues = [];
149
+ const safety = opts.safety ?? DEFAULT_SAFETY;
150
+ const lexicons = loadLexicons(path.join(opts.rulesDir, "lexicons"));
151
+ const profiles = loadProfiles(path.join(opts.rulesDir, "profiles"));
152
+ const { defs, files } = loadDefinitions(path.join(opts.rulesDir, "definitions"));
153
+ const validate = schemaValidator();
154
+ const seen = new Set();
155
+ const compiled = [];
156
+ const timings = {};
157
+ const minPos = opts.minPositive ?? 2;
158
+ const minNeg = opts.minNegative ?? 2;
159
+ const minRev = opts.minReviewers ?? 1;
160
+ for (const def of defs) {
161
+ const id = def?.id ?? files.keys().next().value ?? "?";
162
+ const err = (message) => issues.push({ rule: id, severity: "error", message });
163
+ // 1. Schema
164
+ if (!validate(def)) {
165
+ for (const e of validate.errors ?? [])
166
+ err(`schema ${e.instancePath || "/"}: ${e.message}`);
167
+ continue;
168
+ }
169
+ // 2. IDs
170
+ if (seen.has(def.id)) {
171
+ err("id duplicado");
172
+ continue;
173
+ }
174
+ seen.add(def.id);
175
+ if (!def.id.startsWith(`${def.category}/`))
176
+ err(`el id debe empezar por la categoría "${def.category}/"`);
177
+ const expectedFile = def.id.replace("/", "--") + ".yml";
178
+ if (path.basename(files.get(def.id) ?? "") !== expectedFile)
179
+ err(`el archivo debe llamarse ${expectedFile}`);
180
+ // 3. Léxicos y parámetros
181
+ let params;
182
+ let patterns;
183
+ try {
184
+ ({ params, patterns } = resolveConditions(def, lexicons));
185
+ }
186
+ catch (e) {
187
+ err(e.message);
188
+ continue;
189
+ }
190
+ const exceptions = {};
191
+ if (def.exceptions?.patterns) {
192
+ exceptions.patterns = def.exceptions.patterns.map(String);
193
+ patterns.push(...exceptions.patterns);
194
+ }
195
+ if (def.exceptions?.lexicon) {
196
+ const l = lexicons.get(def.exceptions.lexicon);
197
+ if (!l)
198
+ err(`léxico de excepción desconocido "${def.exceptions.lexicon}"`);
199
+ else {
200
+ exceptions.patterns = [...(exceptions.patterns ?? []), ...l.map((t) => (t.startsWith("re:") ? t.slice(3) : escapeForRe(t)))];
201
+ }
202
+ }
203
+ // 4. Seguridad de patrones
204
+ for (const p of patterns)
205
+ for (const m of checkPattern(p, safety))
206
+ err(`patrón "${p}": ${m}`);
207
+ // Requisitos de estado
208
+ if (def.status === "stable") {
209
+ if (def.examples.positive.length < minPos)
210
+ err(`stable requiere >= ${minPos} ejemplos positivos`);
211
+ if (def.examples.negative.length < minNeg)
212
+ err(`stable requiere >= ${minNeg} ejemplos negativos`);
213
+ if (def.provenance.reviewed_by.length < minRev)
214
+ err(`stable requiere revisión (reviewed_by)`);
215
+ if (def.provenance.known_false_positives.length === 0)
216
+ err("stable requiere falsos positivos conocidos documentados");
217
+ if (!def.provenance.evidence.trim())
218
+ err("stable requiere evidencia");
219
+ }
220
+ else if (def.examples.positive.length + def.examples.negative.length === 0) {
221
+ err("toda regla necesita fixtures (examples)");
222
+ }
223
+ const prof = { ...(def.profiles ?? {}) };
224
+ for (const [pname, map] of profiles) {
225
+ if (map[def.id] !== undefined)
226
+ prof[pname] = map[def.id];
227
+ else if (map[`${def.category}/*`] !== undefined && prof[pname] === undefined)
228
+ prof[pname] = map[`${def.category}/*`];
229
+ }
230
+ const rule = {
231
+ id: def.id,
232
+ revision: def.revision,
233
+ status: def.status,
234
+ title: def.title,
235
+ summary: def.summary,
236
+ category: def.category,
237
+ scope: def.scope,
238
+ detector: def.detector,
239
+ params,
240
+ exceptions,
241
+ default_level: def.default_level,
242
+ score: def.score,
243
+ message: def.message,
244
+ explanation: def.explanation,
245
+ rewrite_guidance: def.rewrite_guidance,
246
+ profiles: prof,
247
+ };
248
+ if (issues.some((i) => i.rule === id && i.severity === "error"))
249
+ continue;
250
+ // 5. Fixtures
251
+ const fixtureIssues = runFixtures(rule, def);
252
+ for (const m of fixtureIssues)
253
+ err(m);
254
+ // Fixtures externas opcionales: rules/fixtures/<id con -->.yml
255
+ const fx = path.join(opts.rulesDir, "fixtures", def.id.replace("/", "--") + ".yml");
256
+ if (fs.existsSync(fx)) {
257
+ const raw = parseYaml(fs.readFileSync(fx, "utf8"));
258
+ for (const m of runFixtures(rule, { examples: raw }))
259
+ err(`fixture externa: ${m}`);
260
+ }
261
+ // Texto adversarial: tiempo por regla
262
+ const adv = buildDocument(adversarialText(opts.adversarialBytes ?? 200_000), { format: "text" });
263
+ const t0 = performance.now();
264
+ try {
265
+ runRules(adv, [rule]);
266
+ }
267
+ catch (e) {
268
+ err(`falla en texto adversarial: ${e.message}`);
269
+ }
270
+ const ms = performance.now() - t0;
271
+ timings[def.id] = Math.round(ms);
272
+ const budget = opts.maxMsPerRule ?? 250;
273
+ if (ms > budget)
274
+ err(`demasiado lenta en texto adversarial: ${Math.round(ms)} ms > ${budget} ms`);
275
+ if (!issues.some((i) => i.rule === id && i.severity === "error"))
276
+ compiled.push(rule);
277
+ }
278
+ // Los perfiles solo pueden nombrar reglas o categorías existentes.
279
+ const allIds = new Set(defs.map((d) => d?.id));
280
+ const allCats = new Set(defs.map((d) => `${d?.category}/*`));
281
+ for (const [pname, map] of profiles) {
282
+ for (const k of Object.keys(map)) {
283
+ if (!allIds.has(k) && !allCats.has(k))
284
+ issues.push({ rule: `profiles/${pname}`, severity: "error", message: `regla o categoría desconocida "${k}"` });
285
+ }
286
+ }
287
+ compiled.sort((a, b) => a.id.localeCompare(b.id, "en"));
288
+ const pack = {
289
+ schema_version: SCHEMA_VERSION,
290
+ name: "textoneitor/oficial",
291
+ version: opts.version,
292
+ generated_at: "build",
293
+ rules: compiled,
294
+ };
295
+ return { pack, issues, definitions: defs, timings };
296
+ }
297
+ function escapeForRe(s) {
298
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "\\s+");
299
+ }
300
+ export function runFixtures(rule, def) {
301
+ const errors = [];
302
+ const check = (kind, ex, i) => {
303
+ const doc = buildDocument(ex.text, { format: ex.format ?? "text" });
304
+ // Las fixtures prueban el detector: una regla desactivada por defecto (solo activa en algún perfil) se evalúa igual.
305
+ const levels = rule.default_level === "off" ? { [rule.id]: "info" } : undefined;
306
+ const found = runRules(doc, [rule], levels ? { levels } : undefined).length;
307
+ if (kind === "positive" && ex.expect === 0)
308
+ errors.push(`examples.positive[${i}] debe esperar >= 1`);
309
+ if (kind === "negative" && ex.expect !== 0)
310
+ errors.push(`examples.negative[${i}] debe esperar 0`);
311
+ if (found !== ex.expect)
312
+ errors.push(`examples.${kind}[${i}]: esperados ${ex.expect}, encontrados ${found}${ex.note ? ` (${ex.note})` : ""}`);
313
+ };
314
+ def.examples.positive.forEach((ex, i) => check("positive", ex, i));
315
+ def.examples.negative.forEach((ex, i) => check("negative", ex, i));
316
+ return errors;
317
+ }
318
+ /** Documentación de reglas en Markdown, generada del pack. */
319
+ export function renderRulesDoc(defs, pack) {
320
+ const byId = new Map(defs.map((d) => [d.id, d]));
321
+ const lines = ["# Reglas oficiales", "", `Rule Pack \`${pack.name}\` v${pack.version}. ${pack.rules.length} reglas compiladas.`, ""];
322
+ lines.push("| Regla | Estado | Categoría | Detector | Nivel | Peso |", "|---|---|---|---|---|---|");
323
+ for (const r of pack.rules)
324
+ lines.push(`| \`${r.id}\` | ${r.status} | ${r.category} | ${r.detector} | ${r.default_level} | ${r.score.weight} (cap ${r.score.cap}) |`);
325
+ lines.push("");
326
+ for (const r of pack.rules) {
327
+ const d = byId.get(r.id);
328
+ lines.push(`## ${r.id}`, "", `**${r.title}** — ${r.summary}`, "", r.explanation, "", `**Orientación:** ${r.rewrite_guidance}`, "");
329
+ if (d) {
330
+ lines.push(`**Evidencia:** ${d.provenance.evidence}`, "");
331
+ if (d.provenance.known_false_positives.length) {
332
+ lines.push("**Falsos positivos conocidos:**");
333
+ for (const fp of d.provenance.known_false_positives)
334
+ lines.push(`- ${fp}`);
335
+ lines.push("");
336
+ }
337
+ const ex = d.examples.positive[0];
338
+ if (ex)
339
+ lines.push("**Ejemplo:**", "", `> ${ex.text.replace(/\n/g, "\n> ")}`, "");
340
+ }
341
+ }
342
+ return lines.join("\n");
343
+ }