Workflow Automation v0.1.2 · claude-code
Archive SHA-256 85be31abe46644f344964c8b1d4b56f6d7218b34a58fd31ffb075c5e5b587476 · 89.5 KB · built Dec 1, 2026
src/markdown.js
// Markdown reading: simple front matter (key: value lines, inline [a, b] lists), ATX headings and
// checkbox tasks. Content is data; nothing in it is interpreted as an instruction.
import { record } from "./values.js";
function scalar(v) {
let s = v.trim();
if ((s.startsWith('"') && s.endsWith('"') && s.length >= 2) || (s.startsWith("'") && s.endsWith("'") && s.length >= 2)) s = s.slice(1, -1);
return s;
}
/** Splits optional front matter (--- ... --- at the very top) from the body. */
export function frontMatter(text) {
const m = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
if (!m) return { data: record(), body: text, lines: 0 };
const data = record();
let lastKey = null;
for (const line of m[1].split(/\r?\n/)) {
const kv = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line);
if (kv) {
const [, k, raw] = kv;
if (k === "__proto__" || k === "constructor" || k === "prototype") continue;
const v = raw.trim();
if (v.startsWith("[") && v.endsWith("]")) data[k] = v.slice(1, -1).split(",").map(scalar).filter(Boolean);
else data[k] = v === "" ? [] : scalar(v);
lastKey = k;
} else {
const item = /^\s+-\s+(.*)$/.exec(line);
if (item && lastKey && Array.isArray(data[lastKey])) data[lastKey].push(scalar(item[1]));
}
}
for (const k of Object.keys(data)) if (Array.isArray(data[k]) && !data[k].length) data[k] = "";
return { data, body: text.slice(m[0].length), lines: m[0].split("\n").length - 1 };
}
/** Headings and tasks with 1-based line numbers (counted in the whole file), outside code fences. */
export function analyzeMarkdown(text) {
const fm = frontMatter(text);
const headings = [];
const tasks = [];
let fence = null;
let section = "";
const lines = fm.body.split(/\r?\n/);
lines.forEach((line, i) => {
const lineNo = i + 1 + fm.lines;
const f = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
if (f) {
if (!fence) fence = f[1][0];
else if (f[1][0] === fence) fence = null;
return;
}
if (fence) return;
const h = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
if (h) {
headings.push(record([["level", h[1].length], ["text", h[2]], ["line", lineNo]]));
section = h[2];
return;
}
const t = /^\s*(?:[-*+]|\d+[.)])\s+\[([ xX])\]\s+(.*)$/.exec(line);
if (t) tasks.push(record([["text", t[2].trim()], ["done", t[1] !== " "], ["line", lineNo], ["section", section]]));
});
const words = fm.body.replace(/```[\s\S]*?```/g, " ").match(/[\p{L}\p{N}][\p{L}\p{N}'’-]*/gu);
const firstH1 = headings.find((h) => h.level === 1);
return { front_matter: fm.data, body: fm.body, headings, tasks, word_count: words ? words.length : 0, title: typeof fm.data.title === "string" && fm.data.title ? fm.data.title : firstH1 ? firstH1.text : "" };
}