@drupflare/spool 0.1.0 → 0.2.0

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.
@@ -0,0 +1,222 @@
1
+ import { type LazyOptions, type ResolvedLazyOptions } from './lazy.js';
2
+ import { type ResolvedResponsiveOptions, type ResponsiveOptions } from './responsive.js';
3
+ /** what an {@link ImageEncoder} is asked to produce */
4
+ export type ImageEncodeOptions = {
5
+ format: 'webp';
6
+ /** 1 to 100 */
7
+ quality: number;
8
+ /** the widest the output may be, in pixels; absent means the source width */
9
+ width?: number;
10
+ /** encode without loss, so `quality` has no effect; absent means lossy */
11
+ lossless?: boolean;
12
+ /**
13
+ * the time the encoder may spend, in milliseconds; absent means no limit. It is a hint for an
14
+ * encoder that can trade quality for time, and the proxy stops waiting at this time either way
15
+ */
16
+ budgetMs?: number;
17
+ };
18
+ /** what an {@link ImageEncoder} returns */
19
+ export type ImageEncoded = {
20
+ bytes: Uint8Array;
21
+ };
22
+ /**
23
+ * Re-encodes JPEG or PNG bytes. The encoder never upscales: `width` is a ceiling, and an image
24
+ * narrower than it keeps its size. It throws on input it cannot decode, and the proxy then serves
25
+ * the original bytes.
26
+ */
27
+ export type ImageEncoder = (input: Uint8Array, options: ImageEncodeOptions) => Promise<ImageEncoded>;
28
+ /** the options tinyimg's `transform` takes that {@link tinyimgEncoder} sets */
29
+ export type TinyimgTransformOptions = {
30
+ format: 'webp';
31
+ quality: number;
32
+ width?: number;
33
+ fit?: 'scale-down';
34
+ lossless?: boolean;
35
+ budgetMs?: number;
36
+ };
37
+ /**
38
+ * The part of tinyimg (`@gmitch215/tinyimg`) that {@link tinyimgEncoder} calls: the loaded
39
+ * `module` and the `transform` function, both from the caller's own import of the package. spool
40
+ * imports nothing from tinyimg.
41
+ */
42
+ export type TinyimgBinding<M = unknown> = {
43
+ module: M;
44
+ transform: (module: M, input: Uint8Array, options: TinyimgTransformOptions) => Promise<{
45
+ bytes(): Uint8Array;
46
+ }>;
47
+ };
48
+ /** the oldest tinyimg that turns an EXIF-rotated JPEG upright; 1.1.0 and earlier leave it sideways */
49
+ export declare const TINYIMG_MIN_VERSION: readonly [1, 1, 1];
50
+ /**
51
+ * An {@link ImageEncoder} over tinyimg. It passes `fit: 'scale-down'` when a width is set, which
52
+ * keeps tinyimg from upscaling, passes `lossless` and `budgetMs` when the proxy sets them, and
53
+ * returns the bytes of the result. A module whose `version` is older than
54
+ * {@link TINYIMG_MIN_VERSION} is refused with a `ProtocolError`, since converting an EXIF-rotated
55
+ * JPEG with it would serve the picture sideways. A module that reports no version is accepted.
56
+ */
57
+ export declare function tinyimgEncoder<M>(binding: TinyimgBinding<M>): ImageEncoder;
58
+ /** converted bytes by content hash, quality and width */
59
+ export type ImageCache = {
60
+ get(key: string): Uint8Array | undefined;
61
+ set(key: string, bytes: Uint8Array): void;
62
+ };
63
+ /** an in-memory {@link ImageCache} that drops the least recently used entry past `maxBytes` */
64
+ export declare function memoryImageCache(maxBytes: number): ImageCache;
65
+ /** how a PNG becomes WebP; see `ImageOptions.png` */
66
+ export type PngMode = 'lossy' | 'auto' | 'lossless';
67
+ /** the largest PNG, in bytes, that `png: 'auto'` encodes both ways */
68
+ export declare const PNG_AUTO_BYTES = 200000;
69
+ /** what `spoolProxy({ images })` takes */
70
+ export type ImageOptions = {
71
+ /** converts the bytes; see {@link tinyimgEncoder} */
72
+ encoder: ImageEncoder;
73
+ /** WebP quality, 1 to 100, by the visitor's connection; defaults 80, 65 for `Save-Data: on`, 70 for `ECT` of `slow-2g`, `2g` or `3g` */
74
+ quality?: {
75
+ default?: number;
76
+ saveData?: number;
77
+ slow?: number;
78
+ };
79
+ /** smallest origin file converted, in bytes; default 4096, so icons and sprites stay as they are */
80
+ minBytes?: number;
81
+ /** largest origin file converted, in bytes; default 15,000,000 */
82
+ maxBytes?: number;
83
+ /** `fallback` is the width ceiling for a request that names none; default `maxWidth`, and it wins over `maxWidth` when both are set */
84
+ width?: {
85
+ fallback?: number;
86
+ };
87
+ /**
88
+ * The width ceiling, 1 to 16384, for a request that carries no width hint; default 2560, `false`
89
+ * for none. A `Sec-CH-Width` or a viewport and DPR pair wins over it. An image narrower than the
90
+ * ceiling keeps its size.
91
+ */
92
+ maxWidth?: number | false;
93
+ /**
94
+ * How long the proxy waits for the encoder, in milliseconds; default 10,000, `false` to wait
95
+ * without limit. When the time runs out the visitor gets the origin's bytes, and the encoder is
96
+ * left to finish: a result that arrives late is cached for the next request.
97
+ */
98
+ timeoutMs?: number | false;
99
+ /**
100
+ * How a PNG becomes WebP; default `'lossy'`. `'lossless'` encodes every PNG without loss, and
101
+ * `'auto'` encodes a PNG under 200 KB both ways and serves the smaller (a screenshot or a flat
102
+ * graphic is often smaller lossless, a photograph in a PNG is not). A JPEG is always lossy. The
103
+ * mode is part of the cache key and the ETag of a PNG that is not `'lossy'`.
104
+ */
105
+ png?: PngMode;
106
+ /**
107
+ * Adds a `srcset` of `?spool-w=<width>` variants to same-origin `<img>` tags in HTML, so a
108
+ * browser that sends no `Sec-CH-Width` (Firefox, Safari) still asks for a smaller file; default
109
+ * `false`, no page is touched for it. See `rewriteResponsive`.
110
+ */
111
+ responsive?: ResponsiveOptions | false;
112
+ /**
113
+ * Adds `loading="lazy"` and `decoding="async"` to `<img>` tags in HTML after the first `skip`
114
+ * (default 2), and `loading="lazy"` to `<iframe>` tags with `iframes`; default `false`, no page
115
+ * is touched for it. See `rewriteLazy`.
116
+ */
117
+ lazy?: LazyOptions | false;
118
+ /** add `Accept-CH` to HTML responses so the browser sends the width hints; default true */
119
+ hints?: boolean;
120
+ /** converted bytes by content hash; default an in-memory cache of 64 MiB, `false` for none */
121
+ cache?: ImageCache | false;
122
+ /** the paths converted, tested against the pathname; default `/\.(?:jpe?g|png)$/i` */
123
+ paths?: RegExp;
124
+ };
125
+ /** `ImageOptions` with every default applied and every value checked */
126
+ export type ResolvedImageOptions = {
127
+ encoder: ImageEncoder;
128
+ quality: {
129
+ default: number;
130
+ saveData: number;
131
+ slow: number;
132
+ };
133
+ minBytes: number;
134
+ maxBytes: number;
135
+ /** `fallback` is `width.fallback` when set, else `maxWidth` */
136
+ width: {
137
+ fallback?: number;
138
+ };
139
+ timeoutMs: number | false;
140
+ png: PngMode;
141
+ responsive: ResolvedResponsiveOptions | false;
142
+ lazy: ResolvedLazyOptions | false;
143
+ hints: boolean;
144
+ paths: RegExp;
145
+ };
146
+ /** what the proxy counted since it started; `bytesIn` and `bytesOut` cover converted responses only */
147
+ export type ImageStats = {
148
+ converted: number;
149
+ bytesIn: number;
150
+ bytesOut: number;
151
+ cacheHits: number;
152
+ /** requests that waited for an encode another request had already started */
153
+ coalesced: number;
154
+ /** `<img>` and `<iframe>` tags that got `loading="lazy"` */
155
+ lazied: number;
156
+ /** `<img>` tags that got a `srcset` of `spool-w` variants */
157
+ responsive: number;
158
+ /**
159
+ * Requests and responses left as they were, by the first test that failed: `path`, `accept`,
160
+ * `range`, `authorization`, `status`, `type`, `set-cookie`, `size-min`, `size-max`, `larger`
161
+ * (the encoder's output was not smaller), `failed` (the encoder threw), `timeout` (the encoder
162
+ * ran past `timeoutMs`) and `not-modified` (answered 304 without encoding).
163
+ */
164
+ skipped: Record<string, number>;
165
+ };
166
+ /** the state `spoolProxy` keeps for `images`: checked options, the cache, the running encodes and the counters */
167
+ export type ImageConverter = {
168
+ readonly options: ResolvedImageOptions;
169
+ readonly cache: ImageCache | undefined;
170
+ readonly stats: ImageStats;
171
+ /** encodes in flight by cache key, so identical requests share one encoder call */
172
+ readonly running: Map<string, Promise<Uint8Array>>;
173
+ };
174
+ /** the Vary entries a converted image answers with */
175
+ export declare const IMAGE_VARY: readonly string[];
176
+ /** the client hints an HTML response asks the browser to send on later image requests */
177
+ export declare const IMAGE_HINTS: readonly string[];
178
+ /** applies the defaults to `options` and refuses a value out of range with `ProtocolError('bad-route')` */
179
+ export declare function resolveImageOptions(options: ImageOptions): ResolvedImageOptions;
180
+ /** a converter with the options resolved, an empty cache and zeroed counters */
181
+ export declare function createImageConverter(options: ImageOptions): ImageConverter;
182
+ /**
183
+ * The WebP quality and width ceiling for one request, from its headers. `Save-Data: on` picks
184
+ * `quality.saveData`, else an `ECT` of `slow-2g`, `2g` or `3g` picks `quality.slow`, else
185
+ * `quality.default`. The width is `Sec-CH-Width`, else `Sec-CH-Viewport-Width` times `Sec-CH-DPR`
186
+ * rounded up, else `width.fallback`; a value that is not a positive number of at most 16384 is
187
+ * ignored.
188
+ */
189
+ export declare function imageVariant(headers: Headers, options?: Pick<ImageOptions, 'quality' | 'width'>): {
190
+ quality: number;
191
+ width?: number;
192
+ };
193
+ /**
194
+ * The request-side tests: a `GET` whose path matches `paths`, that accepts `image/webp` and carries
195
+ * no `Range` or `Authorization`. A request that fails one is counted under `path`, `accept`,
196
+ * `range` or `authorization` and `false` comes back; a method other than `GET` is not an image
197
+ * request and is not counted. The proxy forwards a request that passes without its conditional
198
+ * headers, so the origin sends the whole file.
199
+ */
200
+ export declare function imageRequest(converter: ImageConverter, request: Request): boolean;
201
+ /**
202
+ * The query string the origin should see for `url`: with `responsive` set and a pathname that
203
+ * `paths` matches, every `spool-w` parameter is removed, so the origin never sees a parameter
204
+ * only the proxy reads; otherwise `url.search` as it is.
205
+ */
206
+ export declare function originSearch(converter: ImageConverter, url: URL): string;
207
+ /**
208
+ * Answers one origin response to a request that passed {@link imageRequest}: a `200` JPEG or PNG
209
+ * that sets no cookie and is between `minBytes` and `maxBytes` becomes WebP, and anything else
210
+ * comes back as it was. The conversion keeps the origin's `Cache-Control`, merges {@link IMAGE_VARY}
211
+ * into `Vary`, sets a weak `ETag` from the origin bytes, the quality and the width, and answers
212
+ * `304` when the request's `If-None-Match` matches it. `X-Spool-Image` reads
213
+ * `<bytesIn>-><bytesOut>; q=<quality>; w=<width or 0>`. With `responsive`, a listed `spool-w` in the
214
+ * request URL lowers the width to at most that value; an unlisted one is ignored. A PNG follows
215
+ * `png`.
216
+ *
217
+ * The origin is fetched for every request, so a visitor only ever gets the bytes the origin sent
218
+ * that visitor. An encoder that throws, runs past `timeoutMs`, or produces output that is not
219
+ * smaller serves the origin's bytes with a `200`. The response never fails because of the
220
+ * conversion. Simultaneous requests for the same bytes, quality and width share one encoder call.
221
+ */
222
+ export declare function convertImage(converter: ImageConverter, request: Request, upstream: Response): Promise<Response>;
@@ -0,0 +1,413 @@
1
+ import { ProtocolError } from '../protocol/errors.js';
2
+ import { sourceHash } from '../trim/manifest.js';
3
+ import { mergeList, signalsOf } from './headers.js';
4
+ import { resolveLazyOptions } from './lazy.js';
5
+ import { RESPONSIVE_PARAM, resolveResponsiveOptions, takeWidth } from './responsive.js';
6
+ /** the oldest tinyimg that turns an EXIF-rotated JPEG upright; 1.1.0 and earlier leave it sideways */
7
+ export const TINYIMG_MIN_VERSION = [1, 1, 1];
8
+ /** the version text of a module that reports one older than {@link TINYIMG_MIN_VERSION}, else null */
9
+ function tooOld(module) {
10
+ const version = module?.version;
11
+ if (!Array.isArray(version) || version.length !== 3 || !version.every(Number.isInteger)) {
12
+ return null;
13
+ }
14
+ for (const [at, need] of TINYIMG_MIN_VERSION.entries()) {
15
+ const have = version[at];
16
+ if (have !== need)
17
+ return have < need ? version.join('.') : null;
18
+ }
19
+ return null;
20
+ }
21
+ /**
22
+ * An {@link ImageEncoder} over tinyimg. It passes `fit: 'scale-down'` when a width is set, which
23
+ * keeps tinyimg from upscaling, passes `lossless` and `budgetMs` when the proxy sets them, and
24
+ * returns the bytes of the result. A module whose `version` is older than
25
+ * {@link TINYIMG_MIN_VERSION} is refused with a `ProtocolError`, since converting an EXIF-rotated
26
+ * JPEG with it would serve the picture sideways. A module that reports no version is accepted.
27
+ */
28
+ export function tinyimgEncoder(binding) {
29
+ const old = tooOld(binding.module);
30
+ if (old !== null) {
31
+ throw new ProtocolError('bad-route', `tinyimg ${old} leaves an EXIF-rotated JPEG sideways; use ${TINYIMG_MIN_VERSION.join('.')} or later`);
32
+ }
33
+ return async (input, { format, quality, width, lossless, budgetMs }) => {
34
+ const out = await binding.transform(binding.module, input, {
35
+ format,
36
+ quality,
37
+ ...(width === undefined ? {} : { width, fit: 'scale-down' }),
38
+ ...(lossless ? { lossless: true } : {}),
39
+ ...(budgetMs === undefined ? {} : { budgetMs })
40
+ });
41
+ return { bytes: out.bytes() };
42
+ };
43
+ }
44
+ /** an in-memory {@link ImageCache} that drops the least recently used entry past `maxBytes` */
45
+ export function memoryImageCache(maxBytes) {
46
+ if (!Number.isInteger(maxBytes) || maxBytes < 1) {
47
+ throw new ProtocolError('bad-route', 'image cache maxBytes must be a positive integer');
48
+ }
49
+ const entries = new Map();
50
+ let size = 0;
51
+ return {
52
+ get(key) {
53
+ const hit = entries.get(key);
54
+ if (hit) {
55
+ entries.delete(key);
56
+ entries.set(key, hit);
57
+ }
58
+ return hit;
59
+ },
60
+ set(key, bytes) {
61
+ if (bytes.length > maxBytes)
62
+ return;
63
+ const old = entries.get(key);
64
+ if (old)
65
+ size -= old.length;
66
+ entries.delete(key);
67
+ entries.set(key, bytes);
68
+ size += bytes.length;
69
+ for (const [oldest, held] of entries) {
70
+ if (size <= maxBytes)
71
+ break;
72
+ entries.delete(oldest);
73
+ size -= held.length;
74
+ }
75
+ }
76
+ };
77
+ }
78
+ /** the largest PNG, in bytes, that `png: 'auto'` encodes both ways */
79
+ export const PNG_AUTO_BYTES = 200_000;
80
+ /** the Vary entries a converted image answers with */
81
+ export const IMAGE_VARY = [
82
+ 'Accept',
83
+ 'Save-Data',
84
+ 'Sec-CH-Width',
85
+ 'Sec-CH-DPR',
86
+ 'Sec-CH-Viewport-Width',
87
+ 'ECT'
88
+ ];
89
+ /** the client hints an HTML response asks the browser to send on later image requests */
90
+ export const IMAGE_HINTS = [
91
+ 'Sec-CH-DPR',
92
+ 'Sec-CH-Width',
93
+ 'Sec-CH-Viewport-Width',
94
+ 'ECT'
95
+ ];
96
+ const MAX_WIDTH = 16384;
97
+ const DEFAULT_MAX_WIDTH = 2560;
98
+ const DEFAULT_TIMEOUT_MS = 10_000;
99
+ const DEFAULT_CACHE_BYTES = 64 * 1024 * 1024;
100
+ function integerIn(value, low, high, name) {
101
+ if (!Number.isInteger(value) || value < low || value > high) {
102
+ throw new ProtocolError('bad-route', `images ${name} must be an integer from ${low} to ${high}`);
103
+ }
104
+ return value;
105
+ }
106
+ /** applies the defaults to `options` and refuses a value out of range with `ProtocolError('bad-route')` */
107
+ export function resolveImageOptions(options) {
108
+ const quality = {
109
+ default: integerIn(options.quality?.default ?? 80, 1, 100, 'quality.default'),
110
+ saveData: integerIn(options.quality?.saveData ?? 65, 1, 100, 'quality.saveData'),
111
+ slow: integerIn(options.quality?.slow ?? 70, 1, 100, 'quality.slow')
112
+ };
113
+ const minBytes = integerIn(options.minBytes ?? 4096, 0, Number.MAX_SAFE_INTEGER, 'minBytes');
114
+ const maxBytes = integerIn(options.maxBytes ?? 15_000_000, 1, Number.MAX_SAFE_INTEGER, 'maxBytes');
115
+ if (minBytes > maxBytes) {
116
+ throw new ProtocolError('bad-route', 'images minBytes must not exceed maxBytes');
117
+ }
118
+ const fallback = options.width?.fallback;
119
+ const ceiling = options.maxWidth === undefined ? DEFAULT_MAX_WIDTH : options.maxWidth;
120
+ const checked = ceiling === false ? false : integerIn(ceiling, 1, MAX_WIDTH, 'maxWidth');
121
+ const timeout = options.timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : options.timeoutMs;
122
+ const png = options.png ?? 'lossy';
123
+ if (png !== 'lossy' && png !== 'auto' && png !== 'lossless') {
124
+ throw new ProtocolError('bad-route', "images png must be 'lossy', 'auto' or 'lossless'");
125
+ }
126
+ return {
127
+ encoder: options.encoder,
128
+ quality,
129
+ minBytes,
130
+ maxBytes,
131
+ width: fallback !== undefined
132
+ ? { fallback: integerIn(fallback, 1, MAX_WIDTH, 'width.fallback') }
133
+ : checked === false
134
+ ? {}
135
+ : { fallback: checked },
136
+ timeoutMs: timeout === false ? false : integerIn(timeout, 1, Number.MAX_SAFE_INTEGER, 'timeoutMs'),
137
+ png,
138
+ responsive: options.responsive ? resolveResponsiveOptions(options.responsive) : false,
139
+ lazy: options.lazy ? resolveLazyOptions(options.lazy) : false,
140
+ hints: options.hints !== false,
141
+ paths: options.paths ?? /\.(?:jpe?g|png)$/i
142
+ };
143
+ }
144
+ /** a converter with the options resolved, an empty cache and zeroed counters */
145
+ export function createImageConverter(options) {
146
+ const resolved = resolveImageOptions(options);
147
+ return {
148
+ options: resolved,
149
+ cache: options.cache === false
150
+ ? undefined
151
+ : (options.cache ?? memoryImageCache(DEFAULT_CACHE_BYTES)),
152
+ stats: {
153
+ converted: 0,
154
+ bytesIn: 0,
155
+ bytesOut: 0,
156
+ cacheHits: 0,
157
+ coalesced: 0,
158
+ lazied: 0,
159
+ responsive: 0,
160
+ skipped: {}
161
+ },
162
+ running: new Map()
163
+ };
164
+ }
165
+ function positive(value) {
166
+ if (value === null || !/^\s*\d+\s*$/.test(value))
167
+ return null;
168
+ const n = Number(value);
169
+ return n > 0 && n <= MAX_WIDTH ? n : null;
170
+ }
171
+ /**
172
+ * The WebP quality and width ceiling for one request, from its headers. `Save-Data: on` picks
173
+ * `quality.saveData`, else an `ECT` of `slow-2g`, `2g` or `3g` picks `quality.slow`, else
174
+ * `quality.default`. The width is `Sec-CH-Width`, else `Sec-CH-Viewport-Width` times `Sec-CH-DPR`
175
+ * rounded up, else `width.fallback`; a value that is not a positive number of at most 16384 is
176
+ * ignored.
177
+ */
178
+ export function imageVariant(headers, options = {}) {
179
+ const signals = signalsOf(headers);
180
+ const quality = signals.saveData
181
+ ? (options.quality?.saveData ?? 65)
182
+ : signals.slow
183
+ ? (options.quality?.slow ?? 70)
184
+ : (options.quality?.default ?? 80);
185
+ let width = positive(headers.get('sec-ch-width'));
186
+ if (width === null) {
187
+ const viewport = positive(headers.get('sec-ch-viewport-width'));
188
+ const ratio = Number(headers.get('sec-ch-dpr'));
189
+ if (viewport !== null && Number.isFinite(ratio) && ratio > 0) {
190
+ const scaled = Math.ceil(viewport * ratio);
191
+ if (scaled <= MAX_WIDTH)
192
+ width = scaled;
193
+ }
194
+ }
195
+ width ??= options.width?.fallback ?? null;
196
+ return width === null ? { quality } : { quality, width };
197
+ }
198
+ function skip(converter, why) {
199
+ const { skipped } = converter.stats;
200
+ skipped[why] = (skipped[why] ?? 0) + 1;
201
+ }
202
+ /**
203
+ * The request-side tests: a `GET` whose path matches `paths`, that accepts `image/webp` and carries
204
+ * no `Range` or `Authorization`. A request that fails one is counted under `path`, `accept`,
205
+ * `range` or `authorization` and `false` comes back; a method other than `GET` is not an image
206
+ * request and is not counted. The proxy forwards a request that passes without its conditional
207
+ * headers, so the origin sends the whole file.
208
+ */
209
+ export function imageRequest(converter, request) {
210
+ if (request.method !== 'GET')
211
+ return false;
212
+ const { paths } = converter.options;
213
+ paths.lastIndex = 0;
214
+ if (!paths.test(new URL(request.url).pathname))
215
+ return skipBecause(converter, 'path');
216
+ if (!(request.headers.get('accept') ?? '').toLowerCase().includes('image/webp')) {
217
+ return skipBecause(converter, 'accept');
218
+ }
219
+ if (request.headers.has('range'))
220
+ return skipBecause(converter, 'range');
221
+ if (request.headers.has('authorization'))
222
+ return skipBecause(converter, 'authorization');
223
+ return true;
224
+ }
225
+ /**
226
+ * The query string the origin should see for `url`: with `responsive` set and a pathname that
227
+ * `paths` matches, every `spool-w` parameter is removed, so the origin never sees a parameter
228
+ * only the proxy reads; otherwise `url.search` as it is.
229
+ */
230
+ export function originSearch(converter, url) {
231
+ const { responsive, paths } = converter.options;
232
+ if (!responsive || !url.search.includes(RESPONSIVE_PARAM))
233
+ return url.search;
234
+ paths.lastIndex = 0;
235
+ return paths.test(url.pathname) ? takeWidth(url.search, responsive.widths).search : url.search;
236
+ }
237
+ function skipBecause(converter, why) {
238
+ skip(converter, why);
239
+ return false;
240
+ }
241
+ function magicOf(bytes) {
242
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
243
+ return 'image/jpeg';
244
+ const png = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
245
+ return png.every((byte, at) => bytes[at] === byte) ? 'image/png' : null;
246
+ }
247
+ function hex(hash) {
248
+ return [...atob(hash.slice('sha256-'.length)).slice(0, 8)]
249
+ .map((char) => char.charCodeAt(0).toString(16).padStart(2, '0'))
250
+ .join('');
251
+ }
252
+ function matches(header, etag) {
253
+ if (header === null)
254
+ return false;
255
+ const opaque = etag.slice(2);
256
+ return header
257
+ .split(',')
258
+ .map((part) => part.trim())
259
+ .some((part) => part === '*' || part.replace(/^W\//, '') === opaque);
260
+ }
261
+ /**
262
+ * The encoded bytes for `key`, or `'failed'` when the encoder threw or returned nothing, or
263
+ * `'timeout'` when it ran past `timeoutMs`. A request for a key that is already encoding waits for
264
+ * that encode instead of starting another. The encode caches its own result when it finishes, so
265
+ * one that outlives its waiters still serves the next request.
266
+ */
267
+ async function encode(converter, key, bytes, quality, width, mode) {
268
+ const { options, stats, cache, running } = converter;
269
+ let task = running.get(key);
270
+ if (task) {
271
+ stats.coalesced++;
272
+ }
273
+ else {
274
+ const budget = options.timeoutMs === false ? {} : { budgetMs: options.timeoutMs };
275
+ const run = async (lossless) => (await options.encoder(bytes, {
276
+ format: 'webp',
277
+ quality,
278
+ ...(width === undefined ? {} : { width }),
279
+ ...(lossless ? { lossless: true } : {}),
280
+ ...budget
281
+ })).bytes;
282
+ const started = (async () => {
283
+ let out;
284
+ if (mode === 'auto') {
285
+ // a failed arm loses to the other; both failing fails the encode
286
+ const arms = await Promise.allSettled([run(false), run(true)]);
287
+ const made = arms.flatMap((arm) => arm.status === 'fulfilled' && arm.value.length > 0 ? [arm.value] : []);
288
+ if (made.length === 0)
289
+ throw new Error('the encoder returned no bytes');
290
+ out = made.reduce((best, next) => (next.length < best.length ? next : best));
291
+ }
292
+ else {
293
+ out = await run(mode === 'lossless');
294
+ if (out.length === 0)
295
+ throw new Error('the encoder returned no bytes');
296
+ }
297
+ cache?.set(key, out);
298
+ return out;
299
+ })();
300
+ task = started;
301
+ running.set(key, started);
302
+ const clear = () => {
303
+ if (running.get(key) === started)
304
+ running.delete(key);
305
+ };
306
+ started.then(clear, clear);
307
+ }
308
+ const limit = options.timeoutMs;
309
+ if (limit === false) {
310
+ return task.catch(() => 'failed');
311
+ }
312
+ let timer;
313
+ const expired = new Promise((resolve) => {
314
+ timer = setTimeout(() => resolve('timeout'), limit);
315
+ });
316
+ try {
317
+ return await Promise.race([task, expired]);
318
+ }
319
+ catch {
320
+ return 'failed';
321
+ }
322
+ finally {
323
+ if (timer !== undefined)
324
+ clearTimeout(timer);
325
+ }
326
+ }
327
+ /**
328
+ * Answers one origin response to a request that passed {@link imageRequest}: a `200` JPEG or PNG
329
+ * that sets no cookie and is between `minBytes` and `maxBytes` becomes WebP, and anything else
330
+ * comes back as it was. The conversion keeps the origin's `Cache-Control`, merges {@link IMAGE_VARY}
331
+ * into `Vary`, sets a weak `ETag` from the origin bytes, the quality and the width, and answers
332
+ * `304` when the request's `If-None-Match` matches it. `X-Spool-Image` reads
333
+ * `<bytesIn>-><bytesOut>; q=<quality>; w=<width or 0>`. With `responsive`, a listed `spool-w` in the
334
+ * request URL lowers the width to at most that value; an unlisted one is ignored. A PNG follows
335
+ * `png`.
336
+ *
337
+ * The origin is fetched for every request, so a visitor only ever gets the bytes the origin sent
338
+ * that visitor. An encoder that throws, runs past `timeoutMs`, or produces output that is not
339
+ * smaller serves the origin's bytes with a `200`. The response never fails because of the
340
+ * conversion. Simultaneous requests for the same bytes, quality and width share one encoder call.
341
+ */
342
+ export async function convertImage(converter, request, upstream) {
343
+ const { options, stats, cache } = converter;
344
+ if (upstream.status !== 200)
345
+ return skipWith(converter, 'status', upstream);
346
+ const type = (upstream.headers.get('content-type') ?? '').split(';')[0]?.trim().toLowerCase();
347
+ if (type !== 'image/jpeg' && type !== 'image/png')
348
+ return skipWith(converter, 'type', upstream);
349
+ if (upstream.headers.getSetCookie().length > 0)
350
+ return skipWith(converter, 'set-cookie', upstream);
351
+ const declared = upstream.headers.get('content-length');
352
+ if (declared !== null && Number(declared) > options.maxBytes) {
353
+ return skipWith(converter, 'size-max', upstream);
354
+ }
355
+ const bytes = new Uint8Array(await upstream.arrayBuffer());
356
+ const original = () => new Response(bytes, {
357
+ status: upstream.status,
358
+ statusText: upstream.statusText,
359
+ headers: upstream.headers
360
+ });
361
+ if (magicOf(bytes) !== type)
362
+ return skipWith(converter, 'type', original());
363
+ if (bytes.length < options.minBytes)
364
+ return skipWith(converter, 'size-min', original());
365
+ if (bytes.length > options.maxBytes)
366
+ return skipWith(converter, 'size-max', original());
367
+ const variant = imageVariant(request.headers, options);
368
+ const { quality } = variant;
369
+ let { width } = variant;
370
+ if (options.responsive) {
371
+ const asked = takeWidth(new URL(request.url).search, options.responsive.widths).width;
372
+ if (asked !== undefined)
373
+ width = width === undefined ? asked : Math.min(width, asked);
374
+ }
375
+ // only a PNG has a mode, and `auto` stays lossy above the size it encodes both ways
376
+ const mode = type === 'image/png' && (options.png !== 'auto' || bytes.length < PNG_AUTO_BYTES)
377
+ ? options.png
378
+ : 'lossy';
379
+ const hash = await sourceHash(bytes);
380
+ const etag = `W/"${hex(hash)}-${quality}-${width ?? 0}${mode === 'lossy' ? '' : `-${mode}`}"`;
381
+ const headers = new Headers(upstream.headers);
382
+ headers.set('content-type', 'image/webp');
383
+ headers.delete('content-length');
384
+ headers.delete('accept-ranges');
385
+ mergeList(headers, 'vary', IMAGE_VARY);
386
+ headers.set('etag', etag);
387
+ if (matches(request.headers.get('if-none-match'), etag)) {
388
+ skip(converter, 'not-modified');
389
+ return new Response(null, { status: 304, headers });
390
+ }
391
+ const key = `${hash}|${quality}|${width ?? 0}${mode === 'lossy' ? '' : `|${mode}`}`;
392
+ let out = cache?.get(key);
393
+ if (out) {
394
+ stats.cacheHits++;
395
+ }
396
+ else {
397
+ const result = await encode(converter, key, bytes, quality, width, mode);
398
+ if (typeof result === 'string')
399
+ return skipWith(converter, result, original());
400
+ out = result;
401
+ }
402
+ if (out.length >= bytes.length)
403
+ return skipWith(converter, 'larger', original());
404
+ headers.set('x-spool-image', `${bytes.length}->${out.length}; q=${quality}; w=${width ?? 0}`);
405
+ stats.converted++;
406
+ stats.bytesIn += bytes.length;
407
+ stats.bytesOut += out.length;
408
+ return new Response(out, { status: 200, statusText: upstream.statusText, headers });
409
+ }
410
+ function skipWith(converter, why, response) {
411
+ skip(converter, why);
412
+ return response;
413
+ }
@@ -0,0 +1,6 @@
1
+ export * from './embeds.js';
2
+ export { signalsOf, type MediaSignals } from './headers.js';
3
+ export * from './image.js';
4
+ export * from './lazy.js';
5
+ export * from './responsive.js';
6
+ export * from './video.js';
@@ -0,0 +1,6 @@
1
+ export * from './embeds.js';
2
+ export { signalsOf } from './headers.js';
3
+ export * from './image.js';
4
+ export * from './lazy.js';
5
+ export * from './responsive.js';
6
+ export * from './video.js';
@@ -0,0 +1,26 @@
1
+ /**
2
+ * What `images.lazy` does to `<img>` and `<iframe>` start tags. `skip` is how many `<img>` tags at
3
+ * the top of the page keep loading at once, since the first images are the likeliest to be in the
4
+ * first viewport; default 2. `iframes` adds `loading="lazy"` to `<iframe>` tags too; default false.
5
+ */
6
+ export type LazyOptions = {
7
+ skip?: number;
8
+ iframes?: boolean;
9
+ };
10
+ /** `LazyOptions` with every default applied */
11
+ export type ResolvedLazyOptions = Required<LazyOptions>;
12
+ /** applies the defaults to `options` and refuses a `skip` that is not a whole number of 0 or more */
13
+ export declare function resolveLazyOptions(options?: LazyOptions): ResolvedLazyOptions;
14
+ /**
15
+ * Adds `loading="lazy"` and `decoding="async"` to the `<img>` tags of `html` after the first
16
+ * `skip`, and `loading="lazy"` to `<iframe>` tags with `iframes`, and says how many tags changed.
17
+ * Tags inside `<head>`, `<noscript>` or an HTML comment are neither counted nor edited. A tag that
18
+ * has `loading`, `fetchpriority`, `data-src`, `data-srcset` or a `data-lazy*` attribute, that sits
19
+ * inside a `<header>`, or whose `src` a `<link rel="preload" as="image">` names, is counted toward
20
+ * `skip` and left alone. A tag that already has `decoding` keeps it. Everything outside the edited
21
+ * start tags stays byte for byte, and the edits are ASCII.
22
+ */
23
+ export declare function rewriteLazy(html: string, options?: LazyOptions): {
24
+ html: string;
25
+ rewritten: number;
26
+ };