html-get 2.27.23 → 2.27.24

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
@@ -107,7 +107,9 @@ It determines the strategy to use based on the `url`, being the possibles values
107
107
 
108
108
  Type: `function`
109
109
 
110
- It creates a temporal file.
110
+ It receives the URL and the file extension, and returns `{ path }` for a file html-get writes the fetched PDF or office document to, and the converted HTML of a large PDF. Every call must return a new path: two fetches of the same URL at once would otherwise read each other's file. The default is a random name in `os.tmpdir()`.
111
+
112
+ html-get removes every file it asked for once the fetch ends, whether the conversion succeeded, failed or was canceled.
111
113
 
112
114
  ##### gotOpts
113
115
 
@@ -132,6 +134,10 @@ It can explicitly disabled passing `false`.
132
134
 
133
135
  A custom function receives the arguments and `{ signal, timeout }`: `timeout` is what is left of the fetch timeout, and `signal` aborts when the fetch is canceled. The default runner kills mutool with `SIGKILL` on either.
134
136
 
137
+ The PDF is converted with `-O preserve-images=no`, because mutool otherwise inlines every image as base64: a 151MB scanned PDF of 688 pages became 232MB of HTML, and parsing it took a 7GB heap. MuPDF 1.19 accepts the option and ignores it; 1.28 honors it (the same PDF is 35MB of HTML).
138
+
139
+ The PDF reader only looks at page one and skips images of more than 400x400 pixels in total, with a side under 16px, or used as stencil masks. When it finds none for `og:image`, mutool draws the PDF one page at a time, up to the first 20, and the first image it inlines in a page becomes `og:image`: the image a metadata reader picked from the inlined HTML before. A custom function receives `<file> <page>` for those calls and must resolve `{ stdout }` with mutool's HTML, whose `<div id="pageN">` tells the search which page it got; output without it ends the search.
140
+
135
141
  ##### pandoc
136
142
 
137
143
  Type: `function`|`boolean`<br>
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "html-get",
3
3
  "description": "Get the HTML from any website, fine-tuned for correction & speed",
4
4
  "homepage": "https://nicedoc.com/microlinkhq/html-get",
5
- "version": "2.27.23",
5
+ "version": "2.27.24",
6
6
  "types": "index.d.ts",
7
7
  "main": "src/index.js",
8
8
  "bin": {
package/src/html.js CHANGED
@@ -51,6 +51,7 @@ const addHead = ({ $, url, headers, pdfMeta = {} }) => {
51
51
 
52
52
  if (pdfMeta.title) tags.push(metaTag('og:title', pdfMeta.title, 'property'))
53
53
  if (pdfMeta.author) tags.push(metaTag('author', pdfMeta.author))
54
+ if (pdfMeta.authors) tags.push(metaTag('authors', pdfMeta.authors))
54
55
  if (pdfMeta.description) {
55
56
  tags.push(metaTag('description', pdfMeta.description))
56
57
  tags.push(metaTag('og:description', pdfMeta.description, 'property'))
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const { parseUrl, isMediaUrl, isPdfUrl, memoizeOne } = require('@metascraper/helpers')
4
- const { readFile, writeFile } = require('fs/promises')
4
+ const { readFile, writeFile, rm } = require('fs/promises')
5
5
  const timeSpan = require('@kikobeats/time-span')()
6
6
  const debug = require('debug-logfmt')('html-get')
7
7
  const { execFileSync } = require('child_process')
@@ -16,7 +16,8 @@ const os = require('os')
16
16
 
17
17
  const { getContentLength, getContentType } = require('./util')
18
18
  const { getOfficeFormat, isOfficeUrl } = require('./office')
19
- const { extractSafe } = require('./pdf')
19
+ const { extractSafe, isPdf } = require('./pdf')
20
+ const { firstImage } = require('./pdf/first-image')
20
21
  const autoDomains = require('./auto-domains')
21
22
  const addHtml = require('./html')
22
23
 
@@ -26,6 +27,16 @@ const ABORT_TYPES = ['image', 'stylesheet', 'font']
26
27
 
27
28
  const PDF_SIZE_TRESHOLD = 150 * 1024 // 150kb
28
29
 
30
+ const WITHOUT_IMAGES = '-O preserve-images=no'
31
+
32
+ const firstImageSafe = async (filepath, url, opts) => {
33
+ try {
34
+ return await firstImage(filepath, opts)
35
+ } catch (error) {
36
+ debug('mutool:image:error', { url, message: error.message || error })
37
+ }
38
+ }
39
+
29
40
  // `URL#hash` is empty both when the fragment is missing and when it is
30
41
  // empty. An empty fragment is still present on `href`, and it must win.
31
42
  const inheritRequestFragment = (options, response) => {
@@ -38,6 +49,12 @@ const fetch = PCancelable.fn(
38
49
  { getTemporalFile, mutool, pandoc, reflect = false, timeout = REQ_TIMEOUT, toEncode, ...opts },
39
50
  onCancel
40
51
  ) => {
52
+ const temporalFiles = []
53
+ const temporalFile = (input, ext) => {
54
+ const file = getTemporalFile(input, ext)
55
+ temporalFiles.push(file)
56
+ return file
57
+ }
41
58
  const reqTimeout = reflect ? timeout / 2 : timeout
42
59
  const deadline = Date.now() + reqTimeout
43
60
  const conversion = new AbortController()
@@ -84,18 +101,28 @@ const fetch = PCancelable.fn(
84
101
  if (!convertOffice && contentType === 'application/pdf') {
85
102
  pdfMeta = await extractSafe(res.body, res.url)
86
103
  if (!mutool) return ''
87
- const file = getTemporalFile(url, 'pdf')
104
+ const file = temporalFile(url, 'pdf')
88
105
  await writeFile(file.path, res.body)
89
106
  try {
90
107
  let converted
91
108
  if (getContentLength(res.headers) > PDF_SIZE_TRESHOLD) {
92
- const ofile = getTemporalFile(`${url}-pdf`, 'pdf')
93
- await mutool(`-o ${ofile.path} ${file.path}`, convertOpts())
109
+ const ofile = temporalFile(`${url}-pdf`, 'pdf')
110
+ await mutool(`${WITHOUT_IMAGES} -o ${ofile.path} ${file.path}`, convertOpts())
94
111
  converted = await readFile(ofile.path, 'utf-8')
95
112
  } else {
96
- converted = (await mutool(file.path, convertOpts())).stdout
113
+ converted = (await mutool(`${WITHOUT_IMAGES} ${file.path}`, convertOpts())).stdout
114
+ }
115
+ if (converted) {
116
+ if (!pdfMeta?.image && isPdf(res.body)) {
117
+ const image = await firstImageSafe(file.path, res.url, {
118
+ mutool,
119
+ convertOpts,
120
+ signal: conversion.signal
121
+ })
122
+ pdfMeta = { ...pdfMeta, image }
123
+ }
124
+ return converted
97
125
  }
98
- if (converted) return converted
99
126
  debug('mutool:empty', { url: res.url })
100
127
  } catch (error) {
101
128
  debug('mutool:error', {
@@ -107,7 +134,7 @@ const fetch = PCancelable.fn(
107
134
  }
108
135
 
109
136
  if (convertOffice) {
110
- const file = getTemporalFile(res.url, officeFormat)
137
+ const file = temporalFile(res.url, officeFormat)
111
138
  await writeFile(file.path, res.body)
112
139
  try {
113
140
  const converted = await convertOffice(officeFormat, file.path, convertOpts())
@@ -147,6 +174,8 @@ const fetch = PCancelable.fn(
147
174
  return reflect
148
175
  ? { isRejected: true, error, ...answer }
149
176
  : { ...answer, html: '', mode: 'fetch', redirects }
177
+ } finally {
178
+ await removeTemporalFiles(temporalFiles)
150
179
  }
151
180
  }
152
181
  )
@@ -282,11 +311,19 @@ const defaultGetMode = (url, { prerender }) => {
282
311
  }
283
312
 
284
313
  const defaultGetTemporalFile = (input, ext) => {
285
- const hash = crypto.createHash('sha256').update(input).digest('hex')
286
- const filepath = path.join(os.tmpdir(), ext === undefined ? hash : `${hash}.${ext}`)
287
- return { path: filepath }
314
+ const name = crypto.randomUUID()
315
+ return { path: path.join(os.tmpdir(), ext === undefined ? name : `${name}.${ext}`) }
288
316
  }
289
317
 
318
+ const removeTemporalFiles = files =>
319
+ Promise.all(
320
+ files.map(file =>
321
+ rm(file.path, { force: true }).catch(error =>
322
+ debug('temporal:error', { path: file.path, message: error.message })
323
+ )
324
+ )
325
+ )
326
+
290
327
  // Resolve a binary path once and cache it: html-get owns the pandoc/mutool
291
328
  // lookup, so both the internal runners and the exposed accessors share a single
292
329
  // `which` per binary for the whole process. execFileSync (no shell) is faster
@@ -0,0 +1,20 @@
1
+ 'use strict'
2
+
3
+ const MAX_IMAGE_PAGES = 20
4
+ const IMAGE_SRC = /<img\b[^>]*?\ssrc="(data:[^"]+)"/
5
+
6
+ const imageOf = html => IMAGE_SRC.exec(html)?.[1].replace(/\s+/g, '')
7
+
8
+ const firstImage = async (
9
+ filepath,
10
+ { mutool, convertOpts, signal, maxPages = MAX_IMAGE_PAGES }
11
+ ) => {
12
+ for (let page = 1; page <= maxPages && !signal.aborted; page++) {
13
+ const { stdout } = await mutool(`${filepath} ${page}`, convertOpts())
14
+ if (!stdout.includes(`<div id="page${page}"`)) return
15
+ const image = imageOf(stdout)
16
+ if (image) return image
17
+ }
18
+ }
19
+
20
+ module.exports = { firstImage, MAX_IMAGE_PAGES }