html-get 2.28.0 → 2.28.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/index.d.ts CHANGED
@@ -16,6 +16,8 @@ declare namespace htmlGet {
16
16
  statusCode: number | undefined
17
17
  /** Redirect history */
18
18
  redirects: Array<{ statusCode: number; url: string }>
19
+ /** Set when the body stopped arriving (a timeout or a dropped connection): `html` is what arrived before it */
20
+ partial?: true
19
21
  /** Statistics about the request */
20
22
  stats: {
21
23
  mode: 'fetch' | 'prerender'
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.28.0",
5
+ "version": "2.28.2",
6
6
  "types": "index.d.ts",
7
7
  "main": "src/index.js",
8
8
  "bin": {
package/src/html.js CHANGED
@@ -11,7 +11,7 @@ const cheerio = require('cheerio')
11
11
  const { URL } = require('url')
12
12
  const path = require('path')
13
13
 
14
- const { isMime, isUrl, mimeExtension, parseUrl } = require('@metascraper/helpers')
14
+ const { isMime, isUrl, parseUrl } = require('@metascraper/helpers')
15
15
 
16
16
  const { getContentType, getCharset } = require('./util')
17
17
 
@@ -70,6 +70,20 @@ const addHead = ({ $, url, headers, pdfMeta = {} }) => {
70
70
  tags.forEach(tag => head.append(tag))
71
71
  }
72
72
 
73
+ const escapeText = text =>
74
+ String(text ?? '')
75
+ .replace(/&/g, '&amp;')
76
+ .replace(/</g, '&lt;')
77
+
78
+ const isText = contentType =>
79
+ typeof contentType === 'string' &&
80
+ (contentType.endsWith('/json') ||
81
+ contentType.endsWith('+json') ||
82
+ (contentType.startsWith('text/') && contentType !== 'text/html'))
83
+
84
+ const isDocument = ({ html, headers, mode, converted }) =>
85
+ isHTML(html) && (mode === 'prerender' || converted || !isText(getContentType(headers)))
86
+
73
87
  const addBody = ({ url, headers, html }) => {
74
88
  const contentType = getContentType(headers)
75
89
  let element = ''
@@ -80,8 +94,10 @@ const addBody = ({ url, headers, html }) => {
80
94
  element = `<video><source src="${url}" type="${contentType}"></source></video>`
81
95
  } else if (isMime(contentType, 'audio')) {
82
96
  element = `<audio><source src="${url}" type="${contentType}"></source></audio>`
83
- } else if (mimeExtension(contentType) === 'json') {
84
- element = `<pre>${html}</pre>`
97
+ } else if (isText(contentType)) {
98
+ const text = escapeText(html)
99
+ const preserved = text.startsWith('\n') ? `<!-- -->${text}` : text
100
+ element = `<pre>${preserved}</pre>`
85
101
  }
86
102
 
87
103
  return `<!DOCTYPE html><html><head></head><body>${element}</body></html>`
@@ -191,6 +207,8 @@ module.exports = ({
191
207
  html,
192
208
  url,
193
209
  headers = {},
210
+ mode,
211
+ converted,
194
212
  pdfMeta,
195
213
  styles,
196
214
  hide,
@@ -200,7 +218,9 @@ module.exports = ({
200
218
  scripts,
201
219
  modules
202
220
  }) => {
203
- const content = addDocType(isHTML(html) ? html : addBody({ url, headers, html }))
221
+ const content = addDocType(
222
+ isDocument({ html, headers, mode, converted }) ? html : addBody({ url, headers, html })
223
+ )
204
224
 
205
225
  const $ = cheerio.load(content)
206
226
 
package/src/index.js CHANGED
@@ -9,6 +9,7 @@ const PCancelable = require('p-cancelable')
9
9
  const { AbortError } = require('p-retry')
10
10
  const htmlEncode = require('html-encode')
11
11
  const got = require('@kikobeats/got')
12
+ const { isResponseOk } = require('@kikobeats/got/dist/source/core/utils/is-response-ok')
12
13
  const crypto = require('crypto')
13
14
  const $ = require('tinyspawn')
14
15
  const path = require('path')
@@ -43,6 +44,42 @@ const inheritRequestFragment = (options, response) => {
43
44
  if (!options.url.href.includes('#')) options.url.hash = new URL(response.url).hash
44
45
  }
45
46
 
47
+ const HTML_DOCUMENT_TYPES = ['text/html', 'application/xhtml+xml']
48
+
49
+ const resolvesWithBody = res => isResponseOk(res) || !res.request.options.throwHttpErrors
50
+
51
+ const resolvesWithHtml = res =>
52
+ HTML_DOCUMENT_TYPES.includes(getContentType(res.headers)) && resolvesWithBody(res)
53
+
54
+ const recordHtmlBody = req => {
55
+ let chunks = []
56
+ req.on('request', () => {
57
+ chunks = []
58
+ })
59
+ req.on('response', res => {
60
+ if (resolvesWithHtml(res)) {
61
+ res.on('data', chunk => chunks.push(chunk))
62
+ }
63
+ })
64
+ return () => Buffer.concat(chunks)
65
+ }
66
+
67
+ const isBodyCut = error => error instanceof got.TimeoutError || error instanceof got.ReadError
68
+
69
+ const readCutHtml = async (error, readHtmlBody, toEncode) => {
70
+ if (!isBodyCut(error)) return
71
+ const body = readHtmlBody()
72
+ if (body.length === 0) return
73
+ try {
74
+ return await toEncode(body, error.response.headers['content-type'])
75
+ } catch (encodeError) {
76
+ debug('fetch:partial:error', {
77
+ url: error.response.url,
78
+ message: encodeError?.message || encodeError
79
+ })
80
+ }
81
+ }
82
+
46
83
  const fetch = PCancelable.fn(
47
84
  async (
48
85
  url,
@@ -100,11 +137,13 @@ const fetch = PCancelable.fn(
100
137
 
101
138
  const redirects = []
102
139
  req.on('redirect', res => redirects.push({ statusCode: res.statusCode, url: res.url }))
140
+ const readHtmlBody = recordHtmlBody(req)
103
141
 
104
142
  try {
105
143
  const res = await req
106
144
 
107
145
  let pdfMeta
146
+ let asDocument = false
108
147
  const html = await (async () => {
109
148
  const contentType = getContentType(res.headers)
110
149
 
@@ -137,6 +176,7 @@ const fetch = PCancelable.fn(
137
176
  })
138
177
  pdfMeta = { ...pdfMeta, image }
139
178
  }
179
+ asDocument = true
140
180
  return converted
141
181
  }
142
182
  debug('mutool:empty', { url: res.url })
@@ -155,7 +195,10 @@ const fetch = PCancelable.fn(
155
195
  await writeFile(file.path, res.body)
156
196
  try {
157
197
  const converted = await convertOffice(officeFormat, file.path, convertOpts())
158
- if (converted) return converted
198
+ if (converted) {
199
+ asDocument = true
200
+ return converted
201
+ }
159
202
  debug('pandoc:empty', { url: res.url, format: officeFormat })
160
203
  } catch (error) {
161
204
  debug('pandoc:error', {
@@ -176,6 +219,7 @@ const fetch = PCancelable.fn(
176
219
  headers: res.headers,
177
220
  html,
178
221
  pdfMeta,
222
+ converted: asDocument,
179
223
  mode: 'fetch',
180
224
  url: res.url,
181
225
  statusCode: res.statusCode,
@@ -188,6 +232,11 @@ const fetch = PCancelable.fn(
188
232
  headers: error.response ? error.response.headers : {},
189
233
  statusCode: error.response ? error.response.statusCode : undefined
190
234
  }
235
+ const cutHtml = await readCutHtml(error, readHtmlBody, toEncode)
236
+ if (cutHtml) {
237
+ debug('fetch:partial', { url, bytes: Buffer.byteLength(cutHtml), reflect })
238
+ return { ...answer, html: cutHtml, partial: true, mode: 'fetch', redirects }
239
+ }
191
240
  return reflect
192
241
  ? { isRejected: true, error, ...answer }
193
242
  : { ...answer, html: '', mode: 'fetch', redirects }
@@ -446,10 +495,11 @@ const getContent = PCancelable.fn(
446
495
  onCancel(() => promise.cancel())
447
496
 
448
497
  return promise.then(content => {
449
- const { pdfMeta, ...rest } = content
498
+ const { pdfMeta, converted, ...rest } = content
450
499
  const $ = addHtml({
451
500
  ...rest,
452
501
  pdfMeta,
502
+ converted,
453
503
  ...(isFetchMode ? puppeteerOpts : undefined),
454
504
  rewriteUrls,
455
505
  rewriteHtml