extract-refdoc 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @fileoverview Reading a `.refdoc.html` file back into its pages. Shared by
3
+ * the browser runtime (which boots the docs UI from it) and `parseRefdoc` in
4
+ * Node (via linkedom), so both see the same document. DOM only, no imports.
5
+ *
6
+ * The file layout (written by `renderRefdocHtml` in `refdoc.ts`):
7
+ *
8
+ * ```html
9
+ * <script type="application/refdoc+json" id="refdoc-meta">{ "format": "refdoc", "version": 1, "title": … }</script>
10
+ * <div id="refdoc-root">
11
+ * <article data-refdoc-page="" data-title="…">…overview html…</article>
12
+ * <article data-refdoc-page="01-introduction" data-title="Introduction" data-part="…">…</article>
13
+ * <article data-refdoc-page="references" data-title="References">…</article>
14
+ * </div>
15
+ * ```
16
+ *
17
+ * The pages are plain HTML, so the file reads fine with no script at all,
18
+ * and the content exists exactly once. Each article's id is its slug (the
19
+ * overview's is `overview`) and every heading id is prefixed with its page
20
+ * slug, so one `#id` names a page or a place on it, with or without the
21
+ * runtime. Elements marked `data-refdoc-fallback` (the title block) are
22
+ * dropped by the runtime, which renders its own.
23
+ *
24
+ * @module refdoc-read
25
+ */
26
+
27
+ /** The refdoc format version this package writes and reads. */
28
+ export const REFDOC_VERSION = 1
29
+
30
+ /** Document-level metadata, stored as JSON in `#refdoc-meta`. */
31
+ export interface RefdocMeta {
32
+ format: "refdoc"
33
+ version: number
34
+ title: string
35
+ description?: string
36
+ author?: string
37
+ date?: string
38
+ sourceUrl?: string
39
+ cite?: string
40
+ keywords?: string[]
41
+ /** What wrote the file, e.g. "refdoc 0.2.0". */
42
+ generator?: string
43
+ }
44
+
45
+ /** One heading inside a page, for the table of contents and search. */
46
+ export interface RefdocHeading {
47
+ id: string
48
+ title: string
49
+ /** 2 for `<h2>`, 3 for `<h3>`, … */
50
+ depth: number
51
+ }
52
+
53
+ /** One page: an `<article data-refdoc-page>`. */
54
+ export interface RefdocPage {
55
+ /** "" for the overview page, else the URL slug. */
56
+ slug: string
57
+ title: string
58
+ description?: string
59
+ /** A part heading this page opens (a separator in the sidebar). */
60
+ part?: string
61
+ html: string
62
+ headings: RefdocHeading[]
63
+ }
64
+
65
+ /** A whole refdoc. */
66
+ export interface RefdocDocument extends RefdocMeta {
67
+ pages: RefdocPage[]
68
+ }
69
+
70
+ /** Read the meta JSON and every page from a parsed document. Throws when it is not a refdoc. */
71
+ export function readRefdocFromDocument(doc: Document): RefdocDocument {
72
+ const metaEl = doc.getElementById("refdoc-meta")
73
+ if (!metaEl) throw new Error("Not a refdoc: no <script id=\"refdoc-meta\">")
74
+ const meta = JSON.parse(metaEl.textContent || "{}") as RefdocMeta
75
+ if (meta.format !== "refdoc") throw new Error("Not a refdoc: #refdoc-meta has no format \"refdoc\"")
76
+
77
+ const pages: RefdocPage[] = []
78
+ for (const original of Array.from(doc.querySelectorAll("article[data-refdoc-page]"))) {
79
+ // The title block is only for reading the file without the runtime, which shows its own.
80
+ const article = original.cloneNode(true) as Element
81
+ for (const el of Array.from(article.querySelectorAll("[data-refdoc-fallback]"))) el.remove()
82
+ const headings: RefdocHeading[] = []
83
+ for (const h of Array.from(article.querySelectorAll("h2[id], h3[id], h4[id]"))) {
84
+ headings.push({ id: h.getAttribute("id")!, title: (h.textContent || "").replace(/\s+/g, " ").trim(), depth: Number(h.tagName.slice(1)) })
85
+ }
86
+ pages.push({
87
+ slug: article.getAttribute("data-refdoc-page") || "",
88
+ title: article.getAttribute("data-title") || meta.title,
89
+ description: article.getAttribute("data-description") || undefined,
90
+ part: article.getAttribute("data-part") || undefined,
91
+ html: article.innerHTML,
92
+ headings,
93
+ })
94
+ }
95
+ return { ...meta, pages }
96
+ }
package/src/refdoc.ts ADDED
@@ -0,0 +1,250 @@
1
+ /**
2
+ * @fileoverview The refdoc format: one shareable `.refdoc.html` file that
3
+ * holds the whole document and opens as a full Fumadocs docs site.
4
+ *
5
+ * The file carries every page as plain HTML (`<article data-refdoc-page>`),
6
+ * a little metadata JSON, and two tags that load the runtime from a CDN:
7
+ *
8
+ * ```html
9
+ * <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/extract-refdoc@0/dist/refdoc.css">
10
+ * <script defer src="https://cdn.jsdelivr.net/npm/extract-refdoc@0/dist/refdoc.js"></script>
11
+ * ```
12
+ *
13
+ * The runtime (`runtime/main.tsx`, built to `dist/refdoc.js`) reads the
14
+ * pages out of the file and boots Fumadocs UI in the browser: sidebar,
15
+ * table of contents, ⌘K search, previous/next, light and dark, plus the
16
+ * Reader mode / Underlining / Voice bar and linked references. With no
17
+ * network the file still reads as one long page. `runtime: "inline"` (or
18
+ * `{ js, css }`) embeds the runtime itself for a file that works fully
19
+ * offline, at the cost of size.
20
+ *
21
+ * `paperToRefdoc(paper)` is the converter from a `Paper` (any PDF, link,
22
+ * DOI or text, via `convertToPaper`); `renderRefdocHtml(doc)` writes any
23
+ * `RefdocDocument`, so other sources can produce refdocs too; and
24
+ * `parseRefdoc(html)` reads one back.
25
+ *
26
+ * @module refdoc
27
+ */
28
+ import { parseHTML } from "linkedom"
29
+ import { figureHtml, paragraphsHtml } from "./html"
30
+ import { escapeHtml, markdownInlineToHtml, markdownToPlainText } from "./markdown"
31
+ import { sectionSlug, slugify } from "./mdx"
32
+ import { readRefdocFromDocument, REFDOC_VERSION, type RefdocDocument, type RefdocMeta, type RefdocPage } from "./refdoc-read"
33
+ import type { Paper } from "./types"
34
+
35
+ export { readRefdocFromDocument, REFDOC_VERSION, type RefdocDocument, type RefdocHeading, type RefdocMeta, type RefdocPage } from "./refdoc-read"
36
+
37
+ /** This package's version, written into each file's `generator`. */
38
+ export const REFDOC_PACKAGE_VERSION = "0.2.0"
39
+
40
+ /** Where the runtime is served from: the npm package on jsDelivr, any 0.x. */
41
+ export const REFDOC_CDN = "https://cdn.jsdelivr.net/npm/extract-refdoc@0/dist"
42
+
43
+ /** The id of the overview page's `<article>` (its slug is ""). */
44
+ export const OVERVIEW_ID = "overview"
45
+
46
+ /** How the file gets its runtime. */
47
+ export type RefdocRuntime =
48
+ /** Load `refdoc.js` and `refdoc.css` from `REFDOC_CDN` (the default). */
49
+ | "cdn"
50
+ /** Load them from another base URL, e.g. "./" next to the file, or a pinned version. */
51
+ | { base: string }
52
+ /** Embed them, for a file that works offline. */
53
+ | { js: string; css: string }
54
+
55
+ export interface RenderRefdocOptions {
56
+ runtime?: RefdocRuntime
57
+ }
58
+
59
+ function escapeJsonForScript(json: string): string {
60
+ return json.replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029")
61
+ }
62
+
63
+ function escapeInlineScript(js: string): string {
64
+ return js.replace(/<\/script/gi, "<\\/script")
65
+ }
66
+
67
+ /** Readable styles for the file before (or without) the runtime. */
68
+ const FALLBACK_CSS = `#refdoc-root{max-width:46rem;margin:0 auto;padding:1.5rem 1rem 4rem;font:16px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1c1917}
69
+ #refdoc-root article{border-bottom:1px solid #e7e5e4;padding-bottom:2rem;margin-bottom:2rem}
70
+ #refdoc-root img{max-width:100%;height:auto}#refdoc-root a{color:#2563eb}
71
+ #refdoc-root mark.debate-hl{background:#fef08a}
72
+ @media (prefers-color-scheme:dark){body{background:#0c0a09}#refdoc-root{color:#e7e5e4}#refdoc-root article{border-color:#292524}#refdoc-root a{color:#60a5fa}#refdoc-root mark.debate-hl{background:#854d0e;color:inherit}}
73
+ html.refdoc-booting #refdoc-root{visibility:hidden}`
74
+
75
+ /** Write any `RefdocDocument` as one `.refdoc.html` file (see the module doc). */
76
+ export function renderRefdocHtml(doc: RefdocDocument, options: RenderRefdocOptions = {}): string {
77
+ const { pages, ...rest } = doc
78
+ const meta: RefdocMeta = { ...rest, format: "refdoc", version: REFDOC_VERSION, generator: rest.generator ?? `extract-refdoc ${REFDOC_PACKAGE_VERSION}` }
79
+ const runtime = options.runtime ?? "cdn"
80
+
81
+ let head: string
82
+ let tail: string
83
+ if (typeof runtime === "object" && "js" in runtime) {
84
+ head = `<style id="refdoc-runtime-css">${runtime.css.replace(/<\/style/gi, "<\\/style")}</style>`
85
+ tail = `<script id="refdoc-runtime">${escapeInlineScript(runtime.js)}</script>`
86
+ } else {
87
+ const base = (runtime === "cdn" ? REFDOC_CDN : runtime.base).replace(/\/+$/, "")
88
+ head = `<link rel="stylesheet" href="${escapeHtml(base)}/refdoc.css" />`
89
+ tail = `<script defer src="${escapeHtml(base)}/refdoc.js"></script>`
90
+ }
91
+
92
+ const articles = pages.map((page) => {
93
+ const attrs = [
94
+ `id="${escapeHtml(page.slug || OVERVIEW_ID)}"`,
95
+ `data-refdoc-page="${escapeHtml(page.slug)}"`,
96
+ `data-title="${escapeHtml(page.title)}"`,
97
+ page.description ? `data-description="${escapeHtml(page.description)}"` : "",
98
+ page.part ? `data-part="${escapeHtml(page.part)}"` : "",
99
+ ].filter(Boolean)
100
+ const heading = page.slug === "" ? "h1" : "h2"
101
+ const fallback = `<header data-refdoc-fallback>${page.part ? `<p><small>${escapeHtml(page.part)}</small></p>` : ""}<${heading}>${escapeHtml(page.title)}</${heading}>${page.description ? `<p><em>${escapeHtml(page.description)}</em></p>` : ""}</header>`
102
+ return `<article ${attrs.join(" ")}>\n${fallback}\n${page.html}\n</article>`
103
+ })
104
+
105
+ return `<!doctype html>
106
+ <html lang="en" class="refdoc-booting">
107
+ <head>
108
+ <meta charset="utf-8" />
109
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
110
+ <meta name="generator" content="${escapeHtml(meta.generator!)}" />
111
+ <title>${escapeHtml(meta.title)}</title>
112
+ ${meta.description ? `<meta name="description" content="${escapeHtml(meta.description)}" />\n` : ""}${meta.author ? `<meta name="author" content="${escapeHtml(meta.author)}" />\n` : ""}<script>setTimeout(function(){document.documentElement.classList.remove("refdoc-booting")},2500)</script>
113
+ <style>${FALLBACK_CSS}</style>
114
+ ${head}
115
+ <script type="application/refdoc+json" id="refdoc-meta">${escapeJsonForScript(JSON.stringify(meta))}</script>
116
+ </head>
117
+ <body>
118
+ <div id="refdoc-root">
119
+ ${articles.join("\n")}
120
+ </div>
121
+ ${tail}
122
+ </body>
123
+ </html>
124
+ `
125
+ }
126
+
127
+ /** Read a `.refdoc.html` file back (Node or any runtime; uses linkedom). */
128
+ export function parseRefdoc(html: string): RefdocDocument {
129
+ const { document } = parseHTML(html)
130
+ return readRefdocFromDocument(document as unknown as Document)
131
+ }
132
+
133
+ /**
134
+ * Link numeric citations — `[3]`, `[3, 5]`, `[3–5]` — to their entries on
135
+ * the references page, with the reference text as a tooltip.
136
+ */
137
+ export function linkCitations(html: string, references: string[]): string {
138
+ if (references.length === 0) return html
139
+ const titles = references.map((ref) => escapeHtml(markdownToPlainText(ref).slice(0, 300)))
140
+ const link = (n: number) => `<a class="refdoc-cite" href="#ref-${n}" title="${titles[n - 1]}">${n}</a>`
141
+ // Only in text, never inside a tag.
142
+ return html.replace(/(<[^>]*>)|\[(\d{1,4}(?:\s*[,–-]\s*\d{1,4})*)\]/g, (match, tag: string | undefined, list: string | undefined) => {
143
+ if (tag || !list) return match
144
+ const parts = list.split(/(\s*[,–-]\s*)/)
145
+ const numbers = parts.filter((_, i) => i % 2 === 0).map(Number)
146
+ if (numbers.some((n) => !(n >= 1 && n <= references.length))) return match
147
+ return `[${parts.map((part, i) => (i % 2 === 0 ? link(Number(part)) : part)).join("")}]`
148
+ })
149
+ }
150
+
151
+ /** The `Paper` → refdoc pages: an overview, one page per section, and the references. */
152
+ export function paperToRefdocDocument(paper: Paper): RefdocDocument {
153
+ const pages: RefdocPage[] = []
154
+ const cite = (html: string) => linkCitations(html, paper.references)
155
+
156
+ // Overview: byline, figure, abstract, keywords, citation, contents.
157
+ const overview: string[] = []
158
+ const byline = [paper.author, paper.date].filter(Boolean).map((part) => escapeHtml(part!))
159
+ if (paper.sourceUrl) {
160
+ byline.push(`<a href="${escapeHtml(paper.sourceUrl)}" target="_blank" rel="noopener noreferrer">${escapeHtml(paper.sourceUrl.replace(/^https?:\/\//, ""))}</a>`)
161
+ }
162
+ if (byline.length > 0) overview.push(`<p class="refdoc-byline">${byline.join(" · ")}</p>`)
163
+ if (paper.figure) overview.push(figureHtml(paper.figure, 1))
164
+ if (paper.abstract) overview.push(`<h2 id="${OVERVIEW_ID}-abstract">Abstract</h2>`, `<p class="refdoc-abstract">${cite(markdownInlineToHtml(paper.abstract))}</p>`)
165
+ if (paper.keywords?.length) overview.push(`<p class="refdoc-keywords"><strong>Keywords:</strong> ${escapeHtml(paper.keywords.join(", "))}</p>`)
166
+ if (paper.cite) overview.push(`<h2 id="${OVERVIEW_ID}-cite">Cite</h2>`, `<blockquote class="refdoc-citation">${markdownInlineToHtml(paper.cite)}</blockquote>`)
167
+ if (paper.sections.length > 0 || paper.references.length > 0) {
168
+ const items = paper.sections.map((section, i) => `<li><a href="#${sectionSlug(section, i)}">${escapeHtml(section.title)}</a>${section.description ? ` — ${markdownInlineToHtml(section.description)}` : ""}</li>`)
169
+ if (paper.references.length > 0) items.push(`<li><a href="#references">References</a></li>`)
170
+ overview.push(`<h2 id="${OVERVIEW_ID}-contents">Contents</h2>`, `<ol class="refdoc-contents">${items.join("")}</ol>`)
171
+ }
172
+ pages.push({
173
+ slug: "",
174
+ title: paper.title,
175
+ description: paper.description ? markdownToPlainText(paper.description) : undefined,
176
+ html: overview.join("\n"),
177
+ headings: [],
178
+ })
179
+
180
+ let figureNumber = paper.figure ? 1 : 0
181
+ paper.sections.forEach((section, i) => {
182
+ const slug = sectionSlug(section, i)
183
+ const used = new Set<string>()
184
+ const headingId = (text: string) => {
185
+ let id = `${slug}-${slugify(text)}`
186
+ for (let n = 2; used.has(id); n++) id = `${slug}-${slugify(text)}-${n}`
187
+ used.add(id)
188
+ return id
189
+ }
190
+ const html: string[] = []
191
+ if (section.figure) {
192
+ figureNumber += 1
193
+ html.push(figureHtml(section.figure, figureNumber))
194
+ }
195
+ if (section.summary.length > 0) {
196
+ used.add(`${slug}-summary`)
197
+ html.push(
198
+ `<h2 id="${slug}-summary">Section Summary</h2>`,
199
+ `<ol class="refdoc-summary">${section.summary.map((point) => `<li><strong>${markdownInlineToHtml(point.label)}:</strong> ${cite(markdownInlineToHtml(point.text))}</li>`).join("")}</ol>`,
200
+ )
201
+ }
202
+ if (section.paragraphs.length > 0) {
203
+ if (section.summary.length > 0) {
204
+ used.add(`${slug}-text`)
205
+ html.push(`<h2 id="${slug}-text">Text</h2>`)
206
+ }
207
+ html.push(cite(paragraphsHtml(section.paragraphs, headingId)))
208
+ }
209
+ pages.push({
210
+ slug,
211
+ title: `${i + 1}. ${section.title}`,
212
+ description: section.description ? markdownToPlainText(section.description) : undefined,
213
+ part: section.part,
214
+ html: html.join("\n"),
215
+ headings: [],
216
+ })
217
+ })
218
+
219
+ if (paper.references.length > 0) {
220
+ pages.push({
221
+ slug: "references",
222
+ title: "References",
223
+ html: `<ol class="refdoc-references">${paper.references.map((ref, i) => `<li id="ref-${i + 1}">${markdownInlineToHtml(ref)}</li>`).join("")}</ol>`,
224
+ headings: [],
225
+ })
226
+ }
227
+
228
+ return {
229
+ format: "refdoc",
230
+ version: REFDOC_VERSION,
231
+ title: paper.title,
232
+ description: paper.description ? markdownToPlainText(paper.description) : undefined,
233
+ author: paper.author,
234
+ date: paper.date,
235
+ sourceUrl: paper.sourceUrl,
236
+ cite: paper.cite,
237
+ keywords: paper.keywords,
238
+ pages,
239
+ }
240
+ }
241
+
242
+ /** A `Paper` as one `.refdoc.html` file. */
243
+ export function paperToRefdoc(paper: Paper, options: RenderRefdocOptions = {}): string {
244
+ return renderRefdocHtml(paperToRefdocDocument(paper), options)
245
+ }
246
+
247
+ /** The file name for a paper's refdoc: "<title-slug>.refdoc.html". */
248
+ export function refdocFileName(title: string): string {
249
+ return `${slugify(title)}.refdoc.html`
250
+ }
package/src/server.ts ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * @fileoverview The standalone widget as a tiny web app: one Fetch-API
3
+ * handler (`Request` → `Response`), so it runs under `Bun.serve`, a
4
+ * Cloudflare Worker, Deno or any Node adapter, and stays out of the main
5
+ * site.
6
+ *
7
+ * - `GET /` — the widget page: paste a link, DOI or text, or drop a PDF /
8
+ * `.docx`; pick "Paper" or "Outline"; read the result with Reader mode,
9
+ * Underlining and Voice; download the MDX folder files, one combined
10
+ * `.mdx`, a standalone `.html`, the `.refdoc.html`, or the JSON.
11
+ * - `POST /api/convert` — JSON `{ input, mode, ai }` or multipart with a
12
+ * `file` field. Replies `{ paper, reader, files, mdx, html, refdoc }`.
13
+ * - `GET /api/status` — `{ ai }`, whether a model is configured.
14
+ *
15
+ * Scraping runs server-side, so the page has no CORS limits on what it can
16
+ * read.
17
+ *
18
+ * @module server
19
+ */
20
+ import type { TextGenerator } from "./ai"
21
+ import { paperToHtml, PAPER_READER_CSS, renderPaperReader } from "./html"
22
+ import { paperToMdxFiles, paperToSingleMdx } from "./mdx"
23
+ import { convertToPaper, type ConvertMode } from "./pipeline"
24
+ import { paperToRefdoc } from "./refdoc"
25
+ import { READER_RUNTIME_SOURCE } from "./reader-runtime"
26
+ import type { Extractor } from "./source"
27
+ import type { Paper } from "./types"
28
+
29
+ export interface PaperToWebServerOptions {
30
+ /** The model for AI mode. Without one, AI requests fall back to the offline pass. */
31
+ generate?: TextGenerator
32
+ /** Replace the extractor. */
33
+ extract?: Extractor
34
+ /** Largest upload, in bytes (default 40 MB). */
35
+ maxUploadBytes?: number
36
+ }
37
+
38
+ /** Everything a client needs to show and download a converted paper. */
39
+ export interface ConvertResponse {
40
+ paper: Paper
41
+ /** Reader markup (toolbar + contents + paper) to drop into the page. */
42
+ reader: string
43
+ /** The MDX docs folder, by file name. */
44
+ files: Record<string, string>
45
+ /** The whole paper as one MDX page. */
46
+ mdx: string
47
+ /** A self-contained HTML page. */
48
+ html: string
49
+ /** The `.refdoc.html` file: the whole paper as a Fumadocs docs site (runtime from the CDN). */
50
+ refdoc: string
51
+ }
52
+
53
+ /** Build the response body for a converted paper. */
54
+ export function buildConvertResponse(paper: Paper): ConvertResponse {
55
+ return {
56
+ paper,
57
+ reader: renderPaperReader(paper),
58
+ files: paperToMdxFiles(paper),
59
+ mdx: paperToSingleMdx(paper),
60
+ html: paperToHtml(paper),
61
+ refdoc: paperToRefdoc(paper),
62
+ }
63
+ }
64
+
65
+ function json(body: unknown, status = 200): Response {
66
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8" } })
67
+ }
68
+
69
+ /** The Fetch handler (see the module doc). */
70
+ export function createPaperToWebHandler(options: PaperToWebServerOptions = {}): (request: Request) => Promise<Response> {
71
+ const maxUpload = options.maxUploadBytes ?? 40 * 1024 * 1024
72
+ return async (request) => {
73
+ const url = new URL(request.url)
74
+ if (request.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) {
75
+ return new Response(widgetPageHtml(), { headers: { "content-type": "text/html; charset=utf-8" } })
76
+ }
77
+ if (request.method === "GET" && url.pathname === "/api/status") return json({ ai: Boolean(options.generate) })
78
+ if (url.pathname !== "/api/convert") return json({ error: "Not found" }, 404)
79
+ if (request.method !== "POST") return json({ error: "Use POST" }, 405)
80
+
81
+ let input: string | Uint8Array = ""
82
+ let mode: ConvertMode = "paper"
83
+ let useAi = false
84
+ let fileName: string | undefined
85
+ let focus: string | undefined
86
+ try {
87
+ if ((request.headers.get("content-type") ?? "").includes("multipart/form-data")) {
88
+ const form = await request.formData()
89
+ const file = form.get("file")
90
+ if (file && typeof file !== "string" && file.size > 0) {
91
+ if (file.size > maxUpload) return json({ error: `File is over ${Math.round(maxUpload / 1048576)} MB` }, 413)
92
+ input = new Uint8Array(await file.arrayBuffer())
93
+ fileName = file.name
94
+ } else {
95
+ input = String(form.get("input") ?? "")
96
+ }
97
+ mode = form.get("mode") === "outline" ? "outline" : "paper"
98
+ useAi = form.get("ai") === "on" || form.get("ai") === "true"
99
+ focus = String(form.get("focus") ?? "") || undefined
100
+ } else {
101
+ const body = (await request.json()) as { input?: string; mode?: string; ai?: boolean; focus?: string }
102
+ input = String(body.input ?? "")
103
+ mode = body.mode === "outline" ? "outline" : "paper"
104
+ useAi = Boolean(body.ai)
105
+ focus = body.focus || undefined
106
+ }
107
+ } catch {
108
+ return json({ error: "Could not read the request" }, 400)
109
+ }
110
+ if (typeof input === "string" && !input.trim()) return json({ error: "Give a link, a DOI, some text, or a file" }, 400)
111
+
112
+ try {
113
+ const paper = await convertToPaper(input, {
114
+ mode,
115
+ fileName,
116
+ focus,
117
+ extract: options.extract,
118
+ generate: useAi ? options.generate : undefined,
119
+ })
120
+ return json(buildConvertResponse(paper))
121
+ } catch (error) {
122
+ return json({ error: error instanceof Error ? error.message : String(error) }, 422)
123
+ }
124
+ }
125
+ }
126
+
127
+ /** The widget page served at `/`. */
128
+ export function widgetPageHtml(): string {
129
+ return `<!doctype html>
130
+ <html lang="en">
131
+ <head>
132
+ <meta charset="utf-8" />
133
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
134
+ <title>extract-refdoc</title>
135
+ <style>
136
+ :root{--bg:#fff;--fg:#1c1917;--muted:#78716c;--border:#e7e5e4;--accent:#2563eb}
137
+ @media (prefers-color-scheme:dark){:root{--bg:#0c0a09;--fg:#e7e5e4;--muted:#a8a29e;--border:#292524;--accent:#60a5fa}}
138
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
139
+ .ptw-app{max-width:72rem;margin:0 auto;padding:1.5rem 16px}
140
+ .ptw-app h1{margin:0 0 .25rem;font-size:1.6rem}.ptw-app>p{margin:0 0 1rem;color:var(--muted)}
141
+ .ptw-form{display:grid;gap:.75rem;border:1px solid var(--border);border-radius:.75rem;padding:1rem}
142
+ .ptw-form textarea{width:100%;box-sizing:border-box;min-height:5rem;font:inherit;color:inherit;background:transparent;border:1px solid var(--border);border-radius:.5rem;padding:.6rem}
143
+ .ptw-row{display:flex;flex-wrap:wrap;gap:.75rem;align-items:center}
144
+ .ptw-row input[type=text]{flex:1;min-width:12rem;font:inherit;color:inherit;background:transparent;border:1px solid var(--border);border-radius:.5rem;padding:.4rem .6rem}
145
+ .ptw-form button,.ptw-downloads button{font:inherit;border-radius:.5rem;border:1px solid var(--accent);background:var(--accent);color:#fff;padding:.45rem 1rem;cursor:pointer}
146
+ .ptw-downloads button{background:transparent;color:inherit;border-color:var(--border);font-size:.875rem}
147
+ .ptw-status{color:var(--muted);min-height:1.5rem}.ptw-status.error{color:#dc2626}
148
+ .ptw-downloads{display:flex;flex-wrap:wrap;gap:.5rem;margin:1rem 0}
149
+ ${PAPER_READER_CSS}
150
+ </style>
151
+ </head>
152
+ <body>
153
+ <main class="ptw-app">
154
+ <h1>extract-refdoc</h1>
155
+ <p>Turn a PDF, research paper, archive link or any text into paper sections with summaries, card underlining, reader mode and voice, or write an outline in that format.</p>
156
+ <form class="ptw-form" id="ptw-form">
157
+ <textarea name="input" placeholder="Paste a link (arXiv, DOI, archive.org, any article or PDF URL), a topic, or the text itself"></textarea>
158
+ <div class="ptw-row">
159
+ <label>or a file <input type="file" name="file" accept=".pdf,.docx,.md,.txt,.html" /></label>
160
+ </div>
161
+ <div class="ptw-row">
162
+ <label><input type="radio" name="mode" value="paper" checked /> Paper sections</label>
163
+ <label><input type="radio" name="mode" value="outline" /> Outline</label>
164
+ <label id="ptw-ai-label"><input type="checkbox" name="ai" value="on" /> Use AI</label>
165
+ <input type="text" name="focus" placeholder="Outline focus (optional): an angle, resolution or side" />
166
+ <button type="submit">Convert</button>
167
+ </div>
168
+ <div class="ptw-status" id="ptw-status" role="status"></div>
169
+ </form>
170
+ <div class="ptw-downloads" id="ptw-downloads" hidden></div>
171
+ <div id="ptw-result"></div>
172
+ </main>
173
+ <script>
174
+ var mountPaperReader = ${READER_RUNTIME_SOURCE};
175
+ (function () {
176
+ var form = document.getElementById("ptw-form");
177
+ var status = document.getElementById("ptw-status");
178
+ var result = document.getElementById("ptw-result");
179
+ var downloads = document.getElementById("ptw-downloads");
180
+ var handle = null;
181
+ fetch("/api/status").then(function (r) { return r.json(); }).then(function (s) {
182
+ if (!s.ai) { var label = document.getElementById("ptw-ai-label"); label.title = "Set ANTHROPIC_API_KEY on the server to enable AI"; label.querySelector("input").disabled = true; }
183
+ }).catch(function () {});
184
+ function save(name, text, type) {
185
+ var url = URL.createObjectURL(new Blob([text], { type: type }));
186
+ var a = document.createElement("a"); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();
187
+ setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
188
+ }
189
+ function slug(text) { return (text || "paper").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "paper"; }
190
+ function button(label, fn) { var b = document.createElement("button"); b.type = "button"; b.textContent = label; b.addEventListener("click", fn); downloads.appendChild(b); }
191
+ form.addEventListener("submit", function (event) {
192
+ event.preventDefault();
193
+ var data = new FormData(form);
194
+ status.className = "ptw-status"; status.textContent = "Converting… scraping and extracting can take a minute.";
195
+ form.querySelector("button[type=submit]").disabled = true;
196
+ fetch("/api/convert", { method: "POST", body: data }).then(function (r) { return r.json(); }).then(function (body) {
197
+ if (body.error) throw new Error(body.error);
198
+ if (handle) handle.destroy();
199
+ result.innerHTML = body.reader;
200
+ handle = mountPaperReader(result.querySelector(".ptw-paper"));
201
+ var base = slug(body.paper.title);
202
+ downloads.innerHTML = ""; downloads.hidden = false;
203
+ button("Download .mdx", function () { save(base + ".mdx", body.mdx, "text/markdown"); });
204
+ button("Download .refdoc.html", function () { save(base + ".refdoc.html", body.refdoc, "text/html"); });
205
+ button("Download .html", function () { save(base + ".html", body.html, "text/html"); });
206
+ button("Download .json", function () { save(base + ".json", JSON.stringify(body.paper, null, 2), "application/json"); });
207
+ Object.keys(body.files).forEach(function (name) { button(name, function () { save(name, body.files[name], "text/plain"); }); });
208
+ status.textContent = body.paper.sections.length + " sections";
209
+ }).catch(function (error) {
210
+ status.className = "ptw-status error"; status.textContent = error.message;
211
+ }).then(function () { form.querySelector("button[type=submit]").disabled = false; });
212
+ });
213
+ })();
214
+ </script>
215
+ </body>
216
+ </html>
217
+ `
218
+ }