@johpaz/hive-agents 1.1.4 → 1.1.5

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 (51) hide show
  1. package/README.md +3 -3
  2. package/dist/hive.js +52027 -4372
  3. package/dist/tool-worker.js +49660 -1160
  4. package/dist/ui/assets/{A2UIPage-EDS7lN-K.js → A2UIPage-Dr3p75oE.js} +1 -1
  5. package/dist/ui/assets/{AgentCreateForm-KvhVhAFP.js → AgentCreateForm-DqYhH_gm.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-B2dCpO92.js → AgentDetailPage-BVtE88U5.js} +1 -1
  7. package/dist/ui/assets/{AgentNewPage-CF2B4dbu.js → AgentNewPage-BRpFxJIT.js} +1 -1
  8. package/dist/ui/assets/{AgentsPage-CMvz-CtA.js → AgentsPage-BOIJ55cj.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-tzzL3rZC.js → ApiClientPage-R9UDWfR2.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-fE2vRwup.js → ChannelsPage-C5V2BmjL.js} +1 -1
  11. package/dist/ui/assets/{DashboardPage-57SaHnBL.js → DashboardPage-B18gMzNj.js} +1 -1
  12. package/dist/ui/assets/{LoginPage-Fag9Bp5h.js → LoginPage-nrsYF9AY.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-GVJd_a65.js → LogsPage-DICMU_7m.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-TKQu8Nr-.js → MeetingPage-xslJGfIz.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-DciHLo7R.js → ModelSelector-BX4IvuYY.js} +1 -1
  16. package/dist/ui/assets/Office3DPage-a6cuzt5X.js +727 -0
  17. package/dist/ui/assets/{ProvidersPage-BsWFvzqz.js → ProvidersPage-C8-xGoeh.js} +1 -1
  18. package/dist/ui/assets/{RecoverPage-BkdOyljs.js → RecoverPage-Blms3NBa.js} +1 -1
  19. package/dist/ui/assets/{SettingsPage-D_43Rc2I.js → SettingsPage-BBeeq_QS.js} +1 -1
  20. package/dist/ui/assets/{SetupPage-D6Z3SYZu.js → SetupPage-CAjLseE_.js} +1 -1
  21. package/dist/ui/assets/{Vignette-bSrGVyRd.js → Vignette-DrI2yK2m.js} +1 -1
  22. package/dist/ui/assets/VoicePage-BeSSYstD.js +307 -0
  23. package/dist/ui/assets/{WebChatPage-Dzk3FhiR.js → WebChatPage-Bat7uUfd.js} +1 -1
  24. package/dist/ui/assets/{bia-csMImkVQ.glb → bia-qdLMQRFi.glb} +0 -0
  25. package/dist/ui/assets/{conversationsStore-5hf5grlP.js → conversationsStore-DhM07qYi.js} +1 -1
  26. package/dist/ui/assets/{dialog-DKnsGLwr.js → dialog-BP3GTCPn.js} +1 -1
  27. package/dist/ui/assets/{index-mBw9Tl7u.js → index-BG3nUPKq.js} +2 -2
  28. package/dist/ui/assets/{useAudioDevices-BYFaA0X-.js → useAudioDevices-zj0fuGwZ.js} +1 -1
  29. package/dist/ui/assets/{useHiveAgentsModelLoad-RRQ6-ANC.js → useHiveAgentsModelLoad-Cd9p-bjs.js} +1 -1
  30. package/dist/ui/assets/{useProviders-DXr4pJ57.js → useProviders-Dj1k5PCk.js} +1 -1
  31. package/dist/ui/index.html +1 -1
  32. package/package.json +1 -1
  33. package/packages/cli/src/commands/onboard.ts +8 -7
  34. package/packages/core/src/gateway/routes/providers.ts +26 -79
  35. package/packages/core/src/gateway/server.ts +20 -0
  36. package/packages/core/src/scheduler/integration.ts +26 -20
  37. package/packages/core/src/storage/collections.ts +7 -0
  38. package/packages/core/src/storage/model-sync.ts +404 -0
  39. package/packages/core/src/storage/seed.ts +33 -3
  40. package/packages/core/src/tools/cron/index.ts +25 -3
  41. package/packages/core/src/tools/office/office-escribir-docx.ts +275 -97
  42. package/packages/core/src/tools/office/office-escribir-pdf.ts +489 -99
  43. package/packages/core/src/tools/office/office-escribir-pptx.ts +86 -84
  44. package/packages/core/src/tools/office/office-escribir-xlsx.ts +196 -40
  45. package/packages/core/src/tools/office/office-style.ts +452 -0
  46. package/packages/core/src/tools/web/obscura-install.ts +119 -0
  47. package/packages/core/src/tools/web/obscura.ts +26 -4
  48. package/packages/core/src/utils/date.ts +29 -0
  49. package/packages/skills/src/bundled-data.generated.ts +780 -780
  50. package/dist/ui/assets/Office3DPage-CQnO522l.js +0 -727
  51. package/dist/ui/assets/VoicePage-CCE2EOE9.js +0 -307
@@ -1,5 +1,12 @@
1
1
  /**
2
- * office_escribir_pdf - Generar un archivo PDF desde texto
2
+ * office_escribir_pdf - Generar un archivo PDF con estilos
3
+ *
4
+ * Mismo modelo que el SDK de Rust (`office_write_pdf`): bloques (títulos, párrafos
5
+ * con tramos, listas, tablas, citas, código, reglas, saltos), temas (modern,
6
+ * classic, corporate, minimal) y encabezado/pie con {page}, {pages} y {title}.
7
+ * Las fuentes son las 14 estándar de PDF, medidas con exactitud, así que el texto
8
+ * salta de línea donde el visor lo dibuja. Los caracteres fuera del alfabeto
9
+ * latino occidental se sustituyen por «?» y se informan en la respuesta.
3
10
  *
4
11
  * @category office
5
12
  * @seedId office_escribir_pdf
@@ -10,156 +17,539 @@ import type { Tool } from "../types.ts";
10
17
  import { logger } from "../../utils/logger.ts";
11
18
  import * as path from "node:path";
12
19
  import * as fs from "node:fs";
20
+ import {
21
+ bloquesDeParametros,
22
+ hexValido,
23
+ resolverTemaDocumento,
24
+ rellenarMarcadores,
25
+ type Alineacion,
26
+ type Bloque,
27
+ type Celda,
28
+ type ElementoLista,
29
+ type Familia,
30
+ type TemaDocumento,
31
+ type Tramo,
32
+ } from "./office-style";
13
33
 
14
34
  const log = logger.child("office-escribir-pdf");
15
35
 
36
+ type Variante = "regular" | "bold" | "italic" | "boldItalic";
37
+
38
+ interface Banda {
39
+ left?: string;
40
+ center?: string;
41
+ right?: string;
42
+ size?: number;
43
+ color?: string;
44
+ rule?: boolean;
45
+ }
46
+
47
+ interface Segmento {
48
+ text: string;
49
+ font: any;
50
+ size: number;
51
+ color: [number, number, number];
52
+ underline: boolean;
53
+ link?: string;
54
+ width: number;
55
+ space: boolean;
56
+ }
57
+
58
+ const rgbDe = (hex: string, rgb: any) =>
59
+ rgb(
60
+ parseInt(hex.slice(0, 2), 16) / 255,
61
+ parseInt(hex.slice(2, 4), 16) / 255,
62
+ parseInt(hex.slice(4, 6), 16) / 255,
63
+ );
64
+
65
+ function banda(valor: unknown): Banda | undefined {
66
+ if (!valor || typeof valor !== "object") return undefined;
67
+ const o = valor as Record<string, any>;
68
+ const texto = (v: unknown) => (typeof v === "string" ? v : undefined);
69
+ return {
70
+ left: texto(o.left ?? o.izquierda),
71
+ center: texto(o.center ?? o.centro),
72
+ right: texto(o.right ?? o.derecha),
73
+ size: typeof (o.size ?? o.tamano) === "number" ? (o.size ?? o.tamano) : undefined,
74
+ color: hexValido(o.color) ?? undefined,
75
+ rule: o.rule ?? o.linea,
76
+ };
77
+ }
78
+
16
79
  export const officeEscribirPdfTool: Tool = {
17
80
  name: "office_escribir_pdf",
18
81
  description:
19
- "Generar un archivo PDF desde texto con configuración de márgenes y tamaño de página. Spanish: crear pdf, generar pdf, escribir pdf, exportar a pdf",
82
+ "Generar un PDF con estilo. Da `contenido` (texto; acepta # títulos, - viñetas, 1. listas, > citas, | tablas |, ---) o `bloques`: títulos (nivel 1-3), párrafos (con `tramos` de negrita/cursiva/subrayado/color/tamaño/enlace), listas (viñetas o numeradas, un nivel anidado), tablas (encabezado repetido entre páginas, cebra, alineación y pesos de columna), citas, código, reglas, espacios y saltos de página. `tema.preset` elige modern, classic, corporate o minimal y puede sobreescribir colores y fuentes (sans, serif, mono). `encabezado`/`pie` llevan izquierda/centro/derecha con {page}, {pages} y {title}. Spanish: crear pdf, generar pdf, escribir pdf, exportar a pdf, informe, reporte",
20
83
  parameters: {
21
84
  type: "object",
22
85
  properties: {
23
- ruta: {
24
- type: "string",
25
- description: "Ruta donde guardar el archivo PDF generado",
26
- },
27
- contenido: {
28
- type: "string",
29
- description: "Texto o contenido a escribir en el PDF",
30
- },
31
- titulo: {
32
- type: "string",
33
- description: "Título del documento (opcional)",
86
+ ruta: { type: "string", description: "Ruta donde guardar el archivo .pdf generado" },
87
+ contenido: { type: "string", description: "Texto a escribir. Se interpreta como markdown simple (# títulos, - viñetas, 1. listas, > citas, tablas con |, ---)." },
88
+ titulo: { type: "string", description: "Título del documento: va en los metadatos y como título al inicio" },
89
+ autor: { type: "string", description: "Autor (metadatos)" },
90
+ tamaño_pagina: { type: "string", enum: ["A4", "Letter"], description: "Tamaño de página (default A4)" },
91
+ orientacion: { type: "string", enum: ["vertical", "horizontal"], description: "Orientación (default vertical)" },
92
+ margen: { type: "number", description: "Margen en puntos (default 56)" },
93
+ tamaño_fuente: { type: "number", description: "Tamaño del texto base en puntos (default 11)" },
94
+ interlineado: { type: "number", description: "Interlineado, 1 a 3 (default 1.4)" },
95
+ tema: {
96
+ type: "object",
97
+ description: "{preset: modern|classic|corporate|minimal, colores: {texto, titulo, acento, atenuado, encabezado_tabla_fondo, encabezado_tabla_texto, borde_tabla, cebra, codigo_fondo} (hex de 6 dígitos), fuentes: {cuerpo, titulos} (sans|serif|mono)}",
34
98
  },
35
- tamaño_pagina: {
36
- type: "string",
37
- description: "Tamaño de página: 'A4' o 'Letter' (default: 'A4')",
38
- enum: ["A4", "Letter"],
39
- },
40
- margen: {
41
- type: "number",
42
- description: "Margen en puntos (default: 50)",
43
- },
44
- tamaño_fuente: {
45
- type: "number",
46
- description: "Tamaño de fuente en puntos (default: 12)",
99
+ encabezado: { type: "object", description: "Banda superior en cada página: {izquierda, centro, derecha, tamano, color, linea}" },
100
+ pie: { type: "object", description: "Banda inferior en cada página: {izquierda, centro, derecha, tamano, color, linea}. Ej: {derecha: 'Página {page} de {pages}'}" },
101
+ bloques: {
102
+ type: "array",
103
+ description: "Contenido en bloques. tipo: titulo(nivel) | parrafo(texto|tramos, alineacion, tamano, negrita, cursiva, color) | lista(estilo vinetas|numerada, elementos: string|{texto, elementos}) | tabla(encabezado, cebra, columnas: pesos, alineacion: [..], filas: [[celda|{texto,negrita,color,relleno,alineacion}]]) | cita(texto, autor) | codigo(texto) | regla | espacio(alto) | salto_pagina",
104
+ items: { type: "object" },
47
105
  },
48
106
  },
49
- required: ["ruta", "contenido"],
107
+ required: ["ruta"],
50
108
  },
51
109
  execute: async (params: Record<string, unknown>) => {
52
110
  const ruta = params.ruta as string;
53
- const contenido = params.contenido as string;
54
- const titulo = params.titulo as string | undefined;
55
- const tamañoPagina = (params.tamaño_pagina as string) ?? "A4";
56
- const margen = (params.margen as number) ?? 50;
57
- const tamañoFuente = (params.tamaño_fuente as number) ?? 12;
58
-
59
111
  log.debug(`Generando PDF: ${ruta}`);
60
112
 
61
113
  try {
62
- const { PDFDocument, StandardFonts, rgb, PageSizes } = await import("pdf-lib");
63
-
64
- const pdfDoc = await PDFDocument.create();
114
+ const { PDFDocument, StandardFonts, rgb, PageSizes, PDFName, PDFString } = await import("pdf-lib");
65
115
 
66
- if (titulo) {
67
- pdfDoc.setTitle(titulo);
116
+ const tema = resolverTemaDocumento(params.tema);
117
+ const titulo = typeof params.titulo === "string" ? params.titulo : "";
118
+ const bloques = bloquesDeParametros(params);
119
+ if (!titulo && bloques.length === 0) {
120
+ return { ok: false, error: "Falta contenido: da `contenido` o `bloques`." };
68
121
  }
69
- pdfDoc.setCreator("Hive Agent");
70
- pdfDoc.setCreationDate(new Date());
71
122
 
72
- const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
73
- const pageSize = tamañoPagina === "Letter" ? PageSizes.Letter : PageSizes.A4;
123
+ const base = (params.tamaño_fuente ?? params["tamaño_fuente"]) as number | undefined;
124
+ const fs0 = Math.min(72, Math.max(6, typeof base === "number" ? base : 11));
125
+ const interlineado = Math.min(3, Math.max(1, typeof params.interlineado === "number" ? params.interlineado : 1.4));
126
+ const margen = Math.min(200, Math.max(20, typeof params.margen === "number" ? params.margen : 56));
127
+ const tamPagina = (params.tamaño_pagina ?? params["tamaño_pagina"]) === "Letter" ? PageSizes.Letter : PageSizes.A4;
128
+ const horizontal = params.orientacion === "horizontal";
129
+ const [ancho, alto] = horizontal ? [tamPagina[1], tamPagina[0]] : [tamPagina[0], tamPagina[1]];
74
130
 
75
- const anchoPagina = pageSize[0];
76
- const altoPagina = pageSize[1];
77
- const anchoUtil = anchoPagina - margen * 2;
78
- const lineHeight = tamañoFuente * 1.4;
131
+ const pdf = await PDFDocument.create();
132
+ pdf.setCreator("Hive Agent");
133
+ pdf.setProducer("Hive");
134
+ pdf.setCreationDate(new Date());
135
+ if (titulo) pdf.setTitle(titulo);
136
+ if (typeof params.autor === "string") pdf.setAuthor(params.autor);
79
137
 
80
- // Si hay título, agregarlo primero
81
- const lineasTodas: string[] = [];
82
- if (titulo) {
83
- lineasTodas.push(titulo);
84
- lineasTodas.push(""); // línea en blanco
138
+ // ─── Fuentes ─────────────────────────────────────────────────────────
139
+ const nombres: Record<Familia, Record<Variante, any>> = {
140
+ sans: { regular: StandardFonts.Helvetica, bold: StandardFonts.HelveticaBold, italic: StandardFonts.HelveticaOblique, boldItalic: StandardFonts.HelveticaBoldOblique },
141
+ serif: { regular: StandardFonts.TimesRoman, bold: StandardFonts.TimesRomanBold, italic: StandardFonts.TimesRomanItalic, boldItalic: StandardFonts.TimesRomanBoldItalic },
142
+ mono: { regular: StandardFonts.Courier, bold: StandardFonts.CourierBold, italic: StandardFonts.CourierOblique, boldItalic: StandardFonts.CourierBoldOblique },
143
+ };
144
+ const cacheFuentes = new Map<string, any>();
145
+ const conjuntos = new Map<any, Set<number>>();
146
+ const fuente = async (fam: Familia, v: Variante) => {
147
+ const clave = `${fam}:${v}`;
148
+ let f = cacheFuentes.get(clave);
149
+ if (!f) {
150
+ f = await pdf.embedFont(nombres[fam][v]);
151
+ cacheFuentes.set(clave, f);
152
+ conjuntos.set(f, new Set(f.getCharacterSet()));
153
+ }
154
+ return f;
155
+ };
156
+ // Precarga: el layout es síncrono.
157
+ for (const fam of ["sans", "serif", "mono"] as Familia[]) {
158
+ for (const v of ["regular", "bold", "italic", "boldItalic"] as Variante[]) await fuente(fam, v);
85
159
  }
160
+ const pick = (fam: Familia, bold?: boolean, italic?: boolean) =>
161
+ cacheFuentes.get(`${fam}:${bold && italic ? "boldItalic" : bold ? "bold" : italic ? "italic" : "regular"}`);
86
162
 
87
- // Dividir el contenido en líneas respetando saltos de línea
88
- const lineasContenido = contenido.split("\n");
89
-
90
- // Para cada línea, dividir en sublíneas si es demasiado larga
91
- for (const linea of lineasContenido) {
92
- if (linea.trim() === "") {
93
- lineasTodas.push("");
94
- continue;
163
+ let reemplazados = 0;
164
+ const limpiar = (texto: string, f: any) => {
165
+ const set = conjuntos.get(f)!;
166
+ let salida = "";
167
+ for (const ch of texto.replace(/\t/g, " ").replace(/[\r\n]+/g, " ")) {
168
+ const cp = ch.codePointAt(0)!;
169
+ if (set.has(cp)) salida += ch;
170
+ else if (cp === 0xa0 || cp === 0x202f) salida += " ";
171
+ else if (cp === 0x2011 || cp === 0x2010) salida += "-";
172
+ else if (cp < 32) continue;
173
+ else { salida += "?"; reemplazados++; }
95
174
  }
175
+ return salida;
176
+ };
177
+
178
+ // ─── Estado de página ────────────────────────────────────────────────
179
+ const izq = margen;
180
+ const anchoUtil = ancho - margen * 2;
181
+ const tope = alto - margen;
182
+ const fondo = margen;
183
+ let pagina = pdf.addPage([ancho, alto]);
184
+ let y = tope;
96
185
 
97
- const palabras = linea.split(" ");
98
- let lineaActual = "";
186
+ const nuevaPagina = () => {
187
+ pagina = pdf.addPage([ancho, alto]);
188
+ y = tope;
189
+ };
190
+ const asegurar = (h: number) => {
191
+ if (y - h < fondo && y < tope) nuevaPagina();
192
+ };
99
193
 
100
- for (const palabra of palabras) {
101
- const prueba = lineaActual ? `${lineaActual} ${palabra}` : palabra;
102
- const ancho = font.widthOfTextAtSize(prueba, tamañoFuente);
194
+ const color = (hex: string) => rgbDe(hex, rgb);
103
195
 
104
- if (ancho > anchoUtil && lineaActual) {
105
- lineasTodas.push(lineaActual);
106
- lineaActual = palabra;
107
- } else {
108
- lineaActual = prueba;
196
+ // ─── Texto con tramos ────────────────────────────────────────────────
197
+ const tramosASegmentos = (tramos: Tramo[], tamBase: number, colorBase: string, famBase: Familia, negBase?: boolean, itaBase?: boolean): Segmento[] => {
198
+ const segs: Segmento[] = [];
199
+ for (const t of tramos) {
200
+ const fam = t.font ?? famBase;
201
+ const f = pick(fam, t.bold ?? negBase, t.italic ?? itaBase);
202
+ const size = t.size ?? tamBase;
203
+ const c = hexValido(t.color) ?? colorBase;
204
+ const rgbc = [
205
+ parseInt(c.slice(0, 2), 16) / 255, parseInt(c.slice(2, 4), 16) / 255, parseInt(c.slice(4, 6), 16) / 255,
206
+ ] as [number, number, number];
207
+ for (const trozo of limpiar(t.text, f).split(/( +)/)) {
208
+ if (!trozo) continue;
209
+ segs.push({
210
+ text: trozo, font: f, size, color: rgbc,
211
+ underline: !!t.underline || !!t.link, link: t.link,
212
+ width: f.widthOfTextAtSize(trozo, size), space: trozo.trim() === "",
213
+ });
109
214
  }
110
215
  }
216
+ return segs;
217
+ };
111
218
 
112
- if (lineaActual) {
113
- lineasTodas.push(lineaActual);
219
+ const envolver = (segs: Segmento[], anchoMax: number): Segmento[][] => {
220
+ const lineas: Segmento[][] = [];
221
+ let actual: Segmento[] = [];
222
+ let w = 0;
223
+ for (let s of segs) {
224
+ if (s.space) {
225
+ if (!actual.length) continue; // sin espacios al inicio de línea
226
+ actual.push(s); w += s.width; continue;
227
+ }
228
+ // Palabra más ancha que la línea: se parte por caracteres.
229
+ while (s.width > anchoMax) {
230
+ const hueco = anchoMax - w;
231
+ let n = s.text.length;
232
+ while (n > 0 && s.font.widthOfTextAtSize(s.text.slice(0, n), s.size) > hueco) n--;
233
+ if (n === 0) {
234
+ if (actual.length) { lineas.push(quitarEspacioFinal(actual)); actual = []; w = 0; continue; }
235
+ n = 1;
236
+ }
237
+ actual.push({ ...s, text: s.text.slice(0, n), width: s.font.widthOfTextAtSize(s.text.slice(0, n), s.size) });
238
+ lineas.push(quitarEspacioFinal(actual)); actual = []; w = 0;
239
+ const resto = s.text.slice(n);
240
+ s = { ...s, text: resto, width: s.font.widthOfTextAtSize(resto, s.size) };
241
+ }
242
+ if (w + s.width > anchoMax && actual.length) {
243
+ lineas.push(quitarEspacioFinal(actual)); actual = []; w = 0;
244
+ }
245
+ actual.push(s); w += s.width;
114
246
  }
115
- }
247
+ if (actual.length) lineas.push(quitarEspacioFinal(actual));
248
+ return lineas.length ? lineas : [[]];
249
+ };
250
+ const quitarEspacioFinal = (l: Segmento[]) => {
251
+ while (l.length && l[l.length - 1]!.space) l.pop();
252
+ return l;
253
+ };
254
+ /** Distancia de la base de la línea al fondo de su caja (centrado óptico + descendente). */
255
+ const lineaBase = (altura: number, tam: number) => (altura - tam) / 2 + tam * 0.2;
256
+ const anchoLinea = (l: Segmento[]) => l.reduce((a, s) => a + s.width, 0);
116
257
 
117
- // Distribuir líneas en páginas
118
- const lineasPorPagina = Math.floor((altoPagina - margen * 2) / lineHeight);
119
- let paginaActual = pdfDoc.addPage(pageSize);
120
- let yActual = altoPagina - margen;
121
- let lineasEnPagina = 0;
122
-
123
- for (let i = 0; i < lineasTodas.length; i++) {
124
- if (lineasEnPagina >= lineasPorPagina) {
125
- paginaActual = pdfDoc.addPage(pageSize);
126
- yActual = altoPagina - margen;
127
- lineasEnPagina = 0;
258
+ const dibujarLinea = (l: Segmento[], x: number, anchoCaja: number, baseY: number, alin: Alineacion, esUltima: boolean) => {
259
+ let total = anchoLinea(l);
260
+ let inicio = x;
261
+ let extra = 0;
262
+ if (alin === "center") inicio = x + (anchoCaja - total) / 2;
263
+ else if (alin === "right") inicio = x + anchoCaja - total;
264
+ else if (alin === "justify" && !esUltima) {
265
+ const espacios = l.filter((s) => s.space).length;
266
+ if (espacios) extra = (anchoCaja - total) / espacios;
128
267
  }
268
+ let cx = inicio;
269
+ for (const s of l) {
270
+ const w = s.width + (s.space ? extra : 0);
271
+ if (!s.space) {
272
+ pagina.drawText(s.text, { x: cx, y: baseY, size: s.size, font: s.font, color: rgb(...s.color) });
273
+ }
274
+ if (s.underline && !s.space) {
275
+ pagina.drawLine({ start: { x: cx, y: baseY - s.size * 0.12 }, end: { x: cx + w, y: baseY - s.size * 0.12 }, thickness: Math.max(0.5, s.size / 18), color: rgb(...s.color) });
276
+ }
277
+ if (s.link && !s.space) {
278
+ const ref = pdf.context.register(pdf.context.obj({
279
+ Type: "Annot", Subtype: "Link", Rect: [cx, baseY - s.size * 0.2, cx + w, baseY + s.size * 0.85], Border: [0, 0, 0],
280
+ A: { Type: "Action", S: "URI", URI: PDFString.of(s.link) },
281
+ }));
282
+ const annots = pagina.node.Annots();
283
+ if (annots) annots.push(ref);
284
+ else pagina.node.set(PDFName.of("Annots"), pdf.context.obj([ref]));
285
+ }
286
+ cx += w;
287
+ }
288
+ };
289
+
290
+ /** Dibuja un texto con salto de página entre líneas. Devuelve la altura usada. */
291
+ const parrafo = (segs: Segmento[], x: number, anchoCaja: number, alin: Alineacion) => {
292
+ const lineas = envolver(segs, anchoCaja);
293
+ const tam = Math.max(...segs.map((s) => s.size), fs0);
294
+ const alturaLinea = tam * interlineado;
295
+ lineas.forEach((l, i) => {
296
+ asegurar(alturaLinea);
297
+ y -= alturaLinea;
298
+ dibujarLinea(l, x, anchoCaja, y + lineaBase(alturaLinea, tam), alin, i === lineas.length - 1);
299
+ });
300
+ };
301
+
302
+ const tramosDe = (b: { text: string; runs?: Tramo[] }): Tramo[] =>
303
+ b.runs && b.runs.length ? b.runs : [{ text: b.text }];
129
304
 
130
- const esEncabezado = titulo && i === 0;
131
- const fuenteActual = esEncabezado ? tamañoFuente + 4 : tamañoFuente;
305
+ // ─── Bloques ─────────────────────────────────────────────────────────
306
+ const escalaTitulo = { 1: 1.9, 2: 1.45, 3: 1.2 } as const;
132
307
 
133
- if (lineasTodas[i] !== "") {
134
- paginaActual.drawText(lineasTodas[i], {
135
- x: margen,
136
- y: yActual,
137
- size: fuenteActual,
138
- font,
139
- color: rgb(0, 0, 0),
308
+ const dibujarTitulo = (texto: string, nivel: 1 | 2 | 3, alin: Alineacion = "left", colorTitulo?: string) => {
309
+ const size = fs0 * escalaTitulo[nivel];
310
+ const segs = tramosASegmentos([{ text: texto, bold: true }], size, colorTitulo ?? tema.titulo, tema.fuenteTitulos);
311
+ const lineas = envolver(segs, anchoUtil);
312
+ const h = lineas.length * size * 1.25;
313
+ asegurar(h + size * 1.4); // un título no se queda solo al final de la página
314
+ y -= size * (nivel === 1 ? 0.5 : 0.8);
315
+ lineas.forEach((l) => {
316
+ y -= size * 1.25;
317
+ dibujarLinea(l, izq, anchoUtil, y + size * 0.25, alin, true);
318
+ });
319
+ if (nivel === 1) {
320
+ y -= 4;
321
+ pagina.drawLine({ start: { x: izq, y }, end: { x: izq + anchoUtil, y }, thickness: 1.2, color: color(tema.acento) });
322
+ y -= fs0 * 0.5;
323
+ } else {
324
+ y -= fs0 * 0.25;
325
+ }
326
+ };
327
+
328
+ const dibujarLista = (items: ElementoLista[], estilo: "bullet" | "numbered", nivel: number) => {
329
+ const sangria = 16 + nivel * 18;
330
+ items.forEach((it, i) => {
331
+ const marca = estilo === "numbered" ? `${i + 1}.` : nivel === 0 ? "•" : "-";
332
+ const f = pick(tema.fuenteCuerpo)!;
333
+ const segs = tramosASegmentos([{ text: it.text }], fs0, tema.texto, tema.fuenteCuerpo);
334
+ const lineas = envolver(segs, anchoUtil - sangria - 4);
335
+ const alturaLinea = fs0 * interlineado;
336
+ lineas.forEach((l, k) => {
337
+ asegurar(alturaLinea);
338
+ y -= alturaLinea;
339
+ if (k === 0) {
340
+ pagina.drawText(limpiar(marca, f), { x: izq + sangria - 12 - (estilo === "numbered" ? 4 : 0), y: y + lineaBase(alturaLinea, fs0), size: fs0, font: nivel === 0 && estilo === "bullet" ? pick(tema.fuenteCuerpo, true)! : f, color: color(tema.acento) });
341
+ }
342
+ dibujarLinea(l, izq + sangria, anchoUtil - sangria - 4, y + lineaBase(alturaLinea, fs0), "left", true);
140
343
  });
344
+ if (it.items?.length && nivel < 1) dibujarLista(it.items, "bullet", nivel + 1);
345
+ });
346
+ };
347
+
348
+ const dibujarTabla = (b: Extract<Bloque, { type: "table" }>) => {
349
+ const nCols = Math.max(1, ...b.rows.map((r) => r.length));
350
+ const pesos = Array.from({ length: nCols }, (_, i) => b.columns?.[i] ?? 1);
351
+ const suma = pesos.reduce((a, c) => a + c, 0);
352
+ const anchos = pesos.map((p) => (p / suma) * anchoUtil);
353
+ const pad = 5;
354
+ const tamCelda = Math.max(6, fs0 - 1);
355
+
356
+ const alturaFila = (fila: Celda[], esEnc: boolean) => {
357
+ let max = 1;
358
+ fila.forEach((c, i) => {
359
+ const segs = tramosASegmentos([{ text: c.text, bold: esEnc || c.bold }], tamCelda, tema.texto, tema.fuenteCuerpo);
360
+ max = Math.max(max, envolver(segs, anchos[i]! - pad * 2).length);
361
+ });
362
+ return max * tamCelda * 1.3 + pad * 2;
363
+ };
364
+
365
+ const dibujarFila = (fila: Celda[], esEnc: boolean, indice: number) => {
366
+ const h = alturaFila(fila, esEnc);
367
+ const fondoFila = esEnc ? tema.encabezadoTablaFondo : b.zebra && indice % 2 === 1 ? tema.cebra : null;
368
+ let cx = izq;
369
+ for (let i = 0; i < nCols; i++) {
370
+ const c = fila[i] ?? { text: "" };
371
+ const relleno = c.fill ?? fondoFila;
372
+ if (relleno) pagina.drawRectangle({ x: cx, y: y - h, width: anchos[i]!, height: h, color: color(relleno) });
373
+ pagina.drawRectangle({ x: cx, y: y - h, width: anchos[i]!, height: h, borderColor: color(tema.bordeTabla), borderWidth: 0.5 });
374
+ const segs = tramosASegmentos(
375
+ [{ text: c.text, bold: esEnc || c.bold }], tamCelda,
376
+ hexValido(c.color) ?? (esEnc ? tema.encabezadoTablaTexto : tema.texto), tema.fuenteCuerpo,
377
+ );
378
+ const alin = c.align ?? b.align?.[i] ?? "left";
379
+ const lineas = envolver(segs, anchos[i]! - pad * 2);
380
+ lineas.forEach((l, k) => {
381
+ dibujarLinea(l, cx + pad, anchos[i]! - pad * 2, y - pad - tamCelda * 1.3 * (k + 1) + tamCelda * 0.38, alin, true);
382
+ });
383
+ cx += anchos[i]!;
384
+ }
385
+ y -= h;
386
+ };
387
+
388
+ const encabezado = b.header && b.rows.length > 1 ? b.rows[0]! : null;
389
+ const cuerpo = encabezado ? b.rows.slice(1) : b.rows;
390
+ y -= fs0 * 0.3;
391
+ if (encabezado) {
392
+ asegurar(alturaFila(encabezado, true) + alturaFila(cuerpo[0] ?? [], false));
393
+ dibujarFila(encabezado, true, 0);
141
394
  }
395
+ cuerpo.forEach((fila, i) => {
396
+ const h = alturaFila(fila, false);
397
+ if (y - h < fondo && y < tope) {
398
+ nuevaPagina();
399
+ if (encabezado) dibujarFila(encabezado, true, 0); // encabezado repetido
400
+ }
401
+ dibujarFila(fila, false, i);
402
+ });
403
+ y -= fs0 * 0.8;
404
+ };
142
405
 
143
- yActual -= lineHeight;
144
- lineasEnPagina++;
406
+ // Título del documento (si lo hay), con una línea de acento.
407
+ if (titulo) {
408
+ const size = fs0 * 2.3;
409
+ const lineas = envolver(tramosASegmentos([{ text: titulo, bold: true }], size, tema.titulo, tema.fuenteTitulos), anchoUtil);
410
+ lineas.forEach((l) => {
411
+ y -= size * 1.2;
412
+ dibujarLinea(l, izq, anchoUtil, y + size * 0.25, "left", true);
413
+ });
414
+ y -= 6;
415
+ pagina.drawRectangle({ x: izq, y: y - 3, width: Math.min(80, anchoUtil), height: 3, color: color(tema.acento) });
416
+ y -= fs0 * 1.6;
145
417
  }
146
418
 
419
+ for (const b of bloques) {
420
+ switch (b.type) {
421
+ case "heading":
422
+ dibujarTitulo(b.text, b.level, b.align, b.color);
423
+ break;
424
+ case "paragraph": {
425
+ const size = b.size ?? fs0;
426
+ const segs = tramosASegmentos(tramosDe(b), size, b.color ?? tema.texto, tema.fuenteCuerpo, b.bold, b.italic);
427
+ parrafo(segs, izq + (b.indent ?? 0), anchoUtil - (b.indent ?? 0), b.align ?? "left");
428
+ y -= b.spaceAfter ?? fs0 * 0.6;
429
+ break;
430
+ }
431
+ case "list":
432
+ dibujarLista(b.items, b.style, 0);
433
+ y -= fs0 * 0.6;
434
+ break;
435
+ case "table":
436
+ dibujarTabla(b);
437
+ break;
438
+ case "quote": {
439
+ const segs = tramosASegmentos([{ text: b.text, italic: true }], fs0, tema.atenuado, tema.fuenteCuerpo);
440
+ const lineas = envolver(segs, anchoUtil - 22);
441
+ const alturaLinea = fs0 * interlineado;
442
+ const bloqueH = lineas.length * alturaLinea + (b.author ? alturaLinea : 0);
443
+ asegurar(Math.min(bloqueH, alto - margen * 2));
444
+ const arriba = y;
445
+ lineas.forEach((l) => {
446
+ asegurar(alturaLinea);
447
+ y -= alturaLinea;
448
+ dibujarLinea(l, izq + 16, anchoUtil - 22, y + lineaBase(alturaLinea, fs0), "left", true);
449
+ });
450
+ if (b.author) {
451
+ asegurar(alturaLinea);
452
+ y -= alturaLinea;
453
+ dibujarLinea(envolver(tramosASegmentos([{ text: `— ${b.author}` }], fs0 - 1, tema.atenuado, tema.fuenteCuerpo), anchoUtil - 22)[0]!, izq + 16, anchoUtil - 22, y + lineaBase(alturaLinea, fs0), "right", true);
454
+ }
455
+ if (arriba >= y) pagina.drawRectangle({ x: izq + 2, y: y, width: 3, height: Math.max(0, arriba - y), color: color(tema.acento) });
456
+ y -= fs0 * 0.7;
457
+ break;
458
+ }
459
+ case "code": {
460
+ const tam = Math.max(6, fs0 - 1.5);
461
+ const mono = pick("mono")!;
462
+ const lineasCrudas = b.text.replace(/\r\n?/g, "\n").split("\n");
463
+ const alturaLinea = tam * 1.35;
464
+ const cajaAncho = anchoUtil;
465
+ const maxCaracteres = Math.max(1, Math.floor((cajaAncho - 12) / mono.widthOfTextAtSize("M", tam)));
466
+ const lineas: string[] = [];
467
+ for (const l of lineasCrudas) {
468
+ const limpia = limpiar(l, mono);
469
+ if (limpia.length === 0) lineas.push("");
470
+ for (let i = 0; i < limpia.length; i += maxCaracteres) lineas.push(limpia.slice(i, i + maxCaracteres));
471
+ }
472
+ y -= 4;
473
+ let i = 0;
474
+ while (i < lineas.length) {
475
+ asegurar(alturaLinea + 12);
476
+ const disponibles = Math.max(1, Math.floor((y - fondo - 12) / alturaLinea));
477
+ const trozo = lineas.slice(i, i + disponibles);
478
+ const h = trozo.length * alturaLinea + 10;
479
+ pagina.drawRectangle({ x: izq, y: y - h, width: cajaAncho, height: h, color: color(tema.codigoFondo) });
480
+ pagina.drawRectangle({ x: izq, y: y - h, width: 2.5, height: h, color: color(tema.acento) });
481
+ let cy = y - 5;
482
+ for (const l of trozo) {
483
+ cy -= alturaLinea;
484
+ pagina.drawText(l, { x: izq + 8, y: cy + tam * 0.3, size: tam, font: mono, color: color(tema.texto) });
485
+ }
486
+ y -= h;
487
+ i += trozo.length;
488
+ if (i < lineas.length) nuevaPagina();
489
+ }
490
+ y -= fs0 * 0.8;
491
+ break;
492
+ }
493
+ case "rule":
494
+ asegurar(fs0);
495
+ y -= fs0 * 0.6;
496
+ pagina.drawLine({ start: { x: izq, y }, end: { x: izq + anchoUtil, y }, thickness: 0.75, color: color(tema.bordeTabla) });
497
+ y -= fs0 * 0.6;
498
+ break;
499
+ case "spacer":
500
+ y -= Math.min(400, Math.max(0, b.height));
501
+ if (y < fondo) nuevaPagina();
502
+ break;
503
+ case "page_break":
504
+ nuevaPagina();
505
+ break;
506
+ }
507
+ }
508
+
509
+ // ─── Encabezado y pie en todas las páginas ───────────────────────────
510
+ const enc = banda(params.encabezado ?? params.header);
511
+ const pie = banda(params.pie ?? params.footer);
512
+ const paginas = pdf.getPages();
513
+ const fBanda = pick(tema.fuenteCuerpo)!;
514
+ const dibujarBanda = (b: Banda, pg: any, n: number, esPie: boolean) => {
515
+ const size = Math.min(24, Math.max(5, b.size ?? 8));
516
+ const c = color(b.color ?? tema.atenuado);
517
+ const yTexto = esPie ? margen * 0.5 - size * 0.3 : alto - margen * 0.5 - size * 0.3;
518
+ const partes: Array<[string | undefined, "l" | "c" | "r"]> = [[b.left, "l"], [b.center, "c"], [b.right, "r"]];
519
+ for (const [t, pos] of partes) {
520
+ if (!t) continue;
521
+ const texto = limpiar(rellenarMarcadores(t, n, paginas.length, titulo), fBanda);
522
+ const w = fBanda.widthOfTextAtSize(texto, size);
523
+ const x = pos === "l" ? izq : pos === "c" ? izq + (anchoUtil - w) / 2 : izq + anchoUtil - w;
524
+ pg.drawText(texto, { x, y: yTexto, size, font: fBanda, color: c });
525
+ }
526
+ if (b.rule) {
527
+ const yr = esPie ? yTexto + size + 4 : yTexto - 5;
528
+ pg.drawLine({ start: { x: izq, y: yr }, end: { x: izq + anchoUtil, y: yr }, thickness: 0.5, color: color(tema.bordeTabla) });
529
+ }
530
+ };
531
+ paginas.forEach((pg, i) => {
532
+ if (enc) dibujarBanda(enc, pg, i + 1, false);
533
+ if (pie) dibujarBanda(pie, pg, i + 1, true);
534
+ });
535
+
147
536
  const rutaAbsoluta = path.resolve(ruta);
148
537
  const dirDestino = path.dirname(rutaAbsoluta);
149
- if (!fs.existsSync(dirDestino)) {
150
- fs.mkdirSync(dirDestino, { recursive: true });
151
- }
538
+ if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
152
539
 
153
- const pdfBytes = await pdfDoc.save();
540
+ const pdfBytes = await pdf.save();
154
541
  fs.writeFileSync(rutaAbsoluta, pdfBytes);
155
542
 
156
- log.info(`PDF generado: ${rutaAbsoluta} (${pdfDoc.getPageCount()} páginas)`);
543
+ log.info(`PDF generado: ${rutaAbsoluta} (${pdf.getPageCount()} páginas)`);
157
544
 
158
545
  return {
159
546
  ok: true,
160
547
  ruta: rutaAbsoluta,
161
- paginas: pdfDoc.getPageCount(),
548
+ paginas: pdf.getPageCount(),
162
549
  bytesEscritos: pdfBytes.length,
550
+ ...(reemplazados > 0
551
+ ? { caracteresReemplazados: reemplazados, aviso: "Algunos caracteres fuera del alfabeto latino occidental se sustituyeron por «?»." }
552
+ : {}),
163
553
  };
164
554
  } catch (error) {
165
555
  log.error(`Error generando PDF: ${(error as Error).message}`);