@hamur/image 0.0.0-stage → 0.0.1

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 (156) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +24 -2
  3. package/dist/chunks/bun-index-n7xnn0a2.js +502 -0
  4. package/dist/src/adapters/angular.js +275 -0
  5. package/dist/src/adapters/html.js +70 -0
  6. package/dist/src/adapters/preact.js +82 -0
  7. package/dist/src/adapters/react.js +84 -0
  8. package/dist/src/adapters/solid.js +93 -0
  9. package/dist/src/adapters/svelte.js +15 -0
  10. package/dist/src/adapters/vue.js +147 -0
  11. package/dist/src/index.js +1442 -0
  12. package/dist/src/server/index.js +9 -0
  13. package/dist/types/src/adapters/angular-img.d.ts +40 -0
  14. package/dist/types/src/adapters/angular-picture.d.ts +36 -0
  15. package/dist/types/src/adapters/angular.d.ts +3 -0
  16. package/dist/types/src/adapters/html-img.d.ts +10 -0
  17. package/dist/types/src/adapters/html-picture.d.ts +6 -0
  18. package/dist/types/src/adapters/html.d.ts +6 -0
  19. package/dist/types/src/adapters/preact-img.d.ts +8 -0
  20. package/dist/types/src/adapters/preact-picture.d.ts +6 -0
  21. package/dist/types/src/adapters/preact.d.ts +6 -0
  22. package/dist/types/src/adapters/react-img.d.ts +8 -0
  23. package/dist/types/src/adapters/react-picture.d.ts +6 -0
  24. package/dist/types/src/adapters/react.d.ts +6 -0
  25. package/dist/types/src/adapters/solid-img.d.ts +8 -0
  26. package/dist/types/src/adapters/solid-picture.d.ts +6 -0
  27. package/dist/types/src/adapters/solid.d.ts +6 -0
  28. package/dist/types/src/adapters/svelte.d.ts +3 -0
  29. package/dist/types/src/adapters/vue-img.d.ts +119 -0
  30. package/dist/types/src/adapters/vue-picture.d.ts +121 -0
  31. package/dist/types/src/adapters/vue.d.ts +234 -0
  32. package/dist/types/src/build/endpoint.d.ts +12 -0
  33. package/dist/types/src/build/platform.d.ts +24 -0
  34. package/dist/types/src/build/runtime.d.ts +9 -0
  35. package/dist/types/src/build/types.d.ts +4 -0
  36. package/dist/types/src/build/variants.d.ts +8 -0
  37. package/dist/types/src/domains.d.ts +27 -0
  38. package/dist/types/src/index.d.ts +9 -0
  39. package/dist/types/src/module.d.ts +3 -0
  40. package/dist/types/src/options.d.ts +15 -0
  41. package/dist/types/src/providers/bunny.d.ts +9 -0
  42. package/dist/types/src/providers/cloudflare.d.ts +9 -0
  43. package/dist/types/src/providers/cloudflareImages.d.ts +9 -0
  44. package/dist/types/src/providers/cloudinary.d.ts +9 -0
  45. package/dist/types/src/providers/contentful.d.ts +9 -0
  46. package/dist/types/src/providers/fastly.d.ts +9 -0
  47. package/dist/types/src/providers/hamur-url.d.ts +3 -0
  48. package/dist/types/src/providers/hamur.d.ts +3 -0
  49. package/dist/types/src/providers/imagekit.d.ts +9 -0
  50. package/dist/types/src/providers/imgix.d.ts +9 -0
  51. package/dist/types/src/providers/imgproxy.d.ts +9 -0
  52. package/dist/types/src/providers/ipx.d.ts +9 -0
  53. package/dist/types/src/providers/netlify.d.ts +9 -0
  54. package/dist/types/src/providers/none.d.ts +8 -0
  55. package/dist/types/src/providers/sanity.d.ts +9 -0
  56. package/dist/types/src/providers/shared.d.ts +7 -0
  57. package/dist/types/src/providers/storyblok.d.ts +9 -0
  58. package/dist/types/src/providers/strapi.d.ts +9 -0
  59. package/dist/types/src/providers/supabase.d.ts +9 -0
  60. package/dist/types/src/providers/twicpics.d.ts +9 -0
  61. package/dist/types/src/providers/uploadcare.d.ts +9 -0
  62. package/dist/types/src/providers/vercel-url.d.ts +3 -0
  63. package/dist/types/src/providers/vercel.d.ts +3 -0
  64. package/dist/types/src/providers/weserv.d.ts +9 -0
  65. package/dist/types/src/runtime/image.d.ts +28 -0
  66. package/dist/types/src/runtime/img.d.ts +71 -0
  67. package/dist/types/src/runtime/index.d.ts +9 -0
  68. package/dist/types/src/runtime/picture.d.ts +24 -0
  69. package/dist/types/src/runtime/sizes.d.ts +8 -0
  70. package/dist/types/src/runtime/source.d.ts +3 -0
  71. package/dist/types/src/server/door.d.ts +1 -0
  72. package/dist/types/src/server/endpoint.d.ts +46 -0
  73. package/dist/types/src/server/handler.d.ts +1 -0
  74. package/dist/types/src/server/index.d.ts +1 -0
  75. package/dist/types/src/server/miss-handler.d.ts +1 -0
  76. package/dist/types/src/server/miss.d.ts +1 -0
  77. package/dist/types/src/server/parse.d.ts +30 -0
  78. package/dist/types/src/server/remote.d.ts +20 -0
  79. package/dist/types/src/types.d.ts +178 -0
  80. package/package.json +114 -4
  81. package/src/adapters/Img.svelte +33 -0
  82. package/src/adapters/Picture.svelte +39 -0
  83. package/src/adapters/angular-img.ts +144 -0
  84. package/src/adapters/angular-picture.ts +146 -0
  85. package/src/adapters/angular.ts +3 -0
  86. package/src/adapters/html-img.ts +42 -0
  87. package/src/adapters/html-picture.ts +30 -0
  88. package/src/adapters/html.ts +9 -0
  89. package/src/adapters/preact-img.ts +51 -0
  90. package/src/adapters/preact-picture.ts +40 -0
  91. package/src/adapters/preact.ts +9 -0
  92. package/src/adapters/react-img.ts +54 -0
  93. package/src/adapters/react-picture.ts +49 -0
  94. package/src/adapters/react.ts +9 -0
  95. package/src/adapters/solid-img.ts +47 -0
  96. package/src/adapters/solid-picture.ts +43 -0
  97. package/src/adapters/solid.ts +9 -0
  98. package/src/adapters/svelte.ts +3 -0
  99. package/src/adapters/test/ImgCustomPage.svelte +14 -0
  100. package/src/adapters/test/ImgPage.svelte +5 -0
  101. package/src/adapters/test/ImgPreloadPage.svelte +6 -0
  102. package/src/adapters/test/PicturePage.svelte +6 -0
  103. package/src/adapters/test/PicturePreloadPage.svelte +5 -0
  104. package/src/adapters/test/support.ts +116 -0
  105. package/src/adapters/vue-img.ts +72 -0
  106. package/src/adapters/vue-picture.ts +64 -0
  107. package/src/adapters/vue.ts +7 -0
  108. package/src/build/endpoint.ts +78 -0
  109. package/src/build/platform.ts +99 -0
  110. package/src/build/runtime.ts +118 -0
  111. package/src/build/types.ts +23 -0
  112. package/src/build/variants.ts +174 -0
  113. package/src/domains.ts +84 -0
  114. package/src/env.d.ts +24 -0
  115. package/src/index.ts +23 -0
  116. package/src/module.ts +29 -0
  117. package/src/options.ts +329 -0
  118. package/src/providers/bunny.ts +21 -0
  119. package/src/providers/cloudflare.ts +22 -0
  120. package/src/providers/cloudflareImages.ts +25 -0
  121. package/src/providers/cloudinary.ts +31 -0
  122. package/src/providers/contentful.ts +26 -0
  123. package/src/providers/fastly.ts +29 -0
  124. package/src/providers/hamur-url.ts +81 -0
  125. package/src/providers/hamur.ts +8 -0
  126. package/src/providers/imagekit.ts +30 -0
  127. package/src/providers/imgix.ts +26 -0
  128. package/src/providers/imgproxy.ts +24 -0
  129. package/src/providers/ipx.ts +26 -0
  130. package/src/providers/netlify.ts +23 -0
  131. package/src/providers/none.ts +9 -0
  132. package/src/providers/sanity.ts +29 -0
  133. package/src/providers/shared.ts +17 -0
  134. package/src/providers/storyblok.ts +24 -0
  135. package/src/providers/strapi.ts +24 -0
  136. package/src/providers/supabase.ts +26 -0
  137. package/src/providers/twicpics.ts +26 -0
  138. package/src/providers/uploadcare.ts +32 -0
  139. package/src/providers/vercel-url.ts +18 -0
  140. package/src/providers/vercel.ts +8 -0
  141. package/src/providers/weserv.ts +25 -0
  142. package/src/runtime/image.ts +266 -0
  143. package/src/runtime/img.ts +241 -0
  144. package/src/runtime/index.ts +18 -0
  145. package/src/runtime/picture.ts +62 -0
  146. package/src/runtime/sizes.ts +52 -0
  147. package/src/runtime/source.ts +8 -0
  148. package/src/server/door.ts +1 -0
  149. package/src/server/endpoint.ts +428 -0
  150. package/src/server/handler.ts +33 -0
  151. package/src/server/index.ts +1 -0
  152. package/src/server/miss-handler.ts +20 -0
  153. package/src/server/miss.ts +1 -0
  154. package/src/server/parse.ts +152 -0
  155. package/src/server/remote.ts +166 -0
  156. package/src/types.ts +177 -0
@@ -0,0 +1,428 @@
1
+ import { readImageMeta } from "hamur/server/internal"
2
+ import { compileDomain, matchesDomain } from "../domains.ts"
3
+ import type { ImageBlobStore, ImageEndpointOptions, ImageRuntimeOptions, ImageSources } from "../types.ts"
4
+ import {
5
+ isRefusal,
6
+ parseImagePath,
7
+ refuse,
8
+ type ImageRefusal,
9
+ type ImageRequest,
10
+ type OutputExtension,
11
+ } from "./parse.ts"
12
+ import { fetchRemote, type RemoteEnvironment } from "./remote.ts"
13
+
14
+ export interface SourceSize {
15
+ width: number
16
+ height: number
17
+ }
18
+
19
+ /** Decodes `bytes`, applies the request and encodes it in the request's output format. */
20
+ export type ImageTransform = (
21
+ bytes: Uint8Array<ArrayBuffer>,
22
+ request: ImageRequest,
23
+ source: SourceSize,
24
+ maxPixels: number,
25
+ ) => Promise<Uint8Array>
26
+
27
+ export interface ImageCache {
28
+ getItemRaw(key: string): Promise<Uint8Array | undefined>
29
+ setItemRaw(key: string, value: Uint8Array): Promise<void>
30
+ }
31
+
32
+ export interface EndpointEnvironment {
33
+ options: Pick<ImageRuntimeOptions, "baseURL" | "widths" | "domains" | "alias">
34
+ /** `#hamur/image/sources`; a built server answers only the files it lists. */
35
+ sources: ImageSources
36
+ endpoint: ImageEndpointOptions
37
+ /** The bytes of a file below the source dir (`path` has no leading `/`), `undefined` when there is none. */
38
+ readSource(path: string): Promise<Uint8Array | undefined>
39
+ /** The bytes of an asset URL below `app.baseURL` (`_hamur/<name>`), `undefined` when there is none. */
40
+ readAsset(path: string): Promise<Uint8Array | undefined>
41
+ blob?: ImageBlobStore
42
+ cache(): ImageCache
43
+ transform?: ImageTransform
44
+ /** Told once when a result cannot be written to the cache; the answer is sent anyway. */
45
+ warn?: (message: string) => void
46
+ /** Every address of a remote host; default `Bun.dns.lookup`. */
47
+ lookup?: RemoteEnvironment["lookup"]
48
+ /** Default `fetch`; called with the checked address in the URL. */
49
+ fetch?: RemoteEnvironment["fetch"]
50
+ /** Milliseconds a remote fetch may take; default 10 000. */
51
+ remoteTimeout?: number
52
+ /** Milliseconds one address of several may take to answer; default 2 500. */
53
+ remoteConnectTimeout?: number
54
+ }
55
+
56
+ const TYPES: Record<OutputExtension, string> = { jpg: "image/jpeg", png: "image/png", webp: "image/webp" }
57
+ const NOT_MADE: Record<string, string> = { gif: "GIF", svg: "SVG", avif: "AVIF", heic: "HEIC", tiff: "TIFF" }
58
+ /** The extensions `#hamur/image/sources` lists; a source with another one is not looked up. */
59
+ const SOURCE_FILE = /\.(?:png|jpe?g|gif|webp|avif|svg)$/i
60
+ const IMMUTABLE = "public, max-age=31536000, immutable"
61
+ const HOUR = "public, max-age=3600"
62
+ const REMOTE_TIMEOUT = 10_000
63
+ const REMOTE_CONNECT_TIMEOUT = 2_500
64
+ /** How long a remote URL's source ETag is trusted without asking upstream, as long as `HOUR` lets a browser keep it. */
65
+ const REMOTE_FRESH = 3_600_000
66
+ /** `@hamur/blob`'s pathname limit; the parser's segment checks are its other rules. */
67
+ const MAX_BLOB_KEY_BYTES = 1024
68
+ /** How long a blob's tag is trusted without reading it, so a blob put again is served within a minute. */
69
+ const BLOB_FRESH = 60_000
70
+
71
+ const owned = (bytes: Uint8Array): Uint8Array<ArrayBuffer> =>
72
+ bytes.buffer instanceof ArrayBuffer ? (bytes as Uint8Array<ArrayBuffer>) : new Uint8Array(bytes)
73
+
74
+ async function sha256(data: Uint8Array<ArrayBuffer>): Promise<string> {
75
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", data))
76
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")
77
+ }
78
+
79
+ const ascii = (bytes: Uint8Array, start: number, end: number): string =>
80
+ String.fromCharCode(...bytes.subarray(start, end))
81
+
82
+ /** The container of `bytes` by its magic number; `undefined` for anything else. */
83
+ export function sniffImage(bytes: Uint8Array): string | undefined {
84
+ if (bytes[0] === 0x89 && ascii(bytes, 1, 4) === "PNG") return "png"
85
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpg"
86
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP") return "webp"
87
+ if (ascii(bytes, 0, 4) === "GIF8") return "gif"
88
+ if (ascii(bytes, 0, 4) === "II*\0" || ascii(bytes, 0, 4) === "MM\0*") return "tiff"
89
+ if (ascii(bytes, 4, 8) === "ftyp") {
90
+ const brand = ascii(bytes, 8, 12)
91
+ if (brand === "avif" || brand === "avis") return "avif"
92
+ if (["heic", "heix", "heim", "heis", "hevc", "hevx", "mif1", "msf1"].includes(brand)) return "heic"
93
+ }
94
+ const head = new TextDecoder().decode(bytes.subarray(0, 1024)).replace(/^/, "").trimStart()
95
+ if (head.startsWith("<") && /<svg[\s>]/i.test(head)) return "svg"
96
+ return undefined
97
+ }
98
+
99
+ /** Under `hamur dev`: the first of `dirs` that holds `path`, opened as a `BunFile` from segments the parser checked, never a request string. */
100
+ export function readFromDirs(dirs: readonly string[]): (path: string) => Promise<Uint8Array | undefined> {
101
+ return async (path) => {
102
+ for (const dir of dirs) {
103
+ const file = Bun.file(`${dir}/${path}`)
104
+ try {
105
+ if (await file.exists()) return await file.bytes()
106
+ } catch {}
107
+ }
108
+ return undefined
109
+ }
110
+ }
111
+
112
+ /** The header of a source the endpoint transforms, or why it does not. */
113
+ export function checkSource(bytes: Uint8Array, maxPixels: number): SourceSize | ImageRefusal {
114
+ const kind = sniffImage(bytes)
115
+ if (kind === undefined) return refuse(400, "source is not a JPEG, PNG or WebP image")
116
+ if (Object.hasOwn(NOT_MADE, kind))
117
+ return refuse(400, `source is ${NOT_MADE[kind]}, which this endpoint does not transform; link it directly`)
118
+ let meta: { width: number; height: number; animated?: true }
119
+ try {
120
+ meta = readImageMeta(bytes, kind)
121
+ } catch {
122
+ return refuse(400, "source could not be decoded")
123
+ }
124
+ if (meta.animated)
125
+ return refuse(400, "source is an animated WebP, which this endpoint does not transform; link it directly")
126
+ if (meta.width * meta.height > maxPixels) return refuse(413, "source exceeds image.maxPixels")
127
+ return { width: meta.width, height: meta.height }
128
+ }
129
+
130
+ /** With `Bun.Image`: `rot`, `flip`, `flop`, then the resize, then the encoder of the extension. */
131
+ export const transformImage: ImageTransform = (bytes, request, source, maxPixels) => {
132
+ const image = new Bun.Image(bytes, { maxPixels })
133
+ if (request.rot !== undefined) image.rotate(request.rot)
134
+ if (request.flip) image.flip()
135
+ if (request.flop) image.flop()
136
+ if (request.w !== undefined) {
137
+ if (request.fit === "outside" && request.h !== undefined) {
138
+ const turned = request.rot === 90 || request.rot === 270
139
+ const width = turned ? source.height : source.width
140
+ const height = turned ? source.width : source.height
141
+ const scale = Math.max(request.w / width, request.h / height)
142
+ image.resize(Math.max(1, Math.round(width * scale)), Math.max(1, Math.round(height * scale)), {
143
+ fit: "fill",
144
+ withoutEnlargement: true,
145
+ })
146
+ } else if (request.fit === "fill" || request.fit === "inside") {
147
+ image.resize(request.w, request.h, { fit: request.fit, withoutEnlargement: true })
148
+ } else {
149
+ image.resize(request.w, undefined, { withoutEnlargement: true })
150
+ }
151
+ }
152
+ const quality = request.q === undefined ? {} : { quality: request.q }
153
+ if (request.extension === "jpg") image.jpeg(quality)
154
+ else if (request.extension === "png") image.png()
155
+ else image.webp(quality)
156
+ return image.bytes()
157
+ }
158
+
159
+ function refusalOf(error: unknown): ImageRefusal {
160
+ const code = typeof error === "object" && error !== null ? (error as { code?: unknown }).code : undefined
161
+ if (code === "ERR_IMAGE_TOO_MANY_PIXELS") return refuse(413, "source exceeds image.maxPixels")
162
+ if (code === "ERR_IMAGE_DECODE_FAILED" || code === "ERR_IMAGE_UNKNOWN_FORMAT")
163
+ return refuse(400, "source could not be decoded")
164
+ if (code === "ERR_IMAGE_ENCODE_FAILED") return refuse(500, "source could not be encoded")
165
+ throw error
166
+ }
167
+
168
+ function matchesTag(header: string | null, etag: string): boolean {
169
+ if (header === null) return false
170
+ return header.split(",").some((part) => {
171
+ const tag = part.trim()
172
+ return tag === "*" || tag === etag || tag === `W/${etag}`
173
+ })
174
+ }
175
+
176
+ const answerText = (refusal: ImageRefusal, head: boolean): Response =>
177
+ new Response(head ? null : refusal.message, {
178
+ status: refusal.status,
179
+ headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" },
180
+ })
181
+
182
+ /** Where a request's source is, before any transform. */
183
+ interface Found {
184
+ /** The source ETag of the cache key. */
185
+ tag: string
186
+ width?: number
187
+ pinned: boolean
188
+ shown: string
189
+ load(): Promise<Uint8Array | ImageRefusal | undefined>
190
+ /** Set when `tag` was remembered rather than read: what a cache miss or a width check reads instead. */
191
+ reread?: () => Promise<Found | ImageRefusal>
192
+ }
193
+
194
+ interface Fetched {
195
+ bytes: Uint8Array
196
+ /** The strong `etag`, else `#` and the SHA-256 of the bytes. */
197
+ tag: string
198
+ }
199
+
200
+ /** The `/_hamur/image/**` answer. Every 200 is bytes this endpoint encoded, never a source's own. */
201
+ export function createImageEndpoint(env: EndpointEnvironment): (request: Request) => Promise<Response> {
202
+ const { options, sources, endpoint } = env
203
+ const transform = env.transform ?? transformImage
204
+ const prefix = `${options.baseURL}_hamur/image/`
205
+ const matchers = options.domains.map(compileDomain)
206
+ const aliases = Object.values(options.alias).map((target) => new URL(target).href)
207
+ const running = new Map<string, Promise<Uint8Array | ImageRefusal>>()
208
+ const fetching = new Map<string, Promise<Fetched | ImageRefusal>>()
209
+ let cacheWarned = false
210
+ const belowAlias = (href: string, target: string): boolean =>
211
+ href === target || href.startsWith(target.endsWith("/") ? target : `${target}/`)
212
+ const allowed = (url: URL): boolean =>
213
+ url.username === "" &&
214
+ url.password === "" &&
215
+ (matchers.some((matcher) => matchesDomain(matcher, url)) || aliases.some((target) => belowAlias(url.href, target)))
216
+ const remote: RemoteEnvironment = {
217
+ allowed,
218
+ lookup: env.lookup ?? (async (hostname) => (await Bun.dns.lookup(hostname)).map((entry) => entry.address)),
219
+ fetch: env.fetch ?? ((url, init) => fetch(url, init)),
220
+ maxBytes: endpoint.maxBytes,
221
+ timeout: env.remoteTimeout ?? REMOTE_TIMEOUT,
222
+ connectTimeout: env.remoteConnectTimeout ?? REMOTE_CONNECT_TIMEOUT,
223
+ }
224
+ const encoder = new TextEncoder()
225
+ const indexKey = async (href: string) => `image-remote:${(await sha256(encoder.encode(href))).slice(0, 16)}`
226
+
227
+ /** Never under `hamur dev`, which reads every source live. */
228
+ async function knownTag(index: string, fresh: number): Promise<string | undefined> {
229
+ if (endpoint.dev) return undefined
230
+ try {
231
+ const raw = await env.cache().getItemRaw(index)
232
+ if (!raw) return undefined
233
+ const { tag, at } = JSON.parse(new TextDecoder().decode(raw)) as { tag: unknown; at: unknown }
234
+ return typeof tag === "string" && typeof at === "number" && Date.now() - at < fresh ? tag : undefined
235
+ } catch {
236
+ return undefined
237
+ }
238
+ }
239
+
240
+ /** One upstream fetch per URL at a time, shared by the requests that wait for it. */
241
+ function obtain(url: URL): Promise<Fetched | ImageRefusal> {
242
+ let work = fetching.get(url.href)
243
+ if (work === undefined) {
244
+ work = (async (): Promise<Fetched | ImageRefusal> => {
245
+ const got = await fetchRemote(url, remote)
246
+ if (isRefusal(got)) return got
247
+ const tag = got.etag ?? `#${await sha256(owned(got.bytes))}`
248
+ if (!endpoint.dev) {
249
+ try {
250
+ await env
251
+ .cache()
252
+ .setItemRaw(await indexKey(url.href), encoder.encode(JSON.stringify({ tag, at: Date.now() })))
253
+ } catch {}
254
+ }
255
+ return { bytes: got.bytes, tag }
256
+ })().finally(() => fetching.delete(url.href))
257
+ fetching.set(url.href, work)
258
+ }
259
+ return work
260
+ }
261
+
262
+ async function findRemote(
263
+ source: NonNullable<ImageRequest["remote"]>,
264
+ search: string,
265
+ ): Promise<Found | ImageRefusal> {
266
+ let url: URL
267
+ try {
268
+ url = new URL(`${source.protocol}//${source.host}${source.path}${search}`)
269
+ } catch {
270
+ return refuse(403, `remote host ${source.host} is not in image.domains`)
271
+ }
272
+ if (!allowed(url)) return refuse(403, `remote host ${url.hostname} is not in image.domains`)
273
+ const known = await knownTag(await indexKey(url.href), REMOTE_FRESH)
274
+ if (known !== undefined) {
275
+ const load = async () => {
276
+ const got = await obtain(url)
277
+ return isRefusal(got) ? got : got.bytes
278
+ }
279
+ return { tag: `${url.href}\n${known}`, pinned: false, shown: url.href, load }
280
+ }
281
+ const got = await obtain(url)
282
+ if (isRefusal(got)) return got
283
+ return { tag: `${url.href}\n${got.tag}`, pinned: false, shown: url.href, load: async () => got.bytes }
284
+ }
285
+
286
+ const blobIndexKey = async (key: string) => `image-blob:${(await sha256(encoder.encode(key))).slice(0, 16)}`
287
+ const blobNotFound = (key: string) => refuse(404, `blob ${JSON.stringify(key)} not found`)
288
+
289
+ /** The tag is the hash of the bytes read, so a put between two reads can never file new bytes under an old tag. */
290
+ async function readBlob(store: ImageBlobStore, key: string): Promise<Found | ImageRefusal> {
291
+ const file = await store.get(key)
292
+ if (file === undefined) return blobNotFound(key)
293
+ if (file.size > endpoint.maxBytes) return refuse(413, "blob source is larger than image.maxBytes")
294
+ const bytes = new Uint8Array(await file.arrayBuffer())
295
+ const tag = `blob:${key}\n#${await sha256(bytes)}`
296
+ if (!endpoint.dev) {
297
+ try {
298
+ await env.cache().setItemRaw(await blobIndexKey(key), encoder.encode(JSON.stringify({ tag, at: Date.now() })))
299
+ } catch {}
300
+ }
301
+ return { tag, pinned: false, shown: key, load: async () => bytes }
302
+ }
303
+
304
+ async function findBlob(key: string): Promise<Found | ImageRefusal> {
305
+ if (encoder.encode(key).length > MAX_BLOB_KEY_BYTES)
306
+ return refuse(400, `blob key is longer than ${MAX_BLOB_KEY_BYTES} bytes`)
307
+ const store = env.blob
308
+ if (store === undefined || key.split("/").some((segment) => segment.startsWith("."))) return blobNotFound(key)
309
+ const known = await knownTag(await blobIndexKey(key), BLOB_FRESH)
310
+ if (known === undefined) return readBlob(store, key)
311
+ let fresh: Promise<Found | ImageRefusal> | undefined
312
+ const reread = () => (fresh ??= readBlob(store, key))
313
+ const load = async () => {
314
+ const found = await reread()
315
+ return isRefusal(found) ? found : found.load()
316
+ }
317
+ return { tag: known, pinned: false, shown: key, load, reread }
318
+ }
319
+
320
+ async function findLocal(parsed: ImageRequest): Promise<Found | ImageRefusal> {
321
+ const path = parsed.path!
322
+ const shown = `/${path}`
323
+ const notFound = refuse(404, `source ${JSON.stringify(shown)} not found`)
324
+ if (endpoint.blobPrefix !== undefined && shown.startsWith(endpoint.blobPrefix))
325
+ return findBlob(shown.slice(endpoint.blobPrefix.length))
326
+ if (path.split("/").some((segment) => segment.startsWith(".")) || path.startsWith("_hamur/image/")) return notFound
327
+
328
+ const asset = path.startsWith("_hamur/")
329
+ if (asset ? !/\.(?:jpe?g|png|webp)$/i.test(path) : !SOURCE_FILE.test(path)) return notFound
330
+ const pinned = parsed.v !== undefined || asset
331
+ const read = () => (asset ? env.readAsset(path) : env.readSource(path))
332
+ if (endpoint.dev || asset) {
333
+ const bytes = await read()
334
+ if (!bytes) return notFound
335
+ return { tag: endpoint.dev ? await sha256(owned(bytes)) : shown, pinned, shown, load: async () => bytes }
336
+ }
337
+ const entry = Object.hasOwn(sources, shown) ? sources[shown] : undefined
338
+ if (entry === undefined) return notFound
339
+ if (parsed.v !== undefined && parsed.v !== entry[3])
340
+ return refuse(404, `source ${JSON.stringify(shown)} has no version v_${parsed.v}`)
341
+ let bytes: Uint8Array | undefined
342
+ return { tag: `${shown}@${entry[3]}`, width: entry[0], pinned, shown, load: async () => (bytes ??= await read()) }
343
+ }
344
+
345
+ async function produce(key: string, request: ImageRequest, found: Found): Promise<Uint8Array | ImageRefusal> {
346
+ const bytes = await found.load()
347
+ if (!bytes) return refuse(404, `source ${JSON.stringify(found.shown)} not found`)
348
+ if (isRefusal(bytes)) return bytes
349
+ const size = checkSource(bytes, endpoint.maxPixels)
350
+ if (isRefusal(size)) return size
351
+ let output: Uint8Array
352
+ try {
353
+ output = await transform(owned(bytes), request, size, endpoint.maxPixels)
354
+ } catch (error) {
355
+ return refusalOf(error)
356
+ }
357
+ try {
358
+ await env.cache().setItemRaw(key, output)
359
+ } catch (error) {
360
+ if (!cacheWarned) {
361
+ cacheWarned = true
362
+ env.warn?.(
363
+ `[image] a transformed image could not be cached; each request transforms again: ${error instanceof Error ? error.message : String(error)}`,
364
+ )
365
+ }
366
+ }
367
+ return output
368
+ }
369
+
370
+ async function answerFound(parsed: ImageRequest, found: Found, incoming: Request, head: boolean): Promise<Response> {
371
+ const again = async (reread: NonNullable<Found["reread"]>) => {
372
+ const fresh = await reread()
373
+ return isRefusal(fresh) ? answerText(fresh, head) : answerFound(parsed, fresh, incoming, head)
374
+ }
375
+ if (parsed.w !== undefined && !options.widths.includes(parsed.w)) {
376
+ if (found.width === undefined && found.reread) return again(found.reread)
377
+ let width = found.width
378
+ if (width === undefined) {
379
+ const loaded = await found.load()
380
+ if (!loaded) return answerText(refuse(404, `source ${JSON.stringify(found.shown)} not found`), head)
381
+ if (isRefusal(loaded)) return answerText(loaded, head)
382
+ const size = checkSource(loaded, endpoint.maxPixels)
383
+ if (isRefusal(size)) return answerText(size, head)
384
+ width = size.width
385
+ }
386
+ if (parsed.w !== width)
387
+ return answerText(
388
+ refuse(400, `width ${parsed.w} is not an allowed size (image.widths, or the source's own width)`),
389
+ head,
390
+ )
391
+ }
392
+
393
+ const key = `image:${(await sha256(new TextEncoder().encode(`${found.tag}\n${parsed.modifiers}\n${parsed.extension}`))).slice(0, 16)}`
394
+ const etag = `"${key}"`
395
+ const headers = {
396
+ "content-type": TYPES[parsed.extension],
397
+ etag,
398
+ "cache-control": endpoint.dev ? "no-cache" : found.pinned ? IMMUTABLE : HOUR,
399
+ "x-content-type-options": "nosniff",
400
+ }
401
+ if (matchesTag(incoming.headers.get("if-none-match"), etag)) return new Response(null, { status: 304, headers })
402
+
403
+ let output: Uint8Array | ImageRefusal | undefined = await env.cache().getItemRaw(key)
404
+ if (!output && found.reread) return again(found.reread)
405
+ if (!output) {
406
+ let work = running.get(key)
407
+ if (work === undefined) {
408
+ work = produce(key, parsed, found).finally(() => running.delete(key))
409
+ running.set(key, work)
410
+ }
411
+ output = await work
412
+ }
413
+ if (isRefusal(output)) return answerText(output, head)
414
+ return new Response(head ? null : owned(output), { status: 200, headers })
415
+ }
416
+
417
+ return async (incoming) => {
418
+ const head = incoming.method === "HEAD"
419
+ const { pathname, search } = new URL(incoming.url)
420
+ const parsed = pathname.startsWith(prefix)
421
+ ? parseImagePath(pathname.slice(prefix.length))
422
+ : refuse(404, "not found")
423
+ if (isRefusal(parsed)) return answerText(parsed, head)
424
+ const found = parsed.remote === undefined ? await findLocal(parsed) : await findRemote(parsed.remote, search)
425
+ if (isRefusal(found)) return answerText(found, head)
426
+ return answerFound(parsed, found, incoming, head)
427
+ }
428
+ }
@@ -0,0 +1,33 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import endpoint, { useBlob } from "#hamur/image/endpoint"
3
+ import options from "#hamur/image/options"
4
+ import sources from "#hamur/image/sources"
5
+ import { defineHandler, readAsset, useLogger, useStorage } from "hamur/server"
6
+ import { createImageEndpoint, readFromDirs } from "./endpoint.ts"
7
+
8
+ const bytesOf = async (response: Response): Promise<Uint8Array | undefined> =>
9
+ response.ok ? new Uint8Array(await response.arrayBuffer()) : undefined
10
+ const readPublic = async (path: string) =>
11
+ bytesOf(await readAsset(`${options.baseURL}${path.split("/").map(encodeURIComponent).join("/")}`))
12
+
13
+ const answer = createImageEndpoint({
14
+ options,
15
+ sources,
16
+ endpoint,
17
+ readSource: endpoint.dev
18
+ ? readFromDirs(endpoint.dirs)
19
+ : endpoint.assets
20
+ ? (path) => useStorage("assets:image").getItemRaw(path.split("/").join(":"))
21
+ : readPublic,
22
+ readAsset: readPublic,
23
+ ...(useBlob === undefined ? {} : { blob: useBlob() }),
24
+ cache: () => useStorage("cache"),
25
+ warn: (message) => useLogger().warn(message),
26
+ })
27
+
28
+ export const imageEndpoint = defineHandler({
29
+ route: "/_hamur/image/**:path",
30
+ method: "GET",
31
+ raw: true,
32
+ handler: (_, { event }) => answer(event.request),
33
+ })
@@ -0,0 +1 @@
1
+ export { getImage, getSizes } from "../runtime/index.ts"
@@ -0,0 +1,20 @@
1
+ import { defineHandler, useLogger } from "hamur/server"
2
+
3
+ const logged = new Set<string>()
4
+
5
+ export const imageMiss = defineHandler({
6
+ route: "/_hamur/image/**:path",
7
+ method: "GET",
8
+ raw: true,
9
+ handler: (_, { event }) => {
10
+ const { pathname } = new URL(event.request.url)
11
+ if (!logged.has(pathname)) {
12
+ logged.add(pathname)
13
+ useLogger().warn(`[image] ${pathname} was not generated at build`)
14
+ }
15
+ return new Response("image variant not generated at build; add its source to image.prerender or use a provider", {
16
+ status: 404,
17
+ headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" },
18
+ })
19
+ },
20
+ })
@@ -0,0 +1 @@
1
+ export { imageMiss } from "./miss-handler.ts"
@@ -0,0 +1,152 @@
1
+ export type OutputExtension = "jpg" | "png" | "webp"
2
+
3
+ export interface ImageRequest {
4
+ /** The modifier segment as written, which the parser checked is the one spelling. */
5
+ modifiers: string
6
+ fit?: "fill" | "inside" | "outside"
7
+ flip: boolean
8
+ flop: boolean
9
+ h?: number
10
+ q?: number
11
+ rot?: 90 | 180 | 270
12
+ v?: string
13
+ w?: number
14
+ /** A local source: the decoded path below the source dir, without the leading `/`. */
15
+ path?: string
16
+ /** A remote source: `https:` or `http:`, its host and its path as written. */
17
+ remote?: { protocol: "https:" | "http:"; host: string; path: string }
18
+ extension: OutputExtension
19
+ }
20
+
21
+ export interface ImageRefusal {
22
+ status: number
23
+ message: string
24
+ }
25
+
26
+ const KEYS = ["fit", "flip", "flop", "h", "q", "rot", "v", "w"] as const
27
+ type Key = (typeof KEYS)[number]
28
+ const FITS = ["fill", "inside", "outside"]
29
+ const EXTENSIONS: readonly string[] = ["jpg", "png", "webp"]
30
+ const MAX_SIZE = 16384
31
+ const INTEGER = /^[1-9]\d*$/
32
+ const HEX8 = /^[0-9a-f]{8}$/
33
+ const ENCODED_SEPARATOR = /%(?:2f|5c)/i
34
+
35
+ export const refuse = (status: number, message: string): ImageRefusal => ({ status, message: `image: ${message}` })
36
+ export const isRefusal = (value: unknown): value is ImageRefusal =>
37
+ typeof value === "object" && value !== null && "status" in value && "message" in value
38
+ const escapes = (): ImageRefusal => refuse(400, "source path escapes the source dir")
39
+
40
+ function keyOf(token: string): Key | undefined {
41
+ if (token === "flip" || token === "flop") return token
42
+ const underscore = token.indexOf("_")
43
+ const key = underscore < 1 ? "" : token.slice(0, underscore)
44
+ return key === "flip" || key === "flop" ? undefined : KEYS.find((known) => known === key)
45
+ }
46
+
47
+ function integer(value: string, max: number): number | undefined {
48
+ if (!INTEGER.test(value)) return undefined
49
+ const number = Number(value)
50
+ return number <= max ? number : undefined
51
+ }
52
+
53
+ /** Decoded segments of a local source, or `undefined` when one would leave the source dir. */
54
+ function sourceSegments(encoded: string): string[] | undefined {
55
+ const segments: string[] = []
56
+ for (const raw of encoded.split("/")) {
57
+ if (ENCODED_SEPARATOR.test(raw)) return undefined
58
+ let segment: string
59
+ try {
60
+ segment = decodeURIComponent(raw)
61
+ } catch {
62
+ return undefined
63
+ }
64
+ if (segment === "" || segment === "." || segment === ".." || /[/\\\0]/.test(segment)) return undefined
65
+ segments.push(segment)
66
+ }
67
+ return segments
68
+ }
69
+
70
+ /** `<modifiers>/<source>.<extension>`, the part of the path after `_hamur/image/`, still percent-encoded. */
71
+ export function parseImagePath(rest: string): ImageRequest | ImageRefusal {
72
+ const slash = rest.indexOf("/")
73
+ const segment = slash < 0 ? rest : rest.slice(0, slash)
74
+ const tokens = segment === "_" ? [] : segment.split(",")
75
+ const keys: Key[] = []
76
+ for (const token of tokens) {
77
+ const key = keyOf(token)
78
+ if (key === undefined) return refuse(400, `modifier ${JSON.stringify(token)} is not known (${KEYS.join(", ")})`)
79
+ keys.push(key)
80
+ }
81
+ if (keys.some((key, i) => i > 0 && KEYS.indexOf(key) <= KEYS.indexOf(keys[i - 1]!))) {
82
+ const first = new Map<Key, string>()
83
+ for (const [i, token] of tokens.entries()) if (!first.has(keys[i]!)) first.set(keys[i]!, token)
84
+ const canonical = KEYS.filter((key) => first.has(key)).map((key) => first.get(key)!)
85
+ return refuse(400, `modifiers must be sorted and given once (write ${JSON.stringify(canonical.join(","))})`)
86
+ }
87
+ const request: ImageRequest = { modifiers: segment, flip: false, flop: false, extension: "webp" }
88
+ for (const [i, token] of tokens.entries()) {
89
+ const key = keys[i]!
90
+ const value = token.slice(key.length + 1)
91
+ switch (key) {
92
+ case "fit":
93
+ if (!FITS.includes(value))
94
+ return refuse(400, `fit ${JSON.stringify(value)} is not made here (${FITS.join(", ")})`)
95
+ request.fit = value as ImageRequest["fit"]
96
+ break
97
+ case "flip":
98
+ case "flop":
99
+ request[key] = true
100
+ break
101
+ case "h":
102
+ case "w": {
103
+ const size = integer(value, MAX_SIZE)
104
+ if (size === undefined) return refuse(400, `${key} must be an integer from 1 to ${MAX_SIZE}`)
105
+ request[key] = size
106
+ break
107
+ }
108
+ case "q": {
109
+ const quality = integer(value, 100)
110
+ if (quality === undefined) return refuse(400, "q must be an integer from 1 to 100")
111
+ request.q = quality
112
+ break
113
+ }
114
+ case "rot":
115
+ if (value !== "90" && value !== "180" && value !== "270") return refuse(400, "rot must be 90, 180 or 270")
116
+ request.rot = Number(value) as 90 | 180 | 270
117
+ break
118
+ case "v":
119
+ if (!HEX8.test(value)) return refuse(400, "v must be 8 lower-case hex digits")
120
+ request.v = value
121
+ break
122
+ }
123
+ }
124
+ if (
125
+ (request.h === undefined) !== (request.fit === undefined) ||
126
+ (request.h !== undefined && request.w === undefined)
127
+ ) {
128
+ return refuse(400, "h and fit go together, with w")
129
+ }
130
+ const source = slash < 0 ? "" : rest.slice(slash + 1)
131
+ const dot = source.lastIndexOf(".")
132
+ const extension = dot < 0 || source.lastIndexOf("/") > dot ? "" : source.slice(dot + 1)
133
+ if (!EXTENSIONS.includes(extension))
134
+ return refuse(
135
+ 400,
136
+ `output extension ${JSON.stringify(`.${extension}`)} is not made here (${EXTENSIONS.join(", ")})`,
137
+ )
138
+ request.extension = extension as OutputExtension
139
+ const encoded = source.slice(0, dot)
140
+ const remote = /^_(https?)\//.exec(encoded)
141
+ if (remote) {
142
+ const rest = encoded.slice(remote[0].length)
143
+ const host = rest.split("/", 1)[0]!
144
+ if (!host) return refuse(400, "a remote source names its host (_https/<host>/<path>)")
145
+ request.remote = { protocol: remote[1] === "https" ? "https:" : "http:", host, path: rest.slice(host.length) }
146
+ return request
147
+ }
148
+ const segments = sourceSegments(encoded)
149
+ if (segments === undefined) return escapes()
150
+ request.path = segments.join("/")
151
+ return request
152
+ }