utn-mcp 0.1.0 → 0.2.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.
- package/README.md +37 -2
- package/build/aula-virtual/address.js +39 -0
- package/build/aula-virtual/client/client.js +28 -10
- package/build/aula-virtual/client/moodle-api.js +53 -0
- package/build/aula-virtual/files.js +89 -0
- package/build/aula-virtual/navigate.js +144 -0
- package/build/aula-virtual/tools.js +86 -4
- package/build/http.js +0 -5
- package/build/server.js +1 -1
- package/build/shared/documents/index.js +68 -0
- package/build/shared/documents/office.js +118 -0
- package/build/shared/documents/pdf.js +164 -0
- package/build/shared/documents/png.js +51 -0
- package/build/shared/documents/zip.js +72 -0
- package/build/shared/html.js +19 -0
- package/package.json +5 -2
- package/vendor/pdfjs/LICENSE +177 -0
- package/vendor/pdfjs/pdf.mjs +34672 -0
- package/vendor/pdfjs/pdf.worker.mjs +71124 -0
- package/vendor/pdfjs/wasm/LICENSE_PDFJS_JBIG2 +13 -0
- package/vendor/pdfjs/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
- package/vendor/pdfjs/wasm/jbig2_nowasm_fallback.js +15 -0
- package/vendor/pdfjs/wasm/openjpeg_nowasm_fallback.js +17 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { deTexto, fragmentar } from "./index.js";
|
|
2
|
+
import { leerEntrada, listarZip } from "./zip.js";
|
|
3
|
+
/** Tope por entrada descomprimida: un XML de texto de más que esto es un zip malicioso o no es un documento. */
|
|
4
|
+
const MAX_ENTRADA = 50 * 1024 * 1024;
|
|
5
|
+
const MARCAS = {
|
|
6
|
+
docx: "word/document.xml",
|
|
7
|
+
pptx: "ppt/presentation.xml",
|
|
8
|
+
xlsx: "xl/workbook.xml",
|
|
9
|
+
};
|
|
10
|
+
/** Mira la lista de entradas del zip sin descomprimir nada. */
|
|
11
|
+
export function formatoOffice(bytes) {
|
|
12
|
+
const nombres = new Set(listarZip(bytes).map((e) => e.nombre));
|
|
13
|
+
return Object.keys(MARCAS).find((f) => nombres.has(MARCAS[f])) ?? null;
|
|
14
|
+
}
|
|
15
|
+
export function abrirOffice(bytes, formato) {
|
|
16
|
+
const texto = new TextDecoder();
|
|
17
|
+
const zip = Object.fromEntries(listarZip(bytes)
|
|
18
|
+
.filter((e) => necesaria(formato, e.nombre))
|
|
19
|
+
.map((e) => [e.nombre, texto.decode(leerEntrada(bytes, e, MAX_ENTRADA))]));
|
|
20
|
+
switch (formato) {
|
|
21
|
+
case "docx":
|
|
22
|
+
return deTexto("docx", "fragmento", fragmentar(xmlTexto(leer(zip, "word/document.xml"), "w")).map((texto) => ({ texto })));
|
|
23
|
+
case "pptx":
|
|
24
|
+
return deTexto("pptx", "diapositiva", Object.keys(zip)
|
|
25
|
+
.filter((p) => /^ppt\/slides\/slide\d+\.xml$/.test(p))
|
|
26
|
+
.sort((a, b) => numero(a) - numero(b))
|
|
27
|
+
.map((p) => ({ texto: xmlTexto(leer(zip, p), "a") || "(diapositiva sin texto)" })));
|
|
28
|
+
case "xlsx":
|
|
29
|
+
return deTexto("xlsx", "fragmento", hojas(zip).flatMap(({ nombre, texto }) => {
|
|
30
|
+
const partes = fragmentar(texto);
|
|
31
|
+
return partes.map((t, i) => ({
|
|
32
|
+
titulo: partes.length > 1 ? `hoja "${nombre}" (${i + 1}/${partes.length})` : `hoja "${nombre}"`,
|
|
33
|
+
texto: t,
|
|
34
|
+
}));
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function necesaria(formato, nombre) {
|
|
39
|
+
switch (formato) {
|
|
40
|
+
case "docx":
|
|
41
|
+
return nombre === "word/document.xml";
|
|
42
|
+
case "pptx":
|
|
43
|
+
return /^ppt\/slides\/slide\d+\.xml$/.test(nombre);
|
|
44
|
+
case "xlsx":
|
|
45
|
+
return nombre === "xl/workbook.xml" || nombre === "xl/sharedStrings.xml" ||
|
|
46
|
+
nombre === "xl/_rels/workbook.xml.rels" || nombre.startsWith("xl/worksheets/");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const leer = (zip, ruta) => zip[ruta] ?? "";
|
|
50
|
+
const numero = (ruta) => Number(ruta.match(/(\d+)\.xml$/)?.[1]);
|
|
51
|
+
const ENTIDADES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
52
|
+
const decodificar = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => e[0] !== "#" ? (ENTIDADES[e] ?? m) : String.fromCodePoint(e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : Number(e.slice(1))));
|
|
53
|
+
/**
|
|
54
|
+
* Texto de un XML de Word (`w`) o PowerPoint (`a`), recorriendo los tags en orden: texto de los nodos
|
|
55
|
+
* de texto, salto de línea al cerrar un párrafo, y las tablas como filas con celdas separadas por " | ".
|
|
56
|
+
*/
|
|
57
|
+
function xmlTexto(xml, ns) {
|
|
58
|
+
let out = "";
|
|
59
|
+
let enTexto = false;
|
|
60
|
+
let enCelda = 0;
|
|
61
|
+
for (const [, cierre, tag, , autocierre, chars] of xml.matchAll(/<(\/?)([\w:]+)((?:[^>"]|"[^"]*")*?)(\/?)>|([^<]+)/g)) {
|
|
62
|
+
if (chars !== undefined) {
|
|
63
|
+
if (enTexto)
|
|
64
|
+
out += decodificar(chars);
|
|
65
|
+
}
|
|
66
|
+
else if (tag === `${ns}:t`) {
|
|
67
|
+
enTexto = !cierre && !autocierre;
|
|
68
|
+
}
|
|
69
|
+
else if (tag === `${ns}:tc` && !autocierre) {
|
|
70
|
+
enCelda += cierre ? -1 : 1;
|
|
71
|
+
if (cierre)
|
|
72
|
+
out += " | ";
|
|
73
|
+
}
|
|
74
|
+
else if (tag === `${ns}:tr` && cierre) {
|
|
75
|
+
out += "\n";
|
|
76
|
+
}
|
|
77
|
+
else if (tag === `${ns}:p` && cierre) {
|
|
78
|
+
out += enCelda ? " " : "\n";
|
|
79
|
+
}
|
|
80
|
+
else if (tag === `${ns}:tab`) {
|
|
81
|
+
out += " ";
|
|
82
|
+
}
|
|
83
|
+
else if (tag === `${ns}:br`) {
|
|
84
|
+
out += enCelda ? " " : "\n";
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out
|
|
88
|
+
.split("\n")
|
|
89
|
+
.map((l) => l.replace(/\s+/g, " ").replace(/\s*\|\s*$/, "").trim())
|
|
90
|
+
.filter((l, i, todas) => l !== "|" && (l !== "" || todas[i - 1] !== ""))
|
|
91
|
+
.join("\n")
|
|
92
|
+
.trim();
|
|
93
|
+
}
|
|
94
|
+
/** Cada hoja como filas de celdas separadas por tabs, en el orden del libro. */
|
|
95
|
+
function hojas(zip) {
|
|
96
|
+
const compartidas = [...leer(zip, "xl/sharedStrings.xml").matchAll(/<si>([\s\S]*?)<\/si>/g)].map((m) => decodificar([...m[1].matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map((t) => t[1]).join("")));
|
|
97
|
+
const rels = Object.fromEntries([...leer(zip, "xl/_rels/workbook.xml.rels").matchAll(/<Relationship [^>]*>/g)].map(([tag]) => [
|
|
98
|
+
tag.match(/Id="([^"]+)"/)?.[1],
|
|
99
|
+
tag.match(/Target="([^"]+)"/)?.[1],
|
|
100
|
+
]));
|
|
101
|
+
return [...leer(zip, "xl/workbook.xml").matchAll(/<sheet [^>]*>/g)].map(([tag]) => {
|
|
102
|
+
const nombre = decodificar(tag.match(/name="([^"]*)"/)?.[1] ?? "");
|
|
103
|
+
const destino = rels[tag.match(/r:id="([^"]+)"/)?.[1] ?? ""] ?? "";
|
|
104
|
+
const ruta = destino.replace(/^\//, "").replace(/^(xl\/)?/, "xl/");
|
|
105
|
+
const filas = [...leer(zip, ruta).matchAll(/<row[^>]*>([\s\S]*?)<\/row>/g)].map((fila) => [...fila[1].matchAll(/<c ([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)]
|
|
106
|
+
.map(([, attrs, cuerpo = ""]) => {
|
|
107
|
+
const tipo = attrs.match(/\bt="(\w+)"/)?.[1];
|
|
108
|
+
if (tipo === "s")
|
|
109
|
+
return compartidas[Number(cuerpo.match(/<v>(\d+)<\/v>/)?.[1])] ?? "";
|
|
110
|
+
if (tipo === "inlineStr")
|
|
111
|
+
return decodificar(cuerpo.match(/<t[^>]*>([\s\S]*?)<\/t>/)?.[1] ?? "");
|
|
112
|
+
return decodificar(cuerpo.match(/<v>([\s\S]*?)<\/v>/)?.[1] ?? "");
|
|
113
|
+
})
|
|
114
|
+
.join("\t")
|
|
115
|
+
.replace(/\t+$/, ""));
|
|
116
|
+
return { nombre, texto: filas.filter(Boolean).join("\n") || "(hoja vacía)" };
|
|
117
|
+
});
|
|
118
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { pngGris } from "./png.js";
|
|
2
|
+
/**
|
|
3
|
+
* pdf.js no es una dependencia: scripts/vendor-pdfjs.mjs copia a vendor/pdfjs los pocos archivos que
|
|
4
|
+
* usamos. Está a la misma altura desde src/ y desde build/, así que la ruta sirve en dev y publicado.
|
|
5
|
+
*/
|
|
6
|
+
const VENDOR = new URL("../../../vendor/pdfjs/", import.meta.url);
|
|
7
|
+
/** Al arrancar en Node, pdf.js avisa que le falta canvas para renderizar. No renderizamos: son ruido en el log. */
|
|
8
|
+
const AVISOS_DE_CANVAS = /@napi-rs\/canvas|Cannot polyfill/;
|
|
9
|
+
let pdfjsCargado;
|
|
10
|
+
/** Se carga recién al primer PDF: son 3 MB que el servidor no necesita para arrancar. */
|
|
11
|
+
function pdfjs() {
|
|
12
|
+
pdfjsCargado ??= (async () => {
|
|
13
|
+
const warn = console.warn;
|
|
14
|
+
console.warn = (...args) => {
|
|
15
|
+
if (!AVISOS_DE_CANVAS.test(String(args[0])))
|
|
16
|
+
warn(...args);
|
|
17
|
+
};
|
|
18
|
+
try {
|
|
19
|
+
return (await import(new URL("pdf.mjs", VENDOR).href));
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
console.warn = warn;
|
|
23
|
+
}
|
|
24
|
+
})();
|
|
25
|
+
return pdfjsCargado;
|
|
26
|
+
}
|
|
27
|
+
/** Menos texto que esto en una página la tratamos como escaneada. */
|
|
28
|
+
const MIN_TEXTO = 20;
|
|
29
|
+
/** Lado largo de la imagen de una página: el tamaño que Claude procesa sin reescalar. */
|
|
30
|
+
const LADO_IMAGEN = 1568;
|
|
31
|
+
/** Muestras por eje y por píxel al reducir la imagen; suaviza los bordes y mejora la lectura. */
|
|
32
|
+
const MUESTREO = 2;
|
|
33
|
+
export async function abrirPdf(bytes) {
|
|
34
|
+
const lib = await pdfjs();
|
|
35
|
+
const carga = lib.getDocument({
|
|
36
|
+
data: bytes,
|
|
37
|
+
verbosity: 0,
|
|
38
|
+
isOffscreenCanvasSupported: false,
|
|
39
|
+
// Directo a los decodificadores JS de vendor/pdfjs/wasm: en Node los .wasm no cargan igual.
|
|
40
|
+
useWasm: false,
|
|
41
|
+
wasmUrl: new URL("wasm/", VENDOR).href,
|
|
42
|
+
});
|
|
43
|
+
const pdf = await carga.promise;
|
|
44
|
+
return {
|
|
45
|
+
formato: "pdf",
|
|
46
|
+
unidad: "página",
|
|
47
|
+
total: pdf.numPages,
|
|
48
|
+
parte: async (n) => leerPagina(lib, await pdf.getPage(n)),
|
|
49
|
+
cerrar: () => carga.destroy(),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
async function leerPagina(lib, pagina) {
|
|
53
|
+
const contenido = await pagina.getTextContent();
|
|
54
|
+
let texto = "";
|
|
55
|
+
for (const item of contenido.items) {
|
|
56
|
+
if (!("str" in item))
|
|
57
|
+
continue;
|
|
58
|
+
texto += item.str + (item.hasEOL ? "\n" : "");
|
|
59
|
+
}
|
|
60
|
+
texto = texto.replace(/[ \t]+/g, " ").replace(/ ?\n ?/g, "\n").trim();
|
|
61
|
+
if (texto.length >= MIN_TEXTO)
|
|
62
|
+
return { texto };
|
|
63
|
+
const escaneo = await rasterizarImagenes(lib, pagina);
|
|
64
|
+
if (escaneo)
|
|
65
|
+
return { titulo: "escaneada, como imagen", imagen: escaneo, mimeType: "image/png" };
|
|
66
|
+
return { texto: texto || "(página sin texto)" };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Reconstruye la página dibujando solo sus imágenes, con la posición y rotación con que el PDF
|
|
70
|
+
* las ubica. Una página escaneada es eso: una imagen. Así se evita un renderizador completo, que
|
|
71
|
+
* en Node necesita un canvas nativo.
|
|
72
|
+
*/
|
|
73
|
+
async function rasterizarImagenes({ OPS, Util }, pagina) {
|
|
74
|
+
const base = pagina.getViewport({ scale: 1 });
|
|
75
|
+
const vista = pagina.getViewport({ scale: LADO_IMAGEN / Math.max(base.width, base.height) });
|
|
76
|
+
const ancho = Math.round(vista.width);
|
|
77
|
+
const alto = Math.round(vista.height);
|
|
78
|
+
const lienzo = new Uint8Array(ancho * alto).fill(255);
|
|
79
|
+
const ops = await pagina.getOperatorList();
|
|
80
|
+
let ctm = [1, 0, 0, 1, 0, 0];
|
|
81
|
+
const pila = [];
|
|
82
|
+
let pintadas = 0;
|
|
83
|
+
for (let i = 0; i < ops.fnArray.length; i++) {
|
|
84
|
+
const args = ops.argsArray[i];
|
|
85
|
+
switch (ops.fnArray[i]) {
|
|
86
|
+
case OPS.save:
|
|
87
|
+
pila.push(ctm);
|
|
88
|
+
break;
|
|
89
|
+
case OPS.restore:
|
|
90
|
+
ctm = pila.pop() ?? ctm;
|
|
91
|
+
break;
|
|
92
|
+
case OPS.transform:
|
|
93
|
+
ctm = Util.transform(ctm, args);
|
|
94
|
+
break;
|
|
95
|
+
case OPS.paintFormXObjectBegin:
|
|
96
|
+
pila.push(ctm);
|
|
97
|
+
if (args[0])
|
|
98
|
+
ctm = Util.transform(ctm, args[0]);
|
|
99
|
+
break;
|
|
100
|
+
case OPS.paintFormXObjectEnd:
|
|
101
|
+
ctm = pila.pop() ?? ctm;
|
|
102
|
+
break;
|
|
103
|
+
case OPS.paintImageXObject:
|
|
104
|
+
case OPS.paintInlineImageXObject: {
|
|
105
|
+
const imagen = typeof args[0] === "string" ? await new Promise((res) => pagina.objs.get(args[0], res)) : args[0];
|
|
106
|
+
if (imagen?.data && pintar(lienzo, ancho, alto, imagen, Util.transform(vista.transform, ctm))) {
|
|
107
|
+
pintadas++;
|
|
108
|
+
}
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return pintadas ? pngGris(ancho, alto, lienzo) : null;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Pinta una imagen en el lienzo. La imagen ocupa el cuadrado unitario transformado por `m`; por cada
|
|
117
|
+
* píxel del lienzo se busca el píxel de origen con la transformación inversa, así cualquier rotación
|
|
118
|
+
* o espejado sale bien sin casos especiales.
|
|
119
|
+
*/
|
|
120
|
+
function pintar(lienzo, ancho, alto, img, m) {
|
|
121
|
+
const [a, b, c, d, e, f] = m;
|
|
122
|
+
const det = a * d - b * c;
|
|
123
|
+
if (!det)
|
|
124
|
+
return false;
|
|
125
|
+
const inv = [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];
|
|
126
|
+
const xs = [e, a + e, c + e, a + c + e];
|
|
127
|
+
const ys = [f, b + f, d + f, b + d + f];
|
|
128
|
+
const x0 = Math.max(0, Math.floor(Math.min(...xs)));
|
|
129
|
+
const x1 = Math.min(ancho, Math.ceil(Math.max(...xs)));
|
|
130
|
+
const y0 = Math.max(0, Math.floor(Math.min(...ys)));
|
|
131
|
+
const y1 = Math.min(alto, Math.ceil(Math.max(...ys)));
|
|
132
|
+
const { width: w, height: h, kind } = img;
|
|
133
|
+
const data = img.data;
|
|
134
|
+
const bytesPorFila = (w + 7) >> 3;
|
|
135
|
+
const canales = kind === 2 ? 3 : 4;
|
|
136
|
+
const gris = (col, fila) => {
|
|
137
|
+
if (kind === 1)
|
|
138
|
+
return ((data[fila * bytesPorFila + (col >> 3)] >> (7 - (col & 7))) & 1) * 255;
|
|
139
|
+
const i = (fila * w + col) * canales;
|
|
140
|
+
return data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11;
|
|
141
|
+
};
|
|
142
|
+
for (let y = y0; y < y1; y++) {
|
|
143
|
+
for (let x = x0; x < x1; x++) {
|
|
144
|
+
let suma = 0;
|
|
145
|
+
let n = 0;
|
|
146
|
+
for (let sy = 0; sy < MUESTREO; sy++) {
|
|
147
|
+
for (let sx = 0; sx < MUESTREO; sx++) {
|
|
148
|
+
const px = x + (sx + 0.5) / MUESTREO;
|
|
149
|
+
const py = y + (sy + 0.5) / MUESTREO;
|
|
150
|
+
const u = inv[0] * px + inv[2] * py + inv[4];
|
|
151
|
+
const v = inv[1] * px + inv[3] * py + inv[5];
|
|
152
|
+
if (u < 0 || u >= 1 || v < 0 || v >= 1)
|
|
153
|
+
continue;
|
|
154
|
+
// En el espacio de la imagen v crece hacia arriba; las filas de datos, hacia abajo.
|
|
155
|
+
suma += gris(Math.floor(u * w), Math.floor((1 - v) * h));
|
|
156
|
+
n++;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (n)
|
|
160
|
+
lienzo[y * ancho + x] = suma / n;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { deflateSync } from "node:zlib";
|
|
2
|
+
/** PNG en escala de grises, 8 bits. Alcanza para páginas escaneadas y evita una dependencia de imágenes. */
|
|
3
|
+
export function pngGris(ancho, alto, pixeles) {
|
|
4
|
+
// Cada fila va precedida por el byte de filtro (0 = sin filtro).
|
|
5
|
+
const filas = new Uint8Array(alto * (ancho + 1));
|
|
6
|
+
for (let y = 0; y < alto; y++)
|
|
7
|
+
filas.set(pixeles.subarray(y * ancho, (y + 1) * ancho), y * (ancho + 1) + 1);
|
|
8
|
+
const ihdr = new Uint8Array(13);
|
|
9
|
+
const vista = new DataView(ihdr.buffer);
|
|
10
|
+
vista.setUint32(0, ancho);
|
|
11
|
+
vista.setUint32(4, alto);
|
|
12
|
+
ihdr[8] = 8; // bits por canal
|
|
13
|
+
ihdr[9] = 0; // escala de grises
|
|
14
|
+
return concat([
|
|
15
|
+
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
16
|
+
chunk("IHDR", ihdr),
|
|
17
|
+
chunk("IDAT", deflateSync(filas, { level: 6 })),
|
|
18
|
+
chunk("IEND", new Uint8Array()),
|
|
19
|
+
]);
|
|
20
|
+
}
|
|
21
|
+
function chunk(tipo, datos) {
|
|
22
|
+
const out = new Uint8Array(12 + datos.length);
|
|
23
|
+
const vista = new DataView(out.buffer);
|
|
24
|
+
vista.setUint32(0, datos.length);
|
|
25
|
+
for (let i = 0; i < 4; i++)
|
|
26
|
+
out[4 + i] = tipo.charCodeAt(i);
|
|
27
|
+
out.set(datos, 8);
|
|
28
|
+
vista.setUint32(8 + datos.length, crc32(out.subarray(4, 8 + datos.length)));
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
const TABLA_CRC = Int32Array.from({ length: 256 }, (_, n) => {
|
|
32
|
+
let c = n;
|
|
33
|
+
for (let k = 0; k < 8; k++)
|
|
34
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
35
|
+
return c;
|
|
36
|
+
});
|
|
37
|
+
function crc32(bytes) {
|
|
38
|
+
let c = -1;
|
|
39
|
+
for (const b of bytes)
|
|
40
|
+
c = TABLA_CRC[(c ^ b) & 0xff] ^ (c >>> 8);
|
|
41
|
+
return ~c >>> 0;
|
|
42
|
+
}
|
|
43
|
+
function concat(partes) {
|
|
44
|
+
const out = new Uint8Array(partes.reduce((n, p) => n + p.length, 0));
|
|
45
|
+
let i = 0;
|
|
46
|
+
for (const p of partes) {
|
|
47
|
+
out.set(p, i);
|
|
48
|
+
i += p.length;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { inflateRawSync } from "node:zlib";
|
|
2
|
+
const FIN_DIRECTORIO = 0x06054b50;
|
|
3
|
+
const DIRECTORIO = 0x02014b50;
|
|
4
|
+
const ENCABEZADO_LOCAL = 0x04034b50;
|
|
5
|
+
const SIN_COMPRESION = 0;
|
|
6
|
+
const DEFLATE = 8;
|
|
7
|
+
class ZipInvalido extends Error {
|
|
8
|
+
constructor(detalle) {
|
|
9
|
+
super(`El archivo no es un zip válido: ${detalle}.`);
|
|
10
|
+
this.name = "ZipInvalido";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function listarZip(bytes) {
|
|
14
|
+
const vista = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
15
|
+
// El fin del directorio está al final, seguido de un comentario opcional de hasta 64 KB.
|
|
16
|
+
let fin = -1;
|
|
17
|
+
for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 22 - 0xffff); i--) {
|
|
18
|
+
if (vista.getUint32(i, true) === FIN_DIRECTORIO) {
|
|
19
|
+
fin = i;
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (fin < 0)
|
|
24
|
+
throw new ZipInvalido("no tiene índice");
|
|
25
|
+
const cantidad = vista.getUint16(fin + 10, true);
|
|
26
|
+
let p = vista.getUint32(fin + 16, true);
|
|
27
|
+
if (cantidad === 0xffff || p === 0xffffffff)
|
|
28
|
+
throw new ZipInvalido("usa zip64");
|
|
29
|
+
const entradas = [];
|
|
30
|
+
const nombres = new TextDecoder();
|
|
31
|
+
for (let i = 0; i < cantidad; i++) {
|
|
32
|
+
if (p + 46 > bytes.length || vista.getUint32(p, true) !== DIRECTORIO)
|
|
33
|
+
throw new ZipInvalido("índice corrupto");
|
|
34
|
+
const largoNombre = vista.getUint16(p + 28, true);
|
|
35
|
+
entradas.push({
|
|
36
|
+
nombre: nombres.decode(bytes.subarray(p + 46, p + 46 + largoNombre)),
|
|
37
|
+
metodo: vista.getUint16(p + 10, true),
|
|
38
|
+
comprimido: vista.getUint32(p + 20, true),
|
|
39
|
+
tamanio: vista.getUint32(p + 24, true),
|
|
40
|
+
offset: vista.getUint32(p + 42, true),
|
|
41
|
+
});
|
|
42
|
+
p += 46 + largoNombre + vista.getUint16(p + 30, true) + vista.getUint16(p + 32, true);
|
|
43
|
+
}
|
|
44
|
+
return entradas;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Descomprime una entrada. `max` corta aunque el índice mienta sobre el tamaño: un zip chico que se
|
|
48
|
+
* infla a gigas es un ataque conocido.
|
|
49
|
+
*/
|
|
50
|
+
export function leerEntrada(bytes, entrada, max) {
|
|
51
|
+
if (entrada.tamanio > max)
|
|
52
|
+
throw new ZipInvalido(`"${entrada.nombre}" descomprimido pesa demasiado`);
|
|
53
|
+
const vista = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
54
|
+
const p = entrada.offset;
|
|
55
|
+
if (vista.getUint32(p, true) !== ENCABEZADO_LOCAL)
|
|
56
|
+
throw new ZipInvalido(`falta el encabezado de "${entrada.nombre}"`);
|
|
57
|
+
const inicio = p + 30 + vista.getUint16(p + 26, true) + vista.getUint16(p + 28, true);
|
|
58
|
+
const datos = bytes.subarray(inicio, inicio + entrada.comprimido);
|
|
59
|
+
switch (entrada.metodo) {
|
|
60
|
+
case SIN_COMPRESION:
|
|
61
|
+
return datos;
|
|
62
|
+
case DEFLATE:
|
|
63
|
+
try {
|
|
64
|
+
return inflateRawSync(datos, { maxOutputLength: max });
|
|
65
|
+
}
|
|
66
|
+
catch (e) {
|
|
67
|
+
throw new ZipInvalido(`no se pudo descomprimir "${entrada.nombre}" (${e.message})`);
|
|
68
|
+
}
|
|
69
|
+
default:
|
|
70
|
+
throw new ZipInvalido(`"${entrada.nombre}" usa una compresión no soportada (${entrada.metodo})`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const ENTITIES = { nbsp: " ", amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
2
|
+
/** HTML de Moodle a texto plano: alcanza para que el modelo lo lea, no es un parser. */
|
|
3
|
+
export function htmlToText(html) {
|
|
4
|
+
if (!html)
|
|
5
|
+
return "";
|
|
6
|
+
return html
|
|
7
|
+
.replace(/<(script|style)[\s\S]*?<\/\1>/gi, "")
|
|
8
|
+
.replace(/<br\s*\/?>|<\/(p|div|li|h\d|tr)>/gi, "\n")
|
|
9
|
+
.replace(/<[^>]+>/g, "")
|
|
10
|
+
.replace(/&(#\d+|[a-z]+);/gi, (m, e) => e.startsWith("#") ? String.fromCodePoint(Number(e.slice(1))) : (ENTITIES[e.toLowerCase()] ?? m))
|
|
11
|
+
.replace(/[ \t ]+/g, " ")
|
|
12
|
+
.replace(/\s*\n\s*/g, "\n")
|
|
13
|
+
.trim();
|
|
14
|
+
}
|
|
15
|
+
/** Como htmlToText pero recortado: para índices, donde solo hace falta decidir si entrar. */
|
|
16
|
+
export function htmlToSnippet(html, max = 200) {
|
|
17
|
+
const texto = htmlToText(html);
|
|
18
|
+
return texto.length > max ? `${texto.slice(0, max).trimEnd()}…` : texto;
|
|
19
|
+
}
|
package/package.json
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "utn-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Este es el Model Context Protocol server NO OFICIAL de la UTN para buscar informacion o archivos en el aula virtual.",
|
|
5
5
|
"main": "build/index.js",
|
|
6
6
|
"bin": {
|
|
7
7
|
"utn-mcp": "build/index.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
|
-
"build"
|
|
10
|
+
"build",
|
|
11
|
+
"vendor"
|
|
11
12
|
],
|
|
12
13
|
"scripts": {
|
|
13
14
|
"prebuild": "node -e \"require('fs').rmSync('build',{recursive:true,force:true})\"",
|
|
14
15
|
"build": "tsc",
|
|
15
16
|
"prepublishOnly": "npm run build",
|
|
17
|
+
"prepare": "node scripts/vendor-pdfjs.mjs",
|
|
16
18
|
"start": "node build/index.js",
|
|
17
19
|
"dev": "tsx src/index.ts",
|
|
18
20
|
"test": "echo \"Error: no test specified\" && exit 1",
|
|
@@ -46,6 +48,7 @@
|
|
|
46
48
|
"devDependencies": {
|
|
47
49
|
"@types/express": "^5.0.6",
|
|
48
50
|
"@types/node": "^26.6.4",
|
|
51
|
+
"pdfjs-dist": "^6.4.299",
|
|
49
52
|
"tsx": "^4.23.15",
|
|
50
53
|
"typescript": "^7.0.2"
|
|
51
54
|
},
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|