Toolpal

@toolpal/markdown-to-doc

public

v2.0published 1 download this weekMIT

Converts Markdown (inline or .md/.txt file) or structured JSON/sheets locally into a formatted Word (.docx), PDF (.pdf), or Excel (.xlsx) file. Supports headings, bold/italic/code, links, lists, code blocks, blockquotes, and tables. Offline, no API key needed.

src/index.ts9.4 KBRaw
import { readFileSync, statSync, writeFileSync } from "node:fs";
import { basename, extname, join } from "node:path";
import { defineTool, FilePath, Type } from "@toolpal/tool";
import { renderDocx } from "./docx.js";
import { type MdBlock, parseMarkdown } from "./markdown.js";
import { renderPdf } from "./pdf.js";
import { type Cell, renderXlsx, type Sheet } from "./xlsx.js";

const MAX_BYTES = 20 * 1024 * 1024;

function parseCellValue(raw: string): Cell {
  const s = raw.trim();
  if (s === "") return null;
  if (/^(true|false)$/i.test(s)) return s.toLowerCase() === "true";
  if (/^[-+]?(\d+\.?\d*|\.\d+)$/.test(s)) {
    const n = Number(s);
    if (Number.isFinite(n)) return n;
  }
  return s;
}

function normalizeSheet(input: {
  name: string;
  columns?: string[];
  rows: Array<Record<string, unknown> | unknown[]>;
}): Sheet {
  if (input.rows.length === 0) {
    return { name: input.name, header: input.columns ?? [], rows: [] };
  }
  if (Array.isArray(input.rows[0])) {
    const rows = (input.rows as unknown[][]).map((r) =>
      r.map((v) =>
        typeof v === "string" || typeof v === "number" || typeof v === "boolean" || v === null
          ? v
          : v === undefined
            ? null
            : JSON.stringify(v),
      ),
    );
    const header =
      input.columns ?? Array.from({ length: rows[0]?.length ?? 0 }, (_, i) => `Column ${i + 1}`);
    return { name: input.name, header, rows };
  }
  const objRows = input.rows as Array<Record<string, unknown>>;
  const header =
    input.columns ??
    [...new Set(objRows.flatMap((o) => Object.keys(o)))];
  const rows: Cell[][] = objRows.map((o) =>
    header.map((k) => {
      const v = o[k];
      if (v === null || v === undefined) return null;
      if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") return v;
      return JSON.stringify(v);
    }),
  );
  return { name: input.name, header, rows };
}

function sheetsFromJson(parsed: unknown): Sheet[] {
  if (Array.isArray(parsed)) {
    return [normalizeSheet({ name: "Data", rows: parsed as Array<Record<string, unknown> | unknown[]> })];
  }
  if (parsed && typeof parsed === "object") {
    const obj = parsed as Record<string, unknown>;
    if (Array.isArray(obj.sheets)) {
      return (obj.sheets as Array<{ name: string; columns?: string[]; rows: Array<Record<string, unknown> | unknown[]> }>).map(
        (s, i) => normalizeSheet({ name: s.name || `Sheet ${i + 1}`, columns: s.columns, rows: s.rows ?? [] }),
      );
    }
    const arrayEntries = Object.entries(obj).filter(([, v]) => Array.isArray(v));
    if (arrayEntries.length > 0) {
      return arrayEntries.map(([name, rows]) =>
        normalizeSheet({ name, rows: rows as Array<Record<string, unknown> | unknown[]> }),
      );
    }
  }
  throw new Error("JSON input must be an array of rows/objects or an object containing sheet arrays.");
}

function sheetsFromMarkdown(blocks: MdBlock[]): Sheet[] {
  const tables = blocks.filter((b): b is Extract<MdBlock, { type: "table" }> => b.type === "table");
  if (tables.length > 0) {
    return tables.map((t, i) => ({
      name: t.heading || `Table ${i + 1}`,
      header: t.header,
      rows: t.rows.map((r) => r.map(parseCellValue)),
    }));
  }
  // Fallback when Markdown has no tables: export structured outline.
  let section = "Overview";
  const rows: Cell[][] = [];
  for (const b of blocks) {
    if (b.type === "heading") {
      section = b.text;
    } else if (b.type === "paragraph" || b.type === "quote") {
      rows.push([section, b.type, b.text]);
    } else if (b.type === "bullets" || b.type === "numbered") {
      for (const item of b.items) rows.push([section, "list", item.text]);
    } else if (b.type === "code") {
      rows.push([section, b.language ? `code (${b.language})` : "code", b.code]);
    }
  }
  return [{ name: "Document", header: ["Section", "Type", "Content"], rows }];
}

function markdownFromSheets(sheets: Sheet[]): string {
  const parts: string[] = [];
  for (const s of sheets) {
    parts.push(`## ${s.name}`, "");
    if (s.header.length > 0) {
      parts.push(`| ${s.header.join(" | ")} |`);
      parts.push(`| ${s.header.map(() => "---").join(" | ")} |`);
      for (const row of s.rows) {
        parts.push(`| ${row.map((c) => (c === null || c === undefined ? "" : String(c)).replace(/\|/g, "\\|")).join(" | ")} |`);
      }
      parts.push("");
    }
  }
  return parts.join("\n");
}

function safeStem(raw: string): string {
  return (
    raw
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-+|-+$/g, "")
      .slice(0, 60) || "document"
  );
}

const SheetInput = Type.Object({
  name: Type.String({ minLength: 1, maxLength: 60 }),
  columns: Type.Optional(Type.Array(Type.String(), { maxItems: 100 })),
  rows: Type.Array(Type.Union([Type.Array(Type.Unknown()), Type.Record(Type.String(), Type.Unknown())]), {
    maxItems: 50_000,
  }),
});

export default defineTool({
  description:
    "Converts Markdown (inline or .md/.txt file) or structured JSON/sheets locally into a formatted Word (.docx), PDF (.pdf), or Excel (.xlsx) file. Supports headings, bold/italic/code, links, lists, code blocks, blockquotes, and tables. Offline, no API key needed.",
  input: Type.Object({
    format: Type.Union([Type.Literal("docx"), Type.Literal("pdf"), Type.Literal("xlsx")], {
      description: "Target output format: docx, pdf, or xlsx",
    }),
    markdown: Type.Optional(
      Type.String({ maxLength: 500_000, description: "Markdown text to render" }),
    ),
    file: Type.Optional(
      FilePath({ description: "Input .md, .txt, or .json file (alternative to inline markdown/sheets)" }),
    ),
    sheets: Type.Optional(
      Type.Array(SheetInput, {
        minItems: 1,
        maxItems: 20,
        description: "Structured worksheet data (ideal for format: xlsx, also renders as tables in docx/pdf)",
      }),
    ),
    title: Type.Optional(Type.String({ maxLength: 200, description: "Document title (docx/pdf)" })),
    subtitle: Type.Optional(
      Type.String({ maxLength: 300, description: "Subtitle, author, or date line (docx/pdf)" }),
    ),
    filename: Type.Optional(
      Type.String({ maxLength: 80, description: "Output filename without extension" }),
    ),
    pageSize: Type.Optional(
      Type.Union([Type.Literal("letter"), Type.Literal("a4")], {
        description: "Page size for docx/pdf; letter by default",
      }),
    ),
  }),
  output: Type.Object({
    file: FilePath({ description: "Generated .docx, .pdf, or .xlsx file" }),
    format: Type.String(),
    bytes: Type.Integer(),
    pages: Type.Optional(Type.Integer({ description: "Page count (for PDF output)" })),
    sheets: Type.Optional(Type.Integer({ description: "Worksheet count (for XLSX output)" })),
    blocks: Type.Optional(Type.Integer({ description: "Parsed block count (for DOCX/PDF output)" })),
  }),
  handler: async (input, ctx) => {
    if (!input.markdown && !input.file && !input.sheets) {
      throw new Error("Provide markdown, file, or sheets.");
    }

    let mdText = input.markdown;
    let jsonSheets: Sheet[] | undefined = input.sheets?.map(normalizeSheet);

    if (input.file) {
      const { size } = statSync(input.file);
      if (size > MAX_BYTES) {
        throw new Error(`The file is ${(size / 1048576).toFixed(1)} MB; the limit is 20 MB.`);
      }
      const ext = extname(input.file).toLowerCase();
      const raw = readFileSync(input.file, "utf8");
      if (ext === ".json") {
        let parsed: unknown;
        try {
          parsed = JSON.parse(raw);
        } catch (err) {
          throw new Error(`Invalid JSON file: ${(err as Error).message}`);
        }
        jsonSheets = sheetsFromJson(parsed);
      } else if (ext === ".md" || ext === ".markdown" || ext === ".txt" || ext === "") {
        mdText = raw;
      } else {
        throw new Error(`Unsupported input file "${ext}". Use .md, .txt, or .json.`);
      }
    }

    const stem = safeStem(
      input.filename ??
        input.title ??
        (input.file ? basename(input.file, extname(input.file)) : "document"),
    );
    const outPath = join(ctx.outputDir, `${stem}.${input.format}`);

    if (input.format === "xlsx") {
      const sheets = jsonSheets ?? sheetsFromMarkdown(parseMarkdown(mdText ?? ""));
      const buf = renderXlsx(sheets);
      writeFileSync(outPath, buf);
      ctx.log("info", `Wrote ${outPath} (${sheets.length} sheet(s), ${buf.length} bytes)`);
      return { file: outPath, format: "xlsx", bytes: buf.length, sheets: sheets.length };
    }

    const sourceMd = mdText ?? (jsonSheets ? markdownFromSheets(jsonSheets) : "");
    const blocks = parseMarkdown(sourceMd);
    if (blocks.length === 0 && !input.title) {
      throw new Error("The input contains no content to render.");
    }

    if (input.format === "docx") {
      const buf = renderDocx(blocks, {
        title: input.title,
        subtitle: input.subtitle,
        pageSize: input.pageSize,
      });
      writeFileSync(outPath, buf);
      ctx.log("info", `Wrote ${outPath} (${blocks.length} block(s), ${buf.length} bytes)`);
      return { file: outPath, format: "docx", bytes: buf.length, blocks: blocks.length };
    }

    const { buffer, pages } = renderPdf(blocks, {
      title: input.title,
      subtitle: input.subtitle,
      pageSize: input.pageSize,
    });
    writeFileSync(outPath, buffer);
    ctx.log("info", `Wrote ${outPath} (${pages} page(s), ${buffer.length} bytes)`);
    return {
      file: outPath,
      format: "pdf",
      bytes: buffer.length,
      pages,
      blocks: blocks.length,
    };
  },
});