ReviewOS

also looking at this

stacks/rpx

feat: imgx integration — on-the-fly image transforms from query params

#2264
Merged glennmichael123 wants to merge feat/imgx-integration into main
15 files +1118 -16
packages/rpx/test/imgx.test.tsadded+254-0
Changes to packages/rpx/test/imgx.test.ts
@@ -0,0 +1,254 @@
1import { afterAll, beforeAll, describe, expect, it } from 'bun:test'
2import * as fsp from 'node:fs/promises'
3import * as os from 'node:os'
4import * as path from 'node:path'
5import { createImageData, decode, encode } from 'ts-images'
6import { ImgxCache, hasImgxParams, parseImgxParams, resolveImgx } from '../src/imgx'
7import { createProxyFetchHandler } from '../src/proxy-handler'
8import { resolveStaticRoute } from '../src/static-files'
9
10function req(url: string, headers: Record<string, string> = {}): Request {
11 const u = new URL(url)
12 return new Request(url, { headers: { host: u.host, ...headers } })
13}
14
15/** A solid-color RGBA test image encoded as PNG. */
16async function makePng(width: number, height: number): Promise<Uint8Array<ArrayBuffer>> {
17 const img = createImageData(width, height)
18 for (let i = 0; i < img.data.length; i += 4) {
19 img.data[i] = 200
20 img.data[i + 1] = 40
21 img.data[i + 2] = 40
22 img.data[i + 3] = 255
23 }
24 return new Uint8Array(await encode(img, 'png', {}))
25}
26
27describe('parseImgxParams', () => {
28 it('returns undefined without trigger params', () => {
29 expect(parseImgxParams('')).toBeUndefined()
30 expect(parseImgxParams('?foo=bar')).toBeUndefined()
31 // Modifier-only params don't trigger a transform on their own.
32 expect(parseImgxParams('?fit=crop&dpr=2&bg=fff')).toBeUndefined()
33 })
34
35 it('parses the meema-style core params', () => {
36 const t = parseImgxParams('?w=200&h=1200&q=80')
37 expect(t).toBeDefined()
38 expect(t!.width).toBe(200)
39 expect(t!.height).toBe(1200)
40 expect(t!.quality).toBe(80)
41 expect(t!.fit).toBe('clip')
42 expect(t!.dpr).toBe(1)
43 })
44
45 it('clamps quality and dpr, and keeps 0-1 fractions', () => {
46 expect(parseImgxParams('?q=500')!.quality).toBe(100)
47 expect(parseImgxParams('?q=0')!.quality).toBe(1)
48 expect(parseImgxParams('?w=16&dpr=99')!.dpr).toBe(5)
49 expect(parseImgxParams('?w=0.5')!.width).toBe(0.5)
50 })
51
52 it('normalizes format aliases and auto', () => {
53 expect(parseImgxParams('?fm=jpg')!.format).toBe('jpeg')
54 expect(parseImgxParams('?format=webp')!.format).toBe('webp')
55 expect(parseImgxParams('?fm=auto')!.autoFormat).toBe(true)
56 expect(parseImgxParams('?auto=format')!.autoFormat).toBe(true)
57 // Unknown formats don't trigger a transform by themselves.
58 expect(parseImgxParams('?fm=tiff')).toBeUndefined()
59 })
60
61 it('maps fit fallbacks and crop positions', () => {
62 expect(parseImgxParams('?w=10&fit=clamp')!.fit).toBe('clip')
63 expect(parseImgxParams('?w=10&fit=fillmax')!.fit).toBe('fill')
64 expect(parseImgxParams('?w=10&fit=crop&crop=top,left')!.position).toBe('top-left')
65 expect(parseImgxParams('?w=10&fit=crop&crop=faces')!.position).toBe('center')
66 })
67
68 it('pre-checks cheaply via hasImgxParams', () => {
69 expect(hasImgxParams('?w=1')).toBe(true)
70 expect(hasImgxParams('?word=1')).toBe(false)
71 expect(hasImgxParams('')).toBe(false)
72 })
73})
74
75describe('ImgxCache', () => {
76 it('evicts least-recently-used entries beyond limits', () => {
77 const cache = new ImgxCache(1024, 2)
78 cache.set('a', { bytes: new Uint8Array(10), contentType: 'image/png' })
79 cache.set('b', { bytes: new Uint8Array(10), contentType: 'image/png' })
80 expect(cache.get('a')).toBeDefined() // refresh a
81 cache.set('c', { bytes: new Uint8Array(10), contentType: 'image/png' })
82 expect(cache.get('b')).toBeUndefined() // b was the LRU entry
83 expect(cache.get('a')).toBeDefined()
84 expect(cache.get('c')).toBeDefined()
85 })
86
87 it('bounds total bytes', () => {
88 const cache = new ImgxCache(25, 10)
89 cache.set('a', { bytes: new Uint8Array(10), contentType: 'image/png' })
90 cache.set('b', { bytes: new Uint8Array(10), contentType: 'image/png' })
91 cache.set('c', { bytes: new Uint8Array(10), contentType: 'image/png' })
92 expect(cache.size).toBe(2)
93 expect(cache.get('a')).toBeUndefined()
94 })
95})
96
97describe('imgx proxy integration', () => {
98 let origin: ReturnType<typeof Bun.serve> | null = null
99 let originHost = ''
100 let png: Uint8Array<ArrayBuffer>
101
102 beforeAll(async () => {
103 png = await makePng(64, 48)
104 origin = Bun.serve({
105 port: 0,
106 hostname: '127.0.0.1',
107 fetch(request: Request) {
108 const { pathname } = new URL(request.url)
109 if (pathname === '/img.png')
110 return new Response(png, { headers: { 'content-type': 'image/png', 'cache-control': 'max-age=60', 'etag': '"origin"' } })
111 if (pathname === '/broken.png')
112 return new Response(new Uint8Array([1, 2, 3, 4]), { headers: { 'content-type': 'image/png' } })
113 if (pathname === '/plain.txt')
114 return new Response('hello', { headers: { 'content-type': 'text/plain' } })
115 return new Response('not found', { status: 404 })
116 },
117 })
118 originHost = `127.0.0.1:${origin.port}`
119 })
120
121 afterAll(() => {
122 origin?.stop(true)
123 })
124
125 function handlerWith(imgx: ReturnType<typeof resolveImgx>) {
126 return createProxyFetchHandler(() => ({ sourceHost: originHost, imgx }))
127 }
128
129 it('resizes to a requested width preserving aspect ratio', async () => {
130 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/img.png?w=32'))
131 expect(res!.status).toBe(200)
132 expect(res!.headers.get('content-type')).toBe('image/png')
133 expect(res!.headers.get('x-rpx-imgx')).toBe('miss')
134 // Upstream validators no longer describe the transformed entity.
135 expect(res!.headers.get('etag')).toBeNull()
136 expect(res!.headers.get('cache-control')).toBe('max-age=60')
137 const out = await decode(new Uint8Array(await res!.arrayBuffer()))
138 expect(out.width).toBe(32)
139 expect(out.height).toBe(24)
140 })
141
142 it('crops to exact dimensions with fit=crop', async () => {
143 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/img.png?w=20&h=20&fit=crop'))
144 const out = await decode(new Uint8Array(await res!.arrayBuffer()))
145 expect(out.width).toBe(20)
146 expect(out.height).toBe(20)
147 })
148
149 it('treats 0-1 dimensions as fractions of the source', async () => {
150 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/img.png?w=0.5'))
151 const out = await decode(new Uint8Array(await res!.arrayBuffer()))
152 expect(out.width).toBe(32)
153 expect(out.height).toBe(24)
154 })
155
156 it('multiplies dimensions by dpr', async () => {
157 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/img.png?w=16&dpr=2'))
158 const out = await decode(new Uint8Array(await res!.arrayBuffer()))
159 expect(out.width).toBe(32)
160 })
161
162 it('never enlarges with fit=max', async () => {
163 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/img.png?w=500&fit=max'))
164 const out = await decode(new Uint8Array(await res!.arrayBuffer()))
165 expect(out.width).toBe(64)
166 expect(out.height).toBe(48)
167 })
168
169 it('re-encodes to an explicit format', async () => {
170 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/img.png?fm=jpeg&q=50'))
171 expect(res!.headers.get('content-type')).toBe('image/jpeg')
172 const out = await decode(new Uint8Array(await res!.arrayBuffer()))
173 expect(out.width).toBe(64)
174 expect(out.height).toBe(48)
175 })
176
177 it('negotiates webp from Accept with auto=format', async () => {
178 const res = await handlerWith(resolveImgx(true))(
179 req('http://app.localhost/img.png?w=16&auto=format', { accept: 'image/avif,image/webp,*/*' }),
180 )
181 expect(res!.headers.get('content-type')).toBe('image/webp')
182 expect(res!.headers.get('vary')).toContain('accept')
183 })
184
185 it('passes through when no transform params are present', async () => {
186 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/img.png'))
187 expect(res!.status).toBe(200)
188 expect(res!.headers.get('x-rpx-imgx')).toBeNull()
189 expect(new Uint8Array(await res!.arrayBuffer())).toEqual(png)
190 })
191
192 it('passes through non-image responses untouched', async () => {
193 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/plain.txt?w=32'))
194 expect(res!.headers.get('x-rpx-imgx')).toBeNull()
195 expect(await res!.text()).toBe('hello')
196 })
197
198 it('ignores transform params when imgx is not enabled for the route', async () => {
199 const res = await handlerWith(undefined)(req('http://app.localhost/img.png?w=32'))
200 expect(res!.headers.get('x-rpx-imgx')).toBeNull()
201 expect(new Uint8Array(await res!.arrayBuffer())).toEqual(png)
202 })
203
204 it('serves the original bytes when the image cannot be decoded', async () => {
205 const res = await handlerWith(resolveImgx(true))(req('http://app.localhost/broken.png?w=32'))
206 expect(res!.status).toBe(200)
207 expect(res!.headers.get('x-rpx-imgx')).toBeNull()
208 expect(new Uint8Array(await res!.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3, 4]))
209 })
210
211 it('passes through responses larger than maxInputBytes', async () => {
212 const res = await handlerWith(resolveImgx({ maxInputBytes: 10 }))(req('http://app.localhost/img.png?w=32'))
213 expect(res!.status).toBe(200)
214 expect(res!.headers.get('x-rpx-imgx')).toBeNull()
215 expect(new Uint8Array(await res!.arrayBuffer())).toEqual(png)
216 })
217
218 it('serves repeated transforms from the in-memory cache', async () => {
219 const handler = handlerWith(resolveImgx(true))
220 const first = await handler(req('http://app.localhost/img.png?w=24&h=24&fit=crop'))
221 expect(first!.headers.get('x-rpx-imgx')).toBe('miss')
222 const second = await handler(req('http://app.localhost/img.png?w=24&h=24&fit=crop'))
223 expect(second!.headers.get('x-rpx-imgx')).toBe('hit')
224 expect(new Uint8Array(await second!.arrayBuffer())).toEqual(new Uint8Array(await first!.arrayBuffer()))
225 })
226
227 it('honors per-request quality over the route default', async () => {
228 const handler = handlerWith(resolveImgx(true))
229 const high = await handler(req('http://app.localhost/img.png?fm=jpeg&q=95'))
230 const low = await handler(req('http://app.localhost/img.png?fm=jpeg&q=10'))
231 const highBytes = await high!.arrayBuffer()
232 const lowBytes = await low!.arrayBuffer()
233 expect(lowBytes.byteLength).toBeLessThan(highBytes.byteLength)
234 })
235
236 it('transforms images served from a static route', async () => {
237 const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'rpx-imgx-'))
238 try {
239 await fsp.writeFile(path.join(dir, 'photo.png'), png)
240 const handler = createProxyFetchHandler(() => ({
241 static: resolveStaticRoute(dir, false),
242 imgx: resolveImgx(true),
243 }))
244 const res = await handler(req('http://app.localhost/photo.png?w=32'))
245 expect(res!.status).toBe(200)
246 expect(res!.headers.get('x-rpx-imgx')).toBe('miss')
247 const out = await decode(new Uint8Array(await res!.arrayBuffer()))
248 expect(out.width).toBe(32)
249 }
250 finally {
251 await fsp.rm(dir, { recursive: true, force: true })
252 }
253 })
254})