paper-drift 0.1.0 → 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Sooriya
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  > **Zero-Python, zero-Chromium WebAssembly document parser, HTML renderer, and Markdown engine with GFM tables and math.**
9
9
 
10
- Convert complex academic research papers and enterprise PDFs directly into clean, structured **Markdown** or standalone **HTML** with pixel-perfect visual fidelity—without Puppeteer, Python, Docker, or external servers. Slashes AI Agent token ingestion costs by 90%+.
10
+ Convert complex academic research papers and enterprise PDFs directly into clean, structured **Markdown** or standalone **HTML** with pixel-perfect visual fidelity—without Puppeteer, Python, Docker, or external servers. Drastically reduces LLM token consumption compared to sending raw PDFs or vision images.
11
11
 
12
12
  ---
13
13
 
@@ -18,7 +18,7 @@ Most PDF conversion pipelines in JavaScript suffer from two major flaws:
18
18
  2. **The "Text Soup" Trap**: Spatially naive parsers that dump unordered lines, break multi-column layouts, and butcher tabular grids.
19
19
 
20
20
  **`paper-drift` solves this natively:**
21
- * **Zero-Python & Zero-Chromium**: Runs compiled WebAssembly directly in any V8 runtime (Node.js, Bun, or modern browsers). Under 20 KB package footprint.
21
+ * **Zero-Python & Zero-Chromium**: Runs compiled WebAssembly directly in any V8 runtime (Node.js, Bun, or modern browsers). Zero external microservices or headless browsers required.
22
22
  * **Direct Markdown Engine**: Converts directly into GitHub Flavored Markdown (GFM) with auto-detected `#`, `##` headings, list markers, and clean math.
23
23
  * **Geometric Table Reconstruction**: Discovers column gutters and slices cells into standard pipe tables (`| col1 | col2 |`) with clean universal math exponents (`O(n² · d)`, `10¹⁹`).
24
24
  * **Multi-Column Spatial Ordering**: Resolves 2-column papers via Recursive XY-Cut without column interweaving.
@@ -116,17 +116,61 @@ const { markdown } = await convertPdfToMarkdown(Buffer.from(pdfBuffer));
116
116
 
117
117
  ---
118
118
 
119
- ## 💸 AI Agent Token Savings
119
+ ## 💸 Reduce Token Costs for AI Agents
120
120
 
121
- When feeding 10-page academic papers into LLMs (Claude, GPT-4, Cursor, Antigravity):
121
+ Sending raw PDF documents or full-page screenshots to LLMs wastes massive amounts of context window tokens and introduces vision hallucinations on formulas and tabular data.
122
122
 
123
- | Mode | Tokens Consumed | Cost / Ingestion | Reading Accuracy |
124
- | :--- | :--- | :--- | :--- |
125
- | **Multimodal Vision (Images)** | ~16,000 – 20,000 tokens | ~$0.15 – $0.40 | Heavy hallucinations on dense math |
126
- | **Naive OCR / PDF Text Dump** | ~8,000 tokens | ~$0.08 | Tables destroyed into loose lines |
127
- | **`paper-drift` Markdown** | **~1,200 – 1,800 tokens** | **~$0.01** | **Pixel-accurate reading order, GFM tables, math** |
123
+ **`paper-drift` converts PDFs into clean, structured Markdown before sending them to the model:**
124
+ * **Drastically Reduced Token Footprint**: Markdown transmits only the actual text, pipe tables, and math equations—eliminating the heavy pixel-tiling token overhead of multimodal vision models and unstructured OCR dumps.
125
+ * **100% Reading Order Accuracy**: Recursive XY-Cut sequences multi-column research papers in natural human reading order without column line-mixing.
126
+ * **High-Fidelity Tables & Math**: Tables are converted to clean GFM pipe tables (`| col1 | col2 |`) and math is preserved as clean Unicode/LaTeX without visual distortion.
127
+ * **Fast & Lightweight Ingestion**: Ingests pages locally via WebAssembly in milliseconds, slashing API latency and context costs.
128
+
129
+ ---
130
+
131
+ ## 🤖 Turnkey AI Agent Skill (Claude, Cursor, Antigravity)
132
+
133
+ `paper-drift` is built from the ground up as a native **AI Agent Skill** to eliminate the **"Multimodal PDF Token Tax"**.
134
+
135
+ When an AI coding or research agent ingests raw PDFs as images, it burns thousands of vision tokens per page and quickly crowds context windows. By equipping your agent with the `paper-drift` skill, the agent pre-processes PDFs locally via WebAssembly into clean Markdown, GFM tables, and LaTeX equations in milliseconds—drastically reducing token consumption compared to sending raw PDFs.
136
+
137
+ ### 1-Click Skill Installation
138
+
139
+ Install the canonical [`SKILL.md`](skills/paper-drift/SKILL.md) into any workspace with a single command:
140
+
141
+ ```bash
142
+ # 1. Default: Auto-install to current workspace (.agent/skills/paper-drift/SKILL.md)
143
+ npx paper-drift skill
144
+
145
+ # 2. Target Claude Code workspace (.claude/skills/paper-drift/SKILL.md)
146
+ npx paper-drift skill --claude
147
+
148
+ # 3. Target Cursor workspace rules (.cursor/rules/paper-drift.md)
149
+ npx paper-drift skill --cursor
150
+
151
+ # 4. Install globally for all projects (~/.gemini/... & ~/.claude/...)
152
+ npx paper-drift skill --global
153
+
154
+ # 5. Output raw SKILL.md to stdout (for piping or custom paths)
155
+ npx paper-drift skill cat
156
+ ```
157
+
158
+ ### How the Agent Uses It
159
+
160
+ Once installed, your agent automatically activates the skill whenever you provide a PDF:
161
+
162
+ ```text
163
+ User: "Summarize the experimental results from attention-is-all-you-need.pdf"
164
+
165
+ Agent (Internal):
166
+ 1. Detects paper-drift skill
167
+ 2. Executes: npx -y paper-drift attention-is-all-you-need.pdf --format md --pages 6-8
168
+ 3. Receives clean GFM Table 1 and BLEU score comparisons in < 250ms
169
+ 4. Answers your query directly from clean Markdown text without burning multimodal vision tokens!
170
+ ```
128
171
 
129
- > **Net Savings:** Over **90% token reduction** and **12x faster ingestion**.
172
+ - 📖 **Skill Specification:** [`skills/paper-drift/SKILL.md`](skills/paper-drift/SKILL.md)
173
+ - 🌐 **Interactive Documentation:** [https://sooriya04.github.io/Paper-Drift/#skill](https://sooriya04.github.io/Paper-Drift/#skill)
130
174
 
131
175
  ---
132
176
 
package/bin/cli.js CHANGED
@@ -10,6 +10,7 @@ import fs from 'fs';
10
10
  import path from 'path';
11
11
  import { fileURLToPath } from 'url';
12
12
  import { convertPdfToHtml, convertPdfToMarkdown } from '../src/index.js';
13
+ import { installSkill, getSkillContent } from '../src/skill/installer.js';
13
14
 
14
15
  const __filename = fileURLToPath(import.meta.url);
15
16
  const __dirname = path.dirname(__filename);
@@ -45,12 +46,58 @@ High-fidelity, zero-Chromium PDF parser powered by WebAssembly & spatial layout
45
46
  $ paper-drift paper.pdf output.txt --format text
46
47
  $ paper-drift paper.pdf output.html --scale 2.5
47
48
  $ paper-drift manual.pdf manual.html --pages 1-10 --no-bg
49
+
50
+ \x1b[1mAGENT SKILL:\x1b[0m
51
+ $ paper-drift skill Install skill into agent workspace (.agent/skills)
52
+ $ paper-drift skill --claude Install skill into Claude workspace (.claude/skills)
53
+ $ paper-drift skill --cursor Install skill into Cursor rules (.cursor/rules)
54
+ $ paper-drift skill --global Install skill globally to user home directory
55
+ $ paper-drift skill cat Output raw SKILL.md to stdout
48
56
  `);
49
57
  }
50
58
 
51
59
  async function run() {
52
60
  const args = process.argv.slice(2);
53
61
 
62
+ // Handle agent skill subcommands
63
+ if (args[0] === 'skill' || args.includes('--install-skill')) {
64
+ if (args.includes('cat') || args.includes('print')) {
65
+ process.stdout.write(getSkillContent());
66
+ process.exit(0);
67
+ }
68
+
69
+ const isGlobal = args.includes('--global');
70
+ const isClaude = args.includes('--claude');
71
+ const isCursor = args.includes('--cursor');
72
+ const isAgent = args.includes('--agent') || args.includes('--antigravity');
73
+ let dest = null;
74
+ const destIdx = args.indexOf('--dest');
75
+ if (destIdx !== -1 && args[destIdx + 1]) {
76
+ dest = args[destIdx + 1];
77
+ }
78
+
79
+ try {
80
+ const installed = installSkill({
81
+ global: isGlobal,
82
+ claude: isClaude,
83
+ cursor: isCursor,
84
+ agent: isAgent,
85
+ dest
86
+ });
87
+
88
+ console.log('\n\x1b[1m\x1b[36mpaper-drift\x1b[0m \x1b[32mAgent Skill Installed Successfully!\x1b[0m\n');
89
+ for (const p of installed) {
90
+ console.log(` \x1b[32m✔\x1b[0m ${path.relative(process.cwd(), p) || p}`);
91
+ }
92
+ console.log('\n\x1b[90mYour AI coding agent can now parse PDFs with zero multimodal token tax.\x1b[0m');
93
+ console.log('\x1b[90mAsk your agent: "Read this PDF" or "Extract Table 1 from paper.pdf"\x1b[0m\n');
94
+ process.exit(0);
95
+ } catch (err) {
96
+ console.error(`\x1b[31mError installing skill:\x1b[0m ${err.message}`);
97
+ process.exit(1);
98
+ }
99
+ }
100
+
54
101
  if (args.length === 0 || args.includes('-h') || args.includes('--help')) {
55
102
  printHelp();
56
103
  process.exit(0);
@@ -100,6 +147,12 @@ async function run() {
100
147
  process.exit(1);
101
148
  }
102
149
 
150
+ const validFormats = ['html', 'md', 'markdown', 'text', 'json'];
151
+ if (!validFormats.includes(format)) {
152
+ console.error(`\x1b[31mError: Unsupported format "${format}". Supported: markdown (md) | html | text | json\x1b[0m`);
153
+ process.exit(1);
154
+ }
155
+
103
156
  const isMarkdown = format === 'md' || format === 'markdown';
104
157
  const ext = isMarkdown ? 'md' : (format === 'text' ? 'txt' : (format === 'json' ? 'json' : 'html'));
105
158
  if (!outputFile) {
package/package.json CHANGED
@@ -1,15 +1,20 @@
1
1
  {
2
2
  "name": "paper-drift",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Zero-Python, zero-Chromium WebAssembly document parser, HTML renderer, and Markdown engine with GFM tables and math",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
7
+ "types": "src/index.d.ts",
7
8
  "exports": {
8
- ".": "./src/index.js"
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "import": "./src/index.js"
12
+ }
9
13
  },
10
14
  "files": [
11
15
  "src",
12
16
  "bin",
17
+ "skills",
13
18
  "README.md",
14
19
  "LICENSE"
15
20
  ],
@@ -42,7 +47,6 @@
42
47
  "author": "Sooriya",
43
48
  "license": "Apache-2.0",
44
49
  "dependencies": {
45
- "mupdf": "^1.28.1",
46
- "pdfjs-dist": "^3.11.174"
50
+ "mupdf": "^1.28.1"
47
51
  }
48
52
  }
@@ -0,0 +1,100 @@
1
+ ---
2
+ name: paper-drift
3
+ description: Zero-Python, zero-Chromium WebAssembly PDF document engine. Converts academic and enterprise PDFs into clean, high-density Markdown with GFM tables and LaTeX math, slashing multimodal LLM token consumption by 90%+. Use whenever analyzing, reading, extracting tables from, or converting PDF files.
4
+ ---
5
+
6
+ # `paper-drift` Agent Skill: Zero-Token-Tax PDF Ingestion
7
+
8
+ You are an expert AI researcher and coding agent. When interacting with PDF files (research papers, technical specifications, financial reports, or manuals), **do not ingest raw PDF pages as images or ask the user to convert them manually**.
9
+
10
+ Instead, invoke `paper-drift` locally via WebAssembly to convert the document into clean, natural-reading-order GitHub Flavored Markdown (GFM) with reconstructed tables and LaTeX equations.
11
+
12
+ ---
13
+
14
+ ## 1. Why Use `paper-drift` (Token Savings & Fidelity)
15
+
16
+ Sending raw PDF documents or full-page screenshots to LLMs burns massive vision tokens and causes severe hallucinations on dense math and tables.
17
+
18
+ Converting PDFs to Markdown with `paper-drift` provides:
19
+ - **Drastically Reduced Token Costs**: Markdown sends only pure text, pipe tables, and math—eliminating the heavy pixel-tiling token bloat of multimodal vision models and unstructured OCR dumps.
20
+ - **Accurate Reading Order**: Multi-column papers are properly ordered via Recursive XY-Cut without line interleaving.
21
+ - **Intact Tables & Math**: Reconstructs multi-tier data tables into standard Markdown grids (`| col1 | col2 |`) and math into clean LaTeX/Unicode.
22
+ - **Fast Local Execution**: Runs locally in milliseconds via compiled WebAssembly with zero external dependencies (no Python, no Poppler, no Chromium).
23
+
24
+ ---
25
+
26
+ ## 2. When to Activate This Skill
27
+
28
+ Trigger this workflow whenever:
29
+ - The user provides a `.pdf` file and asks questions, summaries, or code implementations based on it.
30
+ - You need to inspect benchmark results, experimental tables, or equations from an ArXiv paper.
31
+ - You need to convert a PDF into clean Markdown or standalone HTML.
32
+ - An automated pipeline or agent needs to parse documents with zero system dependencies (no Python, no Poppler, no Chromium).
33
+
34
+ ---
35
+
36
+ ## 3. Agent Execution Protocol
37
+
38
+ ### Step 1: Run the CLI via `npx`
39
+ Run `paper-drift` directly in the shell using `npx -y paper-drift`:
40
+
41
+ ```bash
42
+ # Convert entire PDF to Markdown
43
+ npx -y paper-drift path/to/document.pdf --format md -o output.md
44
+
45
+ # Budget tokens for long documents (pages 1 to 5 only)
46
+ npx -y paper-drift path/to/paper.pdf --format md --pages 1-5 -o paper-summary.md
47
+
48
+ # Convert specific non-contiguous pages (e.g. Intro & Experiment Results)
49
+ npx -y paper-drift path/to/paper.pdf --format md --pages 1-3,6,8 -o paper-key-sections.md
50
+
51
+ # Standalone high-DPI HTML visualization (with selectable text layer)
52
+ npx -y paper-drift path/to/document.pdf --format html -o document.html
53
+ ```
54
+
55
+ ### Step 2: Read and Process the Generated Markdown
56
+ Read the generated `.md` file using your file-reading tool. The output contains:
57
+ - `#`, `##`, `###` headings derived from geometric font sizing.
58
+ - Natural two-column reading flow without column weaving.
59
+ - Standalone LaTeX display math blocks:
60
+ ```latex
61
+ $$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V \tag{1}$$
62
+ ```
63
+ - Clean GFM Markdown tables with universal math typography:
64
+ ```markdown
65
+ | Layer | Complexity per Layer | Sequential Operations | Maximum Path Length |
66
+ | :--- | :--- | :--- | :--- |
67
+ | Self-Attention | O(n² · d) | O(1) | O(1) |
68
+ | Recurrent | O(n · d²) | O(n) | O(n) |
69
+ ```
70
+
71
+ ### Step 3: Programmatic Node.js / JavaScript Usage
72
+ When writing automated scripts, crawlers, or agent tools, import `paper-drift` directly:
73
+
74
+ ```javascript
75
+ import { convertPdfToMarkdown, convertPdfToHtml } from 'paper-drift';
76
+ import fs from 'node:fs/promises';
77
+
78
+ // Read local PDF buffer
79
+ const pdfBuffer = await fs.readFile('paper.pdf');
80
+
81
+ // Direct PDF to Markdown with page range
82
+ const markdown = await convertPdfToMarkdown(pdfBuffer, { pages: '1-6' });
83
+ console.log(markdown);
84
+
85
+ // Direct PDF to Standalone HTML with embedded assets
86
+ const html = await convertPdfToHtml(pdfBuffer, { scale: 1.5, pages: '1-3' });
87
+ await fs.writeFile('output.html', html);
88
+ ```
89
+
90
+ ---
91
+
92
+ ## 4. Agent Best Practices & Token Budgeting
93
+
94
+ 1. **Always Use `--pages` for Documents Over 10 Pages:**
95
+ - Don't ingest a 100-page manual at once.
96
+ - For research papers: start with `--pages 1-3` (Title, Abstract, Introduction) to get the thesis, then target specific sections (e.g. `--pages 6-8` for Benchmark Tables).
97
+ 2. **Table Extraction:**
98
+ - Markdown tables generated by `paper-drift` use standard `|` pipes and can be extracted or parsed directly using regular expressions or Markdown parsers.
99
+ 3. **No Heavy Dependencies:**
100
+ - Never install `pdf2image`, `poppler-utils`, `pdfplumber`, or `tesseract` when `paper-drift` is available. `paper-drift` is 100% self-contained WebAssembly.
package/src/converter.js CHANGED
@@ -18,12 +18,21 @@ import { resolveReadingOrder } from './spatial/reading-order.js';
18
18
  * @returns {number[]} 0-indexed page numbers.
19
19
  */
20
20
  export function parsePageRange(range, totalPages) {
21
- if (!range || range === 'all') {
21
+ if (range === undefined || range === null || range === '' || range === 'all') {
22
22
  return Array.from({ length: totalPages }, (_, i) => i);
23
23
  }
24
24
 
25
+ if (typeof range === 'number') {
26
+ if (range >= 1 && range <= totalPages) {
27
+ return [range - 1];
28
+ }
29
+ return [];
30
+ }
31
+
25
32
  if (Array.isArray(range)) {
26
- return range.map(p => p - 1).filter(p => p >= 0 && p < totalPages);
33
+ return range
34
+ .map(p => Number(p) - 1)
35
+ .filter(p => !isNaN(p) && p >= 0 && p < totalPages);
27
36
  }
28
37
 
29
38
  const indices = new Set();
@@ -75,7 +84,7 @@ export async function convertPdfToHtml(input, options = {}) {
75
84
  const startTime = Date.now();
76
85
  const scale = typeof options.scale === 'number' ? options.scale : 2.0;
77
86
  const withBg = options.withBg !== false;
78
- const pageRangeStr = options.pageRange || 'all';
87
+ const pageRangeStr = options.pages !== undefined ? options.pages : (options.pageRange || 'all');
79
88
 
80
89
  let pdfBuffer;
81
90
  let docTitle = options.title || 'Converted Document';
package/src/index.d.ts ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * @file src/index.d.ts
3
+ * @description TypeScript definitions for paper-drift.
4
+ * Part of paper-drift - https://github.com/Sooriya04/Paper-Drift
5
+ */
6
+
7
+ export interface PageResult {
8
+ pageNumber: number;
9
+ width: number;
10
+ height: number;
11
+ tablesCount?: number;
12
+ headingsCount?: number;
13
+ columnsDetected?: number;
14
+ blocksCount?: number;
15
+ markdown?: string;
16
+ text?: string;
17
+ }
18
+
19
+ export interface ConvertMarkdownOptions {
20
+ /** Target page range (e.g. "1-5", "2,4,6", 1, or [1, 2, 3]). Defaults to "all". */
21
+ pages?: string | number | number[];
22
+ /** Legacy alias for `pages`. */
23
+ pageRange?: string | number | number[];
24
+ /** Optional progress callback. */
25
+ onProgress?: (progress: { current: number; total: number; pageNumber: number; totalPages: number }) => void;
26
+ }
27
+
28
+ export interface ConvertMarkdownResult {
29
+ markdown: string;
30
+ pages: PageResult[];
31
+ totalPages: number;
32
+ pagesProcessed: number;
33
+ durationMs: number;
34
+ }
35
+
36
+ export interface ConvertHtmlOptions {
37
+ /** DPI scale for background raster rendering (default: 2.0). */
38
+ scale?: number;
39
+ /** Whether to render lossless background image layer (default: true). */
40
+ withBg?: boolean;
41
+ /** Target page range (e.g. "1-5", "2,4,6", 1, or [1, 2, 3]). Defaults to "all". */
42
+ pages?: string | number | number[];
43
+ /** Legacy alias for `pages`. */
44
+ pageRange?: string | number | number[];
45
+ /** Document title in HTML head. */
46
+ title?: string;
47
+ /** Target output format ('html', 'text', 'json'). */
48
+ format?: 'html' | 'text' | 'json';
49
+ /** Optional progress callback. */
50
+ onProgress?: (progress: { current: number; total: number; pageNumber: number; totalPages: number }) => void;
51
+ }
52
+
53
+ export interface ConvertHtmlResult {
54
+ html: string;
55
+ text: string;
56
+ pages: PageResult[];
57
+ totalPages: number;
58
+ pagesProcessed: number;
59
+ durationMs: number;
60
+ }
61
+
62
+ export interface InstallSkillOptions {
63
+ /** Install globally to user home directory. */
64
+ global?: boolean;
65
+ /** Target Claude Code workspace (.claude/skills/). */
66
+ claude?: boolean;
67
+ /** Target Cursor workspace rules (.cursor/rules/). */
68
+ cursor?: boolean;
69
+ /** Target open Agent standard (.agent/skills/). */
70
+ agent?: boolean;
71
+ /** Custom destination file path. */
72
+ dest?: string;
73
+ }
74
+
75
+ /**
76
+ * Converts a PDF buffer or file path directly into clean GitHub Flavored Markdown (GFM).
77
+ */
78
+ export function convertPdfToMarkdown(
79
+ input: string | Buffer | Uint8Array,
80
+ options?: ConvertMarkdownOptions
81
+ ): Promise<ConvertMarkdownResult>;
82
+
83
+ /**
84
+ * Converts a PDF buffer or file path into a standalone high-fidelity HTML document with selectable text overlay.
85
+ */
86
+ export function convertPdfToHtml(
87
+ input: string | Buffer | Uint8Array,
88
+ options?: ConvertHtmlOptions
89
+ ): Promise<ConvertHtmlResult>;
90
+
91
+ /**
92
+ * Parses page range input into sorted 0-indexed page numbers.
93
+ */
94
+ export function parsePageRange(range: string | number | number[] | undefined | null, totalPages: number): number[];
95
+
96
+ /**
97
+ * Reconstructs a collection of PDF text lines into a standard GFM pipe table.
98
+ */
99
+ export function reconstructTableFromLines(
100
+ lines: Array<{ text: string; bbox: { x: number; y: number; w: number; h: number } }>,
101
+ options?: { rowProximity?: number }
102
+ ): string | null;
103
+
104
+ /**
105
+ * Normalizes table cell formulas and values into clean Unicode math (e.g. O(n² · d)).
106
+ */
107
+ export function formatTableCell(text: string): string;
108
+
109
+ /**
110
+ * Folds multi-tier header rows into a unified column header array.
111
+ */
112
+ export function foldHeaders(headerRows: string[][], colCount: number): string[];
113
+
114
+ /**
115
+ * Resolves spatial reading order using Recursive XY-Cut.
116
+ */
117
+ export function resolveReadingOrder(pageJson: any, pageWidth?: number, pageHeight?: number): {
118
+ blocks: any[];
119
+ text: string;
120
+ columnsDetected: number;
121
+ };
122
+
123
+ /**
124
+ * Installs the paper-drift Agent Skill definition into an agent workspace.
125
+ */
126
+ export function installSkill(options?: InstallSkillOptions): string[];
127
+
128
+ /**
129
+ * Returns the raw markdown content of SKILL.md.
130
+ */
131
+ export function getSkillContent(): string;
132
+
133
+ declare const _default: {
134
+ convertPdfToHtml: typeof convertPdfToHtml;
135
+ convertPdfToMarkdown: typeof convertPdfToMarkdown;
136
+ parsePageRange: typeof parsePageRange;
137
+ reconstructTableFromLines: typeof reconstructTableFromLines;
138
+ formatTableCell: typeof formatTableCell;
139
+ foldHeaders: typeof foldHeaders;
140
+ resolveReadingOrder: typeof resolveReadingOrder;
141
+ installSkill: typeof installSkill;
142
+ getSkillContent: typeof getSkillContent;
143
+ };
144
+
145
+ export default _default;
package/src/index.js CHANGED
@@ -10,6 +10,7 @@ export { convertPdfToHtml, parsePageRange } from './converter.js';
10
10
  export { convertPdfToMarkdown, pageToMarkdown } from './markdown/index.js';
11
11
  export { reconstructTableFromLines, formatTableCell, foldHeaders } from './tables/index.js';
12
12
  export { resolveReadingOrder, recursiveXyCut } from './spatial/reading-order.js';
13
+ export { installSkill, getSkillContent } from './skill/installer.js';
13
14
  export {
14
15
  restoreLineMath,
15
16
  restoreBlockMath,
@@ -180,7 +180,7 @@ export function pageToMarkdown(pageJson, widthPt, heightPt, options = {}) {
180
180
  */
181
181
  export async function convertPdfToMarkdown(input, options = {}) {
182
182
  const startTime = Date.now();
183
- const pageRangeStr = options.pageRange || 'all';
183
+ const pageRangeStr = options.pages !== undefined ? options.pages : (options.pageRange || 'all');
184
184
 
185
185
  let pdfBuffer;
186
186
  if (typeof input === 'string') {
@@ -0,0 +1,95 @@
1
+ /**
2
+ * @file src/skill/installer.js
3
+ * @description Installs the paper-drift Agent Skill directly into local agent workspaces or global directories.
4
+ * Part of paper-drift - https://github.com/Sooriya04/Paper-Drift
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import os from 'node:os';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.dirname(__filename);
14
+
15
+ // Locate packaged SKILL.md
16
+ const SKILL_SOURCE = path.resolve(__dirname, '../../skills/paper-drift/SKILL.md');
17
+
18
+ /**
19
+ * Reads the canonical paper-drift SKILL.md definition.
20
+ * @returns {string} Raw markdown skill content.
21
+ */
22
+ export function getSkillContent() {
23
+ if (!fs.existsSync(SKILL_SOURCE)) {
24
+ throw new Error(`Could not find SKILL.md at ${SKILL_SOURCE}`);
25
+ }
26
+ return fs.readFileSync(SKILL_SOURCE, 'utf-8');
27
+ }
28
+
29
+ /**
30
+ * Installs the paper-drift skill into agent workspaces.
31
+ * @param {Object} options Installation options.
32
+ * @param {boolean} [options.global=false] Install globally to user home directories.
33
+ * @param {boolean} [options.claude=false] Explicitly target Claude Code (.claude/skills).
34
+ * @param {boolean} [options.cursor=false] Explicitly target Cursor rules (.cursor/rules).
35
+ * @param {boolean} [options.agent=false] Explicitly target standard .agent/skills.
36
+ * @param {string} [options.dest] Custom destination path.
37
+ * @returns {string[]} List of installed file paths.
38
+ */
39
+ export function installSkill(options = {}) {
40
+ const content = getSkillContent();
41
+ const installedPaths = [];
42
+ const cwd = process.cwd();
43
+
44
+ if (options.dest) {
45
+ const destPath = path.resolve(cwd, options.dest);
46
+ fs.mkdirSync(path.dirname(destPath), { recursive: true });
47
+ fs.writeFileSync(destPath, content, 'utf-8');
48
+ installedPaths.push(destPath);
49
+ return installedPaths;
50
+ }
51
+
52
+ if (options.global) {
53
+ const home = os.homedir();
54
+ const globalTargets = [
55
+ path.join(home, '.claude', 'skills', 'paper-drift', 'SKILL.md'),
56
+ path.join(home, '.gemini', 'antigravity-cli', 'skills', 'paper-drift', 'SKILL.md')
57
+ ];
58
+ for (const target of globalTargets) {
59
+ try {
60
+ fs.mkdirSync(path.dirname(target), { recursive: true });
61
+ fs.writeFileSync(target, content, 'utf-8');
62
+ installedPaths.push(target);
63
+ } catch (err) {
64
+ // Silently skip if user permissions or folder structure don't allow
65
+ }
66
+ }
67
+ return installedPaths;
68
+ }
69
+
70
+ const explicit = options.claude || options.cursor || options.agent;
71
+
72
+ if (options.claude || (!explicit && fs.existsSync(path.join(cwd, '.claude')))) {
73
+ const claudePath = path.join(cwd, '.claude', 'skills', 'paper-drift', 'SKILL.md');
74
+ fs.mkdirSync(path.dirname(claudePath), { recursive: true });
75
+ fs.writeFileSync(claudePath, content, 'utf-8');
76
+ installedPaths.push(claudePath);
77
+ }
78
+
79
+ if (options.cursor || (!explicit && fs.existsSync(path.join(cwd, '.cursor')))) {
80
+ const cursorPath = path.join(cwd, '.cursor', 'rules', 'paper-drift.md');
81
+ fs.mkdirSync(path.dirname(cursorPath), { recursive: true });
82
+ fs.writeFileSync(cursorPath, content, 'utf-8');
83
+ installedPaths.push(cursorPath);
84
+ }
85
+
86
+ // Always install to .agent/skills/paper-drift/SKILL.md by default
87
+ if (options.agent || !explicit || installedPaths.length === 0) {
88
+ const agentPath = path.join(cwd, '.agent', 'skills', 'paper-drift', 'SKILL.md');
89
+ fs.mkdirSync(path.dirname(agentPath), { recursive: true });
90
+ fs.writeFileSync(agentPath, content, 'utf-8');
91
+ installedPaths.push(agentPath);
92
+ }
93
+
94
+ return installedPaths;
95
+ }
@@ -28,8 +28,12 @@ function toSuperscript(str) {
28
28
  export function formatTableCell(text) {
29
29
  if (!text) return '';
30
30
 
31
- // Escape literal pipe characters to prevent breaking markdown tables
32
- let cleaned = String(text).replace(/\|/g, '\\|').trim();
31
+ // Normalize internal newlines and whitespace to single space, and escape pipe characters
32
+ let cleaned = String(text)
33
+ .replace(/[\r\n\t]+/g, ' ')
34
+ .replace(/\s+/g, ' ')
35
+ .replace(/\|/g, '\\|')
36
+ .trim();
33
37
  if (!cleaned) return '';
34
38
 
35
39
  // Scientific notation with powers of 10 (e.g. 2.3 · 1019 -> 2.3 · 10¹⁹)