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.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # extract-refdoc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `extract-refdoc` turns any PDF, research paper, archive link, DOI or text into **one shareable HTML
4
+ file** that opens as a full [Fumadocs](https://fumadocs.dev) docs site: sidebar, table of
5
+ contents, ⌘K search, references, previous/next, light and dark, plus Reader mode, card
6
+ Underlining and Voice read-aloud.
7
+
8
+ ```bash
9
+ bunx extract-refdoc https://arxiv.org/abs/1706.03762 # → attention-is-all-you-need.refdoc.html
10
+ ```
11
+
12
+ Send that one file to anyone. Opening it (from disk, an email attachment or any web host)
13
+ loads a small runtime from the CDN and boots the docs UI around the content inside the file.
14
+ Formerly `paper-to-web` / `refdoc`; everything it did (MDX docs folders, outlines, the widget and
15
+ server) is still here.
16
+
17
+ ## Citation style badges
18
+
19
+ A document may show one of these citation-style badges:
20
+
21
+ ![APA](https://i.imgur.com/AMDxELp.png)
22
+
23
+ ![Chicago-Number](https://i.imgur.com/U2f1MaU.png)
24
+
25
+ ![Chicago](https://i.imgur.com/Gs3HNXZ.png)
26
+
27
+ ![Harvard](https://i.imgur.com/JLQUXZc.png)
28
+
29
+ ![IEEE](https://i.imgur.com/EkIKeCA.png)
30
+
31
+ ## The refdoc format
32
+
33
+ A `.refdoc.html` file is ordinary HTML with three parts:
34
+
35
+ ```html
36
+ <!doctype html>
37
+ <html lang="en" class="refdoc-booting">
38
+ <head>
39
+ <title>Attention Is All You Need</title>
40
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/extract-refdoc@0/dist/refdoc.css" />
41
+ <!-- 1. Document metadata -->
42
+ <script type="application/refdoc+json" id="refdoc-meta">
43
+ {"format":"refdoc","version":1,"title":"Attention Is All You Need","author":"…","sourceUrl":"…","generator":"extract-refdoc 0.2.0"}
44
+ </script>
45
+ </head>
46
+ <body>
47
+ <!-- 2. The whole document, one <article> per page -->
48
+ <div id="refdoc-root">
49
+ <article id="overview" data-refdoc-page="" data-title="Attention Is All You Need">…abstract, contents…</article>
50
+ <article id="01-introduction" data-refdoc-page="01-introduction" data-title="1. Introduction"
51
+ data-description="…" data-part="…">
52
+ <h2 id="01-introduction-summary">Section Summary</h2> …
53
+ <h3 id="01-introduction-background">Background</h3> …
54
+ </article>
55
+ <article id="references" data-refdoc-page="references" data-title="References">
56
+ <ol><li id="ref-1">…</li></ol>
57
+ </article>
58
+ </div>
59
+ <!-- 3. The runtime loader -->
60
+ <script defer src="https://cdn.jsdelivr.net/npm/extract-refdoc@0/dist/refdoc.js"></script>
61
+ </body>
62
+ </html>
63
+ ```
64
+
65
+ | Part | Rules |
66
+ | --- | --- |
67
+ | `#refdoc-meta` | JSON with `format: "refdoc"`, `version: 1`, `title`, and optional `description`, `author`, `date`, `sourceUrl`, `cite`, `keywords`, `generator`. `<` is written as `\u003c`. |
68
+ | `<article data-refdoc-page>` | One per page, in sidebar order. The value is the page slug; `""` is the overview. `data-title`, `data-description` and `data-part` (a sidebar separator opened by this page) are optional. The body is plain HTML. |
69
+ | ids | Each article's `id` is its slug (`overview` for the overview) and every `id` inside a page is prefixed with that page's slug, so a single `#id` names a page or a place on one. `h2`–`h4` with an `id` become the page's table of contents. |
70
+ | `[data-refdoc-fallback]` | A title block for reading the file without the runtime. The runtime drops it and renders its own title. |
71
+ | runtime | `refdoc.css` + `refdoc.js` from `https://cdn.jsdelivr.net/npm/extract-refdoc@0/dist/` (any 0.x), another base URL, or embedded inline. |
72
+
73
+ Because the content is plain HTML and exists exactly once, the file stays small (the runtime is
74
+ not inside it), reads as one long page if the CDN is unreachable, and is indexable by search
75
+ engines.
76
+
77
+ ### What the runtime does
78
+
79
+ `dist/refdoc.js` (about 410 KB minified, React and Fumadocs UI included) reads the pages out of
80
+ the file and renders Fumadocs' `DocsLayout` and `DocsPage` around them, all client-side:
81
+
82
+ - **Sidebar** from the pages, with `data-part` as separators, plus a link to the source.
83
+ - **Table of contents** with scroll-spy, breadcrumb, previous/next page.
84
+ - **Search** (⌘K / Ctrl+K) over every page title, heading and paragraph in the file.
85
+ - **References**: numeric citations like `[3]`, `[3, 5]` or `[3–5]` link to the references page,
86
+ with the reference as a tooltip.
87
+ - **Reader mode / Underlining / Voice**: the reading bar from the original paper reader. Voice
88
+ reads only the `==underlined==` words while Underlining is on.
89
+ - **Routing by `#id`**, so it works from `file://` and links can point at any heading.
90
+
91
+ ## CLI
92
+
93
+ ```bash
94
+ bunx extract-refdoc https://arxiv.org/abs/1706.03762 # → ./<title>.refdoc.html
95
+ bunx extract-refdoc paper.pdf --out shared # local PDF, .docx, .md, .txt or .html
96
+ bunx extract-refdoc paper.pdf --runtime inline # embed the runtime: works offline (~520 KB)
97
+ bunx extract-refdoc https://bitcoin.org/bitcoin.pdf --ai # Claude writes summaries + underlining
98
+ bunx extract-refdoc paper.pdf --format all # refdoc + MDX folder + .mdx + .html + .json
99
+ bunx extract-refdoc "critiques in policy debate" --outline --ai
100
+ cat notes.md | bunx extract-refdoc - --outline
101
+ bunx extract-refdoc serve --port 8787 # the converter widget as a web app
102
+ ```
103
+
104
+ | Option | |
105
+ | --- | --- |
106
+ | `--format <list>` | `refdoc` (default), `mdx` (Fumadocs docs folder), `single` (one page), `html` (the plain reader page), `json`, or `all` |
107
+ | `--runtime <how>` | `cdn` (default), `inline` (embeds `dist/refdoc.js` and `.css`; build first), or a base URL serving `refdoc.js` and `refdoc.css` |
108
+ | `--outline` | Write an outline in the paper format instead of converting |
109
+ | `--ai` | Use Claude (`ANTHROPIC_API_KEY`, or an `ant auth login` profile) |
110
+ | `--model <id>` | Model for `--ai` (default `claude-opus-5-5`) |
111
+ | `--focus <text>` | Steer an outline: an angle, a resolution, a side |
112
+ | `--out <dir>` | Output folder (default: the current folder for `refdoc` alone, else the title as a slug) |
113
+
114
+ Inputs: any article or PDF URL, arXiv `abs/`/`pdf/` links (read from arXiv's HTML render so
115
+ headings survive), archive.org and web.archive.org links, DOIs, local `.pdf`, `.docx`, `.md`,
116
+ `.txt` and `.html` files, and pasted text. Scraping uses
117
+ [`extract-webpage`](https://www.npmjs.com/package/extract-webpage) and
118
+ [`extract-pdf`](https://www.npmjs.com/package/extract-pdf).
119
+
120
+ ## Library
121
+
122
+ ```ts
123
+ import { convertToPaper, paperToRefdoc, parseRefdoc, renderRefdocHtml } from "extract-refdoc"
124
+
125
+ const paper = await convertToPaper("https://arxiv.org/abs/1706.03762")
126
+ const html = paperToRefdoc(paper) // runtime from the CDN
127
+ const offline = paperToRefdoc(paper, { runtime: { js, css } }) // runtime embedded
128
+ const pinned = paperToRefdoc(paper, { runtime: { base: "https://cdn.jsdelivr.net/npm/extract-refdoc@0.2.0/dist" } })
129
+
130
+ const doc = parseRefdoc(html) // { title, author, …, pages: [{ slug, title, html, headings }] }
131
+ ```
132
+
133
+ `renderRefdocHtml(doc)` writes any `RefdocDocument`, so a refdoc can come from something other
134
+ than a paper: build the `pages` yourself (slug, title, HTML) and pass them in. The other outputs
135
+ are unchanged: `paperToMdxFiles(paper)` (Fumadocs docs folder), `paperToSingleMdx(paper)`,
136
+ `paperToHtml(paper)` (the self-contained reader page) and `generateOutline`.
137
+
138
+ ## Widget and server
139
+
140
+ ```tsx
141
+ import { PaperToWeb, PaperReader } from "extract-refdoc/widget"
142
+
143
+ <PaperToWeb endpoint="/api/convert" /> // the converter: input, mode, AI, downloads (incl. .refdoc.html)
144
+ <PaperReader paper={paper} speak={myTts} /> // just the reader, optionally with your own voice
145
+ ```
146
+
147
+ ```ts
148
+ import { createPaperToWebHandler } from "extract-refdoc/server"
149
+ export default { fetch: createPaperToWebHandler({ generate: createAnthropicGenerator() }) }
150
+ ```
151
+
152
+ The handler is a plain Fetch-API `(Request) => Response` (Bun, Workers, Deno, Node). Its
153
+ `/api/convert` reply now includes `refdoc`, the `.refdoc.html` text.
154
+
155
+ ## Building the runtime
156
+
157
+ ```bash
158
+ bun run build # → dist/refdoc.js + dist/refdoc.css
159
+ bun run example # → dist/example/debate-is-testing.refdoc.html with the runtime inlined; open it
160
+ bun run test
161
+ ```
162
+
163
+ `scripts/build-runtime.ts` bundles `runtime/main.tsx` with Bun into one minified IIFE (a classic
164
+ script, so it runs from `file://`) and appends `runtime/refdoc.css` to Fumadocs UI's prebuilt
165
+ stylesheet. Fumadocs' Markdown search renderer and its API-backed default search dialog are
166
+ swapped for stubs (`runtime/stubs/`), since refdoc searches the file itself; that halves the
167
+ bundle.
168
+
169
+ The CDN copy is the npm package: the repo's npm publish workflow runs `bun run build` and
170
+ publishes `extract-refdoc`, and jsDelivr serves `dist/` at
171
+ `https://cdn.jsdelivr.net/npm/extract-refdoc@0/dist/`. Files pin `@0`, so they pick up runtime
172
+ fixes within 0.x; a breaking format change bumps the major version and `version` in
173
+ `#refdoc-meta`.
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * @fileoverview `extract-refdoc` — the command-line front end.
4
+ *
5
+ * ```
6
+ * extract-refdoc <url | doi | file | -> [options] convert one input
7
+ * extract-refdoc serve [--port 8787] run the widget web app
8
+ *
9
+ * --outline write an outline in the paper format instead
10
+ * --ai use Claude for summaries, underlining and outlines
11
+ * (ANTHROPIC_API_KEY or an `ant auth login` profile)
12
+ * --model <id> model for --ai (default claude-opus-5-5)
13
+ * --focus <text> steer an outline (an angle, resolution or side)
14
+ * --out <dir> where to write (default: here for refdoc alone, else ./<title-slug>)
15
+ * --format <list> refdoc, mdx, single, html, json or all (default refdoc)
16
+ * --runtime <how> refdoc runtime: cdn (default), inline (works offline),
17
+ * or a base URL that serves refdoc.js and refdoc.css
18
+ * ```
19
+ *
20
+ * `extract-refdoc` writes `<title>.refdoc.html`: the whole document in one file that
21
+ * opens as a Fumadocs docs site. `mdx` writes the docs folder (index.mdx, 01-….mdx, references.mdx,
22
+ * meta.json), ready to drop into a Fumadocs content directory; `single` one
23
+ * combined page; `html` a self-contained reader page.
24
+ */
25
+ import { mkdir, readFile, writeFile } from "node:fs/promises"
26
+ import path from "node:path"
27
+ import { parseArgs } from "node:util"
28
+ import { fileURLToPath } from "node:url"
29
+ import { createAnthropicGenerator } from "../src/ai"
30
+ import { paperToHtml } from "../src/html"
31
+ import { paperToMdxFiles, paperToSingleMdx, slugify } from "../src/mdx"
32
+ import { convertToPaper } from "../src/pipeline"
33
+ import { paperToRefdoc, refdocFileName, type RefdocRuntime } from "../src/refdoc"
34
+ import { createPaperToWebHandler } from "../src/server"
35
+
36
+ const HELP = `extract-refdoc <url | doi | file | -> [--outline] [--ai] [--model id] [--focus text] [--out dir] [--format refdoc,mdx,single,html,json|all] [--runtime cdn|inline|<url>]
37
+ extract-refdoc serve [--port 8787] [--ai]`
38
+
39
+ /** The built runtime next to this package, for --runtime inline. */
40
+ async function inlineRuntime(): Promise<RefdocRuntime> {
41
+ const dist = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "dist")
42
+ try {
43
+ return { js: await readFile(path.join(dist, "refdoc.js"), "utf8"), css: await readFile(path.join(dist, "refdoc.css"), "utf8") }
44
+ } catch {
45
+ throw new Error(`--runtime inline needs the built runtime in ${dist}: run \`bun run build\` in packages/extract-refdoc`)
46
+ }
47
+ }
48
+
49
+ async function readStdin(): Promise<string> {
50
+ const chunks: Buffer[] = []
51
+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer)
52
+ return Buffer.concat(chunks).toString("utf8")
53
+ }
54
+
55
+ async function main() {
56
+ const { values, positionals } = parseArgs({
57
+ allowPositionals: true,
58
+ options: {
59
+ outline: { type: "boolean", default: false },
60
+ ai: { type: "boolean", default: false },
61
+ model: { type: "string" },
62
+ focus: { type: "string" },
63
+ out: { type: "string" },
64
+ format: { type: "string", default: "refdoc" },
65
+ runtime: { type: "string", default: "cdn" },
66
+ port: { type: "string", default: "8787" },
67
+ help: { type: "boolean", short: "h", default: false },
68
+ },
69
+ })
70
+ if (values.help || positionals.length === 0) {
71
+ console.log(HELP)
72
+ return
73
+ }
74
+ const generate = values.ai ? createAnthropicGenerator({ model: values.model }) : undefined
75
+
76
+ if (positionals[0] === "serve") {
77
+ const Bun = (globalThis as { Bun?: { serve(options: { port: number; fetch(request: Request): Promise<Response> }): { url: URL } } }).Bun
78
+ if (!Bun) throw new Error("`extract-refdoc serve` runs under Bun: bunx extract-refdoc serve")
79
+ const server = Bun.serve({ port: Number(values.port), fetch: createPaperToWebHandler({ generate: generate ?? (process.env.ANTHROPIC_API_KEY ? createAnthropicGenerator({ model: values.model }) : undefined) }) })
80
+ console.log(`extract-refdoc on ${server.url}`)
81
+ return
82
+ }
83
+
84
+ const target = positionals.join(" ")
85
+ let input: string | Uint8Array
86
+ let fileName: string | undefined
87
+ if (target === "-") {
88
+ input = await readStdin()
89
+ } else if (!/^https?:\/\//i.test(target)) {
90
+ const bytes = await readFile(target).catch(() => null)
91
+ if (bytes) {
92
+ fileName = path.basename(target)
93
+ input = /\.(pdf|docx)$/i.test(target) ? new Uint8Array(bytes) : bytes.toString("utf8")
94
+ } else {
95
+ input = target
96
+ }
97
+ } else {
98
+ input = target
99
+ }
100
+
101
+ const paper = await convertToPaper(input, {
102
+ mode: values.outline ? "outline" : "paper",
103
+ generate,
104
+ fileName,
105
+ focus: values.focus,
106
+ onProgress: (message) => console.error(message),
107
+ })
108
+
109
+ const formats = new Set((values.format === "all" ? "refdoc,mdx,single,html,json" : values.format!).split(",").map((f) => f.trim()))
110
+ // A lone .refdoc.html needs no folder of its own.
111
+ const onlyRefdoc = formats.size === 1 && formats.has("refdoc")
112
+ const outDir = path.resolve(values.out ?? (onlyRefdoc ? "." : slugify(paper.title)))
113
+ await mkdir(outDir, { recursive: true })
114
+ const written: string[] = []
115
+ const put = async (name: string, text: string) => {
116
+ await writeFile(path.join(outDir, name), text)
117
+ written.push(name)
118
+ }
119
+ if (formats.has("refdoc")) {
120
+ const runtime: RefdocRuntime = values.runtime === "inline" ? await inlineRuntime() : values.runtime === "cdn" ? "cdn" : { base: values.runtime! }
121
+ await put(refdocFileName(paper.title), paperToRefdoc(paper, { runtime }))
122
+ }
123
+ if (formats.has("mdx")) for (const [name, text] of Object.entries(paperToMdxFiles(paper))) await put(name, text)
124
+ if (formats.has("single")) await put(`${slugify(paper.title)}.mdx`, paperToSingleMdx(paper))
125
+ if (formats.has("html")) await put("paper.html", paperToHtml(paper))
126
+ if (formats.has("json")) await put("paper.json", `${JSON.stringify(paper, null, 2)}\n`)
127
+ console.error(`${paper.title}: ${paper.sections.length} sections → ${outDir}`)
128
+ for (const name of written) console.log(path.join(outDir, name))
129
+ }
130
+
131
+ main().catch((error) => {
132
+ console.error(error instanceof Error ? error.message : error)
133
+ process.exit(1)
134
+ })