@ureck/alexandria 1.3.3 → 1.5.0

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.
@@ -0,0 +1,262 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/docs/convert.ts
4
+ import fs from "fs";
5
+ import path from "path";
6
+ var PDF_TOKENS_PER_PAGE = 2e3;
7
+ var ROWS_PER_SECTION = 50;
8
+ var SAMPLE_VALUES = 3;
9
+ var MAX_CELL = 160;
10
+ var MIN_CHARS_PER_PAGE = 40;
11
+ var SUPPORTED_EXT = {
12
+ ".pdf": "pdf",
13
+ ".docx": "docx",
14
+ ".html": "html",
15
+ ".htm": "html",
16
+ ".xlsx": "xlsx",
17
+ ".csv": "csv",
18
+ ".tsv": "csv",
19
+ ".md": "markdown",
20
+ ".markdown": "markdown",
21
+ ".txt": "text"
22
+ };
23
+ function formatOf(file) {
24
+ return SUPPORTED_EXT[path.extname(file).toLowerCase()];
25
+ }
26
+ var tokens = (s) => Math.ceil(s.length / 4);
27
+ async function convertFile(abs) {
28
+ const format = formatOf(abs);
29
+ if (!format) throw new Error(`Formato no soportado: ${path.extname(abs) || abs} (soportados: ${Object.keys(SUPPORTED_EXT).join(" ")})`);
30
+ const buf = fs.readFileSync(abs);
31
+ switch (format) {
32
+ case "pdf":
33
+ return pdfToMarkdown(buf);
34
+ case "docx": {
35
+ const mammoth = (await import("mammoth")).default;
36
+ const { value } = await mammoth.convertToHtml({ buffer: buf });
37
+ const markdown = await htmlToMarkdown(value);
38
+ return { format, markdown, tokensOriginal: tokens(markdown) };
39
+ }
40
+ case "html": {
41
+ const markdown = await htmlToMarkdown(buf.toString("utf8"));
42
+ return { format, markdown, tokensOriginal: tokens(buf.toString("utf8")) };
43
+ }
44
+ case "xlsx":
45
+ return xlsxToMarkdown(buf);
46
+ case "csv": {
47
+ const text = buf.toString("utf8");
48
+ const delim = path.extname(abs).toLowerCase() === ".tsv" ? " " : sniffDelimiter(text);
49
+ const rows = parseCsv(text, delim);
50
+ const markdown = sheetsToMarkdown([{ name: path.basename(abs), rows }]);
51
+ return { format, markdown, rows: Math.max(0, rows.length - 1), tokensOriginal: tokens(text) };
52
+ }
53
+ default: {
54
+ const markdown = buf.toString("utf8");
55
+ return { format, markdown, tokensOriginal: tokens(markdown) };
56
+ }
57
+ }
58
+ }
59
+ async function pdfToMarkdown(buf) {
60
+ const { getDocumentProxy } = await import("unpdf");
61
+ const pdf = await getDocumentProxy(new Uint8Array(buf));
62
+ const lines = [];
63
+ for (let p = 1; p <= pdf.numPages; p++) {
64
+ const tc = await (await pdf.getPage(p)).getTextContent();
65
+ const byY = /* @__PURE__ */ new Map();
66
+ for (const it of tc.items) {
67
+ if (!it.str || !it.transform) continue;
68
+ const y = Math.round(it.transform[5]);
69
+ const size = Math.round(Math.hypot(it.transform[0], it.transform[1]) || it.height || 0);
70
+ const arr = byY.get(y) ?? [];
71
+ arr.push({ x: it.transform[4], str: it.str, size });
72
+ byY.set(y, arr);
73
+ }
74
+ for (const y of [...byY.keys()].sort((a, b) => b - a)) {
75
+ const parts = byY.get(y).sort((a, b) => a.x - b.x);
76
+ const text = parts.map((x) => x.str).join(" ").replace(/\s+/g, " ").trim();
77
+ if (text) lines.push({ page: p, text, size: Math.max(...parts.map((x) => x.size)) });
78
+ }
79
+ }
80
+ const bySize = [...lines].sort((a, b) => a.size - b.size);
81
+ const totalChars = lines.reduce((n, l) => n + l.text.length, 0);
82
+ let acc = 0;
83
+ const median = bySize.find((l) => (acc += l.text.length) >= totalChars / 2)?.size ?? 0;
84
+ const isHeading = (l) => median > 0 && l.size >= median * 1.3 && l.text.length <= 120;
85
+ const hasHeadings = lines.some(isHeading);
86
+ const out = [];
87
+ let page = 0;
88
+ let para = [];
89
+ const flush = () => {
90
+ if (para.length) out.push(para.join(" ").replace(/^#/, "\\#"));
91
+ para = [];
92
+ };
93
+ for (const l of lines) {
94
+ if (l.page !== page) {
95
+ flush();
96
+ page = l.page;
97
+ if (!hasHeadings) out.push(`## P\xE1gina ${page}`);
98
+ }
99
+ if (hasHeadings && isHeading(l)) {
100
+ flush();
101
+ const prev = out[out.length - 1];
102
+ const m = prev?.match(/^## (.+) \(p\. (\d+)\)$/);
103
+ if (m && Number(m[2]) === l.page && m[1].length + l.text.length < 240) {
104
+ out[out.length - 1] = `## ${m[1]} ${l.text} (p. ${l.page})`;
105
+ } else {
106
+ out.push(`## ${l.text} (p. ${l.page})`);
107
+ }
108
+ } else {
109
+ para.push(l.text);
110
+ if (/[.:;!?]$/.test(l.text)) flush();
111
+ }
112
+ }
113
+ flush();
114
+ const chars = lines.reduce((n, l) => n + l.text.length, 0);
115
+ if (chars < MIN_CHARS_PER_PAGE * pdf.numPages) {
116
+ out.unshift(
117
+ `## \u26A0 PDF escaneado (sin capa de texto)
118
+
119
+ Solo se extrajeron ${chars} caracteres en ${pdf.numPages} p\xE1gina(s): el contenido es imagen. Alexandria no hace OCR; para leerlo hay que verlo como imagen (Read del archivo, ~${PDF_TOKENS_PER_PAGE.toLocaleString("en")} tokens por p\xE1gina) \u2014 de preferencia solo las p\xE1ginas necesarias.`
120
+ );
121
+ }
122
+ return {
123
+ format: "pdf",
124
+ markdown: out.join("\n\n"),
125
+ pages: pdf.numPages,
126
+ tokensOriginal: pdf.numPages * PDF_TOKENS_PER_PAGE
127
+ };
128
+ }
129
+ async function htmlToMarkdown(html) {
130
+ const TurndownService = (await import("turndown")).default;
131
+ const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced", bulletListMarker: "-" });
132
+ td.remove(["script", "style", "nav", "footer", "aside", "noscript", "iframe", "svg"]);
133
+ td.addRule("table", {
134
+ filter: "table",
135
+ replacement: (_content, node) => {
136
+ const rows = Array.from(node.querySelectorAll("tr")).map(
137
+ (tr) => Array.from(tr.children).map((c) => cell(c.textContent ?? ""))
138
+ );
139
+ return rows.length ? "\n\n" + mdTable(rows) + "\n\n" : "";
140
+ }
141
+ });
142
+ td.addRule("img", { filter: "img", replacement: (_c, node) => node.getAttribute("alt") ? `[imagen: ${node.getAttribute("alt")}]` : "" });
143
+ return td.turndown(html).replace(/\n{3,}/g, "\n\n").trim();
144
+ }
145
+ var cell = (v) => {
146
+ const t = String(v ?? "").replace(/\s+/g, " ").trim();
147
+ return (t.length > MAX_CELL ? t.slice(0, MAX_CELL) + `\u2026(+${t.length - MAX_CELL})` : t).replace(/\|/g, "\\|");
148
+ };
149
+ function mdTable(rows) {
150
+ const width = Math.max(...rows.map((r) => r.length));
151
+ const pad = (r) => [...r, ...Array(width - r.length).fill("")];
152
+ const [head, ...body] = rows.map(pad);
153
+ return [`| ${head.join(" | ")} |`, `| ${head.map(() => "---").join(" | ")} |`, ...body.map((r) => `| ${r.join(" | ")} |`)].join("\n");
154
+ }
155
+ function inferType(values) {
156
+ const vals = values.filter((v) => v !== "");
157
+ if (vals.length === 0) return "vac\xEDa";
158
+ if (vals.every((v) => /^-?\d+(\.\d+)?(e[-+]?\d+)?$/i.test(v.replace(/,/g, "")))) return "n\xFAmero";
159
+ if (vals.every((v) => !isNaN(Date.parse(v)) && /\d{4}|\d{1,2}[/-]\d{1,2}/.test(v))) return "fecha";
160
+ if (new Set(vals).size <= Math.max(5, vals.length * 0.05)) return `categor\xEDa (${new Set(vals).size} valores)`;
161
+ return "texto";
162
+ }
163
+ function sheetsToMarkdown(sheets) {
164
+ const out = [];
165
+ for (const { name, rows } of sheets) {
166
+ const clean = rows.filter((r) => r.some((c) => c !== ""));
167
+ if (clean.length === 0) continue;
168
+ const [header, ...data] = clean;
169
+ const cols = header.map((h, i) => h || `col${i + 1}`);
170
+ out.push(`## Hoja \xAB${name}\xBB \u2014 resumen`);
171
+ out.push(`Filas de datos: ${data.length} \xB7 Columnas: ${cols.length}`);
172
+ out.push(
173
+ mdTable([
174
+ ["columna", "tipo", "ejemplos"],
175
+ ...cols.map((c, i) => {
176
+ const values = data.map((r) => r[i] ?? "");
177
+ const sample = [...new Set(values.filter(Boolean))].slice(0, SAMPLE_VALUES).map((v) => v.slice(0, 40));
178
+ return [cell(c), inferType(values), cell(sample.join(", "))];
179
+ })
180
+ ])
181
+ );
182
+ for (let i = 0; i < data.length; i += ROWS_PER_SECTION) {
183
+ const block = data.slice(i, i + ROWS_PER_SECTION);
184
+ out.push(`## Hoja \xAB${name}\xBB \xB7 filas ${i + 1}\u2013${i + block.length}`);
185
+ out.push(mdTable([cols.map(cell), ...block.map((r) => r.map(cell))]));
186
+ }
187
+ }
188
+ return out.join("\n\n");
189
+ }
190
+ async function xlsxToMarkdown(buf) {
191
+ const ExcelJS = (await import("exceljs")).default;
192
+ const wb = new ExcelJS.Workbook();
193
+ await wb.xlsx.load(buf);
194
+ const sheets = [];
195
+ let totalRows = 0;
196
+ let rawChars = 0;
197
+ wb.eachSheet((ws) => {
198
+ const rows = [];
199
+ ws.eachRow({ includeEmpty: false }, (row) => {
200
+ const vals = row.values.slice(1).map(cellText);
201
+ rows.push(vals);
202
+ rawChars += vals.join(",").length + 1;
203
+ });
204
+ totalRows += Math.max(0, rows.length - 1);
205
+ sheets.push({ name: ws.name, rows });
206
+ });
207
+ return { format: "xlsx", markdown: sheetsToMarkdown(sheets), rows: totalRows, tokensOriginal: Math.ceil(rawChars / 4) };
208
+ }
209
+ function cellText(v) {
210
+ if (v === null || v === void 0) return "";
211
+ if (v instanceof Date) return v.toISOString().slice(0, 10);
212
+ if (typeof v === "object") {
213
+ const o = v;
214
+ if (o.richText) return o.richText.map((t) => t.text).join("");
215
+ if (o.text !== void 0) return String(o.text);
216
+ if (o.result !== void 0) return cellText(o.result);
217
+ return "";
218
+ }
219
+ return String(v);
220
+ }
221
+ function sniffDelimiter(text) {
222
+ const first = text.split(/\r?\n/, 1)[0] ?? "";
223
+ const counts = [",", ";", " ", "|"].map((d) => [d, first.split(d).length]);
224
+ return counts.sort((a, b) => b[1] - a[1])[0][0];
225
+ }
226
+ function parseCsv(text, delim = ",") {
227
+ const rows = [];
228
+ let row = [];
229
+ let field = "";
230
+ let quoted = false;
231
+ for (let i = 0; i < text.length; i++) {
232
+ const c = text[i];
233
+ if (quoted) {
234
+ if (c === '"' && text[i + 1] === '"') {
235
+ field += '"';
236
+ i++;
237
+ } else if (c === '"') quoted = false;
238
+ else field += c;
239
+ } else if (c === '"' && field === "") quoted = true;
240
+ else if (c === delim) {
241
+ row.push(field.trim());
242
+ field = "";
243
+ } else if (c === "\n" || c === "\r") {
244
+ if (c === "\r" && text[i + 1] === "\n") i++;
245
+ row.push(field.trim());
246
+ rows.push(row);
247
+ row = [];
248
+ field = "";
249
+ } else field += c;
250
+ }
251
+ if (field !== "" || row.length) {
252
+ row.push(field.trim());
253
+ rows.push(row);
254
+ }
255
+ return rows;
256
+ }
257
+
258
+ export {
259
+ PDF_TOKENS_PER_PAGE,
260
+ formatOf,
261
+ convertFile
262
+ };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-QB37UGO6.js";
4
+ } from "./chunk-BV2KJV5W.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -1,4 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ currentHarness,
4
+ defaultOutput,
5
+ formatContext,
6
+ normalizeInput
7
+ } from "./chunk-CEHNXDUE.js";
2
8
 
3
9
  // src/hooks/util.ts
4
10
  import fs from "fs";
@@ -16,6 +22,15 @@ async function readStdinJson() {
16
22
  }
17
23
  }
18
24
  var expired = false;
25
+ var emitted = false;
26
+ function emitContext(kind, text) {
27
+ if (expired) return 0;
28
+ const out = formatContext(currentHarness(), kind, text);
29
+ if (out === null) return 0;
30
+ process.stdout.write(out);
31
+ emitted = true;
32
+ return text.length;
33
+ }
19
34
  function logHookError(kind, detail) {
20
35
  try {
21
36
  const dir = process.platform === "win32" && process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "alexandria") : path.join(os.homedir(), ".cache", "alexandria");
@@ -30,7 +45,7 @@ function logHookError(kind, detail) {
30
45
  } catch {
31
46
  }
32
47
  }
33
- function runHook(budgetMs, body) {
48
+ function runHook(budgetMs, body, kind = "stop") {
34
49
  process.env.ALEXANDRIA_HOOK = "1";
35
50
  const cleanup = async () => {
36
51
  try {
@@ -46,11 +61,13 @@ function runHook(budgetMs, body) {
46
61
  }, budgetMs);
47
62
  timer.unref();
48
63
  process.exitCode = 0;
49
- readStdinJson().then((input) => body(input)).catch((e) => {
64
+ readStdinJson().then((raw) => body(normalizeInput(raw))).catch((e) => {
50
65
  logHookError("error", e instanceof Error ? `${e.message}
51
66
  ${e.stack ?? ""}` : String(e));
52
67
  }).finally(() => {
53
68
  clearTimeout(timer);
69
+ const fallback = emitted ? null : defaultOutput(currentHarness(), kind);
70
+ if (fallback) process.stdout.write(fallback);
54
71
  void cleanup();
55
72
  });
56
73
  }
@@ -63,6 +80,7 @@ function truncate(text, max) {
63
80
  }
64
81
 
65
82
  export {
83
+ emitContext,
66
84
  runHook,
67
85
  projectName,
68
86
  truncate