-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathimageFunction.js
144 lines (122 loc) · 3.84 KB
/
imageFunction.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
const { builder } = require('@netlify/functions')
const sharp = require('sharp')
const fetch = require('node-fetch')
const imageType = require('image-type')
const isSvg = require('is-svg')
const etag = require('etag')
const imageSize = require('image-size')
// 6MB is hard max Lambda response size
const MAX_RESPONSE_SIZE = 6291456
function getImageType(buffer) {
const type = imageType(buffer)
if (type) {
return type
}
if (isSvg(buffer)) {
return { ext: 'svg', mime: 'image/svg' }
}
return null
}
const IGNORED_FORMATS = new Set(['svg', 'gif'])
const OUTPUT_FORMATS = new Set(['png', 'jpg', 'webp', 'avif'])
// Function used to mimic next/image
const handler = async (event) => {
const [, , url, w = 500, q = 75] = event.path.split('/')
// Work-around a bug in redirect handling. Remove when fixed.
const parsedUrl = decodeURIComponent(url).replace('+', '%20')
const width = parseInt(w)
if (!width) {
return {
statusCode: 400,
body: 'Invalid image parameters',
}
}
const quality = parseInt(q) || 60
let imageUrl
let isRemoteImage = false
// Relative image
if (parsedUrl.startsWith('/')) {
const protocol = event.headers['x-nf-connection-proto'] || event.headers['x-forwarded-proto'] || 'http'
imageUrl = `${protocol}://${event.headers.host || event.hostname}${parsedUrl}`
} else {
isRemoteImage = true
// Remote images need to be in the allowlist
const allowedDomains = process.env.NEXT_IMAGE_ALLOWED_DOMAINS
? process.env.NEXT_IMAGE_ALLOWED_DOMAINS.split(',').map((domain) => domain.trim())
: []
if (!allowedDomains.includes(new URL(parsedUrl).hostname)) {
return {
statusCode: 403,
body: 'Image is not from a permitted domain',
}
}
imageUrl = parsedUrl
}
const imageData = await fetch(imageUrl)
if (!imageData.ok) {
console.error(`Failed to download image ${imageUrl}. Status ${imageData.status} ${imageData.statusText}`)
return {
statusCode: imageData.status,
body: imageData.statusText,
}
}
const bufferData = await imageData.buffer()
const type = getImageType(bufferData)
if (!type) {
return { statusCode: 400, body: 'Source does not appear to be an image' }
}
const dimensions = imageSize(bufferData)
if (width > dimensions.width) {
// We won't upsize images, and to avoid downloading the same size multiple times,
// we redirect to the largest available size
const Location = `/nextimg/${url}/${dimensions.width}/${q}`
return {
statusCode: 302,
headers: {
Location,
},
}
}
let { ext } = type
// For unsupported formats (gif, svg) we redirect to the original
if (IGNORED_FORMATS.has(ext)) {
return {
statusCode: 302,
headers: {
Location: isRemoteImage ? imageUrl : parsedUrl,
},
}
}
if (process.env.FORCE_WEBP_OUTPUT === 'true' || process.env.FORCE_WEBP_OUTPUT === '1') {
ext = 'webp'
}
if (!OUTPUT_FORMATS.has(ext)) {
ext = 'jpg'
}
// The format methods are just to set options: they don't
// make it return that format.
const { info, data: imageBuffer } = await sharp(bufferData)
.rotate()
.jpeg({ quality, mozjpeg: true, force: ext === 'jpg' })
.png({ quality, palette: true, force: ext === 'png' })
.webp({ quality, force: ext === 'webp' })
.avif({ quality, force: ext === 'avif' })
.resize(width, null, { withoutEnlargement: true })
.toBuffer({ resolveWithObject: true })
if (imageBuffer.length > MAX_RESPONSE_SIZE) {
return {
statusCode: 400,
body: 'Requested image is too large. Maximum size is 6MB.',
}
}
return {
statusCode: 200,
headers: {
'Content-Type': `image/${info.format}`,
etag: etag(imageBuffer),
},
body: imageBuffer.toString('base64'),
isBase64Encoded: true,
}
}
exports.handler = builder(handler)