@prunellejs/images 0.1.1 → 0.7.3

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -11,7 +11,8 @@
11
11
 
12
12
  - `widths`: responsive widths in px (default `[320, 640, 960, 1280, 1920]`).
13
13
  - `formats`: `('avif' | 'webp')[]` (default `['avif', 'webp']`; uses ImageMagick `magick` on `PATH`, falls back to original file with parsed dimensions when unavailable). Each image is decoded once per format, one `magick` run writing all its widths; runs share one budget for the whole build (half the cores, at most 8 `magick` at once), each limited to one thread and 512 MiB and killed after 2 min; a failed run warns with the file, the widths and `magick`'s error and leaves those variants out until the next build retries them (the original ships when none succeeds).
14
- - `quality` (WebP, default `80`), `avifQuality` (default `55`), `cacheDir` (default `'.prunelle-cache/images'`), `pruneCache` (default `true`).
14
+ - Every image the build ships, original included, loses its EXIF (GPS position, camera serial), XMP, IPTC and text metadata; JPEG, PNG and WebP keep only their Orientation, and every variant keeps its ICC colour profile (`magick ... +profile "!icc,*"`, not `-strip`). `prunelle check` warns about each JPEG, PNG or WebP under `public/` still carrying EXIF, XMP or IPTC, since `public/` is copied as is.
15
+ - `quality` (WebP, default `80`), `avifQuality` (default `55`), `cacheDir` (default `'.prunelle-cache/images'`), `pruneCache` (default `true`: after a build that prerendered pages, `og-` and `md-` cache files no page registered are deleted, together with the imported-image cache the build did not load). The runtime `/og/` and `/img/` stores are LRUs of twice the files the build registered, at least 256 and 4096.
15
16
  - `card`: `ShareCardDefaults` (`{ site?, publicDir?, cacheDir?, background?, color?, accent?, mutedColor?, fontFamily?, width? (1200), height? (630) }`).
16
17
  - `markdownSizes`: default `sizes` attribute for relative images inside `@prunellejs/content` Markdown (auto-wired via `CONTENT_IMAGE_RESOLVER_SERVICE`).
17
18
 
@@ -21,7 +22,7 @@
21
22
  - `image(asset, { sizes?, priority? })`: returns `ImgSpreadProps` (`src`, `srcset`, `sizes`, `width`, `height`, `loading`, `decoding`, `fetchpriority`) for `<img {...image(hero)} alt="..." />`.
22
23
  - `shareCard({ title, subtitle?, badge?, image?, background?, color?, accent? })`: renders and caches a PNG card under `public/og/*.png` (via `rsvg-convert` or `magick`) and returns its URL (prefixed with `site` when configured).
23
24
  - `optimizeImageFile(absPath, options?)`: synchronously optimizes a local file into `dist/public/img/`.
24
- - `readImageDimensions(bytes)`: `{ width, height }` from a PNG, GIF, WebP, JPEG or AVIF header, with no process, as the image is displayed: a JPEG whose EXIF Orientation is 5 to 8 has them swapped, as its variants and every imported asset do.
25
+ - `readImageDimensions(bytes)`: `{ width, height }` from a PNG, GIF, WebP, JPEG, AVIF, BMP, ICO, TIFF or SVG header, with no process, as the image is displayed: rotated JPEG/PNG/WebP/TIFF (EXIF Orientation 5–8) and AVIF (`irot` 90°/270°) swap width and height to match their displayed orientation and encoded variants.
25
26
 
26
27
  ## Snippets
27
28
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/images",
3
- "version": "0.1.1",
3
+ "version": "0.7.3",
4
4
  "description": "Build-time responsive AVIF/WebP image optimization plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,6 @@
22
22
  "directory": "packages/plugin-images"
23
23
  },
24
24
  "peerDependencies": {
25
- "prunelle": "^0.1.1"
25
+ "prunelle": "^0.7.3"
26
26
  }
27
27
  }
package/src/cache.ts ADDED
@@ -0,0 +1,53 @@
1
+ // What a build leaves in the image cache, and how many images the runtime stores must be able to hold.
2
+
3
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
4
+ import { basename, join } from 'node:path'
5
+
6
+ /** Cache files a prerendering build did not register: `og-<n>` is the cache of public `og/<n>`, `md-<n>` that of public `img/<n>`, and `md-<stem>-<hash>.json` the meta of a kept variant. */
7
+ export function unusedOgAndMdCacheFiles(cacheEntries: readonly string[], publicFiles: readonly string[]): string[] {
8
+ const kept = new Set<string>()
9
+ for (const rel of publicFiles) {
10
+ if (rel.startsWith('og/'))
11
+ kept.add(`og-${basename(rel)}`)
12
+ else if (rel.startsWith('img/')) {
13
+ const variant = `md-${basename(rel)}`
14
+ kept.add(variant)
15
+ // `md-<stem>-<hash>.json` describes the variants `md-<stem>-<hash>-<width>w.<format>`.
16
+ kept.add(variant.replace(/-\d+w\.\w+$/, '.json'))
17
+ }
18
+ }
19
+ return cacheEntries.filter(entry => (entry.startsWith('og-') || entry.startsWith('md-')) && !kept.has(entry))
20
+ }
21
+
22
+ export function removeUnusedOgAndMd(cacheRoot: string, publicFiles: readonly string[]): void {
23
+ if (!existsSync(cacheRoot))
24
+ return
25
+ for (const entry of unusedOgAndMdCacheFiles(readdirSync(cacheRoot), publicFiles))
26
+ rmSync(join(cacheRoot, entry), { force: true })
27
+ }
28
+
29
+ /** How many `og/` and `img/` files the build registered, kept in its plugin data: what the runtime stores must hold at least. */
30
+ export interface KnownImages {
31
+ knownOg?: number | undefined
32
+ knownImg?: number | undefined
33
+ }
34
+
35
+ export function knownImages(publicFiles: readonly string[]): Required<KnownImages> {
36
+ let knownOg = 0
37
+ let knownImg = 0
38
+ for (const rel of publicFiles) {
39
+ if (rel.startsWith('og/'))
40
+ knownOg++
41
+ else if (rel.startsWith('img/'))
42
+ knownImg++
43
+ }
44
+ return { knownOg, knownImg }
45
+ }
46
+
47
+ export const MIN_OG_ENTRIES = 256
48
+ export const MIN_IMG_ENTRIES = 4096
49
+
50
+ /** The size of the `/og/` and `/img/` stores: twice what the build knows, never under its floor, so an image the HTML references is served and a flood of unique URLs still cannot grow a store for ever. */
51
+ export function runtimeStoreLimits(known: KnownImages | undefined): [maxOg: number, maxImg: number] {
52
+ return [Math.max(MIN_OG_ENTRIES, (known?.knownOg ?? 0) * 2), Math.max(MIN_IMG_ENTRIES, (known?.knownImg ?? 0) * 2)]
53
+ }
package/src/card.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // (cached by content hash in `.prunelle-cache/images/` at build time, or served from memory at runtime for --compile).
4
4
 
5
5
  import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
6
- import { join, resolve } from 'node:path'
6
+ import { extname, join, resolve } from 'node:path'
7
7
  import { isInside, serviceKey } from 'prunelle/config'
8
8
  import { getAppContext } from 'prunelle/internal/server'
9
9
  import { escAttr } from 'prunelle/server'
@@ -95,12 +95,12 @@ function readConfinedSvgImage(imageSpec: string): string {
95
95
  return imageSpec
96
96
  const rootDir = resolve(getAppContext()?.root ?? process.cwd())
97
97
  const absImg = resolve(rootDir, imageSpec)
98
- if (!isInside(rootDir, absImg) || !existsSync(absImg))
98
+ if (extname(absImg).toLowerCase() !== '.svg' || !isInside(rootDir, absImg) || !existsSync(absImg))
99
99
  return ''
100
100
  try {
101
101
  const realRoot = realpathSync(rootDir)
102
102
  const realImg = realpathSync(absImg)
103
- if (!isInside(realRoot, realImg))
103
+ if (extname(realImg).toLowerCase() !== '.svg' || !isInside(realRoot, realImg))
104
104
  return ''
105
105
  return readFileSync(realImg, 'utf8')
106
106
  }
@@ -116,7 +116,7 @@ function buildCardSvg(input: ShareCardInput, cfg: ShareCardDefaults): string {
116
116
  const fg = input.color ?? cfg.color ?? '#dbe0ea'
117
117
  const accent = input.accent ?? cfg.accent ?? '#f5b83d'
118
118
  const muted = cfg.mutedColor ?? '#8b95aa'
119
- const font = cfg.fontFamily ?? 'system-ui, -apple-system, sans-serif'
119
+ const font = cfg.fontFamily ?? '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", "Helvetica Neue", Arial, sans-serif'
120
120
 
121
121
  const hasGraphic = Boolean(input.image)
122
122
  const titleLines = wrapLines(input.title, hasGraphic ? 20 : 26, 3)
@@ -196,7 +196,7 @@ export function shareCard(input: ShareCardInput, overrides?: ShareCardDefaults):
196
196
  const png = await rasterizeSvgToPngBytesAsync(svg)
197
197
  if (png !== undefined)
198
198
  return { body: png, contentType: 'image/png', etag: computeEtag(png) }
199
- return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg) }
199
+ return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg), fallback: true }
200
200
  })
201
201
  return `${site}${urlPath}`
202
202
  }
package/src/dimensions.ts CHANGED
@@ -1,21 +1,23 @@
1
1
  // Image sizes read from the file header, with no decoder and no process.
2
2
 
3
- /** Pure-JS binary header parser for PNG, GIF, WebP, JPEG, and AVIF/HEIF dimensions (zero external dependencies). */
3
+ const SVG_OPEN_TAG_RE = /<svg\b((?:[^<>"']|"[^"]*"|'[^']*')*)\/?>/i
4
+ const SVG_ATTR_RE = /\b(width|height|viewBox)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi
5
+ const SVG_PX_RE = /^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/i
6
+ const SVG_BOX_SEP_RE = /[\s,]+/
7
+
8
+ /** Pure-JS binary header parser for PNG, GIF, WebP, JPEG, AVIF/HEIF, BMP, ICO, TIFF, and SVG dimensions (zero external dependencies). */
4
9
  export function readImageDimensions(bytes: Uint8Array): { width: number, height: number } | undefined {
5
10
  const len = bytes.byteLength
6
- if (len < 10)
11
+ if (len < 6)
7
12
  return undefined
8
13
  const view = new DataView(bytes.buffer, bytes.byteOffset, len)
9
14
 
10
- // PNG: 89 50 4E 47 0D 0A 1A 0A, IHDR width@16, height@20 (uint32BE)
11
- if (len >= 24 && view.getUint32(0) === 0x89504E47 && view.getUint32(4) === 0x0D0A1A0A) {
12
- const width = view.getUint32(16)
13
- const height = view.getUint32(20)
14
- return width > 0 && height > 0 ? { width, height } : undefined
15
- }
15
+ // PNG: 89 50 4E 47 0D 0A 1A 0A, IHDR width@16, height@20 (uint32BE) + optional eXIf/orNT orientation
16
+ if (len >= 24 && view.getUint32(0) === 0x89504E47 && view.getUint32(4) === 0x0D0A1A0A)
17
+ return pngDimensions(bytes, view)
16
18
 
17
19
  // GIF87a / GIF89a: width@6, height@8 (uint16LE)
18
- if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
20
+ if (len >= 10 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
19
21
  const width = view.getUint16(6, true)
20
22
  const height = view.getUint16(8, true)
21
23
  return width > 0 && height > 0 ? { width, height } : undefined
@@ -27,10 +29,59 @@ export function readImageDimensions(bytes: Uint8Array): { width: number, height:
27
29
  return jpegDimensions(bytes, view)
28
30
  if (len >= 24 && view.getUint32(4) === 0x66747970)
29
31
  return isobmffDimensions(bytes, view)
30
- return undefined
32
+ if (len >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D)
33
+ return bmpDimensions(view)
34
+ if (len >= 22 && view.getUint32(0) === 0x00000100)
35
+ return icoDimensions(bytes, view)
36
+ if (len >= 8 && ((bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0x00) || (bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0x00 && bytes[3] === 0x2A)))
37
+ return tiffDimensions(view, len)
38
+ return svgDimensions(bytes)
39
+ }
40
+
41
+ function applyOrientation(width: number, height: number, orientation: number): { width: number, height: number } {
42
+ return orientation >= 5 && orientation <= 8 ? { width: height, height: width } : { width, height }
43
+ }
44
+
45
+ /** Reads EXIF orientation from a payload that holds either raw TIFF bytes (`II`/`MM`) or an `Exif\0\0` prefix followed by TIFF. */
46
+ function rawOrPrefixedExifOrientation(view: DataView, start: number, end: number): number {
47
+ if (end - start >= 14 && view.getUint32(start) === 0x45786966 && view.getUint16(start + 4) === 0)
48
+ return tiffIfdInfo(view, start + 6, end).orientation
49
+ return tiffIfdInfo(view, start, end).orientation
31
50
  }
32
51
 
33
- /** WebP, RIFF....WEBP: the VP8X, VP8L or VP8 chunk's size. */
52
+ /** PNG: IHDR width/height, swapped when an eXIf or ImageMagick orNT chunk carries orientation 5..8. */
53
+ function pngDimensions(bytes: Uint8Array, view: DataView): { width: number, height: number } | undefined {
54
+ const width = view.getUint32(16)
55
+ const height = view.getUint32(20)
56
+ if (width === 0 || height === 0)
57
+ return undefined
58
+ const len = bytes.byteLength
59
+ let orientation = 1
60
+ let at = 8
61
+ while (at + 12 <= len) {
62
+ const size = view.getUint32(at)
63
+ const dataStart = at + 8
64
+ const dataEnd = dataStart + size
65
+ if (size > len - at - 12)
66
+ break
67
+ const type = view.getUint32(at + 4)
68
+ if (type === 0x65584966) {
69
+ // Standard PNG eXIf chunk (raw TIFF, or Exif\0\0 + TIFF).
70
+ orientation = rawOrPrefixedExifOrientation(view, dataStart, dataEnd)
71
+ }
72
+ else if (type === 0x6F724E54 && size >= 1 && orientation === 1) {
73
+ // ImageMagick orNT chunk: single-byte EXIF orientation (1..8).
74
+ orientation = bytes[dataStart]!
75
+ }
76
+ else if (type === 0x49454E44) {
77
+ break
78
+ }
79
+ at = dataEnd + 4
80
+ }
81
+ return applyOrientation(width, height, orientation)
82
+ }
83
+
84
+ /** WebP, RIFF....WEBP: the VP8X, VP8L or VP8 chunk's size, swapped when a VP8X EXIF chunk carries orientation 5..8. */
34
85
  function webpDimensions(bytes: Uint8Array, view: DataView): { width: number, height: number } | undefined {
35
86
  const len = bytes.byteLength
36
87
  const chunk = view.getUint32(12)
@@ -38,7 +89,19 @@ function webpDimensions(bytes: Uint8Array, view: DataView): { width: number, hei
38
89
  if (chunk === 0x56503858) {
39
90
  const width = 1 + (bytes[24]! | (bytes[25]! << 8) | (bytes[26]! << 16))
40
91
  const height = 1 + (bytes[27]! | (bytes[28]! << 8) | (bytes[29]! << 16))
41
- return { width, height }
92
+ let orientation = 1
93
+ let at = 12
94
+ while (at + 8 <= len) {
95
+ const size = view.getUint32(at + 4, true)
96
+ if (size > len - at - 8)
97
+ break
98
+ if (view.getUint32(at) === 0x45584946) {
99
+ orientation = rawOrPrefixedExifOrientation(view, at + 8, at + 8 + size)
100
+ break
101
+ }
102
+ at += 8 + size + (size & 1)
103
+ }
104
+ return applyOrientation(width, height, orientation)
42
105
  }
43
106
  // VP8L lossless
44
107
  if (chunk === 0x5650384C && len >= 25 && bytes[20] === 0x2F) {
@@ -54,9 +117,166 @@ function webpDimensions(bytes: Uint8Array, view: DataView): { width: number, hei
54
117
  return undefined
55
118
  }
56
119
 
57
- /** AVIF / HEIF (ISOBMFF): ftyp, then meta -> iprp -> ipco -> the 'ispe' full box, its version and flags then uint32BE width and height. */
120
+ interface IsoBox {
121
+ type: number
122
+ payloadStart: number
123
+ end: number
124
+ }
125
+
126
+ function readIsoBox(view: DataView, at: number, limit: number): IsoBox | undefined {
127
+ if (at + 8 > limit)
128
+ return undefined
129
+ let size = view.getUint32(at)
130
+ const type = view.getUint32(at + 4)
131
+ let headerLen = 8
132
+ if (size === 0) {
133
+ size = limit - at
134
+ }
135
+ else if (size === 1) {
136
+ if (at + 16 > limit)
137
+ return undefined
138
+ const hi = view.getUint32(at + 8)
139
+ const lo = view.getUint32(at + 12)
140
+ if (hi > 0x1FFFFF)
141
+ return undefined
142
+ size = hi * 0x100000000 + lo
143
+ headerLen = 16
144
+ }
145
+ if (size < headerLen || at + size > limit)
146
+ return undefined
147
+ return { type, payloadStart: at + headerLen, end: at + size }
148
+ }
149
+
150
+ function parseIpmaBox(bytes: Uint8Array, view: DataView, start: number, end: number, assocs: Map<number, number[]>): void {
151
+ if (start + 8 > end)
152
+ return
153
+ const version = bytes[start]!
154
+ const largeProp = (bytes[start + 3]! & 1) !== 0
155
+ const entryCount = view.getUint32(start + 4)
156
+ let cur = start + 8
157
+ for (let e = 0; e < entryCount; e++) {
158
+ const idSize = version < 1 ? 2 : 4
159
+ if (cur + idSize + 1 > end)
160
+ return
161
+ const itemId = version < 1 ? view.getUint16(cur) : view.getUint32(cur)
162
+ cur += idSize
163
+ const assocCount = bytes[cur++]!
164
+ let list = assocs.get(itemId)
165
+ if (list === undefined) {
166
+ list = []
167
+ assocs.set(itemId, list)
168
+ }
169
+ for (let a = 0; a < assocCount; a++) {
170
+ if (largeProp) {
171
+ if (cur + 2 > end)
172
+ return
173
+ list.push(view.getUint16(cur) & 0x7FFF)
174
+ cur += 2
175
+ }
176
+ else {
177
+ if (cur + 1 > end)
178
+ return
179
+ list.push(bytes[cur++]! & 0x7F)
180
+ }
181
+ }
182
+ }
183
+ }
184
+
185
+ function parseIprpBox(
186
+ bytes: Uint8Array,
187
+ view: DataView,
188
+ start: number,
189
+ end: number,
190
+ ispes: Map<number, { width: number, height: number }>,
191
+ irots: Map<number, number>,
192
+ assocs: Map<number, number[]>,
193
+ ): void {
194
+ let at = start
195
+ while (at < end) {
196
+ const box = readIsoBox(view, at, end)
197
+ if (box === undefined)
198
+ break
199
+ if (box.type === 0x6970636F) {
200
+ // ipco: 1-based property list
201
+ let pAt = box.payloadStart
202
+ let idx = 1
203
+ while (pAt < box.end) {
204
+ const prop = readIsoBox(view, pAt, box.end)
205
+ if (prop === undefined)
206
+ break
207
+ if (prop.type === 0x69737065 && prop.end - prop.payloadStart >= 12) {
208
+ const width = view.getUint32(prop.payloadStart + 4)
209
+ const height = view.getUint32(prop.payloadStart + 8)
210
+ if (width > 0 && height > 0 && width <= 65535 && height <= 65535)
211
+ ispes.set(idx, { width, height })
212
+ }
213
+ else if (prop.type === 0x69726F74 && prop.end - prop.payloadStart >= 1) {
214
+ irots.set(idx, bytes[prop.payloadStart]! & 0x03)
215
+ }
216
+ idx++
217
+ pAt = prop.end
218
+ }
219
+ }
220
+ else if (box.type === 0x69706D61) {
221
+ parseIpmaBox(bytes, view, box.payloadStart, box.end, assocs)
222
+ }
223
+ at = box.end
224
+ }
225
+ }
226
+
227
+ /** AVIF / HEIF (ISOBMFF): meta -> pitm + iprp (ipco ispe/irot + ipma), swapping width and height for 90°/270° irot. */
58
228
  function isobmffDimensions(bytes: Uint8Array, view: DataView): { width: number, height: number } | undefined {
59
- for (let i = 12; i + 16 <= bytes.byteLength; i++) {
229
+ const len = bytes.byteLength
230
+ let at = 0
231
+ while (at < len) {
232
+ const box = readIsoBox(view, at, len)
233
+ if (box === undefined)
234
+ break
235
+ if (box.type === 0x6D657461 && box.payloadStart + 4 <= box.end) {
236
+ let primaryId: number | undefined
237
+ const ispes = new Map<number, { width: number, height: number }>()
238
+ const irots = new Map<number, number>()
239
+ const assocs = new Map<number, number[]>()
240
+ let mAt = box.payloadStart + 4
241
+ while (mAt < box.end) {
242
+ const child = readIsoBox(view, mAt, box.end)
243
+ if (child === undefined)
244
+ break
245
+ if (child.type === 0x7069746D && child.end - child.payloadStart >= 6) {
246
+ const version = bytes[child.payloadStart]!
247
+ if (version === 0)
248
+ primaryId = view.getUint16(child.payloadStart + 4)
249
+ else if (child.end - child.payloadStart >= 8)
250
+ primaryId = view.getUint32(child.payloadStart + 4)
251
+ }
252
+ else if (child.type === 0x69707270) {
253
+ parseIprpBox(bytes, view, child.payloadStart, child.end, ispes, irots, assocs)
254
+ }
255
+ mAt = child.end
256
+ }
257
+ const itemProps = primaryId !== undefined ? assocs.get(primaryId) : undefined
258
+ let dims: { width: number, height: number } | undefined
259
+ let angle = 0
260
+ if (itemProps !== undefined) {
261
+ for (const propIdx of itemProps) {
262
+ dims ??= ispes.get(propIdx)
263
+ const rot = irots.get(propIdx)
264
+ if (rot !== undefined)
265
+ angle = (angle + rot) & 3
266
+ }
267
+ }
268
+ else {
269
+ dims = ispes.values().next().value
270
+ for (const rot of irots.values())
271
+ angle = (angle + rot) & 3
272
+ }
273
+ if (dims !== undefined)
274
+ return (angle & 1) === 1 ? { width: dims.height, height: dims.width } : dims
275
+ }
276
+ at = box.end
277
+ }
278
+ // Fallback for minimal fixtures that embed an 'ispe' box without a full meta container.
279
+ for (let i = 12; i + 16 <= len; i++) {
60
280
  if (bytes[i] === 0x69 && bytes[i + 1] === 0x73 && bytes[i + 2] === 0x70 && bytes[i + 3] === 0x65) {
61
281
  const width = view.getUint32(i + 8)
62
282
  const height = view.getUint32(i + 12)
@@ -105,26 +325,130 @@ function jpegDimensions(bytes: Uint8Array, view: DataView): { width: number, hei
105
325
  return undefined
106
326
  }
107
327
 
108
- /** The Orientation tag (0x0112) of an APP1 segment's first IFD, or 1 when it is no Exif segment, has none or is cut short. */
109
- function exifOrientation(view: DataView, start: number, end: number): number {
110
- // "Exif\0\0", then a TIFF header: II or MM, 42, the offset of the first IFD.
111
- if (end - start < 14 || view.getUint32(start) !== 0x45786966 || view.getUint16(start + 4) !== 0)
112
- return 1
113
- const tiff = start + 6
328
+ /** Reads ImageWidth (0x0100), ImageLength (0x0101), and Orientation (0x0112) from a TIFF header's first IFD. */
329
+ function tiffIfdInfo(view: DataView, tiff: number, end: number): { width?: number | undefined, height?: number | undefined, orientation: number } {
330
+ if (end - tiff < 8)
331
+ return { orientation: 1 }
114
332
  const order = view.getUint16(tiff)
115
333
  if (order !== 0x4949 && order !== 0x4D4D)
116
- return 1
334
+ return { orientation: 1 }
117
335
  const little = order === 0x4949
336
+ if (view.getUint16(tiff + 2, little) !== 42)
337
+ return { orientation: 1 }
118
338
  const ifd = tiff + view.getUint32(tiff + 4, little)
119
- if (ifd + 2 > end)
120
- return 1
339
+ if (ifd < tiff || ifd + 2 > end)
340
+ return { orientation: 1 }
121
341
  const count = view.getUint16(ifd, little)
342
+ let width: number | undefined
343
+ let height: number | undefined
344
+ let orientation = 1
122
345
  for (let i = 0; i < count; i++) {
123
346
  const entry = ifd + 2 + i * 12
124
347
  if (entry + 12 > end)
125
- return 1
126
- if (view.getUint16(entry, little) === 0x0112)
127
- return view.getUint16(entry + 8, little)
348
+ break
349
+ const tag = view.getUint16(entry, little)
350
+ const type = view.getUint16(entry + 2, little)
351
+ if (tag === 0x0112)
352
+ orientation = view.getUint16(entry + 8, little)
353
+ else if (tag === 0x0100)
354
+ width = type === 3 ? view.getUint16(entry + 8, little) : type === 4 ? view.getUint32(entry + 8, little) : undefined
355
+ else if (tag === 0x0101)
356
+ height = type === 3 ? view.getUint16(entry + 8, little) : type === 4 ? view.getUint32(entry + 8, little) : undefined
357
+ }
358
+ return { width, height, orientation }
359
+ }
360
+
361
+ /** The Orientation tag (0x0112) of an APP1 segment's first IFD, or 1 when it is no Exif segment, has none or is cut short. */
362
+ function exifOrientation(view: DataView, start: number, end: number): number {
363
+ if (end - start < 14 || view.getUint32(start) !== 0x45786966 || view.getUint16(start + 4) !== 0)
364
+ return 1
365
+ return tiffIfdInfo(view, start + 6, end).orientation
366
+ }
367
+
368
+ function bmpDimensions(view: DataView): { width: number, height: number } | undefined {
369
+ const dibSize = view.getUint32(14, true)
370
+ const width = dibSize === 12 ? view.getUint16(18, true) : dibSize >= 40 ? view.getInt32(18, true) : 0
371
+ const height = dibSize === 12 ? view.getUint16(20, true) : dibSize >= 40 ? Math.abs(view.getInt32(22, true)) : 0
372
+ return width > 0 && height > 0 ? { width, height } : undefined
373
+ }
374
+
375
+ function icoDimensions(bytes: Uint8Array, view: DataView): { width: number, height: number } | undefined {
376
+ const count = view.getUint16(4, true)
377
+ if (count === 0)
378
+ return undefined
379
+ let bestW = 0
380
+ let bestH = 0
381
+ for (let i = 0; i < count; i++) {
382
+ const entry = 6 + i * 16
383
+ if (entry + 16 > bytes.byteLength)
384
+ break
385
+ const w = bytes[entry] === 0 ? 256 : bytes[entry]!
386
+ const h = bytes[entry + 1] === 0 ? 256 : bytes[entry + 1]!
387
+ if (w * h > bestW * bestH) {
388
+ bestW = w
389
+ bestH = h
390
+ }
128
391
  }
129
- return 1
392
+ return bestW > 0 && bestH > 0 ? { width: bestW, height: bestH } : undefined
393
+ }
394
+
395
+ function tiffDimensions(view: DataView, len: number): { width: number, height: number } | undefined {
396
+ const { width, height, orientation } = tiffIfdInfo(view, 0, len)
397
+ if (width === undefined || height === undefined || width <= 0 || height <= 0)
398
+ return undefined
399
+ return orientation >= 5 && orientation <= 8 ? { width: height, height: width } : { width, height }
400
+ }
401
+
402
+ function parseSvgLength(value: string | undefined): number | undefined {
403
+ const match = value === undefined ? null : SVG_PX_RE.exec(value)
404
+ if (match === null)
405
+ return undefined
406
+ const num = Number(match[1])
407
+ return Number.isFinite(num) && num > 0 ? num : undefined
408
+ }
409
+
410
+ function svgDimensions(bytes: Uint8Array): { width: number, height: number } | undefined {
411
+ let at = bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF ? 3 : 0
412
+ while (at < bytes.byteLength && (bytes[at] === 0x20 || bytes[at] === 0x09 || bytes[at] === 0x0A || bytes[at] === 0x0D))
413
+ at++
414
+ if (at >= bytes.byteLength || bytes[at] !== 0x3C)
415
+ return undefined
416
+ const head = new TextDecoder().decode(bytes.subarray(at, Math.min(bytes.byteLength, at + 8192)))
417
+ const tag = SVG_OPEN_TAG_RE.exec(head)
418
+ if (tag === null)
419
+ return undefined
420
+ let width: number | undefined
421
+ let height: number | undefined
422
+ let viewBox: string | undefined
423
+ SVG_ATTR_RE.lastIndex = 0
424
+ for (const [, name, dbl, sgl] of tag[1]!.matchAll(SVG_ATTR_RE)) {
425
+ const val = dbl ?? sgl ?? ''
426
+ const lower = name!.toLowerCase()
427
+ if (lower === 'width')
428
+ width = parseSvgLength(val)
429
+ else if (lower === 'height')
430
+ height = parseSvgLength(val)
431
+ else if (lower === 'viewbox')
432
+ viewBox = val
433
+ }
434
+ if (width === undefined || height === undefined) {
435
+ const parts = viewBox?.trim().split(SVG_BOX_SEP_RE).map(Number)
436
+ if (parts !== undefined && parts.length === 4 && parts.every(Number.isFinite) && parts[2]! > 0 && parts[3]! > 0) {
437
+ const vw = parts[2]!
438
+ const vh = parts[3]!
439
+ if (width !== undefined)
440
+ height = width * (vh / vw)
441
+ else if (height !== undefined)
442
+ width = height * (vw / vh)
443
+ else {
444
+ width = vw
445
+ height = vh
446
+ }
447
+ }
448
+ }
449
+ if (width === undefined || height === undefined)
450
+ return undefined
451
+ const w = Math.round(width)
452
+ const h = Math.round(height)
453
+ return w > 0 && h > 0 ? { width: w, height: h } : undefined
130
454
  }
@@ -0,0 +1,251 @@
1
+ /** Metadata a file can carry about the person or device behind it. */
2
+ export type ImageMetadataKind = 'exif' | 'xmp' | 'iptc' | 'comment' | 'text'
3
+
4
+ export interface StrippedImage {
5
+ /** The image without its metadata, the input itself when nothing was removed. */
6
+ bytes: Uint8Array<ArrayBuffer>
7
+ removed: ImageMetadataKind[]
8
+ }
9
+
10
+ const EXIF_HEADER = [0x45, 0x78, 0x69, 0x66, 0x00, 0x00]
11
+
12
+ function ascii(bytes: Uint8Array, at: number, length: number): string {
13
+ return String.fromCharCode(...bytes.subarray(at, at + length))
14
+ }
15
+
16
+ function concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
17
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
18
+ let at = 0
19
+ for (const part of parts) {
20
+ out.set(part, at)
21
+ at += part.length
22
+ }
23
+ return out
24
+ }
25
+
26
+ // The EXIF Orientation tag of IFD0 (from either raw TIFF or an `Exif\0\0`-prefixed payload), so a stripped photo still displays the right way up.
27
+ function exifOrientation(payload: Uint8Array): number | undefined {
28
+ const hasPrefix = payload.length >= EXIF_HEADER.length && EXIF_HEADER.every((b, i) => payload[i] === b)
29
+ const tiff = hasPrefix ? payload.subarray(EXIF_HEADER.length) : payload
30
+ if (tiff.length < 8)
31
+ return undefined
32
+ const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength)
33
+ const order = view.getUint16(0)
34
+ if (order !== 0x4949 && order !== 0x4D4D)
35
+ return undefined
36
+ const little = order === 0x4949
37
+ if (view.getUint16(2, little) !== 42)
38
+ return undefined
39
+ const ifd = view.getUint32(4, little)
40
+ if (ifd + 2 > tiff.length)
41
+ return undefined
42
+ const count = view.getUint16(ifd, little)
43
+ for (let i = 0; i < count; i++) {
44
+ const entry = ifd + 2 + i * 12
45
+ if (entry + 12 > tiff.length)
46
+ return undefined
47
+ if (view.getUint16(entry, little) === 0x0112)
48
+ return view.getUint16(entry + 8, little)
49
+ }
50
+ return undefined
51
+ }
52
+
53
+ // A minimal big-endian TIFF IFD0 carrying only the Orientation tag (26 bytes, even length).
54
+ function orientationTiff(orientation: number): Uint8Array {
55
+ return new Uint8Array([
56
+ 0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08,
57
+ 0x00, 0x01, 0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, orientation >> 8, orientation & 0xFF, 0x00, 0x00,
58
+ 0x00, 0x00, 0x00, 0x00,
59
+ ])
60
+ }
61
+
62
+ // An APP1 segment holding only an Orientation tag.
63
+ function orientationSegment(orientation: number): Uint8Array {
64
+ return new Uint8Array([0xFF, 0xE1, 0x00, 0x22, ...EXIF_HEADER, ...orientationTiff(orientation)])
65
+ }
66
+
67
+ const CRC32_TABLE = new Uint32Array(256)
68
+ for (let n = 0; n < 256; n++) {
69
+ let c = n
70
+ for (let k = 0; k < 8; k++) c = (c & 1) !== 0 ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)
71
+ CRC32_TABLE[n] = c >>> 0
72
+ }
73
+
74
+ function crc32(bytes: Uint8Array): number {
75
+ let c = 0xFFFFFFFF
76
+ for (let i = 0; i < bytes.length; i++)
77
+ c = CRC32_TABLE[(c ^ bytes[i]!) & 0xFF]! ^ (c >>> 8)
78
+ return (c ^ 0xFFFFFFFF) >>> 0
79
+ }
80
+
81
+ function pngOrientationChunk(orientation: number): Uint8Array {
82
+ const tiff = orientationTiff(orientation)
83
+ const chunk = new Uint8Array(12 + tiff.length)
84
+ const view = new DataView(chunk.buffer)
85
+ view.setUint32(0, tiff.length)
86
+ chunk.set([0x65, 0x58, 0x49, 0x66], 4)
87
+ chunk.set(tiff, 8)
88
+ view.setUint32(8 + tiff.length, crc32(chunk.subarray(4, 8 + tiff.length)))
89
+ return chunk
90
+ }
91
+
92
+ function webpOrientationChunk(orientation: number): Uint8Array {
93
+ const tiff = orientationTiff(orientation)
94
+ const chunk = new Uint8Array(8 + tiff.length)
95
+ chunk.set([0x45, 0x58, 0x49, 0x46], 0)
96
+ new DataView(chunk.buffer).setUint32(4, tiff.length, true)
97
+ chunk.set(tiff, 8)
98
+ return chunk
99
+ }
100
+
101
+ function jpegSegmentKind(marker: number, payload: Uint8Array): ImageMetadataKind | undefined {
102
+ if (marker === 0xE1)
103
+ return EXIF_HEADER.every((b, i) => payload[i] === b) ? 'exif' : 'xmp'
104
+ if (marker === 0xED)
105
+ return 'iptc'
106
+ if (marker === 0xFE)
107
+ return 'comment'
108
+ return undefined
109
+ }
110
+
111
+ function isStandaloneJpegMarker(marker: number): boolean {
112
+ return marker === 0x01 || (marker >= 0xD0 && marker <= 0xD7) || marker === 0xD9
113
+ }
114
+
115
+ function stripJpeg(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
116
+ const kept: Uint8Array[] = [bytes.subarray(0, 2)]
117
+ const removed = new Set<ImageMetadataKind>()
118
+ let orientation: number | undefined
119
+ let insertAt = 1
120
+ let at = 2
121
+ while (at < bytes.length) {
122
+ if (bytes[at] !== 0xFF)
123
+ return { bytes, removed: [] }
124
+ const start = at
125
+ while (at < bytes.length && bytes[at] === 0xFF)
126
+ at++
127
+ if (at >= bytes.length)
128
+ return { bytes, removed: [] }
129
+ const marker = bytes[at]!
130
+ if (marker === 0x00)
131
+ return { bytes, removed: [] }
132
+ if (marker === 0xDA) {
133
+ kept.push(bytes.subarray(start))
134
+ at = bytes.length
135
+ break
136
+ }
137
+ if (isStandaloneJpegMarker(marker)) {
138
+ kept.push(bytes.subarray(start, at + 1))
139
+ at += 1
140
+ if (marker === 0xD9)
141
+ break
142
+ continue
143
+ }
144
+ if (at + 3 > bytes.length)
145
+ return { bytes, removed: [] }
146
+ const length = (bytes[at + 1]! << 8) | bytes[at + 2]!
147
+ const end = at + 1 + length
148
+ if (length < 2 || end > bytes.length)
149
+ return { bytes, removed: [] }
150
+ const payload = bytes.subarray(at + 3, end)
151
+ const kind = jpegSegmentKind(marker, payload)
152
+ if (kind === undefined) {
153
+ if (kept.length === 1 && marker === 0xE0)
154
+ insertAt = 2
155
+ kept.push(bytes.subarray(start, end))
156
+ }
157
+ else {
158
+ removed.add(kind)
159
+ if (kind === 'exif')
160
+ orientation ??= exifOrientation(payload)
161
+ }
162
+ at = end
163
+ }
164
+ if (at !== bytes.length || removed.size === 0)
165
+ return { bytes, removed: [] }
166
+ if (orientation !== undefined && orientation > 1 && orientation <= 8)
167
+ kept.splice(insertAt, 0, orientationSegment(orientation))
168
+ return { bytes: concat(kept), removed: [...removed] }
169
+ }
170
+
171
+ const PNG_METADATA: Record<string, ImageMetadataKind> = { eXIf: 'exif', iTXt: 'text', tEXt: 'text', zTXt: 'text', tIME: 'text' }
172
+
173
+ function stripPng(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
174
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
175
+ const kept: Uint8Array[] = [bytes.subarray(0, 8)]
176
+ const removed = new Set<ImageMetadataKind>()
177
+ let orientation: number | undefined
178
+ let at = 8
179
+ while (at + 12 <= bytes.length) {
180
+ const size = view.getUint32(at)
181
+ const end = at + 12 + size
182
+ if (size > bytes.length - at - 12 || end > bytes.length)
183
+ return { bytes, removed: [] }
184
+ const type = ascii(bytes, at + 4, 4)
185
+ const kind = type === 'iTXt' && ascii(bytes, at + 8, 17) === 'XML:com.adobe.xmp' ? 'xmp' : PNG_METADATA[type]
186
+ if (kind === undefined) {
187
+ kept.push(bytes.subarray(at, end))
188
+ }
189
+ else {
190
+ removed.add(kind)
191
+ if (kind === 'exif')
192
+ orientation ??= exifOrientation(bytes.subarray(at + 8, at + 8 + size))
193
+ }
194
+ at = end
195
+ }
196
+ if (at !== bytes.length || removed.size === 0)
197
+ return { bytes, removed: [] }
198
+ if (orientation !== undefined && orientation > 1 && orientation <= 8)
199
+ kept.splice(kept.length > 1 ? 2 : 1, 0, pngOrientationChunk(orientation))
200
+ return { bytes: concat(kept), removed: [...removed] }
201
+ }
202
+
203
+ const WEBP_METADATA: Record<string, ImageMetadataKind> = { 'EXIF': 'exif', 'XMP ': 'xmp' }
204
+
205
+ function stripWebp(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
206
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
207
+ const kept: Uint8Array[] = []
208
+ const removed = new Set<ImageMetadataKind>()
209
+ let orientation: number | undefined
210
+ let at = 12
211
+ while (at + 8 <= bytes.length) {
212
+ const size = view.getUint32(at + 4, true)
213
+ const end = Math.min(at + 8 + size + (size & 1), bytes.length)
214
+ if (size > bytes.length - at - 8 || at + 8 + size > bytes.length)
215
+ return { bytes, removed: [] }
216
+ const kind = WEBP_METADATA[ascii(bytes, at, 4)]
217
+ if (kind === undefined) {
218
+ kept.push(bytes.slice(at, end))
219
+ }
220
+ else {
221
+ removed.add(kind)
222
+ if (kind === 'exif')
223
+ orientation ??= exifOrientation(bytes.subarray(at + 8, at + 8 + size))
224
+ }
225
+ at = end
226
+ }
227
+ if (removed.size === 0)
228
+ return { bytes, removed: [] }
229
+ const keptOrientation = orientation !== undefined && orientation > 1 && orientation <= 8 ? orientation : undefined
230
+ const vp8x = kept.find(chunk => ascii(chunk, 0, 4) === 'VP8X')
231
+ if (vp8x !== undefined)
232
+ vp8x[8] = keptOrientation !== undefined ? ((vp8x[8]! & ~0x04) | 0x08) : (vp8x[8]! & ~0x0C)
233
+ if (keptOrientation !== undefined)
234
+ kept.push(webpOrientationChunk(keptOrientation))
235
+ const body = concat(kept)
236
+ const header = new Uint8Array(12)
237
+ header.set(bytes.subarray(0, 12))
238
+ new DataView(header.buffer).setUint32(4, body.length + 4, true)
239
+ return { bytes: concat([header, body]), removed: [...removed] }
240
+ }
241
+
242
+ /** Removes EXIF (GPS position, device serial), XMP, IPTC and text metadata from a JPEG, PNG or WebP file while preserving its EXIF orientation. Other formats and unreadable files come back unchanged. */
243
+ export function stripImageMetadata(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
244
+ if (bytes[0] === 0xFF && bytes[1] === 0xD8)
245
+ return stripJpeg(bytes)
246
+ if (ascii(bytes, 1, 3) === 'PNG')
247
+ return stripPng(bytes)
248
+ if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP')
249
+ return stripWebp(bytes)
250
+ return { bytes, removed: [] }
251
+ }
package/src/pipeline.ts CHANGED
@@ -35,6 +35,9 @@ function magickBinary(): string {
35
35
  return magickBin.bin
36
36
  }
37
37
 
38
+ /** Every profile goes (EXIF with its GPS position, XMP, IPTC) except the ICC one, which `-strip` also drops and which keeps a wide-gamut photo in its colours. */
39
+ export const DROP_METADATA_KEEP_ICC = ['+profile', '!icc,*']
40
+
38
41
  let activeSlots = 0
39
42
  const waitingForSlot: (() => void)[] = []
40
43
 
@@ -149,7 +152,7 @@ async function encodeFormatAsync(srcPath: string, jobs: readonly VariantEncodeJo
149
152
  const result = await runMagick([
150
153
  `${srcPath}[0]`,
151
154
  '-auto-orient',
152
- '-strip',
155
+ ...DROP_METADATA_KEEP_ICC,
153
156
  '-write',
154
157
  'mpr:src',
155
158
  '+delete',
@@ -196,8 +199,8 @@ export async function encodeVariants(srcPath: string, jobs: readonly VariantEnco
196
199
  return jobs.filter(job => existsSync(job.cachedFile))
197
200
  }
198
201
 
199
- // Bumped when the same source and options give other variants or sizes, so a cache from before is not reused: 2 sizes photos after their EXIF orientation (#3676).
200
- const VARIANT_CACHE_VERSION = 2
202
+ // Bumped when the same source and options give other variants or sizes, so a cache from before is not reused: 2 sizes photos after their EXIF orientation (#3676), 3 keeps their ICC profile (#257), 4 sizes rotated PNG, WebP and AVIF after their orientation (#171).
203
+ const VARIANT_CACHE_VERSION = 4
201
204
 
202
205
  export function computeImageKey(srcPath: string, rawBytes: Uint8Array, cfg: VariantPipelineConfig): { hash: string, stem: string, rawFileName: string } {
203
206
  const ext = extname(srcPath).toLowerCase()
package/src/plugin.ts CHANGED
@@ -2,17 +2,20 @@
2
2
  // Built strictly on the public PrunellePlugin API (bunPlugins + build(ctx).emitAsset).
3
3
 
4
4
  import type { BunPlugin } from 'bun'
5
- import type { PrunellePlugin } from 'prunelle/config'
5
+ import type { CheckPluginContext, PrunellePlugin } from 'prunelle/config'
6
6
  import type { ShareCardDefaults } from './card'
7
7
  import type { ImageAsset } from './helpers'
8
8
  import type { CachedImageMeta, VariantPipelineConfig } from './pipeline'
9
9
  import type { RuntimeImageStore } from './runtime'
10
10
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
11
- import { dirname, extname, join, resolve } from 'node:path'
11
+ import { dirname, extname, join, relative, resolve } from 'node:path'
12
12
  import { CONTENT_IMAGE_RESOLVER_SERVICE, definePlugin, isInside } from 'prunelle/config'
13
13
  import { getAppContext } from 'prunelle/internal/server'
14
+ import type { KnownImages } from './cache'
15
+ import { knownImages, removeUnusedOgAndMd, runtimeStoreLimits } from './cache'
14
16
  import { SHARE_CARD_CONFIG_SERVICE } from './card'
15
17
  import { readImageDimensions } from './dimensions'
18
+ import { stripImageMetadata } from './metadata'
16
19
  import {
17
20
  ALLOWED_IMAGE_EXTS,
18
21
  assembleImageAsset,
@@ -58,9 +61,49 @@ export interface ImagesPluginOptions {
58
61
 
59
62
  const DEFAULT_WIDTHS = [320, 640, 960, 1280, 1920]
60
63
  const DEFAULT_FORMATS: ('avif' | 'webp')[] = ['avif', 'webp']
64
+ const PUBLIC_IMAGE = /\.(?:png|jpe?g|webp)$/i
65
+ const PERSONAL_METADATA = new Set(['exif', 'xmp', 'iptc'])
66
+ // Formats shipped as-is rather than rasterized to AVIF/WebP variants.
67
+ const RAW_ONLY_IMAGE_EXTS = new Set(['.svg', '.ico'])
68
+ // Non-core Markdown image formats that fall back to the original <img> when their header cannot be parsed.
69
+ const FALLBACK_MARKDOWN_EXTS = new Set(['.ico', '.bmp', '.tif', '.tiff'])
70
+
71
+ function walkPublicImages(dir: string, out: string[] = []): string[] {
72
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
73
+ const abs = join(dir, entry.name)
74
+ if (entry.isDirectory())
75
+ walkPublicImages(abs, out)
76
+ else if (entry.isFile() && PUBLIC_IMAGE.test(entry.name))
77
+ out.push(abs)
78
+ }
79
+ return out
80
+ }
81
+
82
+ // Files in publicDir are served as they are, so a photo there hands its GPS position and camera serial to every visitor.
83
+ function publicImageMetadataWarnings(root: string, publicDir: string): string[] {
84
+ if (!existsSync(publicDir))
85
+ return []
86
+ const warnings: string[] = []
87
+ for (const abs of walkPublicImages(publicDir).sort()) {
88
+ const kinds = stripImageMetadata(new Uint8Array(readFileSync(abs))).removed.filter(kind => PERSONAL_METADATA.has(kind))
89
+ if (kinds.length > 0) {
90
+ const rel = relative(root, abs).replace(/\\/g, '/')
91
+ warnings.push(`@prunellejs/images: ${rel} carries ${kinds.map(k => k.toUpperCase()).join(' and ')} metadata (GPS position, camera serial) that every visitor can download: import it from src/ so the build strips it, or strip it yourself (\`magick ${rel} +profile "!icc,*" ${rel}\`, which keeps the ICC colour profile).`)
92
+ }
93
+ }
94
+ return warnings
95
+ }
96
+
97
+ function checkImages(ctx: CheckPluginContext): void {
98
+ if (!hasMagick())
99
+ ctx.error(MISSING_MAGICK_MESSAGE)
100
+ for (const warning of publicImageMetadataWarnings(ctx.root, ctx.publicDir ?? join(ctx.root, 'public')))
101
+ ctx.warn(warning)
102
+ }
103
+
61
104
  const MISSING_MAGICK_MESSAGE = '@prunellejs/images: ImageMagick ("magick") was not found on PATH; AVIF/WebP optimization is disabled. Install ImageMagick to enable responsive image optimization.'
62
105
 
63
- interface PersistedImagesConfig {
106
+ interface PersistedImagesConfig extends KnownImages {
64
107
  cacheDirRel: string
65
108
  widths: number[]
66
109
  formats: ('avif' | 'webp')[]
@@ -92,10 +135,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
92
135
 
93
136
  return definePlugin({
94
137
  name: '@prunellejs/images',
95
- check(ctx) {
96
- if (!hasMagick())
97
- ctx.error(MISSING_MAGICK_MESSAGE)
98
- },
138
+ check: checkImages,
99
139
  bunPlugins: ({ root, assetPrefix }): BunPlugin[] => {
100
140
  const cacheRoot = resolve(root, cacheDirRel)
101
141
  lastCacheRoot = cacheRoot
@@ -112,7 +152,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
112
152
  if (args.path.includes('/node_modules/'))
113
153
  return undefined
114
154
 
115
- const rawBytes = new Uint8Array(readFileSync(args.path))
155
+ const rawBytes = stripImageMetadata(new Uint8Array(readFileSync(args.path))).bytes
116
156
  const { hash, stem, rawFileName } = computeImageKey(args.path, rawBytes, pipelineCfg)
117
157
  const emitRaw = (width: number, height: number) => {
118
158
  const rel = `img/${rawFileName}`
@@ -202,12 +242,16 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
202
242
  },
203
243
  async afterPrerender(ctx) {
204
244
  await flushBuildPhase(ctx.outDir)
245
+ ctx.setData(knownImages(ctx.publicFiles))
246
+ // Only a build that rendered pages registered the cards and variants it uses: without one the runtime still reads those cache files.
247
+ if (pruneCache && lastCacheRoot !== undefined && ctx.routes.some(route => Object.keys(route.prerendered ?? {}).length > 0))
248
+ removeUnusedOgAndMd(lastCacheRoot, ctx.publicFiles)
205
249
  },
206
250
  server(api) {
207
251
  const persisted = api.getBuildData<PersistedImagesConfig>()
208
252
  const publicDir = join(api.outDir, 'public')
209
253
  const cacheDir = resolve(api.root, persisted?.cacheDirRel ?? cacheDirRel)
210
- const runtimeStore = createRuntimeImageStore()
254
+ const runtimeStore = createRuntimeImageStore(...runtimeStoreLimits(persisted))
211
255
  api.provide(RUNTIME_IMAGE_STORE_SERVICE, runtimeStore)
212
256
  registerRuntimeImageMiddleware(api, runtimeStore)
213
257
  api.onShutdown(() => {
@@ -270,7 +314,7 @@ function optimizeForRuntime(
270
314
  return { body: bytes, contentType: mime, etag: computeEtag(bytes) }
271
315
  }
272
316
  catch {
273
- return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
317
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
274
318
  }
275
319
  })
276
320
  })
@@ -289,7 +333,7 @@ function optimizeForRuntime(
289
333
  const encoded = await encodeVariantToBytesAsync(absPath, job.width, job.format, job.quality)
290
334
  if (encoded !== undefined)
291
335
  return { body: encoded, contentType: targetMime, etag: computeEtag(encoded) }
292
- return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
336
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
293
337
  })
294
338
  })
295
339
  }
@@ -308,8 +352,9 @@ export function optimizeImageFile(absPath: string, options: OptimizeImageFileOpt
308
352
  cachePrefix: 'md-',
309
353
  }
310
354
  const appCtx = getAppContext()
311
- const rawBytes = new Uint8Array(readFileSync(absPath))
312
- const dims = readImageDimensions(rawBytes)
355
+ const rawBytes = stripImageMetadata(new Uint8Array(readFileSync(absPath))).bytes
356
+ const isRawOnly = RAW_ONLY_IMAGE_EXTS.has(ext)
357
+ const dims = readImageDimensions(rawBytes) ?? (ext === '.svg' ? { width: 0, height: 0 } : undefined)
313
358
  if (dims === undefined)
314
359
  throw new Error(`@prunellejs/images: could not determine dimensions for "${absPath}"`)
315
360
 
@@ -319,8 +364,13 @@ export function optimizeImageFile(absPath: string, options: OptimizeImageFileOpt
319
364
 
320
365
  // Runtime server mode (including --compile): never write to dist/public or block on Bun.spawnSync.
321
366
  const runtimeStore = options.outPublicDir === undefined ? appCtx?.inject(RUNTIME_IMAGE_STORE_SERVICE) : undefined
322
- if (runtimeStore !== undefined && !inBuild)
367
+ if (runtimeStore !== undefined && !inBuild) {
368
+ if (isRawOnly) {
369
+ runtimeStore.setStatic(`/img/${rawFileName}`, rawBytes, mimeForImageExt(ext))
370
+ return { src: `/img/${rawFileName}`, width: dims.width, height: dims.height }
371
+ }
323
372
  return optimizeForRuntime(absPath, ext, rawBytes, dims, stem, hash, rawFileName, cacheRoot, pipelineCfg, runtimeStore)
373
+ }
324
374
 
325
375
  const outPublicDir = resolve(options.outPublicDir ?? appCtx?.publicDir ?? 'dist/public')
326
376
  const imgOutDir = join(outPublicDir, 'img')
@@ -331,7 +381,7 @@ export function optimizeImageFile(absPath: string, options: OptimizeImageFileOpt
331
381
  return { src: `/img/${rawFileName}`, width: dims.width, height: dims.height }
332
382
  }
333
383
 
334
- if (!hasMagick())
384
+ if (isRawOnly || !hasMagick())
335
385
  return emitRaw()
336
386
 
337
387
  const metaPath = join(cacheRoot, `md-${stem}-${hash}.json`)
@@ -411,7 +461,10 @@ export function createMarkdownImageResolver(options: MarkdownImageResolverOption
411
461
  }
412
462
  if (!isInside(realBoundary, realTarget))
413
463
  return undefined
414
- if (!ALLOWED_IMAGE_EXTS.has(extname(realTarget).toLowerCase()))
464
+ const targetExt = extname(realTarget).toLowerCase()
465
+ if (!ALLOWED_IMAGE_EXTS.has(targetExt))
466
+ return undefined
467
+ if (FALLBACK_MARKDOWN_EXTS.has(targetExt) && readImageDimensions(new Uint8Array(readFileSync(realTarget))) === undefined)
415
468
  return undefined
416
469
 
417
470
  const asset = optimizeImageFile(realTarget, options)
@@ -421,9 +474,8 @@ export function createMarkdownImageResolver(options: MarkdownImageResolverOption
421
474
  ...(srcset !== undefined ? { srcset } : {}),
422
475
  ...(asset.avifSrcset !== undefined && asset.webpSrcset !== undefined ? { avifSrcset: asset.avifSrcset } : {}),
423
476
  ...(srcset !== undefined ? { sizes } : {}),
424
- width: asset.width,
425
- height: asset.height,
426
- loading: 'lazy' as const,
477
+ ...(asset.width > 0 ? { width: asset.width } : {}),
478
+ ...(asset.height > 0 ? { height: asset.height } : {}),
427
479
  }
428
480
  }
429
481
  }
package/src/runtime.ts CHANGED
@@ -2,12 +2,15 @@
2
2
 
3
3
  import type { ServerPluginAPI } from 'prunelle/config'
4
4
  import { serviceKey } from 'prunelle/config'
5
- import { runMagick } from './pipeline'
5
+ import { MIN_IMG_ENTRIES, MIN_OG_ENTRIES } from './cache'
6
+ import { DROP_METADATA_KEEP_ICC, runMagick } from './pipeline'
6
7
 
7
8
  export interface RuntimeImagePayload {
8
9
  body: Uint8Array<ArrayBuffer> | string
9
10
  contentType: string
10
11
  etag: string
12
+ /** Marks a transient fallback payload: served with `Cache-Control: no-store` and never pinned to `entry.resolved`. */
13
+ fallback?: boolean | undefined
11
14
  }
12
15
 
13
16
  interface LazyEntry {
@@ -58,16 +61,25 @@ function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
58
61
  return trimmed.split(',').some(part => strip(part.trim()) === target)
59
62
  }
60
63
 
61
- export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
62
- const entries = new Map<string, LazyEntry>()
64
+ export function createRuntimeImageStore(maxOgEntries = MIN_OG_ENTRIES, maxImgEntries = MIN_IMG_ENTRIES): RuntimeImageStore {
65
+ // `/og/` share cards and `/img/` variants each sit in their own LRU, so flooding unique `/og/` URLs can never evict live `/img/` entries to 404.
66
+ const ogEntries = new Map<string, LazyEntry>()
67
+ const imgEntries = new Map<string, LazyEntry>()
68
+
69
+ function bucketFor(pathname: string): { map: Map<string, LazyEntry>, limit: number } {
70
+ return pathname.startsWith('/og/')
71
+ ? { map: ogEntries, limit: maxOgEntries }
72
+ : { map: imgEntries, limit: maxImgEntries }
73
+ }
63
74
 
64
75
  function put(pathname: string, entry: LazyEntry): void {
65
- entries.delete(pathname)
66
- entries.set(pathname, entry)
67
- if (entries.size > maxEntries) {
68
- const oldest = entries.keys().next()
76
+ const { map, limit } = bucketFor(pathname)
77
+ map.delete(pathname)
78
+ map.set(pathname, entry)
79
+ if (map.size > limit) {
80
+ const oldest = map.keys().next()
69
81
  if (!oldest.done)
70
- entries.delete(oldest.value)
82
+ map.delete(oldest.value)
71
83
  }
72
84
  }
73
85
 
@@ -76,25 +88,27 @@ export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
76
88
  put(pathname, { resolved: { body, contentType, etag: computeEtag(body) } })
77
89
  },
78
90
  setLazy(pathname, load) {
79
- if (entries.has(pathname))
91
+ const { map } = bucketFor(pathname)
92
+ if (map.has(pathname))
80
93
  return
81
94
  put(pathname, { load })
82
95
  },
83
96
  has(pathname) {
84
- return entries.has(pathname)
97
+ return bucketFor(pathname).map.has(pathname)
85
98
  },
86
99
  async serve(pathname, request) {
87
- const entry = entries.get(pathname)
100
+ const { map } = bucketFor(pathname)
101
+ const entry = map.get(pathname)
88
102
  if (entry === undefined)
89
103
  return undefined
90
104
  // Refresh LRU position
91
- entries.delete(pathname)
92
- entries.set(pathname, entry)
105
+ map.delete(pathname)
106
+ map.set(pathname, entry)
93
107
 
94
108
  let payload = entry.resolved
95
109
  if (payload === undefined && entry.load !== undefined) {
96
110
  entry.pending ??= entry.load().then((res) => {
97
- if (res !== undefined) {
111
+ if (res !== undefined && !res.fallback) {
98
112
  entry.resolved = res
99
113
  entry.load = undefined
100
114
  }
@@ -109,12 +123,17 @@ export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
109
123
  if (payload === undefined)
110
124
  return undefined
111
125
 
112
- const headers: Record<string, string> = {
113
- 'content-type': payload.contentType,
114
- 'cache-control': 'public, max-age=31536000, immutable',
115
- 'etag': payload.etag,
116
- }
117
- if (etagMatchesHeader(request.headers.get('if-none-match'), payload.etag))
126
+ const headers: Record<string, string> = payload.fallback
127
+ ? {
128
+ 'content-type': payload.contentType,
129
+ 'cache-control': 'no-store',
130
+ }
131
+ : {
132
+ 'content-type': payload.contentType,
133
+ 'cache-control': 'public, max-age=31536000, immutable',
134
+ 'etag': payload.etag,
135
+ }
136
+ if (!payload.fallback && etagMatchesHeader(request.headers.get('if-none-match'), payload.etag))
118
137
  return new Response(null, { status: 304, headers })
119
138
  if (request.method === 'HEAD')
120
139
  return new Response(null, { status: 200, headers })
@@ -190,8 +209,30 @@ export async function flushBuildPhase(outDir: string): Promise<void> {
190
209
  }
191
210
  }
192
211
 
212
+ export const RSVG_SLOTS = 4
213
+ export const RSVG_TIMEOUT_MS = 15_000
214
+
215
+ let activeRsvgSlots = 0
216
+ const waitingForRsvgSlot: (() => void)[] = []
217
+
218
+ async function takeRsvgSlot(): Promise<void> {
219
+ if (activeRsvgSlots < RSVG_SLOTS) {
220
+ activeRsvgSlots++
221
+ return
222
+ }
223
+ await new Promise<void>(resolve => waitingForRsvgSlot.push(resolve))
224
+ }
225
+
226
+ function releaseRsvgSlot(): void {
227
+ const next = waitingForRsvgSlot.shift()
228
+ if (next !== undefined)
229
+ next()
230
+ else
231
+ activeRsvgSlots--
232
+ }
233
+
193
234
  let magickCache: { path: string | undefined, available: boolean } | undefined
194
- let rsvgCache: { path: string | undefined, available: boolean } | undefined
235
+ let rsvgCache: { path: string | undefined, available: boolean, bin: string } | undefined
195
236
 
196
237
  export function hasMagick(): boolean {
197
238
  const envPath = process.env.PATH
@@ -202,18 +243,74 @@ export function hasMagick(): boolean {
202
243
 
203
244
  export function hasRsvgConvert(): boolean {
204
245
  const envPath = process.env.PATH
205
- if (rsvgCache === undefined || rsvgCache.path !== envPath)
206
- rsvgCache = { path: envPath, available: (envPath ?? '') !== '' && Bun.which('rsvg-convert', { PATH: envPath! }) !== null }
246
+ if (rsvgCache === undefined || rsvgCache.path !== envPath) {
247
+ const resolved = (envPath ?? '') !== '' ? Bun.which('rsvg-convert', { PATH: envPath! }) : null
248
+ rsvgCache = { path: envPath, available: resolved !== null, bin: resolved ?? 'rsvg-convert' }
249
+ }
207
250
  return rsvgCache.available
208
251
  }
209
252
 
210
- /** Non-blocking SVG->PNG rasterization over stdin/stdout pipes (zero temp files, works on read-only FS). */
211
- export async function rasterizeSvgToPngBytesAsync(svg: string): Promise<Uint8Array<ArrayBuffer> | undefined> {
253
+ async function readStreamChunks(reader: ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer>> {
254
+ const chunks: Uint8Array<ArrayBuffer>[] = []
255
+ let total = 0
256
+ while (true) {
257
+ const { done, value } = await reader.read()
258
+ if (done)
259
+ break
260
+ chunks.push(value)
261
+ total += value.byteLength
262
+ }
263
+ if (chunks.length === 1)
264
+ return chunks[0]!
265
+ const out = new Uint8Array(total)
266
+ let offset = 0
267
+ for (const chunk of chunks) {
268
+ out.set(chunk, offset)
269
+ offset += chunk.byteLength
270
+ }
271
+ return out
272
+ }
273
+
274
+ async function runRsvgConvert(svg: string, timeoutMs: number): Promise<Uint8Array<ArrayBuffer> | undefined> {
275
+ const bin = rsvgCache?.bin ?? 'rsvg-convert'
276
+ await takeRsvgSlot()
277
+ try {
278
+ const proc = Bun.spawn([bin], { stdin: new Response(svg), stdout: 'pipe', stderr: 'ignore', timeout: timeoutMs, killSignal: 'SIGKILL' })
279
+ const reader = proc.stdout.getReader()
280
+ let timedOut = false
281
+ const timer = setTimeout(() => {
282
+ timedOut = true
283
+ if (!proc.killed)
284
+ proc.kill('SIGKILL')
285
+ void reader.cancel()
286
+ }, timeoutMs)
287
+ try {
288
+ const [exitCode, bytes] = await Promise.all([
289
+ proc.exited,
290
+ readStreamChunks(reader).catch(() => new Uint8Array(0)),
291
+ ])
292
+ if (!timedOut && proc.signalCode !== 'SIGKILL' && exitCode === 0 && bytes.byteLength > 8)
293
+ return bytes
294
+ return undefined
295
+ }
296
+ finally {
297
+ clearTimeout(timer)
298
+ }
299
+ }
300
+ finally {
301
+ releaseRsvgSlot()
302
+ }
303
+ }
304
+
305
+ /** Non-blocking SVG->PNG rasterization over stdin/stdout pipes (zero temp files, bounded concurrency & timeout). */
306
+ export async function rasterizeSvgToPngBytesAsync(
307
+ svg: string,
308
+ options?: { timeoutMs?: number | undefined },
309
+ ): Promise<Uint8Array<ArrayBuffer> | undefined> {
212
310
  if (hasRsvgConvert()) {
213
- const proc = Bun.spawn(['rsvg-convert'], { stdin: new Response(svg), stdout: 'pipe', stderr: 'ignore' })
214
- const [exitCode, buf] = await Promise.all([proc.exited, new Response(proc.stdout).arrayBuffer()])
215
- if (exitCode === 0 && buf.byteLength > 8)
216
- return new Uint8Array(buf)
311
+ const png = await runRsvgConvert(svg, options?.timeoutMs ?? RSVG_TIMEOUT_MS)
312
+ if (png !== undefined)
313
+ return png
217
314
  }
218
315
  if (hasMagick()) {
219
316
  const result = await runMagick(['svg:-', 'png:-'], new Response(svg))
@@ -232,7 +329,7 @@ export async function encodeVariantToBytesAsync(
232
329
  ): Promise<Uint8Array<ArrayBuffer> | undefined> {
233
330
  if (!hasMagick())
234
331
  return undefined
235
- const result = await runMagick([`${srcPath}[0]`, '-auto-orient', '-strip', '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
332
+ const result = await runMagick([`${srcPath}[0]`, '-auto-orient', ...DROP_METADATA_KEEP_ICC, '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
236
333
  if (result.ok && result.stdout.byteLength > 0)
237
334
  return result.stdout
238
335
  return undefined