1
- const probe = require ( 'probe-image-size' ) ;
1
+ const fetch = require ( 'node-fetch' ) ;
2
+ const { imageSize } = require ( 'image-size' ) ;
2
3
const errorLogger = require ( './error-logger' ) ;
3
4
const { getCache, setCache } = require ( './cache' ) ;
4
5
const defaultDimensions = { width : 600 , height : 400 } ;
5
6
7
+ async function probeImage ( url ) {
8
+ const response = await fetch ( url ) ;
9
+ if ( ! response . ok )
10
+ throw new Error ( `Failed to fetch image: ${ response . statusText } ` ) ;
11
+
12
+ const chunks = [ ] ;
13
+ const reader = response . body ;
14
+
15
+ for await ( const chunk of reader ) {
16
+ chunks . push ( chunk ) ;
17
+
18
+ try {
19
+ // Try to determine image size with available data
20
+ const dimensions = imageSize ( Buffer . concat ( chunks ) ) ;
21
+ if ( dimensions . width && dimensions . height ) {
22
+ response . body . destroy ( ) ; // Stop data stream
23
+ return dimensions ;
24
+ }
25
+ } catch ( err ) {
26
+ // Keep reading if more data is needed
27
+ }
28
+ }
29
+
30
+ throw new Error ( 'Could not determine image size' ) ;
31
+ }
32
+
6
33
const getImageDimensions = async ( url , description ) => {
7
34
try {
35
+ if ( url . startsWith ( 'data:' ) )
36
+ throw new Error ( 'Data URI images are not supported' ) ;
8
37
let imageDimensions = getCache ( url ) ;
9
38
if ( imageDimensions ) return imageDimensions ;
10
39
11
- const res = await probe ( url ) ;
40
+ const res = await probeImage ( url ) ;
12
41
imageDimensions = {
13
42
width : res ?. width ? res ?. width : defaultDimensions . width ,
14
43
height : res ?. height ? res ?. height : defaultDimensions . height
@@ -17,7 +46,7 @@ const getImageDimensions = async (url, description) => {
17
46
18
47
return imageDimensions ;
19
48
} catch ( err ) {
20
- if ( err . statusCode ) errorLogger ( { type : 'image' , name : description } ) ; // Only write HTTP status code errors to log
49
+ errorLogger ( { type : 'image' , name : description } ) ;
21
50
22
51
return defaultDimensions ;
23
52
}
0 commit comments