import { Hono } from "https://esm.sh/hono";
import { html } from "https://esm.sh/hono/html";
import TurndownService from "https://esm.sh/turndown";
const app = new Hono();
app.get("/", (c) => {
return c.html(html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML to Markdown Converter</title>
<script src="https://unpkg.com/htmx.org@1.9.2"></script>
<script src="https://unpkg.com/alpinejs@3.12.2/dist/cdn.min.js" defer></script>
</head>
<body>
<div x-data="{ markdown: '' }">
<h1>HTML to Markdown Converter</h1>
<div>
<h2>HTML Input</h2>
<textarea id="html-input" name="html-input" rows="10" cols="50"></textarea>
</div>
<button hx-post="/convert" hx-trigger="click" hx-target="#markdown-output" hx-include="#html-input">
Convert to Markdown
</button>
<div>
<h2>Markdown Output</h2>
<textarea id="markdown-output" x-model="markdown" rows="10" cols="50" readonly></textarea>
</div>
<button @click="navigator.clipboard.writeText(markdown)">Copy to Clipboard</button>
<p>
<a href="${import.meta.url.replace("esm.town", "val.town")}">View Source</a>
</p>
</div>
</body>
</html>
`);
});
app.post("/convert", async (c) => {
try {
const body = await c.req.text();
const params = new URLSearchParams(body);
let html = params.get("html-input");
if (typeof html !== "string") {
return c.text("Invalid input: HTML must be a string");
}
html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
html = html.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, "");
html = html.replace(/<(meta|link|input|br|hr)[^>]*>/gi, "");
html = html.replace(/<!--[\s\S]*?-->/g, "");
const turndownService = new TurndownService();
const markdown = turndownService.turndown(html);
const cleanedMarkdown = markdown.trim().replace(/\n{3,}/g, "\n\n");
return c.text(cleanedMarkdown);
} catch (error) {
console.error("Error in /convert:", error);
return c.text(`An error occurred: ${error.message}`);
}
});
export default async function server(req: Request): Promise<Response> {
return app.fetch(req);
}