@prunellejs/images 0.7.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt CHANGED
@@ -11,7 +11,7 @@
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
- - 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.
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, in path order, about each JPEG, PNG or WebP under `publicDir` (`public/` by default) still carrying EXIF, XMP or IPTC, since it is copied as is.
15
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.
16
16
  - `card`: `ShareCardDefaults` (`{ site?, publicDir?, cacheDir?, background?, color?, accent?, mutedColor?, fontFamily?, width? (1200), height? (630) }`).
17
17
  - `markdownSizes`: default `sizes` attribute for relative images inside `@prunellejs/content` Markdown (auto-wired via `CONTENT_IMAGE_RESOLVER_SERVICE`).
@@ -20,7 +20,7 @@
20
20
 
21
21
  - `<Picture src={hero} alt="..." sizes? priority? class? pictureClass? ...imgAttrs />`: renders `<picture>` with `<source type="image/avif">`, `<source type="image/webp">`, and `<img>`.
22
22
  - `image(asset, { sizes?, priority? })`: returns `ImgSpreadProps` (`src`, `srcset`, `sizes`, `width`, `height`, `loading`, `decoding`, `fetchpriority`) for `<img {...image(hero)} alt="..." />`.
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
+ - `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). On a page rendered per request the card is served from memory and its SVG source is kept in the cache folder (`ogsrc-*.svg`), so the URL answers after a restart; replicas not sharing that folder answer it only after rendering the page.
24
24
  - `optimizeImageFile(absPath, options?)`: synchronously optimizes a local file into `dist/public/img/`.
25
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.
26
26
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/images",
3
- "version": "0.7.4",
3
+ "version": "0.8.0",
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.7.4"
25
+ "prunelle": "^0.8.0"
26
26
  }
27
27
  }
package/src/card.ts CHANGED
@@ -7,6 +7,7 @@ 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'
10
+ import type { RuntimeImagePayload, RuntimeImageResolver } from './runtime'
10
11
  import {
11
12
  computeEtag,
12
13
  hasMagick,
@@ -216,6 +217,56 @@ function writePngAtomic(dstPath: string, bytes: Uint8Array): void {
216
217
  }
217
218
  }
218
219
 
220
+ async function renderCardPayload(svg: string, cachedPng: string | undefined): Promise<RuntimeImagePayload> {
221
+ if (cachedPng !== undefined && existsSync(cachedPng)) {
222
+ const cached = await Bun.file(cachedPng).arrayBuffer().then(buf => new Uint8Array(buf), () => undefined)
223
+ if (cached !== undefined)
224
+ return { body: cached, contentType: 'image/png', etag: computeEtag(cached) }
225
+ }
226
+ const png = await rasterizeSvgToPngBytesAsync(svg)
227
+ if (png !== undefined)
228
+ return { body: png, contentType: 'image/png', etag: computeEtag(png) }
229
+ return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg), fallback: true }
230
+ }
231
+
232
+ // The card's SVG is kept next to the PNG cache so `/og/<slug>-<hash>.png` still answers after a restart, when no page has rendered the card yet.
233
+ function persistCardSource(cacheDir: string, stem: string, svg: string): void {
234
+ const file = join(cacheDir, `ogsrc-${stem}.svg`)
235
+ try {
236
+ if (existsSync(file))
237
+ return
238
+ mkdirSync(cacheDir, { recursive: true })
239
+ writePngAtomic(file, new TextEncoder().encode(svg))
240
+ }
241
+ catch {
242
+ // A read-only cache folder only costs the restart survival of this card.
243
+ return
244
+ }
245
+ }
246
+
247
+ const CARD_PATH = /^\/og\/([a-z0-9-]+)\.(png|svg)$/
248
+
249
+ /** Resolver for `createRuntimeImageStore`: rebuilds a `/og/` card from the SVG a page persisted in `cacheDir`, so a restarted or fresh process answers it without rendering the page first. */
250
+ export function persistedCardResolver(cacheDir: string): RuntimeImageResolver {
251
+ return (pathname) => {
252
+ const match = CARD_PATH.exec(pathname)
253
+ if (match === null)
254
+ return undefined
255
+ const [, stem, ext] = match
256
+ const source = join(cacheDir, `ogsrc-${stem}.svg`)
257
+ if (!existsSync(source))
258
+ return undefined
259
+ return async () => {
260
+ const svg = await Bun.file(source).text().catch(() => undefined)
261
+ if (svg === undefined)
262
+ return undefined
263
+ if (ext === 'svg')
264
+ return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg) }
265
+ return renderCardPayload(svg, join(cacheDir, `og-${stem}.png`))
266
+ }
267
+ }
268
+ }
269
+
219
270
  /** Generate an OG social share card (async PNG via rsvg-convert/magick when available, SVG fallback) and return its public URL. */
220
271
  export function shareCard(input: ShareCardInput, overrides?: ShareCardDefaults): string {
221
272
  const cfg = { ...getCardConfig(), ...overrides }
@@ -236,21 +287,15 @@ export function shareCard(input: ShareCardInput, overrides?: ShareCardDefaults):
236
287
  const urlPath = `/og/${fileName}`
237
288
  const cacheDir = cfg.cacheDir !== undefined ? resolve(cfg.cacheDir) : undefined
238
289
  const cachedPng = cacheDir !== undefined ? join(cacheDir, `og-${fileName}`) : undefined
239
- runtimeStore.setLazy(urlPath, async () => {
240
- if (cachedPng !== undefined && existsSync(cachedPng)) {
241
- const cached = await Bun.file(cachedPng).arrayBuffer().then(buf => new Uint8Array(buf), () => undefined)
242
- if (cached !== undefined)
243
- return { body: cached, contentType: 'image/png', etag: computeEtag(cached) }
244
- }
245
- const png = await rasterizeSvgToPngBytesAsync(svg)
246
- if (png !== undefined)
247
- return { body: png, contentType: 'image/png', etag: computeEtag(png) }
248
- return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg), fallback: true }
249
- })
290
+ if (cacheDir !== undefined)
291
+ persistCardSource(cacheDir, `${slug}-${hash}`, svg)
292
+ runtimeStore.setLazy(urlPath, () => renderCardPayload(svg, cachedPng))
250
293
  return `${site}${urlPath}`
251
294
  }
252
295
  const svgFile = `${slug}-${hash}.svg`
253
296
  const urlPath = `/og/${svgFile}`
297
+ if (cfg.cacheDir !== undefined)
298
+ persistCardSource(resolve(cfg.cacheDir), `${slug}-${hash}`, svg)
254
299
  runtimeStore.setStatic(urlPath, svg, 'image/svg+xml')
255
300
  return `${site}${urlPath}`
256
301
  }
package/src/plugin.ts CHANGED
@@ -13,7 +13,7 @@ import { CONTENT_IMAGE_RESOLVER_SERVICE, definePlugin, isInside } from 'prunelle
13
13
  import { getAppContext } from 'prunelle/internal/server'
14
14
  import type { KnownImages } from './cache'
15
15
  import { knownImages, removeUnusedOgAndMd, runtimeStoreLimits } from './cache'
16
- import { SHARE_CARD_CONFIG_SERVICE } from './card'
16
+ import { persistedCardResolver, SHARE_CARD_CONFIG_SERVICE } from './card'
17
17
  import { readImageDimensions } from './dimensions'
18
18
  import { stripImageMetadata } from './metadata'
19
19
  import {
@@ -251,7 +251,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
251
251
  const persisted = api.getBuildData<PersistedImagesConfig>()
252
252
  const publicDir = join(api.outDir, 'public')
253
253
  const cacheDir = resolve(api.root, persisted?.cacheDirRel ?? cacheDirRel)
254
- const runtimeStore = createRuntimeImageStore(...runtimeStoreLimits(persisted))
254
+ const runtimeStore = createRuntimeImageStore(...runtimeStoreLimits(persisted), persistedCardResolver(cacheDir))
255
255
  api.provide(RUNTIME_IMAGE_STORE_SERVICE, runtimeStore)
256
256
  registerRuntimeImageMiddleware(api, runtimeStore)
257
257
  api.onShutdown(() => {
package/src/runtime.ts CHANGED
@@ -61,7 +61,10 @@ function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
61
61
  return trimmed.split(',').some(part => strip(part.trim()) === target)
62
62
  }
63
63
 
64
- export function createRuntimeImageStore(maxOgEntries = MIN_OG_ENTRIES, maxImgEntries = MIN_IMG_ENTRIES): RuntimeImageStore {
64
+ /** Rebuilds the loader of a path no page registered in this process (after a restart, or on another replica), or returns undefined for a path it does not know. */
65
+ export type RuntimeImageResolver = (pathname: string) => (() => Promise<RuntimeImagePayload | undefined>) | undefined
66
+
67
+ export function createRuntimeImageStore(maxOgEntries = MIN_OG_ENTRIES, maxImgEntries = MIN_IMG_ENTRIES, resolveMissing?: RuntimeImageResolver): RuntimeImageStore {
65
68
  // `/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
69
  const ogEntries = new Map<string, LazyEntry>()
67
70
  const imgEntries = new Map<string, LazyEntry>()
@@ -98,9 +101,14 @@ export function createRuntimeImageStore(maxOgEntries = MIN_OG_ENTRIES, maxImgEnt
98
101
  },
99
102
  async serve(pathname, request) {
100
103
  const { map } = bucketFor(pathname)
101
- const entry = map.get(pathname)
102
- if (entry === undefined)
103
- return undefined
104
+ let entry = map.get(pathname)
105
+ if (entry === undefined) {
106
+ const load = resolveMissing?.(pathname)
107
+ if (load === undefined)
108
+ return undefined
109
+ entry = { load }
110
+ put(pathname, entry)
111
+ }
104
112
  // Refresh LRU position
105
113
  map.delete(pathname)
106
114
  map.set(pathname, entry)