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

View file

@ -148,6 +148,7 @@ export const blocksChild = (ownerKind) => ({
"button",
"callout",
"schedule",
"table",
],
{ required: true },
),

249
server/src/docx.js Normal file
View file

@ -0,0 +1,249 @@
/* ═══════════════════════════════════════════════════════════════
DOCX → CONTENT BLOCKS
Reads a Word document and turns it into a blog post's content
blocks (routes/import.js; Blog posts → Import from Word):
the Title, or the first Heading 1 the post's title
a date line right under it the post's date
Heading 1 and 2 heading blocks
Heading 3 and below subheading blocks
paragraphs paragraph blocks
runs of list paragraphs one list block, one item each
tables table blocks (a row per line,
cells split by |)
bold, italic, links **bold**, *italic*, [text](url)
Images, text boxes, footnotes and comments aren't carried over;
the result counts what was skipped so the editor can say so.
A .docx is a zip of XML. Both are read here with no library: the
zip through Node's own zlib, the XML with a small tokenizer. The
file is someone's upload, so every size is capped and the XML is
walked once, with no pattern that rescans it.
═══════════════════════════════════════════════════════════════ */
import { inflateRawSync } from "node:zlib";
export class DocxError extends Error {
constructor(message) {
super(message);
this.status = 400;
}
}
const MAX_PART_BYTES = 20 * 1024 * 1024; // any one XML part, unpacked
const PARTS = ["word/document.xml", "word/styles.xml", "word/_rels/document.xml.rels"];
/* ── Zip ───────────────────────────────────────────────────────── */
/* The named entries of a zip, unpacked. Reads the central directory
(the index at the end), so it never walks the whole file. */
function unzip(buf, wanted) {
const out = {};
// End of central directory: the last 0x06054b50 in the final 64 KB.
let eocd = -1;
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
if (buf.readUInt32LE(i) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd === -1) throw new DocxError("That file isn't a Word document (.docx).");
const count = buf.readUInt16LE(eocd + 10);
let at = buf.readUInt32LE(eocd + 16);
for (let n = 0; n < count && at + 46 <= buf.length; n++) {
if (buf.readUInt32LE(at) !== 0x02014b50) break;
const method = buf.readUInt16LE(at + 10);
const packed = buf.readUInt32LE(at + 20);
const size = buf.readUInt32LE(at + 24);
const nameLen = buf.readUInt16LE(at + 28);
const extraLen = buf.readUInt16LE(at + 30);
const commentLen = buf.readUInt16LE(at + 32);
const local = buf.readUInt32LE(at + 42);
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
at += 46 + nameLen + extraLen + commentLen;
if (!wanted.includes(name)) continue;
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
const data = buf.subarray(dataAt, dataAt + packed);
if (method === 0) out[name] = data.toString("utf8");
else if (method === 8) out[name] = inflateRawSync(data, { maxOutputLength: MAX_PART_BYTES }).toString("utf8");
}
return out;
}
/* ── XML ───────────────────────────────────────────────────────── */
const ENTITY = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
const decode = (s) =>
s.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos);/gi, (_, e) => {
if (e[0] !== "#") return ENTITY[e.toLowerCase()];
const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1));
return String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
});
/* A tree of { name, attrs, children, text }. One pass of one global
regex over the tags, so its cost is the file's length. */
function parseXml(xml) {
const root = { name: "#root", attrs: {}, children: [] };
const stack = [root];
const token = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([^\s>/]+)([^>]*?)(\/?)>|([^<]+)/g;
let m;
while ((m = token.exec(xml))) {
const top = stack[stack.length - 1];
if (m[1] !== undefined) top.children.push({ name: "#text", text: m[1] });
else if (m[6] !== undefined) top.children.push({ name: "#text", text: decode(m[6]) });
else if (m[3]) {
if (m[2]) {
if (stack.length > 1) stack.pop();
} else {
const attrs = {};
for (const a of m[4].matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g)) attrs[a[1]] = decode(a[2]);
const node = { name: m[3], attrs, children: [] };
top.children.push(node);
if (!m[5]) stack.push(node);
}
}
}
return root;
}
const kids = (node, name) => (node?.children ?? []).filter((c) => c.name === name);
const kid = (node, name) => (node?.children ?? []).find((c) => c.name === name);
function* all(node, name) {
for (const c of node?.children ?? []) {
if (c.name === name) yield c;
yield* all(c, name);
}
}
const on = (el) => el && !["0", "false"].includes(el.attrs["w:val"]);
/* ── Text ──────────────────────────────────────────────────────── */
function runText(r) {
let t = "";
for (const c of r.children) {
if (c.name === "w:t") t += c.children.map((x) => x.text ?? "").join("");
else if (c.name === "w:tab") t += " ";
else if (c.name === "w:br" || c.name === "w:cr") t += " ";
}
if (!t.trim()) return t;
const rpr = kid(r, "w:rPr");
const b = on(kid(rpr, "w:b"));
const i = on(kid(rpr, "w:i"));
const lead = t.match(/^\s*/)[0];
const trail = t.match(/\s*$/)[0];
const core = t.trim();
const marked = b && i ? `***${core}***` : b ? `**${core}**` : i ? `*${core}*` : core;
return lead + marked + trail;
}
const SAFE_LINK = /^(https?:|mailto:)/i;
function paragraphText(p, rels, counts) {
let out = "";
for (const c of p.children) {
if (c.name === "w:r") {
if (kid(c, "w:drawing") || kid(c, "w:pict")) counts.images++;
out += runText(c);
} else if (c.name === "w:hyperlink") {
const label = [...all(c, "w:r")].map(runText).join("").trim();
const href = rels[c.attrs["r:id"]];
out += href && SAFE_LINK.test(href) && label ? `[${label.replace(/[[\]]/g, "")}](${href})` : label;
} else if (c.name === "w:ins" || c.name === "w:smartTag" || c.name === "w:sdt") {
out += [...all(c, "w:r")].map(runText).join("");
}
}
// Word splits a phrase into runs; adjacent bold runs meet as "** **".
return out.replace(/\*\*(\s*)\*\*/g, "$1").replace(/\s+/g, " ").trim();
}
/* ── Document ──────────────────────────────────────────────────── */
const DATE_LINE = /^([A-Z][a-z]{2,8}\.? \d{1,2},? \d{4}|\d{4}-\d{2}-\d{2}|\d{1,2} [A-Z][a-z]{2,8} \d{4})\b/;
export function readDocx(buf) {
const parts = unzip(buf, PARTS);
if (!parts["word/document.xml"]) throw new DocxError("That file isn't a Word document (.docx).");
const rels = {};
for (const r of all(parseXml(parts["word/_rels/document.xml.rels"] ?? ""), "Relationship")) {
if (r.attrs.TargetMode === "External" || /^https?:|^mailto:/i.test(r.attrs.Target ?? "")) rels[r.attrs.Id] = r.attrs.Target;
}
const styleName = {};
for (const s of all(parseXml(parts["word/styles.xml"] ?? ""), "w:style")) {
styleName[s.attrs["w:styleId"]] = (kid(s, "w:name")?.attrs["w:val"] ?? s.attrs["w:styleId"]).toLowerCase();
}
const body = kid(kid(parseXml(parts["word/document.xml"]), "w:document"), "w:body");
if (!body) throw new DocxError("That document has no body to import.");
const counts = { images: 0 };
const blocks = [];
let title = null;
let date = null;
let list = null; // the list block being filled
const close = () => {
if (list) blocks.push(list);
list = null;
};
for (const el of body.children) {
if (el.name === "w:tbl") {
close();
const rows = kids(el, "w:tr").map((tr) =>
kids(tr, "w:tc")
.map((tc) =>
kids(tc, "w:p")
.map((p) => paragraphText(p, rels, counts))
.filter(Boolean)
.join(" / ")
.replace(/\|/g, "\\|"),
)
.join(" | "),
);
if (rows.some((r) => r.replace(/[|\s]/g, ""))) blocks.push({ type: "table", text: rows.join("\n") });
continue;
}
if (el.name !== "w:p") continue;
const ppr = kid(el, "w:pPr");
const style = styleName[kid(ppr, "w:pStyle")?.attrs["w:val"]] ?? "";
const text = paragraphText(el, rels, counts);
if (!text) continue;
const level = style === "title" ? 0 : Number(/^heading (\d)/.exec(style)?.[1] ?? NaN);
if (!title && (level === 0 || level === 1)) {
close();
title = text.replace(/\*/g, "");
continue;
}
// The line under the title, when it starts with a date ("Sep 28,
// 2026 · @Aidan"), is the post's date, not part of the body.
if (title && !date && blocks.length === 0 && !list) {
const d = DATE_LINE.exec(text.replace(/\*/g, ""));
const parsed = d && new Date(d[1]);
if (parsed && !Number.isNaN(parsed.getTime())) {
date = parsed.toISOString().slice(0, 10);
continue;
}
}
if (level >= 1) {
close();
blocks.push({ type: level <= 2 ? "heading" : "subheading", text: text.replace(/\*/g, "") });
continue;
}
if (kid(ppr, "w:numPr") || /list/.test(style)) {
if (!list) list = { type: "list", items: [] };
list.items.push({ text });
continue;
}
close();
blocks.push({ type: "paragraph", text });
}
close();
return { title, date, blocks, skipped: counts };
}

View file

@ -34,6 +34,7 @@ import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js";
import clips from "./routes/clips.js";
import imports from "./routes/import.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
@ -179,6 +180,7 @@ app.route("/api/auth", auth);
app.route("/api/admin", admin);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", imports);
app.route("/api/admin", clips);
app.route("/api/admin", adminEntities);

View file

@ -0,0 +1,72 @@
-- ═══════════════════════════════════════════════════════════════
-- 044 TABLE BLOCKS
--
-- A content block of type 'table': a grid of text, for comparison
-- charts and the like (a blog post imported from Word, say). The
-- grid is the block's text, one row per line, cells split by "|",
-- the first row the header; cells take the same inline formatting as
-- a paragraph (**bold**, *italic*, [link](url)). ContentBlocks.tsx
-- draws it.
--
-- Only the type's CHECK changes, and SQLite can't alter a CHECK, so
-- the table is rebuilt the way 031, 032 and 034 did it
-- (legacy_alter_table around the rename, then its index and owner
-- trigger again).
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider',
'video', 'button', 'callout', 'schedule', 'table')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
END;
END;

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;