Import a Word document as a blog post, and add table blocks

- Table content blocks (migration 044): a grid of text, a row per
  line, cells split by |, the first row the header; cells take the
  same formatting as a paragraph; wide tables scroll on a phone
- Blog posts -> Import from Word: the server reads the .docx (zip and
  XML read without a library, sizes capped) and creates an unpublished
  post through the CRUD engine: title, date, headings, paragraphs,
  lists, tables, bold, italic and links; the editor opens with a note
  of what came over and what didn't (images)
- docs/importing.md, and an nginx block for the upload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 12:44:20 -05:00
parent adc88e5714
commit 7f12824c93
16 changed files with 656 additions and 6 deletions

121
server/src/routes/import.js Normal file
View file

@ -0,0 +1,121 @@
/* ═══════════════════════════════════════════════════════════════
IMPORT ROUTES (mounted under /api/admin)
POST /import/docx a Word document → a new blog post, unpublished
Blog posts → Import from Word. The document becomes a draft post
(docx.js decides what each part becomes), created through the same
CRUD engine as the editor, so it's validated the same way. The
reply says what came over and what didn't (images), and the admin
opens the new post for review before anyone publishes it.
nginx caps /api/ bodies at 64k; this path needs its own block
with a larger client_max_body_size (docs/media-uploads.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { createRow, HttpError } from "../admin-crud.js";
import { ENTITIES } from "../admin-schema.js";
import { DocxError, readDocx } from "../docx.js";
import { NO_STORE } from "../shape.js";
const MAX_DOCX_BYTES = 10 * 1024 * 1024;
const imports = new Hono();
imports.use("*", requireAuth);
const slug = (text) =>
String(text ?? "")
.toLowerCase()
.normalize("NFKD")
.replace(/[^\w\s-]/g, "")
.trim()
.replace(/[\s_]+/g, "-")
.replace(/-+/g, "-")
.slice(0, 64)
.replace(/-$/, "") || "imported-post";
/* A free URL ID: the title's slug, or it with -2, -3... */
function freeId(db, base) {
const taken = (id) => db.prepare(`SELECT 1 FROM blog_posts WHERE id = ?`).get(id);
let id = base;
for (let n = 2; taken(id); n++) id = `${base.slice(0, 60)}-${n}`;
return id;
}
imports.post(
"/import/docx",
requireRole("editor"),
bodyLimit({
maxSize: MAX_DOCX_BYTES + 64 * 1024,
onError: (c) => c.json({ error: "That document is too large (10 MB at most)." }, 413),
}),
async (c) => {
const db = c.get("db");
let body;
try {
body = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = body.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
let doc;
try {
doc = readDocx(Buffer.from(await file.arrayBuffer()));
} catch (err) {
if (err instanceof DocxError) return c.json({ error: err.message }, 400);
return c.json({ error: "That document couldn't be read. Save it again as .docx and retry." }, 400);
}
if (doc.blocks.length === 0) return c.json({ error: "That document has no text to import." }, 400);
const title = doc.title || String(file.name ?? "").replace(/\.docx$/i, "") || "Imported post";
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
const payload = {
id: freeId(db, slug(title)),
title: title.slice(0, 200),
published_on: doc.date,
is_published: 0,
is_listed: 1,
// A long document with sections reads better with its contents.
show_contents: headings >= 3 ? 1 : 0,
content_blocks: doc.blocks.map((block) => ({
slot: "body",
type: block.type,
text: block.text ?? null,
items: block.items ?? [],
})),
};
try {
const row = createRow(db, ENTITIES.blog_posts, payload);
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
console.log(`blog_posts ${row.id} imported from Word by ${c.get("user").email}`);
return c.json(
{
id: row.id,
summary: {
blocks: doc.blocks.length,
headings,
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
skipped: doc.skipped,
},
},
201,
NO_STORE,
);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;
}
},
);
export default imports;