@drupflare/spool 0.0.0-stage → 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.
Files changed (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1749 -2
  3. package/dist/cdn/client.js +1 -0
  4. package/dist/cdn/location.d.ts +11 -0
  5. package/dist/cdn/location.js +15 -0
  6. package/dist/cdn/manifest.json +16 -0
  7. package/dist/cdn/spool-sw.js +1 -0
  8. package/dist/client/entry.d.ts +1 -0
  9. package/dist/client/entry.js +25 -0
  10. package/dist/client/index.d.ts +3 -0
  11. package/dist/client/index.js +2 -0
  12. package/dist/client/lifecycle.d.ts +10 -0
  13. package/dist/client/lifecycle.js +10 -0
  14. package/dist/client/loads.d.ts +16 -0
  15. package/dist/client/loads.js +41 -0
  16. package/dist/client/register.d.ts +34 -0
  17. package/dist/client/register.js +58 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +2 -0
  20. package/dist/media/embeds.d.ts +59 -0
  21. package/dist/media/embeds.js +120 -0
  22. package/dist/media/headers.d.ts +13 -0
  23. package/dist/media/headers.js +44 -0
  24. package/dist/media/html.d.ts +27 -0
  25. package/dist/media/html.js +93 -0
  26. package/dist/media/image.d.ts +222 -0
  27. package/dist/media/image.js +413 -0
  28. package/dist/media/index.d.ts +6 -0
  29. package/dist/media/index.js +6 -0
  30. package/dist/media/lazy.d.ts +26 -0
  31. package/dist/media/lazy.js +74 -0
  32. package/dist/media/responsive.d.ts +45 -0
  33. package/dist/media/responsive.js +98 -0
  34. package/dist/media/video.d.ts +30 -0
  35. package/dist/media/video.js +75 -0
  36. package/dist/node/listener.d.ts +19 -0
  37. package/dist/node/listener.js +76 -0
  38. package/dist/protocol/artifact.d.ts +54 -0
  39. package/dist/protocol/artifact.js +79 -0
  40. package/dist/protocol/assembly.d.ts +34 -0
  41. package/dist/protocol/assembly.js +72 -0
  42. package/dist/protocol/beacon.d.ts +59 -0
  43. package/dist/protocol/beacon.js +86 -0
  44. package/dist/protocol/collector.d.ts +41 -0
  45. package/dist/protocol/collector.js +84 -0
  46. package/dist/protocol/config.d.ts +89 -0
  47. package/dist/protocol/config.js +13 -0
  48. package/dist/protocol/envelope.d.ts +47 -0
  49. package/dist/protocol/envelope.js +162 -0
  50. package/dist/protocol/errors.d.ts +7 -0
  51. package/dist/protocol/errors.js +9 -0
  52. package/dist/protocol/graph.d.ts +81 -0
  53. package/dist/protocol/graph.js +201 -0
  54. package/dist/protocol/index.d.ts +19 -0
  55. package/dist/protocol/index.js +19 -0
  56. package/dist/protocol/manifest.d.ts +29 -0
  57. package/dist/protocol/manifest.js +94 -0
  58. package/dist/protocol/normalise.d.ts +20 -0
  59. package/dist/protocol/normalise.js +29 -0
  60. package/dist/protocol/pattern.d.ts +12 -0
  61. package/dist/protocol/pattern.js +82 -0
  62. package/dist/protocol/provision.d.ts +100 -0
  63. package/dist/protocol/provision.js +105 -0
  64. package/dist/protocol/route.d.ts +179 -0
  65. package/dist/protocol/route.js +135 -0
  66. package/dist/protocol/sync.d.ts +31 -0
  67. package/dist/protocol/sync.js +87 -0
  68. package/dist/protocol/tag.d.ts +12 -0
  69. package/dist/protocol/tag.js +26 -0
  70. package/dist/protocol/template/compile.d.ts +35 -0
  71. package/dist/protocol/template/compile.js +82 -0
  72. package/dist/protocol/template/interpret.d.ts +9 -0
  73. package/dist/protocol/template/interpret.js +82 -0
  74. package/dist/protocol/vector.d.ts +32 -0
  75. package/dist/protocol/vector.js +56 -0
  76. package/dist/protocol/view.d.ts +110 -0
  77. package/dist/protocol/view.js +201 -0
  78. package/dist/proxy/dictionary.d.ts +58 -0
  79. package/dist/proxy/dictionary.js +197 -0
  80. package/dist/proxy/eligible.d.ts +45 -0
  81. package/dist/proxy/eligible.js +96 -0
  82. package/dist/proxy/index.d.ts +5 -0
  83. package/dist/proxy/index.js +5 -0
  84. package/dist/proxy/proxy.d.ts +133 -0
  85. package/dist/proxy/proxy.js +507 -0
  86. package/dist/proxy/purge.d.ts +10 -0
  87. package/dist/proxy/purge.js +66 -0
  88. package/dist/proxy/tags.d.ts +8 -0
  89. package/dist/proxy/tags.js +36 -0
  90. package/dist/report/derive.d.ts +223 -0
  91. package/dist/report/derive.js +494 -0
  92. package/dist/report/economics.d.ts +14 -0
  93. package/dist/report/economics.js +24 -0
  94. package/dist/report/index.d.ts +9 -0
  95. package/dist/report/index.js +9 -0
  96. package/dist/report/inputs.d.ts +141 -0
  97. package/dist/report/inputs.js +216 -0
  98. package/dist/report/ledger.d.ts +169 -0
  99. package/dist/report/ledger.js +278 -0
  100. package/dist/report/measurement.d.ts +48 -0
  101. package/dist/report/measurement.js +117 -0
  102. package/dist/report/model.d.ts +42 -0
  103. package/dist/report/model.js +74 -0
  104. package/dist/report/thirdparty.d.ts +62 -0
  105. package/dist/report/thirdparty.js +107 -0
  106. package/dist/report/traffic.d.ts +140 -0
  107. package/dist/report/traffic.js +228 -0
  108. package/dist/report/trim.d.ts +81 -0
  109. package/dist/report/trim.js +105 -0
  110. package/dist/server/beacon.d.ts +20 -0
  111. package/dist/server/beacon.js +47 -0
  112. package/dist/server/embedded.d.ts +6 -0
  113. package/dist/server/embedded.js +6 -0
  114. package/dist/server/ga4.d.ts +70 -0
  115. package/dist/server/ga4.js +165 -0
  116. package/dist/server/identity.d.ts +12 -0
  117. package/dist/server/identity.js +17 -0
  118. package/dist/server/index.d.ts +7 -0
  119. package/dist/server/index.js +7 -0
  120. package/dist/server/sink.d.ts +56 -0
  121. package/dist/server/sink.js +133 -0
  122. package/dist/server/size.d.ts +7 -0
  123. package/dist/server/size.js +18 -0
  124. package/dist/server/spool.d.ts +97 -0
  125. package/dist/server/spool.js +463 -0
  126. package/dist/server/stub.d.ts +9 -0
  127. package/dist/server/stub.js +19 -0
  128. package/dist/server/sync.d.ts +12 -0
  129. package/dist/server/sync.js +48 -0
  130. package/dist/server/work.d.ts +22 -0
  131. package/dist/server/work.js +30 -0
  132. package/dist/stores/durable-object.d.ts +19 -0
  133. package/dist/stores/durable-object.js +53 -0
  134. package/dist/stores/index.d.ts +2 -0
  135. package/dist/stores/index.js +2 -0
  136. package/dist/stores/memory.d.ts +4 -0
  137. package/dist/stores/memory.js +10 -0
  138. package/dist/stores/version-store.d.ts +11 -0
  139. package/dist/stores/version-store.js +1 -0
  140. package/dist/sw/analytics.d.ts +81 -0
  141. package/dist/sw/analytics.js +275 -0
  142. package/dist/sw/collect.d.ts +8 -0
  143. package/dist/sw/collect.js +33 -0
  144. package/dist/sw/core.d.ts +1 -0
  145. package/dist/sw/core.js +3 -0
  146. package/dist/sw/freshness.d.ts +15 -0
  147. package/dist/sw/freshness.js +20 -0
  148. package/dist/sw/graph/index.d.ts +67 -0
  149. package/dist/sw/graph/index.js +170 -0
  150. package/dist/sw/graph/invalidate.d.ts +23 -0
  151. package/dist/sw/graph/invalidate.js +109 -0
  152. package/dist/sw/graph/projections.d.ts +7 -0
  153. package/dist/sw/graph/projections.js +9 -0
  154. package/dist/sw/graph/records.d.ts +7 -0
  155. package/dist/sw/graph/records.js +9 -0
  156. package/dist/sw/graph/store.d.ts +32 -0
  157. package/dist/sw/graph/store.js +52 -0
  158. package/dist/sw/idb.d.ts +8 -0
  159. package/dist/sw/idb.js +117 -0
  160. package/dist/sw/index.d.ts +2 -0
  161. package/dist/sw/index.js +1 -0
  162. package/dist/sw/partition.d.ts +21 -0
  163. package/dist/sw/partition.js +137 -0
  164. package/dist/sw/policy.d.ts +8 -0
  165. package/dist/sw/policy.js +24 -0
  166. package/dist/sw/provision.d.ts +39 -0
  167. package/dist/sw/provision.js +61 -0
  168. package/dist/sw/render.d.ts +21 -0
  169. package/dist/sw/render.js +53 -0
  170. package/dist/sw/replica.d.ts +77 -0
  171. package/dist/sw/replica.js +299 -0
  172. package/dist/sw/router.d.ts +42 -0
  173. package/dist/sw/router.js +48 -0
  174. package/dist/sw/routing.d.ts +23 -0
  175. package/dist/sw/routing.js +48 -0
  176. package/dist/sw/runtime.d.ts +112 -0
  177. package/dist/sw/runtime.js +1070 -0
  178. package/dist/sw/scheduler.d.ts +83 -0
  179. package/dist/sw/scheduler.js +149 -0
  180. package/dist/sw/seal.d.ts +37 -0
  181. package/dist/sw/seal.js +183 -0
  182. package/dist/sw/serve.d.ts +15 -0
  183. package/dist/sw/serve.js +63 -0
  184. package/dist/sw/shadow.d.ts +16 -0
  185. package/dist/sw/shadow.js +27 -0
  186. package/dist/sw/static.d.ts +17 -0
  187. package/dist/sw/static.js +81 -0
  188. package/dist/sw/storage.d.ts +64 -0
  189. package/dist/sw/storage.js +34 -0
  190. package/dist/sw/thirdparty.d.ts +17 -0
  191. package/dist/sw/thirdparty.js +36 -0
  192. package/dist/trim/css.d.ts +38 -0
  193. package/dist/trim/css.js +328 -0
  194. package/dist/trim/index.d.ts +3 -0
  195. package/dist/trim/index.js +3 -0
  196. package/dist/trim/manifest.d.ts +67 -0
  197. package/dist/trim/manifest.js +134 -0
  198. package/dist/trim/tokens.d.ts +47 -0
  199. package/dist/trim/tokens.js +142 -0
  200. package/dist/version.d.ts +2 -0
  201. package/dist/version.js +3 -0
  202. package/package.json +150 -5
@@ -0,0 +1,44 @@
1
+ /** the connection signals in a request's `Save-Data` and `ECT` headers */
2
+ export function signalsOf(headers) {
3
+ const ect = (headers.get('ect') ?? '').trim().toLowerCase();
4
+ return {
5
+ saveData: (headers.get('save-data') ?? '').trim().toLowerCase() === 'on',
6
+ slow: ect === 'slow-2g' || ect === '2g' || ect === '3g'
7
+ };
8
+ }
9
+ /** adds each name to a comma-separated header, skipping any it already lists in any case */
10
+ export function mergeList(headers, name, additions) {
11
+ const current = headers.get(name);
12
+ const have = (current ?? '')
13
+ .split(',')
14
+ .map((part) => part.trim())
15
+ .filter((part) => part !== '');
16
+ if (have.includes('*'))
17
+ return;
18
+ const lower = new Set(have.map((part) => part.toLowerCase()));
19
+ const added = additions.filter((part) => !lower.has(part.toLowerCase()));
20
+ if (added.length === 0)
21
+ return;
22
+ headers.set(name, [...have, ...added].join(', '));
23
+ }
24
+ /** makes `Cache-Control` private: `public` becomes `private`, and a header with none gets `private, max-age=0` */
25
+ export function makePrivate(headers) {
26
+ const value = headers.get('cache-control');
27
+ if (!value) {
28
+ headers.set('cache-control', 'private, max-age=0');
29
+ return;
30
+ }
31
+ const parts = value
32
+ .split(',')
33
+ .map((part) => part.trim())
34
+ .filter((part) => part !== '');
35
+ const names = parts.map((part) => (part.split('=')[0] ?? '').trim().toLowerCase());
36
+ if (names.includes('private'))
37
+ return;
38
+ const at = names.indexOf('public');
39
+ if (at >= 0)
40
+ parts[at] = 'private';
41
+ else
42
+ parts.unshift('private');
43
+ headers.set('cache-control', parts.join(', '));
44
+ }
@@ -0,0 +1,27 @@
1
+ import { type Attribute, type Tag } from '../trim/tokens.js';
2
+ /** one replacement in an HTML string: the text from `at` to `to` becomes `text` */
3
+ export type Edit = {
4
+ at: number;
5
+ to: number;
6
+ text: string;
7
+ };
8
+ /** the `[start, end)` ranges of the HTML comments in `html`; a comment that never closes runs to the end */
9
+ export declare function commentRanges(html: string): Array<[number, number]>;
10
+ /** the ranges of every `<noscript>` element, from its start tag to its end tag or the end of the HTML */
11
+ export declare function noscriptRanges(html: string, tags: readonly Tag[]): Array<[number, number]>;
12
+ /** the ranges of the outermost elements called `name`, from the start tag to the matching end tag or the end of the HTML */
13
+ export declare function elementRanges(html: string, tags: readonly Tag[], name: string): Array<[number, number]>;
14
+ /** the range of `<head>`, from its start tag to the first `<body>` or `</head>`, or null without one */
15
+ export declare function headRange(html: string, tags: readonly Tag[]): [number, number] | null;
16
+ /** whether `at` falls inside any of `ranges` */
17
+ export declare const within: (ranges: ReadonlyArray<[number, number]>, at: number) => boolean;
18
+ /** the first attribute of `tag` called `name`, whose name is already lowercase */
19
+ export declare const find: (tag: Tag, name: string) => Attribute | undefined;
20
+ /** the edit that gives the attribute `a` the value `value`, keeping its quote style */
21
+ export declare function setValue(html: string, a: Attribute, value: string): Edit;
22
+ /** the edit that adds `attributes` (such as `preload="none"`) to the end of `tag`, before a closing slash */
23
+ export declare function appendAttributes(html: string, tag: Tag, attributes: readonly string[]): Edit;
24
+ /** `html` with `edits` applied; they may arrive in any order and must not overlap */
25
+ export declare function applyEdits(html: string, edits: readonly Edit[]): string;
26
+ /** the start tags of `html` that are named `name`, close with `>` and sit outside comments */
27
+ export declare function tagsNamed(html: string, name: string, tags?: readonly Tag[]): Tag[];
@@ -0,0 +1,93 @@
1
+ import { tagsOf } from '../trim/tokens.js';
2
+ /** the `[start, end)` ranges of the HTML comments in `html`; a comment that never closes runs to the end */
3
+ export function commentRanges(html) {
4
+ const ranges = [];
5
+ let at = html.indexOf('<!--');
6
+ while (at >= 0) {
7
+ const close = html.indexOf('-->', at + 4);
8
+ const end = close < 0 ? html.length : close + 3;
9
+ ranges.push([at, end]);
10
+ at = html.indexOf('<!--', end);
11
+ }
12
+ return ranges;
13
+ }
14
+ /** the ranges of every `<noscript>` element, from its start tag to its end tag or the end of the HTML */
15
+ export function noscriptRanges(html, tags) {
16
+ const ranges = [];
17
+ for (const tag of tags) {
18
+ if (tag.name !== 'noscript')
19
+ continue;
20
+ const after = html.slice(tag.end).search(/<\/noscript\s*>/i);
21
+ ranges.push([tag.start, after < 0 ? html.length : tag.end + after]);
22
+ }
23
+ return ranges;
24
+ }
25
+ /** the ranges of the outermost elements called `name`, from the start tag to the matching end tag or the end of the HTML */
26
+ export function elementRanges(html, tags, name) {
27
+ const ranges = [];
28
+ let open = -1;
29
+ for (const tag of tags) {
30
+ if (tag.name !== name || tag.start < open)
31
+ continue;
32
+ const pattern = new RegExp(`<(/?)${name}\\b[^>]*>`, 'gi');
33
+ pattern.lastIndex = tag.end;
34
+ let depth = 1;
35
+ let end = html.length;
36
+ for (let hit = pattern.exec(html); hit; hit = pattern.exec(html)) {
37
+ depth += hit[1] ? -1 : 1;
38
+ if (depth === 0) {
39
+ end = hit.index + hit[0].length;
40
+ break;
41
+ }
42
+ }
43
+ ranges.push([tag.start, end]);
44
+ open = end;
45
+ }
46
+ return ranges;
47
+ }
48
+ /** the range of `<head>`, from its start tag to the first `<body>` or `</head>`, or null without one */
49
+ export function headRange(html, tags) {
50
+ const head = tags.find((tag) => tag.name === 'head');
51
+ if (!head)
52
+ return null;
53
+ const rest = html.slice(head.end);
54
+ const stop = rest.search(/<\/head\s*>|<body[\s>]/i);
55
+ return [head.start, stop < 0 ? html.length : head.end + stop];
56
+ }
57
+ /** whether `at` falls inside any of `ranges` */
58
+ export const within = (ranges, at) => ranges.some(([start, end]) => at >= start && at < end);
59
+ /** the first attribute of `tag` called `name`, whose name is already lowercase */
60
+ export const find = (tag, name) => tag.attributes.find((a) => a.name === name);
61
+ /** the edit that gives the attribute `a` the value `value`, keeping its quote style */
62
+ export function setValue(html, a, value) {
63
+ const raw = html.slice(a.start, a.end);
64
+ const prefix = /^[^=\s]+\s*=\s*/.exec(raw);
65
+ if (!prefix)
66
+ return { at: a.end, to: a.end, text: `="${value}"` };
67
+ const quote = raw[prefix[0].length];
68
+ const q = quote === '"' || quote === "'" ? quote : '';
69
+ return { at: a.start + prefix[0].length, to: a.end, text: `${q}${value}${q}` };
70
+ }
71
+ /** the edit that adds `attributes` (such as `preload="none"`) to the end of `tag`, before a closing slash */
72
+ export function appendAttributes(html, tag, attributes) {
73
+ const floor = tag.attributes.at(-1)?.end ?? tag.start + 1 + tag.name.length;
74
+ const slash = html[tag.end - 1] === '/' && floor < tag.end;
75
+ const at = slash ? tag.end - 1 : tag.end;
76
+ const gap = /\s/.test(html[at - 1]) ? '' : ' ';
77
+ return { at, to: at, text: `${gap}${attributes.join(' ')}` };
78
+ }
79
+ /** `html` with `edits` applied; they may arrive in any order and must not overlap */
80
+ export function applyEdits(html, edits) {
81
+ let out = '';
82
+ let from = 0;
83
+ for (const edit of [...edits].sort((a, b) => a.at - b.at)) {
84
+ out += html.slice(from, edit.at) + edit.text;
85
+ from = edit.to;
86
+ }
87
+ return out + html.slice(from);
88
+ }
89
+ /** the start tags of `html` that are named `name`, close with `>` and sit outside comments */
90
+ export function tagsNamed(html, name, tags = tagsOf(html)) {
91
+ const comments = commentRanges(html);
92
+ return tags.filter((tag) => tag.name === name && html[tag.end] === '>' && !within(comments, tag.start));
93
+ }
@@ -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>;