metascraper-image 5.58.13 → 5.59.3

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/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "metascraper-image",
3
3
  "description": "Metascraper rule to extract the image from HTML using Open Graph, JSON-LD, and fallback selectors.",
4
4
  "homepage": "https://github.com/microlinkhq/metascraper/packages/metascraper-image",
5
- "version": "5.58.13",
5
+ "version": "5.59.3",
6
6
  "types": "src/index.d.ts",
7
7
  "main": "src/index.js",
8
8
  "author": {
@@ -31,7 +31,10 @@
31
31
  "thumbnail"
32
32
  ],
33
33
  "dependencies": {
34
- "@metascraper/helpers": "5.58.13"
34
+ "@metascraper/helpers": "5.59.3"
35
+ },
36
+ "devDependencies": {
37
+ "ava": "8"
35
38
  },
36
39
  "engines": {
37
40
  "node": ">= 22"
@@ -40,8 +43,8 @@
40
43
  "src"
41
44
  ],
42
45
  "scripts": {
43
- "test": "exit 0"
46
+ "test": "NODE_PATH=.. TZ=UTC ava --timeout 15s"
44
47
  },
45
48
  "license": "MIT",
46
- "gitHead": "62841e86839aa2a9ae0dee7316c2b01982b9836d"
49
+ "gitHead": "aa2f5c54d37d63962f75366e897ca461c6bb18be"
47
50
  }
package/src/budget.js ADDED
@@ -0,0 +1,30 @@
1
+ 'use strict'
2
+
3
+ const createBudget = size => {
4
+ let remaining = size
5
+ return {
6
+ spend: () => {
7
+ if (remaining === 0) return false
8
+ remaining--
9
+ return true
10
+ },
11
+ isSpent: () => remaining === 0,
12
+ topUp: minimum => {
13
+ remaining = Math.max(remaining, minimum)
14
+ }
15
+ }
16
+ }
17
+
18
+ const perExtraction = create => {
19
+ const states = new WeakMap()
20
+ return extraction => {
21
+ let state = states.get(extraction)
22
+ if (state === undefined) {
23
+ state = create()
24
+ states.set(extraction, state)
25
+ }
26
+ return state
27
+ }
28
+ }
29
+
30
+ module.exports = { createBudget, perExtraction }
package/src/img.js ADDED
@@ -0,0 +1,153 @@
1
+ 'use strict'
2
+
3
+ const { imageExtensions } = require('@metascraper/helpers')
4
+
5
+ const { isDataUri } = require('./placeholder')
6
+ const { ASCII_WHITESPACE, isInteger, isValidFloat } = require('./syntax')
7
+ const { isTrackingPixel } = require('./visibility')
8
+
9
+ const LAZY_SOURCE_ATTRIBUTES = ['data-src', 'data-lazy-src', 'data-original']
10
+
11
+ const LAZY_SRCSET_ATTRIBUTES = ['data-srcset', 'data-lazy-srcset']
12
+
13
+ const TEMPLATE_OR_WHITESPACE = /[\s{}]/
14
+
15
+ const URL_SUFFIX = /[?#]/
16
+
17
+ const IMAGE_EXTENSIONS = new Set(
18
+ Object.keys(imageExtensions).map(extension => extension.toLowerCase())
19
+ )
20
+
21
+ const isDensity = value => isValidFloat(value) && Number(value) >= 0
22
+
23
+ const isSrcsetSeparator = char => char === ',' || ASCII_WHITESPACE.has(char)
24
+
25
+ const skipSeparators = (srcset, index) => {
26
+ while (index < srcset.length && isSrcsetSeparator(srcset[index])) index++
27
+ return index
28
+ }
29
+
30
+ const readUntilWhitespace = (srcset, index) => {
31
+ while (index < srcset.length && !ASCII_WHITESPACE.has(srcset[index])) index++
32
+ return index
33
+ }
34
+
35
+ const readDescriptorsEnd = (srcset, index) => {
36
+ let inParens = false
37
+ for (; index < srcset.length; index++) {
38
+ const char = srcset[index]
39
+ if (char === '(') inParens = true
40
+ else if (char === ')') inParens = false
41
+ else if (char === ',' && !inParens) break
42
+ }
43
+ return index
44
+ }
45
+
46
+ const descriptorTokensOf = text => {
47
+ const tokens = []
48
+ let token = ''
49
+ for (const char of text) {
50
+ if (!ASCII_WHITESPACE.has(char)) token += char
51
+ else if (token) {
52
+ tokens.push(token)
53
+ token = ''
54
+ }
55
+ }
56
+ if (token) tokens.push(token)
57
+ return tokens
58
+ }
59
+
60
+ const DESCRIPTOR_VALUE_IS_VALID = {
61
+ w: value => isInteger(value) && Number(value) > 0,
62
+ h: value => isInteger(value) && Number(value) > 0,
63
+ x: isDensity
64
+ }
65
+
66
+ const areValidDescriptors = text => {
67
+ const kinds = new Set()
68
+ for (const token of descriptorTokensOf(text)) {
69
+ const kind = token[token.length - 1]
70
+ const isValidValue = DESCRIPTOR_VALUE_IS_VALID[kind]
71
+ if (isValidValue === undefined || kinds.has(kind)) return false
72
+ if (!isValidValue(token.slice(0, -1))) return false
73
+ kinds.add(kind)
74
+ }
75
+ if (kinds.has('x') && kinds.has('w')) return false
76
+ return !kinds.has('h') || kinds.has('w')
77
+ }
78
+
79
+ const trimTrailingCommas = (srcset, start, end) => {
80
+ while (end > start && srcset[end - 1] === ',') end--
81
+ return end
82
+ }
83
+
84
+ const isImageFilename = value => {
85
+ const filename = value.split(URL_SUFFIX, 1)[0]
86
+ const dot = filename.lastIndexOf('.')
87
+ return (
88
+ dot !== -1 && IMAGE_EXTENSIONS.has(filename.slice(dot + 1).toLowerCase())
89
+ )
90
+ }
91
+
92
+ const isUrlLike = value =>
93
+ !TEMPLATE_OR_WHITESPACE.test(value) &&
94
+ (value.includes('/') || isImageFilename(value))
95
+
96
+ const isLinkedUrl = value => {
97
+ if (value === undefined) return false
98
+ const url = value.trim()
99
+ return !isDataUri(url) && isUrlLike(url)
100
+ }
101
+
102
+ const findSrcsetImage = (srcset, toImageUrl) => {
103
+ if (srcset === undefined) return
104
+ let index = skipSeparators(srcset, 0)
105
+ while (index < srcset.length) {
106
+ const start = index
107
+ index = readUntilWhitespace(srcset, index)
108
+ const end = trimTrailingCommas(srcset, start, index)
109
+ let hasValidDescriptors = true
110
+ if (end === index) {
111
+ const descriptorsEnd = readDescriptorsEnd(srcset, index)
112
+ hasValidDescriptors = areValidDescriptors(
113
+ srcset.slice(index, descriptorsEnd)
114
+ )
115
+ index = descriptorsEnd
116
+ }
117
+ const candidate = srcset.slice(start, end)
118
+ const image =
119
+ hasValidDescriptors && isLinkedUrl(candidate)
120
+ ? toImageUrl(candidate)
121
+ : undefined
122
+ if (image) return image
123
+ index = skipSeparators(srcset, index)
124
+ }
125
+ }
126
+
127
+ const isDataSource = src => src !== undefined && isDataUri(src)
128
+
129
+ const findLazySource = (el, toImageUrl) => {
130
+ for (const attribute of LAZY_SOURCE_ATTRIBUTES) {
131
+ const value = el.attr(attribute)
132
+ const image = isLinkedUrl(value) ? toImageUrl(value) : undefined
133
+ if (image) return image
134
+ }
135
+ for (const attribute of LAZY_SRCSET_ATTRIBUTES) {
136
+ const image = findSrcsetImage(el.attr(attribute), toImageUrl)
137
+ if (image) return image
138
+ }
139
+ }
140
+
141
+ const findSource = (el, toImageUrl) => {
142
+ const src = el.attr('src')
143
+ const srcset = () => findSrcsetImage(el.attr('srcset'), toImageUrl)
144
+ if (isDataSource(src)) {
145
+ return findLazySource(el, toImageUrl) ?? srcset() ?? toImageUrl(src)
146
+ }
147
+ return toImageUrl(src) ?? findLazySource(el, toImageUrl) ?? srcset()
148
+ }
149
+
150
+ const findImgSource = (el, toImageUrl) =>
151
+ isTrackingPixel(el) ? undefined : findSource(el, toImageUrl)
152
+
153
+ module.exports = { findImgSource }
package/src/index.js CHANGED
@@ -1,16 +1,84 @@
1
1
  'use strict'
2
2
 
3
- const {
4
- $jsonld,
5
- $filter,
6
- $meta,
7
- image,
8
- toRule
9
- } = require('@metascraper/helpers')
3
+ const { $jsonld, $meta, image, toRule } = require('@metascraper/helpers')
10
4
 
11
- const toImage = toRule(image)
5
+ const { isBeaconUrl, isGuessedPlaceholderUrl } = require('./placeholder')
6
+ const { createImageValidator } = require('./validate')
7
+ const { findImgSource } = require('./img')
8
+ const { isInvisible } = require('./visibility')
9
+ const { createBudget, perExtraction } = require('./budget')
12
10
 
13
- const getSrc = el => el.attr('src')
11
+ const MAX_GUESSED_URL_LENGTH = 8192
12
+
13
+ const MAX_GUESSED_CANDIDATES = 64
14
+
15
+ const LAST_RESORT_CANDIDATES = 8
16
+
17
+ const isDeclaredImage = createImageValidator({ isPlaceholderUrl: isBeaconUrl })
18
+
19
+ const isGuessedImage = createImageValidator({
20
+ isPlaceholderUrl: isGuessedPlaceholderUrl,
21
+ maxLength: MAX_GUESSED_URL_LENGTH
22
+ })
23
+
24
+ const extractionStateOf = perExtraction(() => ({
25
+ budget: createBudget(MAX_GUESSED_CANDIDATES),
26
+ rejected: new WeakSet(),
27
+ checkedCounts: new WeakMap()
28
+ }))
29
+
30
+ const createScan = ({ alreadyChecked, budget, check }) => {
31
+ let calls = 0
32
+ let checked = alreadyChecked
33
+ let isCutShort = false
34
+ return {
35
+ toImageUrl: value => {
36
+ calls++
37
+ if (calls <= alreadyChecked) return
38
+ if (!budget.spend()) {
39
+ isCutShort = true
40
+ return
41
+ }
42
+ checked = calls
43
+ return check(value)
44
+ },
45
+ isCutShort: () => isCutShort,
46
+ checkedCount: () => checked
47
+ }
48
+ }
49
+
50
+ const toImage = toRule((value, { url }) => isDeclaredImage(value, url, image))
51
+
52
+ const firstIfItHasSrc = elements => elements.first().filter('[src]')
53
+
54
+ const toImgImage =
55
+ (
56
+ selector,
57
+ {
58
+ isSkipped = () => false,
59
+ select = elements => elements,
60
+ minimumCandidates = 0
61
+ } = {}
62
+ ) =>
63
+ extraction => {
64
+ const { htmlDom: $, url } = extraction
65
+ const { budget, rejected, checkedCounts } = extractionStateOf(extraction)
66
+ budget.topUp(minimumCandidates)
67
+ for (const node of select($(selector)).toArray()) {
68
+ if (budget.isSpent()) return
69
+ const el = $(node)
70
+ if (rejected.has(node) || isSkipped(el)) continue
71
+ const scan = createScan({
72
+ alreadyChecked: checkedCounts.get(node) ?? 0,
73
+ budget,
74
+ check: value => isGuessedImage(value, url, image)
75
+ })
76
+ const found = findImgSource(el, scan.toImageUrl)
77
+ if (found) return found
78
+ if (scan.isCutShort()) checkedCounts.set(node, scan.checkedCount())
79
+ else rejected.add(node)
80
+ }
81
+ }
14
82
 
15
83
  module.exports = () => {
16
84
  const rules = {
@@ -24,10 +92,13 @@ module.exports = () => {
24
92
  toImage($jsonld('image.0.url')),
25
93
  toImage($jsonld('image.url')),
26
94
  toImage($jsonld('image')),
27
- toImage($ => $filter($, $('article img[src]'), getSrc)),
28
- toImage($ => $filter($, $('#content img[src]'), getSrc)),
29
- toImage($ => $('img[alt*="author" i]').attr('src')),
30
- toImage($ => $('img[src]:not([aria-hidden="true"])').attr('src'))
95
+ toImgImage('article img[src]'),
96
+ toImgImage('#content img[src]'),
97
+ toImgImage('img[alt*="author" i]', { select: firstIfItHasSrc }),
98
+ toImgImage('img[src]:not([aria-hidden="true"])', {
99
+ isSkipped: isInvisible,
100
+ minimumCandidates: LAST_RESORT_CANDIDATES
101
+ })
31
102
  ]
32
103
  }
33
104
 
package/src/media.js ADDED
@@ -0,0 +1,12 @@
1
+ 'use strict'
2
+
3
+ const { isAudioExtension, isVideoExtension } = require('@metascraper/helpers')
4
+
5
+ const filenameOf = pathname => pathname.slice(pathname.lastIndexOf('/') + 1)
6
+
7
+ const isMediaPathname = pathname => {
8
+ const filename = filenameOf(pathname)
9
+ return isVideoExtension(filename) || isAudioExtension(filename)
10
+ }
11
+
12
+ module.exports = { filenameOf, isMediaPathname }
@@ -0,0 +1,119 @@
1
+ 'use strict'
2
+
3
+ const { filenameOf } = require('./media')
4
+
5
+ const PLACEHOLDER_FILENAMES = new Set([
6
+ '1x1.gif',
7
+ '1x1.png',
8
+ 'blank.gif',
9
+ 'blank.png',
10
+ 'pixel.gif',
11
+ 'pixel.png',
12
+ 'spacer.gif',
13
+ 'spacer.png',
14
+ 'transparent.gif',
15
+ 'transparent.png'
16
+ ])
17
+
18
+ const BEACON_URLS = [
19
+ /^https?:\/\/fls-[a-z]+\.amazon\.[a-z.]+\/1\/batch\//,
20
+ /^https?:\/\/t\.co\/1\/i\/adsct/,
21
+ /^https?:\/\/(?:www\.)?facebook\.com\/tr\/?(?:[?#]|$)/,
22
+ /^https?:\/\/bat\.bing\.com\/action\//,
23
+ /^https?:\/\/[^/]+\/sbbi\/\?(?:[^#]*&)?sbbpg=/
24
+ ]
25
+
26
+ const BASE64_IMAGE_HEADER = /^data:image\/(?:gif|png)[^,]*;base64,/i
27
+
28
+ const GIF_SIGNATURE = Buffer.from('GIF8')
29
+ const PNG_SIGNATURE = Buffer.from([
30
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
31
+ ])
32
+
33
+ const GIF_WIDTH_OFFSET = 6
34
+ const GIF_HEIGHT_OFFSET = 8
35
+ const PNG_WIDTH_OFFSET = 16
36
+ const PNG_HEIGHT_OFFSET = 20
37
+
38
+ const MAX_PIXEL_SIZE = 1
39
+
40
+ const DATA_SCHEME = 'data:'
41
+
42
+ const IMAGE_DATA_PREFIX = 'data:image/'
43
+
44
+ const decodePercentEscapes = value => {
45
+ try {
46
+ return decodeURIComponent(value)
47
+ } catch (_) {
48
+ return value
49
+ }
50
+ }
51
+
52
+ const startsWith = (bytes, signature) =>
53
+ bytes.subarray(0, signature.length).equals(signature)
54
+
55
+ const readDimensions = bytes => {
56
+ if (
57
+ bytes.length >= GIF_HEIGHT_OFFSET + 2 &&
58
+ startsWith(bytes, GIF_SIGNATURE)
59
+ ) {
60
+ return [
61
+ bytes.readUInt16LE(GIF_WIDTH_OFFSET),
62
+ bytes.readUInt16LE(GIF_HEIGHT_OFFSET)
63
+ ]
64
+ }
65
+ if (
66
+ bytes.length >= PNG_HEIGHT_OFFSET + 4 &&
67
+ startsWith(bytes, PNG_SIGNATURE)
68
+ ) {
69
+ return [
70
+ bytes.readUInt32BE(PNG_WIDTH_OFFSET),
71
+ bytes.readUInt32BE(PNG_HEIGHT_OFFSET)
72
+ ]
73
+ }
74
+ }
75
+
76
+ const isTinyDimensions = ([width, height]) =>
77
+ width <= MAX_PIXEL_SIZE && height <= MAX_PIXEL_SIZE
78
+
79
+ const isPlaceholderDataUri = value => {
80
+ const header = BASE64_IMAGE_HEADER.exec(value)
81
+ if (!header) return false
82
+ const payload = decodePercentEscapes(value.slice(header[0].length))
83
+ const dimensions = readDimensions(Buffer.from(payload, 'base64'))
84
+ return dimensions !== undefined && isTinyDimensions(dimensions)
85
+ }
86
+
87
+ const isPlaceholderFilename = pathname =>
88
+ PLACEHOLDER_FILENAMES.has(filenameOf(pathname).toLowerCase())
89
+
90
+ const isBeaconUrl = url => BEACON_URLS.some(pattern => pattern.test(url.href))
91
+
92
+ const startsWithIgnoringCase = (value, prefix) =>
93
+ value.slice(0, prefix.length).toLowerCase() === prefix
94
+
95
+ const isDataUri = value => startsWithIgnoringCase(value, DATA_SCHEME)
96
+
97
+ const hasLowercaseDataScheme = value => value.startsWith(DATA_SCHEME)
98
+
99
+ const subtypeOf = value => {
100
+ const comma = value.indexOf(',')
101
+ if (comma === -1) return ''
102
+ return value.slice(IMAGE_DATA_PREFIX.length, comma).split(';', 1)[0]
103
+ }
104
+
105
+ const isImageDataUri = value =>
106
+ startsWithIgnoringCase(value, IMAGE_DATA_PREFIX) && subtypeOf(value) !== ''
107
+
108
+ const isGuessedPlaceholderUrl = url =>
109
+ isBeaconUrl(url) || isPlaceholderFilename(url.pathname)
110
+
111
+ module.exports = {
112
+ MAX_PIXEL_SIZE,
113
+ isBeaconUrl,
114
+ hasLowercaseDataScheme,
115
+ isDataUri,
116
+ isGuessedPlaceholderUrl,
117
+ isImageDataUri,
118
+ isPlaceholderDataUri
119
+ }
package/src/syntax.js ADDED
@@ -0,0 +1,47 @@
1
+ 'use strict'
2
+
3
+ const ASCII_WHITESPACE = new Set([' ', '\t', '\n', '\f', '\r'])
4
+
5
+ const isDigit = char => char >= '0' && char <= '9'
6
+
7
+ const isInteger = value => [...value].every(isDigit)
8
+
9
+ const skipDigits = (value, index) => {
10
+ while (index < value.length && isDigit(value[index])) index++
11
+ return index
12
+ }
13
+
14
+ const skipAsciiWhitespace = (value, index) => {
15
+ while (index < value.length && ASCII_WHITESPACE.has(value[index])) index++
16
+ return index
17
+ }
18
+
19
+ const skipExponent = (value, index) => {
20
+ if (value[index] !== 'e' && value[index] !== 'E') return index
21
+ let digitsStart = index + 1
22
+ if (value[digitsStart] === '-' || value[digitsStart] === '+') digitsStart++
23
+ const digitsEnd = skipDigits(value, digitsStart)
24
+ return digitsEnd === digitsStart ? -1 : digitsEnd
25
+ }
26
+
27
+ const isValidFloat = value => {
28
+ let index = value[0] === '-' ? 1 : 0
29
+ const integerEnd = skipDigits(value, index)
30
+ let hasDigits = integerEnd > index
31
+ index = integerEnd
32
+ if (value[index] === '.') {
33
+ const fractionEnd = skipDigits(value, index + 1)
34
+ if (fractionEnd === index + 1) return false
35
+ hasDigits = true
36
+ index = fractionEnd
37
+ }
38
+ return hasDigits && skipExponent(value, index) === value.length
39
+ }
40
+
41
+ module.exports = {
42
+ ASCII_WHITESPACE,
43
+ isInteger,
44
+ isValidFloat,
45
+ skipAsciiWhitespace,
46
+ skipDigits
47
+ }
@@ -0,0 +1,71 @@
1
+ 'use strict'
2
+
3
+ const {
4
+ hasLowercaseDataScheme,
5
+ isDataUri,
6
+ isImageDataUri,
7
+ isPlaceholderDataUri
8
+ } = require('./placeholder')
9
+ const { isMediaPathname } = require('./media')
10
+
11
+ const parseUrl = (value, baseUrl) => {
12
+ try {
13
+ return new URL(value, baseUrl)
14
+ } catch (_) {}
15
+ }
16
+
17
+ const resolveUrl = (value, baseUrl) => {
18
+ const resolved = parseUrl(value, baseUrl) ?? parseUrl(value)
19
+ if (resolved === undefined) return
20
+ resolved.username = ''
21
+ resolved.password = ''
22
+ return resolved
23
+ }
24
+
25
+ const WEB_PROTOCOLS = new Set(['http:', 'https:'])
26
+
27
+ const isRejectedUrl = (value, baseUrl, { isPlaceholderUrl, maxLength }) => {
28
+ const resolved = resolveUrl(value, baseUrl)
29
+ return (
30
+ resolved === undefined ||
31
+ !WEB_PROTOCOLS.has(resolved.protocol) ||
32
+ resolved.href.length > maxLength ||
33
+ isMediaPathname(resolved.pathname) ||
34
+ isPlaceholderUrl(resolved)
35
+ )
36
+ }
37
+
38
+ const isRejectedDataUri = (value, { maxLength }) =>
39
+ !isImageDataUri(value) ||
40
+ isPlaceholderDataUri(value) ||
41
+ (!hasLowercaseDataScheme(value) && value.length > maxLength)
42
+
43
+ const isUrlPadding = value => value <= ' '
44
+
45
+ const stripUrlPadding = value => {
46
+ let start = 0
47
+ let end = value.length
48
+ while (start < end && isUrlPadding(value[start])) start++
49
+ while (end > start && isUrlPadding(value[end - 1])) end--
50
+ return value.slice(start, end)
51
+ }
52
+
53
+ const isPaddedOrBlank = url => url === '' || url.trim() !== url
54
+
55
+ const isRejected = (value, baseUrl, options) => {
56
+ const url = stripUrlPadding(value)
57
+ if (isPaddedOrBlank(url)) return true
58
+ return isDataUri(url)
59
+ ? isRejectedDataUri(url, options)
60
+ : isRejectedUrl(url, baseUrl, options)
61
+ }
62
+
63
+ const createImageValidator =
64
+ ({ isPlaceholderUrl, maxLength = Infinity }) =>
65
+ (value, baseUrl, image) =>
66
+ typeof value !== 'string' ||
67
+ isRejected(value, baseUrl, { isPlaceholderUrl, maxLength })
68
+ ? undefined
69
+ : image(value, { url: baseUrl })
70
+
71
+ module.exports = { createImageValidator }
@@ -0,0 +1,376 @@
1
+ 'use strict'
2
+
3
+ const { MAX_PIXEL_SIZE } = require('./placeholder')
4
+ const {
5
+ ASCII_WHITESPACE,
6
+ isValidFloat,
7
+ skipAsciiWhitespace,
8
+ skipDigits
9
+ } = require('./syntax')
10
+
11
+ const HIDDEN_VALUES = {
12
+ display: new Set(['none']),
13
+ visibility: new Set(['hidden', 'collapse'])
14
+ }
15
+
16
+ const IMPORTANT = 'important'
17
+
18
+ const UNTIL_FOUND = 'until-found'
19
+
20
+ const PIXEL_UNIT = 'px'
21
+
22
+ const PERCENT = '%'
23
+
24
+ const COMMENT_START = '/*'
25
+
26
+ const COMMENT_END = '*/'
27
+
28
+ const ESCAPE = '\\'
29
+
30
+ const HEX_DIGIT = /^[0-9a-f]$/i
31
+
32
+ const MAX_HEX_ESCAPE_LENGTH = 6
33
+
34
+ const MAX_CODE_POINT = 0x10ffff
35
+
36
+ const REPLACEMENT_CHARACTER = '�'
37
+
38
+ const UNMEASURED = Infinity
39
+
40
+ const AUTO = 'auto'
41
+
42
+ const NONE = 'none'
43
+
44
+ const CSS_FUNCTION_START = '('
45
+
46
+ const CSS_WHITESPACE = /\s+/
47
+
48
+ const GLOBAL_KEYWORDS = [
49
+ 'inherit',
50
+ 'initial',
51
+ 'unset',
52
+ 'revert',
53
+ 'revert-layer'
54
+ ]
55
+
56
+ const DISPLAY_KEYWORDS = new Set([
57
+ 'none',
58
+ 'contents',
59
+ 'block',
60
+ 'inline',
61
+ 'run-in',
62
+ 'flow',
63
+ 'flow-root',
64
+ 'table',
65
+ 'flex',
66
+ 'grid',
67
+ 'ruby',
68
+ 'math',
69
+ 'list-item',
70
+ 'inline-block',
71
+ 'inline-table',
72
+ 'inline-flex',
73
+ 'inline-grid',
74
+ 'table-row-group',
75
+ 'table-header-group',
76
+ 'table-footer-group',
77
+ 'table-row',
78
+ 'table-cell',
79
+ 'table-column-group',
80
+ 'table-column',
81
+ 'table-caption',
82
+ 'ruby-base',
83
+ 'ruby-text',
84
+ 'ruby-base-container',
85
+ 'ruby-text-container',
86
+ '-webkit-box',
87
+ '-webkit-inline-box',
88
+ '-webkit-flex',
89
+ '-webkit-inline-flex',
90
+ '-moz-box',
91
+ '-moz-inline-box',
92
+ '-ms-flexbox',
93
+ '-ms-inline-flexbox',
94
+ '-ms-grid',
95
+ '-ms-inline-grid',
96
+ ...GLOBAL_KEYWORDS
97
+ ])
98
+
99
+ const withoutComments = style => {
100
+ let result = ''
101
+ let index = 0
102
+ while (index < style.length) {
103
+ const start = style.indexOf(COMMENT_START, index)
104
+ if (start === -1) return result + style.slice(index)
105
+ result += style.slice(index, start)
106
+ const end = style.indexOf(COMMENT_END, start + COMMENT_START.length)
107
+ if (end === -1) return result
108
+ index = end + COMMENT_END.length
109
+ }
110
+ return result
111
+ }
112
+
113
+ const isHexDigit = char => char !== undefined && HEX_DIGIT.test(char)
114
+
115
+ const characterOf = codePoint =>
116
+ codePoint > MAX_CODE_POINT
117
+ ? REPLACEMENT_CHARACTER
118
+ : String.fromCodePoint(codePoint)
119
+
120
+ const readEscape = (text, index) => {
121
+ let end = index
122
+ while (end - index < MAX_HEX_ESCAPE_LENGTH && isHexDigit(text[end])) end++
123
+ if (end === index) return { character: text[index] ?? '', end: index + 1 }
124
+ const character = characterOf(parseInt(text.slice(index, end), 16))
125
+ return { character, end: ASCII_WHITESPACE.has(text[end]) ? end + 1 : end }
126
+ }
127
+
128
+ const unescape = text => {
129
+ let result = ''
130
+ let index = 0
131
+ while (index < text.length) {
132
+ const escape = text.indexOf(ESCAPE, index)
133
+ if (escape === -1) return result + text.slice(index)
134
+ const { character, end } = readEscape(text, escape + 1)
135
+ result += text.slice(index, escape) + character
136
+ index = end
137
+ }
138
+ return result
139
+ }
140
+
141
+ const indexOfUnescaped = (text, char, from) => {
142
+ for (let index = from; index < text.length; index++) {
143
+ if (text[index] === ESCAPE) index++
144
+ else if (text[index] === char) return index
145
+ }
146
+ return -1
147
+ }
148
+
149
+ const splitUnescaped = (text, separator) => {
150
+ const parts = []
151
+ let start = 0
152
+ let end = indexOfUnescaped(text, separator, start)
153
+ while (end !== -1) {
154
+ parts.push(text.slice(start, end))
155
+ start = end + 1
156
+ end = indexOfUnescaped(text, separator, start)
157
+ }
158
+ parts.push(text.slice(start))
159
+ return parts
160
+ }
161
+
162
+ const normalize = text => unescape(text).trim().toLowerCase()
163
+
164
+ const declarationOf = text => {
165
+ const colon = indexOfUnescaped(text, ':', 0)
166
+ if (colon === -1) return
167
+ const value = normalize(text.slice(colon + 1))
168
+ const bang = value.lastIndexOf('!')
169
+ const important = bang !== -1 && value.slice(bang + 1).trim() === IMPORTANT
170
+ return {
171
+ property: normalize(text.slice(0, colon)),
172
+ value: important ? value.slice(0, bang).trimEnd() : value,
173
+ important
174
+ }
175
+ }
176
+
177
+ const attributePixelsOf = value => {
178
+ const start = skipAsciiWhitespace(value, 0)
179
+ let end = skipDigits(value, start)
180
+ if (end === start) return
181
+ if (value[end] === '.') end = skipDigits(value, end + 1)
182
+ if (value[end] === PERCENT) return
183
+ return Number(value.slice(start, end))
184
+ }
185
+
186
+ const isUnitCharacter = char => (char >= 'a' && char <= 'z') || char === PERCENT
187
+
188
+ const unitStartOf = value => {
189
+ let index = value.length
190
+ while (index > 0 && isUnitCharacter(value[index - 1])) index--
191
+ return index
192
+ }
193
+
194
+ const stylePixelsOf = value => {
195
+ const unitStart = unitStartOf(value)
196
+ const unit = value.slice(unitStart)
197
+ const number = value.slice(value[0] === '+' ? 1 : 0, unitStart)
198
+ if (!isValidFloat(number)) return
199
+ const pixels = Number(number)
200
+ if (pixels < 0) return
201
+ if (unit === PIXEL_UNIT) return pixels
202
+ if (unit === '') return pixels === 0 ? pixels : undefined
203
+ return LENGTH_UNITS.has(unit) ? UNMEASURED : undefined
204
+ }
205
+
206
+ const SIZING_KEYWORDS = [
207
+ 'min-content',
208
+ 'max-content',
209
+ 'fit-content',
210
+ 'stretch',
211
+ '-webkit-fill-available',
212
+ '-moz-available',
213
+ ...GLOBAL_KEYWORDS
214
+ ]
215
+
216
+ const PREFERRED_SIZE_KEYWORDS = new Set([AUTO, ...SIZING_KEYWORDS])
217
+
218
+ const MAXIMUM_SIZE_KEYWORDS = new Set([NONE, ...SIZING_KEYWORDS])
219
+
220
+ const LENGTH_UNITS = new Set([
221
+ '%',
222
+ 'em',
223
+ 'rem',
224
+ 'ex',
225
+ 'rex',
226
+ 'ch',
227
+ 'rch',
228
+ 'ic',
229
+ 'ric',
230
+ 'cap',
231
+ 'rcap',
232
+ 'lh',
233
+ 'rlh',
234
+ 'vw',
235
+ 'vh',
236
+ 'vi',
237
+ 'vb',
238
+ 'vmin',
239
+ 'vmax',
240
+ 'svw',
241
+ 'svh',
242
+ 'svi',
243
+ 'svb',
244
+ 'svmin',
245
+ 'svmax',
246
+ 'lvw',
247
+ 'lvh',
248
+ 'lvi',
249
+ 'lvb',
250
+ 'lvmin',
251
+ 'lvmax',
252
+ 'dvw',
253
+ 'dvh',
254
+ 'dvi',
255
+ 'dvb',
256
+ 'dvmin',
257
+ 'dvmax',
258
+ 'cqw',
259
+ 'cqh',
260
+ 'cqi',
261
+ 'cqb',
262
+ 'cqmin',
263
+ 'cqmax',
264
+ 'cm',
265
+ 'mm',
266
+ 'q',
267
+ 'in',
268
+ 'pt',
269
+ 'pc'
270
+ ])
271
+
272
+ const VISIBILITY_KEYWORDS = new Set([
273
+ 'visible',
274
+ 'hidden',
275
+ 'collapse',
276
+ ...GLOBAL_KEYWORDS
277
+ ])
278
+
279
+ const isCssFunction = value => value.includes(CSS_FUNCTION_START)
280
+
281
+ const isSizeValue = keywords => value =>
282
+ keywords.has(value) || stylePixelsOf(value) !== undefined
283
+
284
+ const isPreferredSize = isSizeValue(PREFERRED_SIZE_KEYWORDS)
285
+
286
+ const isMaximumSize = isSizeValue(MAXIMUM_SIZE_KEYWORDS)
287
+
288
+ const VALUE_IS_VALID = new Map([
289
+ [
290
+ 'display',
291
+ value =>
292
+ value
293
+ .split(CSS_WHITESPACE)
294
+ .every(keyword => DISPLAY_KEYWORDS.has(keyword))
295
+ ],
296
+ ['visibility', value => VISIBILITY_KEYWORDS.has(value)],
297
+ ['width', isPreferredSize],
298
+ ['height', isPreferredSize],
299
+ ['min-width', isPreferredSize],
300
+ ['min-height', isPreferredSize],
301
+ ['max-width', isMaximumSize],
302
+ ['max-height', isMaximumSize]
303
+ ])
304
+
305
+ const isValidDeclaration = ({ property, value }) => {
306
+ const isValid = VALUE_IS_VALID.get(property)
307
+ return isValid !== undefined && (isCssFunction(value) || isValid(value))
308
+ }
309
+
310
+ const styleOf = el => {
311
+ const effective = new Map()
312
+ const style = el.attr('style')
313
+ if (style === undefined) return effective
314
+ for (const text of splitUnescaped(withoutComments(style), ';')) {
315
+ const declaration = declarationOf(text)
316
+ if (declaration === undefined || !isValidDeclaration(declaration)) continue
317
+ const current = effective.get(declaration.property)
318
+ if (current?.important && !declaration.important) continue
319
+ effective.set(declaration.property, declaration)
320
+ }
321
+ return effective
322
+ }
323
+
324
+ const declaredPixelsOf = (style, property) => {
325
+ const declared = style.get(property)
326
+ if (declared === undefined) return
327
+ return stylePixelsOf(declared.value) ?? UNMEASURED
328
+ }
329
+
330
+ const preferredSizeOf = (el, style, dimension) => {
331
+ const styled = declaredPixelsOf(style, dimension)
332
+ if (styled !== undefined) return styled
333
+ const attribute = el.attr(dimension)
334
+ return attribute === undefined ? undefined : attributePixelsOf(attribute)
335
+ }
336
+
337
+ const minimumSizeOf = (style, dimension) => {
338
+ const property = `min-${dimension}`
339
+ if (style.get(property)?.value === AUTO) return 0
340
+ return declaredPixelsOf(style, property) ?? 0
341
+ }
342
+
343
+ const sizeOf = (el, style, dimension) => {
344
+ const preferred = preferredSizeOf(el, style, dimension) ?? UNMEASURED
345
+ const maximum = declaredPixelsOf(style, `max-${dimension}`) ?? UNMEASURED
346
+ const minimum = minimumSizeOf(style, dimension)
347
+ return Math.max(minimum, Math.min(preferred, maximum))
348
+ }
349
+
350
+ const isTiny = size => size <= MAX_PIXEL_SIZE
351
+
352
+ const isTrackingPixel = el => {
353
+ const style = styleOf(el)
354
+ return (
355
+ isTiny(sizeOf(el, style, 'width')) && isTiny(sizeOf(el, style, 'height'))
356
+ )
357
+ }
358
+
359
+ const isHiddenByAttribute = (hidden, style) =>
360
+ hidden !== undefined &&
361
+ (hidden.toLowerCase() === UNTIL_FOUND || !style.has('display'))
362
+
363
+ const isHiddenByStyle = style =>
364
+ Object.entries(HIDDEN_VALUES).some(([property, hiddenValues]) =>
365
+ hiddenValues.has(style.get(property)?.value)
366
+ )
367
+
368
+ const isInvisible = el => {
369
+ const style = styleOf(el)
370
+ return (
371
+ isHiddenByAttribute(el.get(0).attribs.hidden, style) ||
372
+ isHiddenByStyle(style)
373
+ )
374
+ }
375
+
376
+ module.exports = { isInvisible, isTrackingPixel }