@prunellejs/images 0.0.0-stage → 0.7.2
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 +21 -0
- package/llms.txt +54 -0
- package/package.json +25 -4
- package/src/Picture.tsx +24 -0
- package/src/ambient.d.ts +25 -0
- package/src/cache.ts +53 -0
- package/src/card.ts +251 -0
- package/src/dimensions.ts +130 -0
- package/src/helpers.ts +46 -0
- package/src/index.ts +10 -0
- package/src/metadata.ts +191 -0
- package/src/pipeline.ts +285 -0
- package/src/plugin.ts +468 -0
- package/src/runtime.ts +336 -0
- package/README.md +0 -3
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
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# @prunellejs/images Reference
|
|
2
|
+
|
|
3
|
+
> Build-time AVIF/WebP responsive image pipeline with content-hashed disk cache, `<Picture>` / `image()` helpers, automatic `@prunellejs/content` Markdown image optimization, and 1200×630 PNG OG `shareCard()`.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/images`: `images`, `image`, `Picture`, `shareCard`, `configureShareCard`, `optimizeImageFile`, `createMarkdownImageResolver`, `readImageDimensions`; types `ImagesPluginOptions`, `ImageAsset`, `ImageHelperOptions`, `ImgSpreadProps`, `PictureProps`, `ShareCardDefaults`, `ShareCardInput`, `OptimizeImageFileOptions`, `MarkdownImageResolverOptions`.
|
|
8
|
+
- `@prunellejs/images/ambient`: ambient module declarations for `.png`, `.jpg`, `.jpeg`, `.webp`, `.avif`, `.gif` imports as `ImageAsset` (auto-referenced when importing `@prunellejs/images`).
|
|
9
|
+
|
|
10
|
+
## Plugin Setup (`images(options?)`)
|
|
11
|
+
|
|
12
|
+
- `widths`: responsive widths in px (default `[320, 640, 960, 1280, 1920]`).
|
|
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; a JPEG keeps only its 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.
|
|
16
|
+
- `card`: `ShareCardDefaults` (`{ site?, publicDir?, cacheDir?, background?, color?, accent?, mutedColor?, fontFamily?, width? (1200), height? (630) }`).
|
|
17
|
+
- `markdownSizes`: default `sizes` attribute for relative images inside `@prunellejs/content` Markdown (auto-wired via `CONTENT_IMAGE_RESOLVER_SERVICE`).
|
|
18
|
+
|
|
19
|
+
## Components & Helpers
|
|
20
|
+
|
|
21
|
+
- `<Picture src={hero} alt="..." sizes? priority? class? pictureClass? ...imgAttrs />`: renders `<picture>` with `<source type="image/avif">`, `<source type="image/webp">`, and `<img>`.
|
|
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).
|
|
24
|
+
- `optimizeImageFile(absPath, options?)`: synchronously optimizes a local file into `dist/public/img/`.
|
|
25
|
+
- `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.
|
|
26
|
+
|
|
27
|
+
## Snippets
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// prunelle.config.ts
|
|
31
|
+
import { images } from '@prunellejs/images'
|
|
32
|
+
import { defineConfig } from 'prunelle/config'
|
|
33
|
+
|
|
34
|
+
export default defineConfig({
|
|
35
|
+
site: 'https://example.com',
|
|
36
|
+
plugins: [images({ card: { background: '#090c13', color: '#dbe0ea', accent: '#f5b83d' } })],
|
|
37
|
+
})
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```tsx
|
|
41
|
+
import { Picture, shareCard } from '@prunellejs/images'
|
|
42
|
+
import { Head } from 'prunelle'
|
|
43
|
+
import hero from '../assets/hero.png'
|
|
44
|
+
|
|
45
|
+
export default function Home() {
|
|
46
|
+
const og = shareCard({ title: 'Welcome', badge: 'Blog' })
|
|
47
|
+
return (
|
|
48
|
+
<>
|
|
49
|
+
<Head><meta property="og:image" content={og} /></Head>
|
|
50
|
+
<Picture src={hero} alt="Hero banner" sizes="(min-width: 60rem) 50vw, 100vw" priority />
|
|
51
|
+
</>
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/images",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.2",
|
|
4
|
+
"description": "Build-time responsive AVIF/WebP image optimization plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts",
|
|
14
|
+
"./ambient": "./src/ambient.d.ts"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"bun": ">=1.4.0"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
22
|
+
"directory": "packages/plugin-images"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"prunelle": "^0.7.2"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/Picture.tsx
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** @jsxImportSource prunelle */
|
|
2
|
+
import type { ImageAsset } from './helpers'
|
|
3
|
+
import { image } from './helpers'
|
|
4
|
+
|
|
5
|
+
export interface PictureProps {
|
|
6
|
+
src: ImageAsset
|
|
7
|
+
alt: string
|
|
8
|
+
sizes?: string | undefined
|
|
9
|
+
priority?: boolean | undefined
|
|
10
|
+
class?: string | undefined
|
|
11
|
+
pictureClass?: string | undefined
|
|
12
|
+
[attr: string]: unknown
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function Picture({ src, alt, sizes, priority, class: cls, pictureClass, ...rest }: PictureProps) {
|
|
16
|
+
const imgProps = image(src, { sizes, priority })
|
|
17
|
+
return (
|
|
18
|
+
<picture class={pictureClass}>
|
|
19
|
+
{src.avifSrcset && <source type="image/avif" srcset={src.avifSrcset} sizes={sizes} />}
|
|
20
|
+
{src.webpSrcset && <source type="image/webp" srcset={src.webpSrcset} sizes={sizes} />}
|
|
21
|
+
<img {...imgProps} {...rest} class={cls} alt={alt} />
|
|
22
|
+
</picture>
|
|
23
|
+
)
|
|
24
|
+
}
|
package/src/ambient.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
declare module '*.jpg' {
|
|
2
|
+
import type { ImageAsset } from '@prunellejs/images'
|
|
3
|
+
const asset: ImageAsset
|
|
4
|
+
export default asset
|
|
5
|
+
}
|
|
6
|
+
declare module '*.jpeg' {
|
|
7
|
+
import type { ImageAsset } from '@prunellejs/images'
|
|
8
|
+
const asset: ImageAsset
|
|
9
|
+
export default asset
|
|
10
|
+
}
|
|
11
|
+
declare module '*.png' {
|
|
12
|
+
import type { ImageAsset } from '@prunellejs/images'
|
|
13
|
+
const asset: ImageAsset
|
|
14
|
+
export default asset
|
|
15
|
+
}
|
|
16
|
+
declare module '*.webp' {
|
|
17
|
+
import type { ImageAsset } from '@prunellejs/images'
|
|
18
|
+
const asset: ImageAsset
|
|
19
|
+
export default asset
|
|
20
|
+
}
|
|
21
|
+
declare module '*.avif' {
|
|
22
|
+
import type { ImageAsset } from '@prunellejs/images'
|
|
23
|
+
const asset: ImageAsset
|
|
24
|
+
export default asset
|
|
25
|
+
}
|
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
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// OG shareCard() generator for @prunellejs/images:
|
|
2
|
+
// Renders a crisp 1200x630 SVG social card and rasterizes asynchronously to PNG via `rsvg-convert` or `magick`
|
|
3
|
+
// (cached by content hash in `.prunelle-cache/images/` at build time, or served from memory at runtime for --compile).
|
|
4
|
+
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { extname, join, resolve } from 'node:path'
|
|
7
|
+
import { isInside, serviceKey } from 'prunelle/config'
|
|
8
|
+
import { getAppContext } from 'prunelle/internal/server'
|
|
9
|
+
import { escAttr } from 'prunelle/server'
|
|
10
|
+
import {
|
|
11
|
+
computeEtag,
|
|
12
|
+
hasMagick,
|
|
13
|
+
hasRsvgConvert,
|
|
14
|
+
isBuildPhase,
|
|
15
|
+
queueBuildTask,
|
|
16
|
+
rasterizeSvgToPngBytesAsync,
|
|
17
|
+
RUNTIME_IMAGE_STORE_SERVICE,
|
|
18
|
+
} from './runtime'
|
|
19
|
+
|
|
20
|
+
export { hasMagick, hasRsvgConvert }
|
|
21
|
+
|
|
22
|
+
export interface ShareCardDefaults {
|
|
23
|
+
/** Base URL prepended to returned card URL (optional, e.g. 'https://log.kaynooo.fr'). */
|
|
24
|
+
site?: string | undefined
|
|
25
|
+
/** Output public directory where `og/*.png` is written (default: `dist/public`). */
|
|
26
|
+
publicDir?: string | undefined
|
|
27
|
+
/** Disk cache directory (default: `.prunelle-cache/images`). */
|
|
28
|
+
cacheDir?: string | undefined
|
|
29
|
+
background?: string | undefined
|
|
30
|
+
color?: string | undefined
|
|
31
|
+
accent?: string | undefined
|
|
32
|
+
mutedColor?: string | undefined
|
|
33
|
+
fontFamily?: string | undefined
|
|
34
|
+
width?: number | undefined
|
|
35
|
+
height?: number | undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ShareCardInput {
|
|
39
|
+
title: string
|
|
40
|
+
subtitle?: string | undefined
|
|
41
|
+
badge?: string | undefined
|
|
42
|
+
/** Optional inline SVG markup or path to an SVG file embedded on the right side of the card. */
|
|
43
|
+
image?: string | undefined
|
|
44
|
+
background?: string | undefined
|
|
45
|
+
color?: string | undefined
|
|
46
|
+
accent?: string | undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const SHARE_CARD_CONFIG_SERVICE = serviceKey<ShareCardDefaults>('prunelle.images.shareCardConfig')
|
|
50
|
+
|
|
51
|
+
let standaloneCardConfig: ShareCardDefaults | undefined
|
|
52
|
+
|
|
53
|
+
export function configureShareCard(defaults: ShareCardDefaults): void {
|
|
54
|
+
const appCtx = getAppContext()
|
|
55
|
+
if (appCtx !== undefined)
|
|
56
|
+
appCtx.provide(SHARE_CARD_CONFIG_SERVICE, defaults)
|
|
57
|
+
else
|
|
58
|
+
standaloneCardConfig = defaults
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function getCardConfig(): ShareCardDefaults {
|
|
62
|
+
const appCtx = getAppContext()
|
|
63
|
+
const scoped = appCtx?.inject(SHARE_CARD_CONFIG_SERVICE)
|
|
64
|
+
if (scoped !== undefined)
|
|
65
|
+
return scoped
|
|
66
|
+
if (appCtx !== undefined)
|
|
67
|
+
return { publicDir: appCtx.publicDir }
|
|
68
|
+
return standaloneCardConfig ?? {}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
function wrapLines(text: string, maxChars: number, maxLines: number): string[] {
|
|
73
|
+
const words = text.trim().split(/\s+/).filter(Boolean)
|
|
74
|
+
const lines: string[] = []
|
|
75
|
+
let cur = ''
|
|
76
|
+
for (const w of words) {
|
|
77
|
+
const next = cur ? `${cur} ${w}` : w
|
|
78
|
+
if (next.length > maxChars && cur) {
|
|
79
|
+
lines.push(cur)
|
|
80
|
+
cur = w
|
|
81
|
+
if (lines.length >= maxLines - 1)
|
|
82
|
+
break
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
cur = next
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (cur && lines.length < maxLines)
|
|
89
|
+
lines.push(cur)
|
|
90
|
+
return lines
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function readConfinedSvgImage(imageSpec: string): string {
|
|
94
|
+
if (imageSpec.trim().startsWith('<svg'))
|
|
95
|
+
return imageSpec
|
|
96
|
+
const rootDir = resolve(getAppContext()?.root ?? process.cwd())
|
|
97
|
+
const absImg = resolve(rootDir, imageSpec)
|
|
98
|
+
if (extname(absImg).toLowerCase() !== '.svg' || !isInside(rootDir, absImg) || !existsSync(absImg))
|
|
99
|
+
return ''
|
|
100
|
+
try {
|
|
101
|
+
const realRoot = realpathSync(rootDir)
|
|
102
|
+
const realImg = realpathSync(absImg)
|
|
103
|
+
if (extname(realImg).toLowerCase() !== '.svg' || !isInside(realRoot, realImg))
|
|
104
|
+
return ''
|
|
105
|
+
return readFileSync(realImg, 'utf8')
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return ''
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function buildCardSvg(input: ShareCardInput, cfg: ShareCardDefaults): string {
|
|
113
|
+
const width = cfg.width ?? 1200
|
|
114
|
+
const height = cfg.height ?? 630
|
|
115
|
+
const bg = input.background ?? cfg.background ?? '#090c13'
|
|
116
|
+
const fg = input.color ?? cfg.color ?? '#dbe0ea'
|
|
117
|
+
const accent = input.accent ?? cfg.accent ?? '#f5b83d'
|
|
118
|
+
const muted = cfg.mutedColor ?? '#8b95aa'
|
|
119
|
+
const font = cfg.fontFamily ?? '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", "Helvetica Neue", Arial, sans-serif'
|
|
120
|
+
|
|
121
|
+
const hasGraphic = Boolean(input.image)
|
|
122
|
+
const titleLines = wrapLines(input.title, hasGraphic ? 20 : 26, 3)
|
|
123
|
+
const subLines = input.subtitle ? wrapLines(input.subtitle, hasGraphic ? 42 : 56, 2) : []
|
|
124
|
+
|
|
125
|
+
const titleStartY = input.badge ? 235 : 210
|
|
126
|
+
const titleSvg = titleLines
|
|
127
|
+
.map((line, i) => `<text x="80" y="${titleStartY + i * 76}" fill="${escAttr(fg)}" font-family="${escAttr(font)}" font-size="62" font-weight="700">${escAttr(line)}</text>`)
|
|
128
|
+
.join('')
|
|
129
|
+
|
|
130
|
+
const subStartY = titleStartY + titleLines.length * 76 + 26
|
|
131
|
+
const subSvg = subLines
|
|
132
|
+
.map((line, i) => `<text x="80" y="${subStartY + i * 38}" fill="${escAttr(muted)}" font-family="${escAttr(font)}" font-size="28" font-weight="400">${escAttr(line)}</text>`)
|
|
133
|
+
.join('')
|
|
134
|
+
|
|
135
|
+
const badgeSvg = input.badge
|
|
136
|
+
? `<text x="80" y="135" fill="${escAttr(accent)}" font-family="${escAttr(font)}" font-size="24" font-weight="600" letter-spacing="3">${escAttr(input.badge.toUpperCase())}</text>`
|
|
137
|
+
: ''
|
|
138
|
+
|
|
139
|
+
let graphicSvg = ''
|
|
140
|
+
if (input.image) {
|
|
141
|
+
const rawImg = readConfinedSvgImage(input.image)
|
|
142
|
+
if (rawImg.includes('<svg')) {
|
|
143
|
+
const dataUri = `data:image/svg+xml;base64,${Buffer.from(rawImg, 'utf8').toString('base64')}`
|
|
144
|
+
graphicSvg = `<image href="${dataUri}" x="${width - 340}" y="175" width="260" height="260" />`
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
|
|
149
|
+
+ `<rect width="${width}" height="${height}" fill="${escAttr(bg)}"/>`
|
|
150
|
+
+ `<rect x="0" y="0" width="${width}" height="8" fill="${escAttr(accent)}"/>`
|
|
151
|
+
+ `<rect x="44" y="44" width="${width - 88}" height="${height - 88}" fill="none" stroke="${escAttr(muted)}" stroke-opacity="0.2" stroke-width="1.5"/>`
|
|
152
|
+
+ badgeSvg
|
|
153
|
+
+ titleSvg
|
|
154
|
+
+ subSvg
|
|
155
|
+
+ graphicSvg
|
|
156
|
+
+ `</svg>`
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function writePngAtomic(dstPath: string, bytes: Uint8Array): void {
|
|
160
|
+
const tmpPath = `${dstPath}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
161
|
+
writeFileSync(tmpPath, bytes)
|
|
162
|
+
try {
|
|
163
|
+
renameSync(tmpPath, dstPath)
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
rmSync(tmpPath, { force: true })
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Generate an OG social share card (async PNG via rsvg-convert/magick when available, SVG fallback) and return its public URL. */
|
|
171
|
+
export function shareCard(input: ShareCardInput, overrides?: ShareCardDefaults): string {
|
|
172
|
+
const cfg = { ...getCardConfig(), ...overrides }
|
|
173
|
+
const svg = buildCardSvg(input, cfg)
|
|
174
|
+
const hash = Bun.hash(svg).toString(36)
|
|
175
|
+
const slug = input.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'card'
|
|
176
|
+
const appCtx = getAppContext()
|
|
177
|
+
const rawSite = cfg.site ?? appCtx?.site
|
|
178
|
+
const site = rawSite ? rawSite.replace(/\/$/, '') : ''
|
|
179
|
+
const canRasterize = hasRsvgConvert() || hasMagick()
|
|
180
|
+
const inBuild = appCtx !== undefined && isBuildPhase(appCtx.outDir)
|
|
181
|
+
|
|
182
|
+
// Runtime server mode (including --compile): serve from bounded in-memory store with async Bun.spawn, zero dist/public writes.
|
|
183
|
+
const runtimeStore = overrides?.publicDir === undefined ? appCtx?.inject(RUNTIME_IMAGE_STORE_SERVICE) : undefined
|
|
184
|
+
if (runtimeStore !== undefined && !inBuild) {
|
|
185
|
+
if (canRasterize) {
|
|
186
|
+
const fileName = `${slug}-${hash}.png`
|
|
187
|
+
const urlPath = `/og/${fileName}`
|
|
188
|
+
const cacheDir = cfg.cacheDir !== undefined ? resolve(cfg.cacheDir) : undefined
|
|
189
|
+
const cachedPng = cacheDir !== undefined ? join(cacheDir, `og-${fileName}`) : undefined
|
|
190
|
+
runtimeStore.setLazy(urlPath, async () => {
|
|
191
|
+
if (cachedPng !== undefined && existsSync(cachedPng)) {
|
|
192
|
+
const cached = await Bun.file(cachedPng).arrayBuffer().then(buf => new Uint8Array(buf), () => undefined)
|
|
193
|
+
if (cached !== undefined)
|
|
194
|
+
return { body: cached, contentType: 'image/png', etag: computeEtag(cached) }
|
|
195
|
+
}
|
|
196
|
+
const png = await rasterizeSvgToPngBytesAsync(svg)
|
|
197
|
+
if (png !== undefined)
|
|
198
|
+
return { body: png, contentType: 'image/png', etag: computeEtag(png) }
|
|
199
|
+
return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg), fallback: true }
|
|
200
|
+
})
|
|
201
|
+
return `${site}${urlPath}`
|
|
202
|
+
}
|
|
203
|
+
const svgFile = `${slug}-${hash}.svg`
|
|
204
|
+
const urlPath = `/og/${svgFile}`
|
|
205
|
+
runtimeStore.setStatic(urlPath, svg, 'image/svg+xml')
|
|
206
|
+
return `${site}${urlPath}`
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Build / prerender or standalone explicit publicDir mode
|
|
210
|
+
const publicDir = resolve(cfg.publicDir ?? appCtx?.publicDir ?? 'dist/public')
|
|
211
|
+
const ogDir = join(publicDir, 'og')
|
|
212
|
+
mkdirSync(ogDir, { recursive: true })
|
|
213
|
+
|
|
214
|
+
if (canRasterize) {
|
|
215
|
+
const fileName = `${slug}-${hash}.png`
|
|
216
|
+
const outPath = join(ogDir, fileName)
|
|
217
|
+
if (existsSync(outPath)) {
|
|
218
|
+
appCtx?.registerPublicFile(`og/${fileName}`)
|
|
219
|
+
return `${site}/og/${fileName}`
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const cacheDir = resolve(cfg.cacheDir ?? '.prunelle-cache/images')
|
|
223
|
+
const cachedPng = join(cacheDir, `og-${fileName}`)
|
|
224
|
+
if (existsSync(cachedPng)) {
|
|
225
|
+
writeFileSync(outPath, readFileSync(cachedPng))
|
|
226
|
+
appCtx?.registerPublicFile(`og/${fileName}`)
|
|
227
|
+
return `${site}/og/${fileName}`
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (inBuild) {
|
|
231
|
+
appCtx.registerPublicFile(`og/${fileName}`)
|
|
232
|
+
queueBuildTask(appCtx.outDir, (async () => {
|
|
233
|
+
const png = await rasterizeSvgToPngBytesAsync(svg)
|
|
234
|
+
if (png === undefined)
|
|
235
|
+
return
|
|
236
|
+
mkdirSync(cacheDir, { recursive: true })
|
|
237
|
+
writePngAtomic(cachedPng, png)
|
|
238
|
+
mkdirSync(ogDir, { recursive: true })
|
|
239
|
+
writeFileSync(outPath, png)
|
|
240
|
+
})())
|
|
241
|
+
return `${site}/og/${fileName}`
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const svgFile = `${slug}-${hash}.svg`
|
|
246
|
+
const svgOut = join(ogDir, svgFile)
|
|
247
|
+
if (!existsSync(svgOut))
|
|
248
|
+
writeFileSync(svgOut, svg)
|
|
249
|
+
appCtx?.registerPublicFile(`og/${svgFile}`)
|
|
250
|
+
return `${site}/og/${svgFile}`
|
|
251
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Image sizes read from the file header, with no decoder and no process.
|
|
2
|
+
|
|
3
|
+
/** Pure-JS binary header parser for PNG, GIF, WebP, JPEG, and AVIF/HEIF dimensions (zero external dependencies). */
|
|
4
|
+
export function readImageDimensions(bytes: Uint8Array): { width: number, height: number } | undefined {
|
|
5
|
+
const len = bytes.byteLength
|
|
6
|
+
if (len < 10)
|
|
7
|
+
return undefined
|
|
8
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, len)
|
|
9
|
+
|
|
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
|
+
}
|
|
16
|
+
|
|
17
|
+
// 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) {
|
|
19
|
+
const width = view.getUint16(6, true)
|
|
20
|
+
const height = view.getUint16(8, true)
|
|
21
|
+
return width > 0 && height > 0 ? { width, height } : undefined
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (len >= 30 && view.getUint32(0) === 0x52494646 && view.getUint32(8) === 0x57454250)
|
|
25
|
+
return webpDimensions(bytes, view)
|
|
26
|
+
if (bytes[0] === 0xFF && bytes[1] === 0xD8)
|
|
27
|
+
return jpegDimensions(bytes, view)
|
|
28
|
+
if (len >= 24 && view.getUint32(4) === 0x66747970)
|
|
29
|
+
return isobmffDimensions(bytes, view)
|
|
30
|
+
return undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** WebP, RIFF....WEBP: the VP8X, VP8L or VP8 chunk's size. */
|
|
34
|
+
function webpDimensions(bytes: Uint8Array, view: DataView): { width: number, height: number } | undefined {
|
|
35
|
+
const len = bytes.byteLength
|
|
36
|
+
const chunk = view.getUint32(12)
|
|
37
|
+
// VP8X extended
|
|
38
|
+
if (chunk === 0x56503858) {
|
|
39
|
+
const width = 1 + (bytes[24]! | (bytes[25]! << 8) | (bytes[26]! << 16))
|
|
40
|
+
const height = 1 + (bytes[27]! | (bytes[28]! << 8) | (bytes[29]! << 16))
|
|
41
|
+
return { width, height }
|
|
42
|
+
}
|
|
43
|
+
// VP8L lossless
|
|
44
|
+
if (chunk === 0x5650384C && len >= 25 && bytes[20] === 0x2F) {
|
|
45
|
+
const bits = view.getUint32(21, true)
|
|
46
|
+
return { width: (bits & 0x3FFF) + 1, height: ((bits >> 14) & 0x3FFF) + 1 }
|
|
47
|
+
}
|
|
48
|
+
// VP8 lossy
|
|
49
|
+
if (chunk === 0x56503820 && bytes[23] === 0x9D && bytes[24] === 0x01 && bytes[25] === 0x2A) {
|
|
50
|
+
const width = view.getUint16(26, true) & 0x3FFF
|
|
51
|
+
const height = view.getUint16(28, true) & 0x3FFF
|
|
52
|
+
return width > 0 && height > 0 ? { width, height } : undefined
|
|
53
|
+
}
|
|
54
|
+
return undefined
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** AVIF / HEIF (ISOBMFF): ftyp, then meta -> iprp -> ipco -> the 'ispe' full box, its version and flags then uint32BE width and height. */
|
|
58
|
+
function isobmffDimensions(bytes: Uint8Array, view: DataView): { width: number, height: number } | undefined {
|
|
59
|
+
for (let i = 12; i + 16 <= bytes.byteLength; i++) {
|
|
60
|
+
if (bytes[i] === 0x69 && bytes[i + 1] === 0x73 && bytes[i + 2] === 0x70 && bytes[i + 3] === 0x65) {
|
|
61
|
+
const width = view.getUint32(i + 8)
|
|
62
|
+
const height = view.getUint32(i + 12)
|
|
63
|
+
if (width > 0 && height > 0 && width <= 65535 && height <= 65535)
|
|
64
|
+
return { width, height }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return undefined
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A JPEG's size as it is displayed: FF D8 then markers, SOF0..SOF15 (except C4, C8, CC) carrying height@+5 and width@+7,
|
|
72
|
+
* turned a quarter when an earlier Exif segment's Orientation is 5 to 8, as `magick -auto-orient` and browsers turn it.
|
|
73
|
+
*/
|
|
74
|
+
function jpegDimensions(bytes: Uint8Array, view: DataView): { width: number, height: number } | undefined {
|
|
75
|
+
const len = bytes.byteLength
|
|
76
|
+
let orientation = 1
|
|
77
|
+
let offset = 2
|
|
78
|
+
while (offset + 4 <= len) {
|
|
79
|
+
if (bytes[offset] !== 0xFF)
|
|
80
|
+
return undefined
|
|
81
|
+
while (offset < len && bytes[offset] === 0xFF) offset++
|
|
82
|
+
if (offset >= len)
|
|
83
|
+
return undefined
|
|
84
|
+
const marker = bytes[offset++]!
|
|
85
|
+
if (marker === 0xD9 || marker === 0xDA)
|
|
86
|
+
return undefined
|
|
87
|
+
if (marker === 0x01 || (marker >= 0xD0 && marker <= 0xD7))
|
|
88
|
+
continue
|
|
89
|
+
if (offset + 2 > len)
|
|
90
|
+
return undefined
|
|
91
|
+
const segLen = view.getUint16(offset)
|
|
92
|
+
if (segLen < 2 || offset + segLen > len)
|
|
93
|
+
return undefined
|
|
94
|
+
if (marker === 0xE1 && orientation === 1)
|
|
95
|
+
orientation = exifOrientation(view, offset + 2, offset + segLen)
|
|
96
|
+
if (marker >= 0xC0 && marker <= 0xCF && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC && segLen >= 7) {
|
|
97
|
+
const height = view.getUint16(offset + 3)
|
|
98
|
+
const width = view.getUint16(offset + 5)
|
|
99
|
+
if (width === 0 || height === 0)
|
|
100
|
+
return undefined
|
|
101
|
+
return orientation >= 5 && orientation <= 8 ? { width: height, height: width } : { width, height }
|
|
102
|
+
}
|
|
103
|
+
offset += segLen
|
|
104
|
+
}
|
|
105
|
+
return undefined
|
|
106
|
+
}
|
|
107
|
+
|
|
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
|
|
114
|
+
const order = view.getUint16(tiff)
|
|
115
|
+
if (order !== 0x4949 && order !== 0x4D4D)
|
|
116
|
+
return 1
|
|
117
|
+
const little = order === 0x4949
|
|
118
|
+
const ifd = tiff + view.getUint32(tiff + 4, little)
|
|
119
|
+
if (ifd + 2 > end)
|
|
120
|
+
return 1
|
|
121
|
+
const count = view.getUint16(ifd, little)
|
|
122
|
+
for (let i = 0; i < count; i++) {
|
|
123
|
+
const entry = ifd + 2 + i * 12
|
|
124
|
+
if (entry + 12 > end)
|
|
125
|
+
return 1
|
|
126
|
+
if (view.getUint16(entry, little) === 0x0112)
|
|
127
|
+
return view.getUint16(entry + 8, little)
|
|
128
|
+
}
|
|
129
|
+
return 1
|
|
130
|
+
}
|
package/src/helpers.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export interface ImageAsset {
|
|
2
|
+
src: string
|
|
3
|
+
width: number
|
|
4
|
+
height: number
|
|
5
|
+
webpSrcset?: string | undefined
|
|
6
|
+
avifSrcset?: string | undefined
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface ImageHelperOptions {
|
|
10
|
+
sizes?: string | undefined
|
|
11
|
+
priority?: boolean | undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ImgSpreadProps {
|
|
15
|
+
src: string
|
|
16
|
+
srcset?: string | undefined
|
|
17
|
+
sizes?: string | undefined
|
|
18
|
+
width?: number | undefined
|
|
19
|
+
height?: number | undefined
|
|
20
|
+
loading?: 'lazy' | 'eager' | undefined
|
|
21
|
+
decoding?: 'async' | 'sync' | 'auto' | undefined
|
|
22
|
+
fetchpriority?: 'high' | 'low' | 'auto' | undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Returns responsive <img> props for spreading: `<img {...image(hero, { sizes: '50vw' })} alt="..." />`. */
|
|
26
|
+
export function image(asset: ImageAsset | string, options: ImageHelperOptions = {}): ImgSpreadProps {
|
|
27
|
+
if (typeof asset === 'string') {
|
|
28
|
+
return {
|
|
29
|
+
src: asset,
|
|
30
|
+
loading: options.priority ? 'eager' : 'lazy',
|
|
31
|
+
decoding: options.priority ? 'sync' : 'async',
|
|
32
|
+
...(options.priority ? { fetchpriority: 'high' } : {}),
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
src: asset.src,
|
|
38
|
+
...(asset.webpSrcset ? { srcset: asset.webpSrcset } : {}),
|
|
39
|
+
...(options.sizes ? { sizes: options.sizes } : {}),
|
|
40
|
+
...(asset.width > 0 ? { width: asset.width } : {}),
|
|
41
|
+
...(asset.height > 0 ? { height: asset.height } : {}),
|
|
42
|
+
loading: options.priority ? 'eager' : 'lazy',
|
|
43
|
+
decoding: options.priority ? 'sync' : 'async',
|
|
44
|
+
...(options.priority ? { fetchpriority: 'high' } : {}),
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/// <reference path="./ambient.d.ts" />
|
|
2
|
+
export { configureShareCard, shareCard } from './card'
|
|
3
|
+
export type { ShareCardDefaults, ShareCardInput } from './card'
|
|
4
|
+
export { image } from './helpers'
|
|
5
|
+
export type { ImageAsset, ImageHelperOptions, ImgSpreadProps } from './helpers'
|
|
6
|
+
export { Picture } from './Picture'
|
|
7
|
+
export type { PictureProps } from './Picture'
|
|
8
|
+
export { readImageDimensions } from './dimensions'
|
|
9
|
+
export { createMarkdownImageResolver, images, optimizeImageFile } from './plugin'
|
|
10
|
+
export type { ImagesPluginOptions, MarkdownImageResolverOptions, OptimizeImageFileOptions } from './plugin'
|