import { copyFileSync } from "node:fs"; import path from "node:path"; import { cleanupStaged, planOutput } from "../core/paths.ts"; import { cleanupPreviewDirectory, makeWorkDirectory, removeWorkDirectory } from "../core/temp.ts"; import { finalizePdfOutput, type PdfArtifactResult } from "../pdf/operations.ts"; import { PdfRuntime } from "../pdf/runtime.ts"; import { wordConvertPdf, wordCreate, type DocumentType } from "../word/operations.ts"; import { WordRuntime } from "../word/runtime.ts"; import type { StylePreset, WordStyleInput } from "../word/styles.ts"; export async function createPdfThroughWord(word: WordRuntime, pdf: PdfRuntime, options: { outputPath: string; title?: string; author?: string; documentType?: DocumentType; markdown?: string; text?: string; stylePreset?: StylePreset; style?: WordStyleInput; overwrite?: boolean; previewDirectory?: string; }): Promise { const plan = planOutput({ outputPath: options.outputPath, cwd: pdf.cwd, extension: ".pdf", overwrite: options.overwrite }); const work = makeWorkDirectory(); const docxPath = path.join(work, "source.docx"); const convertedPath = path.join(work, "converted.pdf"); const previewDirectories: string[] = []; try { const created = await wordCreate(word, { outputPath: docxPath, ...(options.title !== undefined ? { title: options.title } : {}), ...(options.author !== undefined ? { author: options.author } : {}), ...(options.documentType !== undefined ? { documentType: options.documentType } : {}), ...(options.markdown !== undefined ? { markdown: options.markdown } : {}), ...(options.text !== undefined ? { text: options.text } : {}), ...(options.stylePreset !== undefined ? { stylePreset: options.stylePreset } : {}), ...(options.style !== undefined ? { style: options.style } : {}), }); previewDirectories.push(created.previewDirectory); const converted = await wordConvertPdf(word, { inputPath: docxPath, outputPath: convertedPath }); previewDirectories.push(converted.previewDirectory); copyFileSync(convertedPath, plan.stagedPath); const result = await finalizePdfOutput(pdf, plan, options.previewDirectory); return { ...result, intermediate: "temporary-docx" }; } catch (error) { cleanupStaged(plan); throw error; } finally { for (const directory of previewDirectories) { try { cleanupPreviewDirectory(directory); } catch { /* managed preview cleanup is best effort */ } } removeWorkDirectory(work); } }