Skip to content

Commit c690933

Browse files
committed
refactor: drop zod and parserSchema, export ParserOutput as a plain type
1 parent 4fa8ac7 commit c690933

5 files changed

Lines changed: 59 additions & 99 deletions

File tree

‎README.md‎

Lines changed: 45 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ Extracts the main article from a web page and converts it to Markdown. Used by
1414
- [API](#api)
1515
- [`parseArticle({url, html, onDebug?})`](#parsearticleurl-html-ondebug)
1616
- [`ParserOutput`](#parseroutput)
17-
- [`parserSchema`](#parserschema)
1817
- [`ParseError`](#parseerror)
1918
- [Exported Types](#exported-types)
2019
- [How article detection works](#how-article-detection-works)
@@ -43,26 +42,25 @@ To find the article, it tries three strategies in order and uses the first one t
4342
## Install
4443

4544
```sh
46-
pnpm add @readstack/parser zod
45+
pnpm add @readstack/parser
4746
```
4847

49-
- **Zod 4 is a peer dependency** Install it alongside this package.
5048
- **Node.js 24 and ESM** This package targets Node.js 24 and ships as an ES module. Load it with `import`, or with `require` on Node.js 24.
5149
- **pnpm and `re2`** One of the parser's dependencies uses [re2](https://github.com/uhop/node-re2) to match URLs safely on untrusted pages. re2 needs to build itself when it is installed. pnpm blocks this by default, so the install ends with an error. To fix it, run `pnpm approve-builds` and pick `re2`. The parser still works if you skip this, but it is less protected against harmful pages.
5250

5351
## Usage
5452

5553
```ts
56-
import { parseArticle } from "@readstack/parser";
54+
import {parseArticle} from '@readstack/parser'
5755

58-
const url = "https://example.com/blog/my-post";
59-
const html = await (await fetch(url)).text();
56+
const url = 'https://example.com/blog/my-post'
57+
const html = await (await fetch(url)).text()
6058

61-
const article = await parseArticle({ url, html });
59+
const article = await parseArticle({url, html})
6260

63-
console.log(article.title);
64-
console.log(article.markdown);
65-
console.log(article.meta.readingTimeInSeconds);
61+
console.log(article.title)
62+
console.log(article.markdown)
63+
console.log(article.meta.readingTimeInSeconds)
6664
```
6765

6866
## API
@@ -80,7 +78,7 @@ Finds the article in `html` and resolves to a `ParserOutput` object.
8078
The parser never logs to the console on its own. To inspect what it is doing, pass an `onDebug` callback:
8179

8280
```ts
83-
await parseArticle({ url, html, onDebug: (message) => console.log(message) });
81+
await parseArticle({url, html, onDebug: (message) => console.log(message)})
8482
```
8583

8684
### `ParserOutput`
@@ -89,47 +87,26 @@ Returned by `parseArticle`:
8987

9088
```json5
9189
{
92-
title: "My post",
93-
markdown: "Some article text...",
90+
title: 'My post',
91+
markdown: 'Some article text...',
9492
meta: {
95-
url: "https://example.com/blog/my-post",
93+
url: 'https://example.com/blog/my-post',
9694

97-
domain: "example.com",
95+
domain: 'example.com',
9896

9997
readingTimeInSeconds: 240,
100-
processedAt: "2026-12-02T10:00:00.000Z",
98+
processedAt: '2026-12-02T10:00:00.000Z',
10199

102100
// languages detected from any code blocks
103-
codeLanguages: ["javascript"],
101+
codeLanguages: ['javascript'],
104102

105103
// open graph
106-
ogImage: "https://example.com/images/my-post.png",
107-
ogDescription: "A short summary of the post.",
104+
ogImage: 'https://example.com/images/my-post.png',
105+
ogDescription: 'A short summary of the post.',
108106
},
109107
}
110108
```
111109

112-
### `parserSchema`
113-
114-
A Zod schema that describes `ParserOutput`.
115-
116-
The `ParserOutput` type only exists while TypeScript compiles your code. Once parser output is sent somewhere, such as in an HTTP response or through a queue, nothing checks its shape. Use `parserSchema` to check it at runtime at that point. The schema is strict, so any extra field fails the check.
117-
118-
You can use it on its own, or place it inside your own schema. The [Readstack](https://readstack.io) parser service uses this to check each response before sending it:
119-
120-
```ts
121-
import { parserSchema } from "@readstack/parser";
122-
import { z } from "zod";
123-
124-
const responseSchema = z.strictObject({
125-
data: parserSchema,
126-
});
127-
128-
responseSchema.parse({ data: article });
129-
```
130-
131-
To place it inside your own schema, your app and this package must use the same copy of Zod. This is why Zod is a peer dependency.
132-
133110
### `ParseError`
134111

135112
Thrown when no article can be found on the page. It usually includes a `details` property, but it can be missing:
@@ -140,15 +117,15 @@ Thrown when no article can be found on the page. It usually includes a `details`
140117
Other errors (such as an invalid URL) are thrown as standard errors. Check the error type before reading `details`:
141118

142119
```ts
143-
import { ParseError, parseArticle } from "@readstack/parser";
120+
import {ParseError, parseArticle} from '@readstack/parser'
144121

145122
try {
146-
await parseArticle({ url, html });
123+
await parseArticle({url, html})
147124
} catch (error) {
148125
if (error instanceof ParseError) {
149-
console.log(error.details?.candidate);
126+
console.log(error.details?.candidate)
150127
}
151-
throw error;
128+
throw error
152129
}
153130
```
154131

@@ -158,7 +135,7 @@ try {
158135

159136
## How article detection works
160137

161-
Most websites do not use HTML in a reliable way, so the parser does not automatically trust tags like `<article>` or `<main>`.
138+
Most websites do not use HTML in a reliable way, so the parser does not automatically trust tags like `<article>` or `<main>`.
162139
Instead, it looks for the section of the page with the highest concentration of article content with elements like paragraphs, headings, lists, images, tables, and code blocks. It then cleans up any leftovers like duplicate titles or link-heavy lists.
163140

164141
## Writing a custom parser
@@ -177,23 +154,23 @@ A parser is a class in `src/parsers/` with two methods:
177154
The simplest approach is to extend `DefaultParser`, remove the unwanted elements, and let default detection handle the rest. This example follows the same pattern as `BbcUkParser`:
178155

179156
```ts
180-
import type { ExtractParams } from "./BaseParser";
181-
import { DefaultParser } from "./DefaultParser";
157+
import type {ExtractParams} from './BaseParser'
158+
import {DefaultParser} from './DefaultParser'
182159

183160
class ExampleParser extends DefaultParser {
184161
canParse(url: string) {
185-
const { hostname } = new URL(url);
186-
return hostname === "example.com" || hostname.endsWith(".example.com");
162+
const {hostname} = new URL(url)
163+
return hostname === 'example.com' || hostname.endsWith('.example.com')
187164
}
188165

189166
protected async extract(params: ExtractParams) {
190-
const { $ } = params;
191-
$(".author-box, .newsletter-signup").remove();
192-
return super.extract(params);
167+
const {$} = params
168+
$('.author-box, .newsletter-signup').remove()
169+
return super.extract(params)
193170
}
194171
}
195172

196-
export { ExampleParser };
173+
export {ExampleParser}
197174
```
198175

199176
### Advanced
@@ -205,41 +182,41 @@ For example, imagine a site that used paragraphs like `<div class="para">` inste
205182
This parser selects the story and turns those divs into paragraphs:
206183

207184
```ts
208-
import { ParseError } from "../ParseError";
209-
import { BaseParser, type ExtractParams } from "./BaseParser";
185+
import {ParseError} from '../ParseError'
186+
import {BaseParser, type ExtractParams} from './BaseParser'
210187

211188
class ExampleParser extends BaseParser {
212189
constructor() {
213190
// BaseParser takes default options, and this parser has none
214-
super({});
191+
super({})
215192
}
216193

217194
canParse(url: string) {
218-
const { hostname } = new URL(url);
219-
return hostname === "example.com" || hostname.endsWith(".example.com");
195+
const {hostname} = new URL(url)
196+
return hostname === 'example.com' || hostname.endsWith('.example.com')
220197
}
221198

222-
protected async extract({ $, url, onDebug }: ExtractParams) {
223-
const story = $(".story-body").first();
199+
protected async extract({$, url, onDebug}: ExtractParams) {
200+
const story = $('.story-body').first()
224201

225202
if (story.length === 0) {
226-
throw new ParseError("no story body found", {
203+
throw new ParseError('no story body found', {
227204
parser: this.constructor.name,
228-
});
205+
})
229206
}
230207

231208
// the site uses div.para for paragraphs, which detection does not see
232-
const paragraphs = story.find("div.para");
209+
const paragraphs = story.find('div.para')
233210
paragraphs.each((_, el) => {
234-
el.tagName = "p";
235-
});
211+
el.tagName = 'p'
212+
})
236213

237-
onDebug?.(`converted ${paragraphs.length} paragraphs: ${url}`);
238-
return story;
214+
onDebug?.(`converted ${paragraphs.length} paragraphs: ${url}`)
215+
return story
239216
}
240217
}
241218

242-
export { ExampleParser };
219+
export {ExampleParser}
243220
```
244221

245222
### Steps to add your parser

‎package.json‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,6 @@
5050
"metascraper-title": "^5.58.7",
5151
"turndown": "^7.2.5"
5252
},
53-
"peerDependencies": {
54-
"zod": "^4.6.7"
55-
},
5653
"devDependencies": {
5754
"@commitlint/cli": "^21.3.0",
5855
"@commitlint/config-conventional": "^21.3.0",
@@ -70,7 +67,6 @@
7067
"semantic-release": "^25.0.9",
7168
"tsdown": "^0.23.7",
7269
"typescript": "^6.0.3",
73-
"vitest": "^5.1.0",
74-
"zod": "^4.6.7"
70+
"vitest": "^5.1.0"
7571
}
7672
}

‎pnpm-lock.yaml‎

Lines changed: 0 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/index.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,4 @@ export type {OnDebug} from './OnDebug'
22
export {ParseError} from './ParseError'
33
export type {CandidateSnapshot, ParseErrorDetails} from './ParseError'
44
export {parseArticle} from './parsers/registry'
5-
export {parserSchema} from './util/schema'
65
export type {ParserOutput} from './util/schema'

‎src/util/schema.ts‎

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
1-
import {z} from 'zod'
2-
3-
export const parserSchema = z.strictObject({
4-
title: z.string(),
5-
markdown: z.string(),
6-
meta: z.strictObject({
7-
domain: z.string().nullable(),
8-
codeLanguages: z.array(z.string()),
9-
readingTimeInSeconds: z.number(),
10-
processedAt: z.string(),
11-
url: z.string(),
12-
ogImage: z.string().nullable(),
13-
ogDescription: z.string().nullable(),
14-
}),
15-
})
16-
17-
export type ParserOutput = z.infer<typeof parserSchema>
1+
export type ParserOutput = {
2+
title: string
3+
markdown: string
4+
meta: {
5+
domain: string | null
6+
codeLanguages: string[]
7+
readingTimeInSeconds: number
8+
processedAt: string
9+
url: string
10+
ogImage: string | null
11+
ogDescription: string | null
12+
}
13+
}

0 commit comments

Comments
 (0)