import { ClassicPreset } from 'rete'; import { BaseWorkflowNode } from './base-node'; import { pdfSocket } from '../sockets'; import type { PDFData, SocketData, MultiPDFData } from '../types'; import { loadPyMuPDF } from '../../utils/pymupdf-loader.js'; import MarkdownIt from 'markdown-it'; import { loadPdfDocument } from '../../utils/load-pdf-document.js'; import { wfError } from '../errors'; const md = new MarkdownIt({ html: true, linkify: true, typographer: true }); export class MarkdownToPdfNode extends BaseWorkflowNode { readonly category = 'Input' as const; readonly icon = 'ph-markdown-logo'; readonly description = 'Upload Markdown files and convert to PDF'; private files: File[] = []; constructor() { super('Markdown Input'); this.addOutput('pdf', new ClassicPreset.Output(pdfSocket, 'PDF')); } async addFiles(fileList: File[]): Promise { for (const file of fileList) { const name = file.name.toLowerCase(); if (name.endsWith('.md') || name.endsWith('.markdown')) { this.files.push(file); } } } removeFile(index: number): void { this.files.splice(index, 1); } hasFile(): boolean { return this.files.length > 0; } getFileCount(): number { return this.files.length; } getFilenames(): string[] { return this.files.map((f) => f.name); } getFilename(): string { if (this.files.length === 0) return ''; if (this.files.length === 1) return this.files[0].name; return `${this.files.length} Markdown files`; } async data( _inputs: Record ): Promise> { if (this.files.length === 0) throw new Error(wfError('noMarkdownUploaded')); const pymupdf = await loadPyMuPDF(); const results: PDFData[] = []; for (const file of this.files) { const textContent = await file.text(); const htmlContent = `${md.render(textContent)}`; const pdfBlob = await ( pymupdf as unknown as { htmlToPdf(html: string, options: unknown): Promise; } ).htmlToPdf(htmlContent, { pageSize: 'a4', }); const bytes = new Uint8Array(await pdfBlob.arrayBuffer()); const pdfDoc = await loadPdfDocument(bytes); results.push({ type: 'pdf', document: pdfDoc, bytes, filename: file.name.replace(/\.(md|markdown)$/i, '.pdf'), }); } if (results.length === 1) return { pdf: results[0] }; return { pdf: { type: 'multi-pdf', items: results } as MultiPDFData }; } }