@prunellejs/images 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +53 -0
- package/package.json +25 -4
- package/src/Picture.tsx +24 -0
- package/src/ambient.d.ts +25 -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/pipeline.ts +282 -0
- package/src/plugin.ts +429 -0
- package/src/runtime.ts +239 -0
- package/README.md +0 -3
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
// @prunellejs/images — Build-time AVIF/WebP responsive image optimization with content-hashed disk cache.
|
|
2
|
+
// Built strictly on the public PrunellePlugin API (bunPlugins + build(ctx).emitAsset).
|
|
3
|
+
|
|
4
|
+
import type { BunPlugin } from 'bun'
|
|
5
|
+
import type { PrunellePlugin } from 'prunelle/config'
|
|
6
|
+
import type { ShareCardDefaults } from './card'
|
|
7
|
+
import type { ImageAsset } from './helpers'
|
|
8
|
+
import type { CachedImageMeta, VariantPipelineConfig } from './pipeline'
|
|
9
|
+
import type { RuntimeImageStore } from './runtime'
|
|
10
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
|
|
11
|
+
import { dirname, extname, join, resolve } from 'node:path'
|
|
12
|
+
import { CONTENT_IMAGE_RESOLVER_SERVICE, definePlugin, isInside } from 'prunelle/config'
|
|
13
|
+
import { getAppContext } from 'prunelle/internal/server'
|
|
14
|
+
import { SHARE_CARD_CONFIG_SERVICE } from './card'
|
|
15
|
+
import { readImageDimensions } from './dimensions'
|
|
16
|
+
import {
|
|
17
|
+
ALLOWED_IMAGE_EXTS,
|
|
18
|
+
assembleImageAsset,
|
|
19
|
+
computeImageKey,
|
|
20
|
+
encodeVariants,
|
|
21
|
+
identifyImageAsync,
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
planVariantJobs,
|
|
25
|
+
readCachedMeta,
|
|
26
|
+
writeFileAtomic,
|
|
27
|
+
} from './pipeline'
|
|
28
|
+
import {
|
|
29
|
+
computeEtag,
|
|
30
|
+
createRuntimeImageStore,
|
|
31
|
+
encodeVariantToBytesAsync,
|
|
32
|
+
enterBuildPhase,
|
|
33
|
+
flushBuildPhase,
|
|
34
|
+
hasMagick,
|
|
35
|
+
isBuildPhase,
|
|
36
|
+
leaveBuildPhase,
|
|
37
|
+
mimeForImageExt,
|
|
38
|
+
queueBuildTask,
|
|
39
|
+
registerRuntimeImageMiddleware,
|
|
40
|
+
RUNTIME_IMAGE_STORE_SERVICE,
|
|
41
|
+
} from './runtime'
|
|
42
|
+
|
|
43
|
+
export { CONTENT_IMAGE_RESOLVER_SERVICE }
|
|
44
|
+
|
|
45
|
+
export interface ImagesPluginOptions {
|
|
46
|
+
widths?: number[] | undefined
|
|
47
|
+
formats?: ('avif' | 'webp')[] | undefined
|
|
48
|
+
quality?: number | undefined
|
|
49
|
+
avifQuality?: number | undefined
|
|
50
|
+
cacheDir?: string | undefined
|
|
51
|
+
/** Remove stale cache files unused by the current build (default: true). */
|
|
52
|
+
pruneCache?: boolean | undefined
|
|
53
|
+
/** Optional defaults for build-time `shareCard()` OG image generation. */
|
|
54
|
+
card?: ShareCardDefaults | undefined
|
|
55
|
+
/** Default `sizes` attribute for relative images auto-optimized inside `@prunellejs/content` Markdown. */
|
|
56
|
+
markdownSizes?: string | undefined
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const DEFAULT_WIDTHS = [320, 640, 960, 1280, 1920]
|
|
60
|
+
const DEFAULT_FORMATS: ('avif' | 'webp')[] = ['avif', 'webp']
|
|
61
|
+
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
|
+
|
|
63
|
+
interface PersistedImagesConfig {
|
|
64
|
+
cacheDirRel: string
|
|
65
|
+
widths: number[]
|
|
66
|
+
formats: ('avif' | 'webp')[]
|
|
67
|
+
quality: number
|
|
68
|
+
avifQuality: number
|
|
69
|
+
markdownSizes?: string | undefined
|
|
70
|
+
card?: ShareCardDefaults | undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
|
|
74
|
+
const widths = (options.widths ?? DEFAULT_WIDTHS).slice().sort((a, b) => a - b)
|
|
75
|
+
const formats = options.formats ?? DEFAULT_FORMATS
|
|
76
|
+
const quality = options.quality ?? 80
|
|
77
|
+
const avifQuality = options.avifQuality ?? 55
|
|
78
|
+
const cacheDirRel = options.cacheDir ?? '.prunelle-cache/images'
|
|
79
|
+
const pruneCache = options.pruneCache ?? true
|
|
80
|
+
|
|
81
|
+
const emittedAssets = new Map<string, Uint8Array>()
|
|
82
|
+
const activeCacheFiles = new Set<string>()
|
|
83
|
+
let lastCacheRoot: string | undefined
|
|
84
|
+
let warnedMissingMagick = false
|
|
85
|
+
|
|
86
|
+
function warnMissingMagickOnce(): void {
|
|
87
|
+
if (!warnedMissingMagick) {
|
|
88
|
+
warnedMissingMagick = true
|
|
89
|
+
console.warn(MISSING_MAGICK_MESSAGE)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return definePlugin({
|
|
94
|
+
name: '@prunellejs/images',
|
|
95
|
+
check(ctx) {
|
|
96
|
+
if (!hasMagick())
|
|
97
|
+
ctx.error(MISSING_MAGICK_MESSAGE)
|
|
98
|
+
},
|
|
99
|
+
bunPlugins: ({ root, assetPrefix }): BunPlugin[] => {
|
|
100
|
+
const cacheRoot = resolve(root, cacheDirRel)
|
|
101
|
+
lastCacheRoot = cacheRoot
|
|
102
|
+
const prefix = assetPrefix.replace(/\/$/, '')
|
|
103
|
+
const pipelineCfg: VariantPipelineConfig = { widths, formats, quality, avifQuality, cachePrefix: '' }
|
|
104
|
+
const magickAvailable = hasMagick()
|
|
105
|
+
if (!magickAvailable)
|
|
106
|
+
warnMissingMagickOnce()
|
|
107
|
+
|
|
108
|
+
return [{
|
|
109
|
+
name: 'prunelle-images',
|
|
110
|
+
setup(b) {
|
|
111
|
+
b.onLoad({ filter: /\.(?:png|jpe?g|webp|avif)$/i }, async (args) => {
|
|
112
|
+
if (args.path.includes('/node_modules/'))
|
|
113
|
+
return undefined
|
|
114
|
+
|
|
115
|
+
const rawBytes = new Uint8Array(readFileSync(args.path))
|
|
116
|
+
const { hash, stem, rawFileName } = computeImageKey(args.path, rawBytes, pipelineCfg)
|
|
117
|
+
const emitRaw = (width: number, height: number) => {
|
|
118
|
+
const rel = `img/${rawFileName}`
|
|
119
|
+
emittedAssets.set(rel, rawBytes)
|
|
120
|
+
const asset: ImageAsset = { src: `${prefix}/${rel}`, width, height }
|
|
121
|
+
return { contents: `export default ${JSON.stringify(asset)};\n`, loader: 'js' as const }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (!magickAvailable) {
|
|
125
|
+
const dims = readImageDimensions(rawBytes)
|
|
126
|
+
if (dims === undefined)
|
|
127
|
+
throw new Error(`@prunellejs/images: could not determine dimensions for "${args.path}" (ImageMagick is unavailable and binary header could not be parsed)`)
|
|
128
|
+
return emitRaw(dims.width, dims.height)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
mkdirSync(cacheRoot, { recursive: true })
|
|
132
|
+
const metaName = `${stem}-${hash}.json`
|
|
133
|
+
const metaPath = join(cacheRoot, metaName)
|
|
134
|
+
activeCacheFiles.add(metaName)
|
|
135
|
+
let meta = readCachedMeta(metaPath, cacheRoot, '')
|
|
136
|
+
|
|
137
|
+
if (meta === undefined) {
|
|
138
|
+
const dims = readImageDimensions(rawBytes) ?? await identifyImageAsync(args.path)
|
|
139
|
+
if (dims === undefined)
|
|
140
|
+
throw new Error(`@prunellejs/images: could not determine dimensions for "${args.path}"`)
|
|
141
|
+
|
|
142
|
+
const jobs = planVariantJobs(dims, stem, hash, cacheRoot, pipelineCfg)
|
|
143
|
+
const encoded = await encodeVariants(args.path, jobs)
|
|
144
|
+
const files: CachedImageMeta['files'] = encoded.map(job => ({ rel: `img/${job.fileName}`, width: job.width, format: job.format }))
|
|
145
|
+
if (files.length === 0)
|
|
146
|
+
return emitRaw(dims.width, dims.height)
|
|
147
|
+
|
|
148
|
+
meta = { width: dims.width, height: dims.height, files }
|
|
149
|
+
// Kept only once every variant is in: a variant left out by a failed run is tried again by the next build.
|
|
150
|
+
if (files.length === jobs.length)
|
|
151
|
+
writeFileAtomic(metaPath, JSON.stringify(meta))
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const asset = assembleImageAsset(meta, cacheRoot, '', prefix, (rel, fileName, cachedFile) => {
|
|
155
|
+
activeCacheFiles.add(fileName)
|
|
156
|
+
if (!emittedAssets.has(rel))
|
|
157
|
+
emittedAssets.set(rel, new Uint8Array(readFileSync(cachedFile)))
|
|
158
|
+
})
|
|
159
|
+
return { contents: `export default ${JSON.stringify(asset)};\n`, loader: 'js' }
|
|
160
|
+
})
|
|
161
|
+
},
|
|
162
|
+
}]
|
|
163
|
+
},
|
|
164
|
+
build(ctx) {
|
|
165
|
+
enterBuildPhase(ctx.outDir)
|
|
166
|
+
const publicDir = join(ctx.outDir, 'public')
|
|
167
|
+
const cacheDir = resolve(ctx.root, cacheDirRel)
|
|
168
|
+
const cardWithSite: ShareCardDefaults | undefined = options.card !== undefined || ctx.site !== undefined
|
|
169
|
+
? { ...(ctx.site !== undefined ? { site: ctx.site } : {}), ...options.card }
|
|
170
|
+
: undefined
|
|
171
|
+
const persisted: PersistedImagesConfig = {
|
|
172
|
+
cacheDirRel,
|
|
173
|
+
widths,
|
|
174
|
+
formats,
|
|
175
|
+
quality,
|
|
176
|
+
avifQuality,
|
|
177
|
+
markdownSizes: options.markdownSizes,
|
|
178
|
+
card: cardWithSite,
|
|
179
|
+
}
|
|
180
|
+
ctx.setData(persisted as unknown as Record<string, unknown>)
|
|
181
|
+
ctx.provide(SHARE_CARD_CONFIG_SERVICE, { ...cardWithSite, publicDir, cacheDir } satisfies ShareCardDefaults)
|
|
182
|
+
ctx.provide(CONTENT_IMAGE_RESOLVER_SERVICE, createMarkdownImageResolver({
|
|
183
|
+
root: resolve(ctx.root),
|
|
184
|
+
outPublicDir: publicDir,
|
|
185
|
+
cacheDir,
|
|
186
|
+
widths,
|
|
187
|
+
formats,
|
|
188
|
+
quality,
|
|
189
|
+
avifQuality,
|
|
190
|
+
sizes: options.markdownSizes,
|
|
191
|
+
}))
|
|
192
|
+
for (const [rel, bytes] of emittedAssets)
|
|
193
|
+
ctx.emitAsset(rel, bytes)
|
|
194
|
+
if (pruneCache && !ctx.dev && lastCacheRoot !== undefined && activeCacheFiles.size > 0 && existsSync(lastCacheRoot)) {
|
|
195
|
+
for (const entry of readdirSync(lastCacheRoot)) {
|
|
196
|
+
if (!entry.startsWith('og-') && !entry.startsWith('md-') && !activeCacheFiles.has(entry))
|
|
197
|
+
rmSync(join(lastCacheRoot, entry), { force: true })
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
emittedAssets.clear()
|
|
201
|
+
activeCacheFiles.clear()
|
|
202
|
+
},
|
|
203
|
+
async afterPrerender(ctx) {
|
|
204
|
+
await flushBuildPhase(ctx.outDir)
|
|
205
|
+
},
|
|
206
|
+
server(api) {
|
|
207
|
+
const persisted = api.getBuildData<PersistedImagesConfig>()
|
|
208
|
+
const publicDir = join(api.outDir, 'public')
|
|
209
|
+
const cacheDir = resolve(api.root, persisted?.cacheDirRel ?? cacheDirRel)
|
|
210
|
+
const runtimeStore = createRuntimeImageStore()
|
|
211
|
+
api.provide(RUNTIME_IMAGE_STORE_SERVICE, runtimeStore)
|
|
212
|
+
registerRuntimeImageMiddleware(api, runtimeStore)
|
|
213
|
+
api.onShutdown(() => {
|
|
214
|
+
if (isBuildPhase(api.outDir))
|
|
215
|
+
leaveBuildPhase(api.outDir)
|
|
216
|
+
})
|
|
217
|
+
api.provide(SHARE_CARD_CONFIG_SERVICE, {
|
|
218
|
+
...(api.site !== undefined ? { site: api.site } : {}),
|
|
219
|
+
...(persisted?.card ?? options.card),
|
|
220
|
+
publicDir,
|
|
221
|
+
cacheDir,
|
|
222
|
+
} satisfies ShareCardDefaults)
|
|
223
|
+
api.provide(CONTENT_IMAGE_RESOLVER_SERVICE, createMarkdownImageResolver({
|
|
224
|
+
root: resolve(api.root),
|
|
225
|
+
cacheDir,
|
|
226
|
+
widths: persisted?.widths ?? widths,
|
|
227
|
+
formats: persisted?.formats ?? formats,
|
|
228
|
+
quality: persisted?.quality ?? quality,
|
|
229
|
+
avifQuality: persisted?.avifQuality ?? avifQuality,
|
|
230
|
+
sizes: persisted?.markdownSizes ?? options.markdownSizes,
|
|
231
|
+
}))
|
|
232
|
+
},
|
|
233
|
+
})
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export interface OptimizeImageFileOptions {
|
|
237
|
+
outPublicDir?: string | undefined
|
|
238
|
+
cacheDir?: string | undefined
|
|
239
|
+
widths?: number[] | undefined
|
|
240
|
+
formats?: ('avif' | 'webp')[] | undefined
|
|
241
|
+
quality?: number | undefined
|
|
242
|
+
avifQuality?: number | undefined
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function optimizeForRuntime(
|
|
246
|
+
absPath: string,
|
|
247
|
+
ext: string,
|
|
248
|
+
rawBytes: Uint8Array<ArrayBuffer>,
|
|
249
|
+
dims: { width: number, height: number },
|
|
250
|
+
stem: string,
|
|
251
|
+
hash: string,
|
|
252
|
+
rawFileName: string,
|
|
253
|
+
cacheRoot: string,
|
|
254
|
+
pipelineCfg: VariantPipelineConfig,
|
|
255
|
+
runtimeStore: RuntimeImageStore,
|
|
256
|
+
): ImageAsset {
|
|
257
|
+
const rawMime = mimeForImageExt(ext)
|
|
258
|
+
if (!hasMagick()) {
|
|
259
|
+
runtimeStore.setStatic(`/img/${rawFileName}`, rawBytes, rawMime)
|
|
260
|
+
return { src: `/img/${rawFileName}`, width: dims.width, height: dims.height }
|
|
261
|
+
}
|
|
262
|
+
const metaPath = join(cacheRoot, `md-${stem}-${hash}.json`)
|
|
263
|
+
const cachedMeta = readCachedMeta(metaPath, cacheRoot, 'md-')
|
|
264
|
+
if (cachedMeta !== undefined) {
|
|
265
|
+
return assembleImageAsset(cachedMeta, cacheRoot, 'md-', '', (_rel, fileName, cachedFile) => {
|
|
266
|
+
const mime = mimeForImageExt(extname(fileName))
|
|
267
|
+
runtimeStore.setLazy(`/img/${fileName}`, async () => {
|
|
268
|
+
try {
|
|
269
|
+
const bytes = new Uint8Array(await Bun.file(cachedFile).arrayBuffer())
|
|
270
|
+
return { body: bytes, contentType: mime, etag: computeEtag(bytes) }
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
|
|
274
|
+
}
|
|
275
|
+
})
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
const jobs = planVariantJobs(dims, stem, hash, cacheRoot, pipelineCfg)
|
|
279
|
+
const plannedMeta: CachedImageMeta = {
|
|
280
|
+
width: dims.width,
|
|
281
|
+
height: dims.height,
|
|
282
|
+
files: jobs.map(j => ({ rel: `img/${j.fileName}`, width: j.width, format: j.format })),
|
|
283
|
+
}
|
|
284
|
+
const jobByFile = new Map(jobs.map(j => [j.fileName, j]))
|
|
285
|
+
return assembleImageAsset(plannedMeta, cacheRoot, 'md-', '', (_rel, fileName) => {
|
|
286
|
+
const job = jobByFile.get(fileName)!
|
|
287
|
+
const targetMime = mimeForImageExt(`.${job.format}`)
|
|
288
|
+
runtimeStore.setLazy(`/img/${fileName}`, async () => {
|
|
289
|
+
const encoded = await encodeVariantToBytesAsync(absPath, job.width, job.format, job.quality)
|
|
290
|
+
if (encoded !== undefined)
|
|
291
|
+
return { body: encoded, contentType: targetMime, etag: computeEtag(encoded) }
|
|
292
|
+
return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
|
|
293
|
+
})
|
|
294
|
+
})
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Optimize a local image file (e.g. from Markdown) with non-blocking encoding and runtime in-memory serving for --compile. */
|
|
298
|
+
export function optimizeImageFile(absPath: string, options: OptimizeImageFileOptions = {}): ImageAsset {
|
|
299
|
+
const ext = extname(absPath).toLowerCase()
|
|
300
|
+
if (!ALLOWED_IMAGE_EXTS.has(ext))
|
|
301
|
+
throw new Error(`@prunellejs/images: unsupported image extension "${ext || '(none)'}" for "${absPath}"`)
|
|
302
|
+
|
|
303
|
+
const pipelineCfg: VariantPipelineConfig = {
|
|
304
|
+
widths: (options.widths ?? [640, 1280]).slice().sort((a, b) => a - b),
|
|
305
|
+
formats: options.formats ?? ['webp'],
|
|
306
|
+
quality: options.quality ?? 80,
|
|
307
|
+
avifQuality: options.avifQuality ?? 55,
|
|
308
|
+
cachePrefix: 'md-',
|
|
309
|
+
}
|
|
310
|
+
const appCtx = getAppContext()
|
|
311
|
+
const rawBytes = new Uint8Array(readFileSync(absPath))
|
|
312
|
+
const dims = readImageDimensions(rawBytes)
|
|
313
|
+
if (dims === undefined)
|
|
314
|
+
throw new Error(`@prunellejs/images: could not determine dimensions for "${absPath}"`)
|
|
315
|
+
|
|
316
|
+
const { hash, stem, rawFileName } = computeImageKey(absPath, rawBytes, pipelineCfg)
|
|
317
|
+
const cacheRoot = resolve(options.cacheDir ?? '.prunelle-cache/images')
|
|
318
|
+
const inBuild = appCtx !== undefined && isBuildPhase(appCtx.outDir)
|
|
319
|
+
|
|
320
|
+
// Runtime server mode (including --compile): never write to dist/public or block on Bun.spawnSync.
|
|
321
|
+
const runtimeStore = options.outPublicDir === undefined ? appCtx?.inject(RUNTIME_IMAGE_STORE_SERVICE) : undefined
|
|
322
|
+
if (runtimeStore !== undefined && !inBuild)
|
|
323
|
+
return optimizeForRuntime(absPath, ext, rawBytes, dims, stem, hash, rawFileName, cacheRoot, pipelineCfg, runtimeStore)
|
|
324
|
+
|
|
325
|
+
const outPublicDir = resolve(options.outPublicDir ?? appCtx?.publicDir ?? 'dist/public')
|
|
326
|
+
const imgOutDir = join(outPublicDir, 'img')
|
|
327
|
+
mkdirSync(imgOutDir, { recursive: true })
|
|
328
|
+
const emitRaw = (): ImageAsset => {
|
|
329
|
+
writeFileSync(join(imgOutDir, rawFileName), rawBytes)
|
|
330
|
+
appCtx?.registerPublicFile(`img/${rawFileName}`)
|
|
331
|
+
return { src: `/img/${rawFileName}`, width: dims.width, height: dims.height }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (!hasMagick())
|
|
335
|
+
return emitRaw()
|
|
336
|
+
|
|
337
|
+
const metaPath = join(cacheRoot, `md-${stem}-${hash}.json`)
|
|
338
|
+
const cachedMeta = readCachedMeta(metaPath, cacheRoot, 'md-')
|
|
339
|
+
if (cachedMeta !== undefined) {
|
|
340
|
+
return assembleImageAsset(cachedMeta, cacheRoot, 'md-', '', (_rel, fileName, cachedFile) => {
|
|
341
|
+
writeFileSync(join(imgOutDir, fileName), readFileSync(cachedFile))
|
|
342
|
+
appCtx?.registerPublicFile(`img/${fileName}`)
|
|
343
|
+
})
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (!inBuild)
|
|
347
|
+
return emitRaw()
|
|
348
|
+
|
|
349
|
+
// Build / prerender mode: queue non-blocking async Bun.spawn encoding and flush in afterPrerender().
|
|
350
|
+
const jobs = planVariantJobs(dims, stem, hash, cacheRoot, pipelineCfg)
|
|
351
|
+
const plannedMeta: CachedImageMeta = {
|
|
352
|
+
width: dims.width,
|
|
353
|
+
height: dims.height,
|
|
354
|
+
files: jobs.map(j => ({ rel: `img/${j.fileName}`, width: j.width, format: j.format })),
|
|
355
|
+
}
|
|
356
|
+
queueBuildTask(appCtx.outDir, (async () => {
|
|
357
|
+
mkdirSync(cacheRoot, { recursive: true })
|
|
358
|
+
mkdirSync(imgOutDir, { recursive: true })
|
|
359
|
+
const encoded = await encodeVariants(absPath, jobs)
|
|
360
|
+
for (const job of encoded)
|
|
361
|
+
writeFileSync(join(imgOutDir, job.fileName), readFileSync(job.cachedFile))
|
|
362
|
+
const files = encoded.map(job => ({ rel: `img/${job.fileName}`, width: job.width, format: job.format }))
|
|
363
|
+
if (files.length === jobs.length)
|
|
364
|
+
writeFileAtomic(metaPath, JSON.stringify({ width: dims.width, height: dims.height, files }))
|
|
365
|
+
})())
|
|
366
|
+
return assembleImageAsset(plannedMeta, cacheRoot, 'md-', '', (_rel, fileName) => {
|
|
367
|
+
appCtx.registerPublicFile(`img/${fileName}`)
|
|
368
|
+
})
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export interface MarkdownImageResolverOptions extends OptimizeImageFileOptions {
|
|
372
|
+
sizes?: string | undefined
|
|
373
|
+
/** Project root boundary confining resolved relative Markdown image paths. */
|
|
374
|
+
root?: string | undefined
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Creates a `@prunellejs/content` `resolveImage` function backed by `optimizeImageFile()`. Automatically wired by `images()`. */
|
|
378
|
+
export function createMarkdownImageResolver(options: MarkdownImageResolverOptions = {}) {
|
|
379
|
+
const sizes = options.sizes ?? '(min-width: 48rem) 42rem, 100vw'
|
|
380
|
+
return (src: string, file: string | undefined) => {
|
|
381
|
+
if (!file || !src.startsWith('.'))
|
|
382
|
+
return undefined
|
|
383
|
+
const absFile = resolve(file)
|
|
384
|
+
let boundary: string
|
|
385
|
+
if (options.root !== undefined) {
|
|
386
|
+
boundary = resolve(options.root)
|
|
387
|
+
}
|
|
388
|
+
else {
|
|
389
|
+
const prunelleRoot = getAppContext()?.root
|
|
390
|
+
boundary = (typeof prunelleRoot === 'string' && prunelleRoot !== '' && isInside(resolve(prunelleRoot), absFile))
|
|
391
|
+
? resolve(prunelleRoot)
|
|
392
|
+
: dirname(absFile)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const abs = resolve(dirname(absFile), src)
|
|
396
|
+
if (!isInside(boundary, abs))
|
|
397
|
+
return undefined
|
|
398
|
+
if (!ALLOWED_IMAGE_EXTS.has(extname(abs).toLowerCase()))
|
|
399
|
+
return undefined
|
|
400
|
+
if (!existsSync(abs))
|
|
401
|
+
return undefined
|
|
402
|
+
|
|
403
|
+
let realBoundary: string
|
|
404
|
+
let realTarget: string
|
|
405
|
+
try {
|
|
406
|
+
realBoundary = realpathSync(boundary)
|
|
407
|
+
realTarget = realpathSync(abs)
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
return undefined
|
|
411
|
+
}
|
|
412
|
+
if (!isInside(realBoundary, realTarget))
|
|
413
|
+
return undefined
|
|
414
|
+
if (!ALLOWED_IMAGE_EXTS.has(extname(realTarget).toLowerCase()))
|
|
415
|
+
return undefined
|
|
416
|
+
|
|
417
|
+
const asset = optimizeImageFile(realTarget, options)
|
|
418
|
+
const srcset = asset.webpSrcset ?? asset.avifSrcset
|
|
419
|
+
return {
|
|
420
|
+
src: asset.src,
|
|
421
|
+
...(srcset !== undefined ? { srcset } : {}),
|
|
422
|
+
...(asset.avifSrcset !== undefined && asset.webpSrcset !== undefined ? { avifSrcset: asset.avifSrcset } : {}),
|
|
423
|
+
...(srcset !== undefined ? { sizes } : {}),
|
|
424
|
+
width: asset.width,
|
|
425
|
+
height: asset.height,
|
|
426
|
+
loading: 'lazy' as const,
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// In-memory runtime image store, non-blocking Bun.spawn encoders, and build-phase task coordination for @prunellejs/images.
|
|
2
|
+
|
|
3
|
+
import type { ServerPluginAPI } from 'prunelle/config'
|
|
4
|
+
import { serviceKey } from 'prunelle/config'
|
|
5
|
+
import { runMagick } from './pipeline'
|
|
6
|
+
|
|
7
|
+
export interface RuntimeImagePayload {
|
|
8
|
+
body: Uint8Array<ArrayBuffer> | string
|
|
9
|
+
contentType: string
|
|
10
|
+
etag: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface LazyEntry {
|
|
14
|
+
resolved?: RuntimeImagePayload | undefined
|
|
15
|
+
pending?: Promise<RuntimeImagePayload | undefined> | undefined
|
|
16
|
+
load?: (() => Promise<RuntimeImagePayload | undefined>) | undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface RuntimeImageStore {
|
|
20
|
+
setStatic(pathname: string, body: Uint8Array<ArrayBuffer> | string, contentType: string): void
|
|
21
|
+
setLazy(pathname: string, load: () => Promise<RuntimeImagePayload | undefined>): void
|
|
22
|
+
has(pathname: string): boolean
|
|
23
|
+
serve(pathname: string, request: Request): Promise<Response | undefined>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const RUNTIME_IMAGE_STORE_SERVICE = serviceKey<RuntimeImageStore>('prunelle.images.runtimeStore')
|
|
27
|
+
|
|
28
|
+
const IMAGE_MIME: Record<string, string> = {
|
|
29
|
+
'.png': 'image/png',
|
|
30
|
+
'.jpg': 'image/jpeg',
|
|
31
|
+
'.jpeg': 'image/jpeg',
|
|
32
|
+
'.webp': 'image/webp',
|
|
33
|
+
'.avif': 'image/avif',
|
|
34
|
+
'.gif': 'image/gif',
|
|
35
|
+
'.svg': 'image/svg+xml',
|
|
36
|
+
'.ico': 'image/x-icon',
|
|
37
|
+
'.bmp': 'image/bmp',
|
|
38
|
+
'.tiff': 'image/tiff',
|
|
39
|
+
'.tif': 'image/tiff',
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function mimeForImageExt(ext: string): string {
|
|
43
|
+
return IMAGE_MIME[ext.toLowerCase()] ?? 'application/octet-stream'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function computeEtag(body: Uint8Array | string): string {
|
|
47
|
+
return `W/"${Bun.hash(body).toString(36)}"`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
|
|
51
|
+
if (!ifNoneMatch)
|
|
52
|
+
return false
|
|
53
|
+
const trimmed = ifNoneMatch.trim()
|
|
54
|
+
if (trimmed === '*')
|
|
55
|
+
return true
|
|
56
|
+
const strip = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
|
|
57
|
+
const target = strip(etag)
|
|
58
|
+
return trimmed.split(',').some(part => strip(part.trim()) === target)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
|
|
62
|
+
const entries = new Map<string, LazyEntry>()
|
|
63
|
+
|
|
64
|
+
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()
|
|
69
|
+
if (!oldest.done)
|
|
70
|
+
entries.delete(oldest.value)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
setStatic(pathname, body, contentType) {
|
|
76
|
+
put(pathname, { resolved: { body, contentType, etag: computeEtag(body) } })
|
|
77
|
+
},
|
|
78
|
+
setLazy(pathname, load) {
|
|
79
|
+
if (entries.has(pathname))
|
|
80
|
+
return
|
|
81
|
+
put(pathname, { load })
|
|
82
|
+
},
|
|
83
|
+
has(pathname) {
|
|
84
|
+
return entries.has(pathname)
|
|
85
|
+
},
|
|
86
|
+
async serve(pathname, request) {
|
|
87
|
+
const entry = entries.get(pathname)
|
|
88
|
+
if (entry === undefined)
|
|
89
|
+
return undefined
|
|
90
|
+
// Refresh LRU position
|
|
91
|
+
entries.delete(pathname)
|
|
92
|
+
entries.set(pathname, entry)
|
|
93
|
+
|
|
94
|
+
let payload = entry.resolved
|
|
95
|
+
if (payload === undefined && entry.load !== undefined) {
|
|
96
|
+
entry.pending ??= entry.load().then((res) => {
|
|
97
|
+
if (res !== undefined) {
|
|
98
|
+
entry.resolved = res
|
|
99
|
+
entry.load = undefined
|
|
100
|
+
}
|
|
101
|
+
entry.pending = undefined
|
|
102
|
+
return res
|
|
103
|
+
}).catch(() => {
|
|
104
|
+
entry.pending = undefined
|
|
105
|
+
return undefined
|
|
106
|
+
})
|
|
107
|
+
payload = await entry.pending
|
|
108
|
+
}
|
|
109
|
+
if (payload === undefined)
|
|
110
|
+
return undefined
|
|
111
|
+
|
|
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))
|
|
118
|
+
return new Response(null, { status: 304, headers })
|
|
119
|
+
if (request.method === 'HEAD')
|
|
120
|
+
return new Response(null, { status: 200, headers })
|
|
121
|
+
return new Response(payload.body, { status: 200, headers })
|
|
122
|
+
},
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function registerRuntimeImageMiddleware(api: ServerPluginAPI, store: RuntimeImageStore): void {
|
|
127
|
+
const serveRuntime = async (ctx: { request: Request, url: URL }, next: () => Promise<Response>): Promise<Response> => {
|
|
128
|
+
if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
|
|
129
|
+
const served = await store.serve(ctx.url.pathname, ctx.request)
|
|
130
|
+
if (served !== undefined)
|
|
131
|
+
return served
|
|
132
|
+
}
|
|
133
|
+
return next()
|
|
134
|
+
}
|
|
135
|
+
api.use(serveRuntime, { scope: '/og' })
|
|
136
|
+
api.use(serveRuntime, { scope: '/img' })
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Build-phase coordination shared across native and bundled copies of @prunellejs/images in the same process.
|
|
140
|
+
interface BuildPhaseState {
|
|
141
|
+
activeOutDirs: Set<string>
|
|
142
|
+
tasks: Map<string, Promise<void>[]>
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const BUILD_STATE_KEY = Symbol.for('pru.images.buildState')
|
|
146
|
+
|
|
147
|
+
function buildState(): BuildPhaseState {
|
|
148
|
+
const g = globalThis as Record<symbol, BuildPhaseState | undefined>
|
|
149
|
+
return (g[BUILD_STATE_KEY] ??= { activeOutDirs: new Set(), tasks: new Map() })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function enterBuildPhase(outDir: string): void {
|
|
153
|
+
buildState().activeOutDirs.add(outDir)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function leaveBuildPhase(outDir: string): void {
|
|
157
|
+
const state = buildState()
|
|
158
|
+
state.activeOutDirs.delete(outDir)
|
|
159
|
+
state.tasks.delete(outDir)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function isBuildPhase(outDir: string): boolean {
|
|
163
|
+
return buildState().activeOutDirs.has(outDir)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function queueBuildTask(outDir: string, task: Promise<void>): void {
|
|
167
|
+
const state = buildState()
|
|
168
|
+
let list = state.tasks.get(outDir)
|
|
169
|
+
if (list === undefined) {
|
|
170
|
+
list = []
|
|
171
|
+
state.tasks.set(outDir, list)
|
|
172
|
+
}
|
|
173
|
+
list.push(task)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function flushBuildPhase(outDir: string): Promise<void> {
|
|
177
|
+
const state = buildState()
|
|
178
|
+
try {
|
|
179
|
+
while (true) {
|
|
180
|
+
const pending = state.tasks.get(outDir)
|
|
181
|
+
if (pending === undefined || pending.length === 0)
|
|
182
|
+
break
|
|
183
|
+
state.tasks.set(outDir, [])
|
|
184
|
+
await Promise.all(pending)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
state.activeOutDirs.delete(outDir)
|
|
189
|
+
state.tasks.delete(outDir)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
let magickCache: { path: string | undefined, available: boolean } | undefined
|
|
194
|
+
let rsvgCache: { path: string | undefined, available: boolean } | undefined
|
|
195
|
+
|
|
196
|
+
export function hasMagick(): boolean {
|
|
197
|
+
const envPath = process.env.PATH
|
|
198
|
+
if (magickCache === undefined || magickCache.path !== envPath)
|
|
199
|
+
magickCache = { path: envPath, available: (envPath ?? '') !== '' && Bun.which('magick', { PATH: envPath! }) !== null }
|
|
200
|
+
return magickCache.available
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function hasRsvgConvert(): boolean {
|
|
204
|
+
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 }
|
|
207
|
+
return rsvgCache.available
|
|
208
|
+
}
|
|
209
|
+
|
|
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> {
|
|
212
|
+
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)
|
|
217
|
+
}
|
|
218
|
+
if (hasMagick()) {
|
|
219
|
+
const result = await runMagick(['svg:-', 'png:-'], new Response(svg))
|
|
220
|
+
if (result.ok && result.stdout.byteLength > 8)
|
|
221
|
+
return result.stdout
|
|
222
|
+
}
|
|
223
|
+
return undefined
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Non-blocking image variant encoding via stdout pipe (zero temp files, works on read-only FS). */
|
|
227
|
+
export async function encodeVariantToBytesAsync(
|
|
228
|
+
srcPath: string,
|
|
229
|
+
width: number,
|
|
230
|
+
format: 'avif' | 'webp',
|
|
231
|
+
quality: number,
|
|
232
|
+
): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
233
|
+
if (!hasMagick())
|
|
234
|
+
return undefined
|
|
235
|
+
const result = await runMagick([`${srcPath}[0]`, '-auto-orient', '-strip', '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
|
|
236
|
+
if (result.ok && result.stdout.byteLength > 0)
|
|
237
|
+
return result.stdout
|
|
238
|
+
return undefined
|
|
239
|
+
}
|
package/README.md
DELETED