-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.ts
More file actions
62 lines (53 loc) · 1.88 KB
/
parser.ts
File metadata and controls
62 lines (53 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { wrappedFetch } from '@src/utils/fetcher.ts'
import { ANYPARSER_VERSION } from '@anyparser/core'
import { buildForm } from './form.ts'
import { validateAndParse } from './validator/index.ts'
import { transformToCamel } from '@src/utils/camel-case.ts'
import type { AnyparserOption, Result } from '@anyparser/core'
/**
* Main class for parsing items using the Anyparser API.
*/
export class Anyparser {
public options?: AnyparserOption
/**
* Initialize the parser with optional configuration.
* @param options - Configuration options for the parser
*/
constructor (options?: AnyparserOption) {
this.options = options
}
/**
* Parse files using the Anyparser API.
* @param filePathsOrUrl - A single file path or list of file paths to parse, or a start URL for crawling
* @returns List of parsed file results if format is JSON, or raw text content if format is text/markdown
* @throws Error if the API request fails
*/
async parse (filePathsOrUrl: string | string[]): Promise<Result> {
const parsed = await validateAndParse(filePathsOrUrl, this.options)
const { apiUrl, apiKey } = parsed
const formData = buildForm(parsed)
const fetchOptions = {
method: 'POST',
body: formData,
headers: {
...(apiKey ?
{
Authorization: `Bearer ${apiKey}`,
'User-Agent': `@anyparser/core@${ANYPARSER_VERSION}` // eslint-disable-line @typescript-eslint/naming-convention
} :
{})
}
}
const url = new URL('/parse/v1', apiUrl)
const response = await wrappedFetch(url, fetchOptions)
switch (parsed.format) {
case 'json':
return transformToCamel<Result>(await response.json())
case 'markdown':
case 'html':
return await response.text()
default:
throw new Error(`Unsupported format: ${parsed.format}`)
}
}
}