@prunellejs/images 0.0.0-stage → 0.5.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/src/runtime.ts ADDED
@@ -0,0 +1,338 @@
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
+ /** Marks a transient fallback payload: served with `Cache-Control: no-store` and never pinned to `entry.resolved`. */
12
+ fallback?: boolean | undefined
13
+ }
14
+
15
+ interface LazyEntry {
16
+ resolved?: RuntimeImagePayload | undefined
17
+ pending?: Promise<RuntimeImagePayload | undefined> | undefined
18
+ load?: (() => Promise<RuntimeImagePayload | undefined>) | undefined
19
+ }
20
+
21
+ export interface RuntimeImageStore {
22
+ setStatic(pathname: string, body: Uint8Array<ArrayBuffer> | string, contentType: string): void
23
+ setLazy(pathname: string, load: () => Promise<RuntimeImagePayload | undefined>): void
24
+ has(pathname: string): boolean
25
+ serve(pathname: string, request: Request): Promise<Response | undefined>
26
+ }
27
+
28
+ export const RUNTIME_IMAGE_STORE_SERVICE = serviceKey<RuntimeImageStore>('prunelle.images.runtimeStore')
29
+
30
+ const IMAGE_MIME: Record<string, string> = {
31
+ '.png': 'image/png',
32
+ '.jpg': 'image/jpeg',
33
+ '.jpeg': 'image/jpeg',
34
+ '.webp': 'image/webp',
35
+ '.avif': 'image/avif',
36
+ '.gif': 'image/gif',
37
+ '.svg': 'image/svg+xml',
38
+ '.ico': 'image/x-icon',
39
+ '.bmp': 'image/bmp',
40
+ '.tiff': 'image/tiff',
41
+ '.tif': 'image/tiff',
42
+ }
43
+
44
+ export function mimeForImageExt(ext: string): string {
45
+ return IMAGE_MIME[ext.toLowerCase()] ?? 'application/octet-stream'
46
+ }
47
+
48
+ export function computeEtag(body: Uint8Array | string): string {
49
+ return `W/"${Bun.hash(body).toString(36)}"`
50
+ }
51
+
52
+ function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
53
+ if (!ifNoneMatch)
54
+ return false
55
+ const trimmed = ifNoneMatch.trim()
56
+ if (trimmed === '*')
57
+ return true
58
+ const strip = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
59
+ const target = strip(etag)
60
+ return trimmed.split(',').some(part => strip(part.trim()) === target)
61
+ }
62
+
63
+ export function createRuntimeImageStore(maxOgEntries = 256): RuntimeImageStore {
64
+ // Keep dynamic `/og/` share cards in a bounded LRU separate from the `/img/` asset store
65
+ // 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>, bounded: boolean } {
70
+ return pathname.startsWith('/og/')
71
+ ? { map: ogEntries, bounded: true }
72
+ : { map: imgEntries, bounded: false }
73
+ }
74
+
75
+ function put(pathname: string, entry: LazyEntry): void {
76
+ const { map, bounded } = bucketFor(pathname)
77
+ map.delete(pathname)
78
+ map.set(pathname, entry)
79
+ if (bounded && map.size > maxOgEntries) {
80
+ const oldest = map.keys().next()
81
+ if (!oldest.done)
82
+ map.delete(oldest.value)
83
+ }
84
+ }
85
+
86
+ return {
87
+ setStatic(pathname, body, contentType) {
88
+ put(pathname, { resolved: { body, contentType, etag: computeEtag(body) } })
89
+ },
90
+ setLazy(pathname, load) {
91
+ const { map } = bucketFor(pathname)
92
+ if (map.has(pathname))
93
+ return
94
+ put(pathname, { load })
95
+ },
96
+ has(pathname) {
97
+ return bucketFor(pathname).map.has(pathname)
98
+ },
99
+ async serve(pathname, request) {
100
+ const { map, bounded } = bucketFor(pathname)
101
+ const entry = map.get(pathname)
102
+ if (entry === undefined)
103
+ return undefined
104
+ if (bounded) {
105
+ // Refresh LRU position
106
+ map.delete(pathname)
107
+ map.set(pathname, entry)
108
+ }
109
+
110
+ let payload = entry.resolved
111
+ if (payload === undefined && entry.load !== undefined) {
112
+ entry.pending ??= entry.load().then((res) => {
113
+ if (res !== undefined && !res.fallback) {
114
+ entry.resolved = res
115
+ entry.load = undefined
116
+ }
117
+ entry.pending = undefined
118
+ return res
119
+ }).catch(() => {
120
+ entry.pending = undefined
121
+ return undefined
122
+ })
123
+ payload = await entry.pending
124
+ }
125
+ if (payload === undefined)
126
+ return undefined
127
+
128
+ const headers: Record<string, string> = payload.fallback
129
+ ? {
130
+ 'content-type': payload.contentType,
131
+ 'cache-control': 'no-store',
132
+ }
133
+ : {
134
+ 'content-type': payload.contentType,
135
+ 'cache-control': 'public, max-age=31536000, immutable',
136
+ 'etag': payload.etag,
137
+ }
138
+ if (!payload.fallback && etagMatchesHeader(request.headers.get('if-none-match'), payload.etag))
139
+ return new Response(null, { status: 304, headers })
140
+ if (request.method === 'HEAD')
141
+ return new Response(null, { status: 200, headers })
142
+ return new Response(payload.body, { status: 200, headers })
143
+ },
144
+ }
145
+ }
146
+
147
+ export function registerRuntimeImageMiddleware(api: ServerPluginAPI, store: RuntimeImageStore): void {
148
+ const serveRuntime = async (ctx: { request: Request, url: URL }, next: () => Promise<Response>): Promise<Response> => {
149
+ if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
150
+ const served = await store.serve(ctx.url.pathname, ctx.request)
151
+ if (served !== undefined)
152
+ return served
153
+ }
154
+ return next()
155
+ }
156
+ api.use(serveRuntime, { scope: '/og' })
157
+ api.use(serveRuntime, { scope: '/img' })
158
+ }
159
+
160
+ // Build-phase coordination shared across native and bundled copies of @prunellejs/images in the same process.
161
+ interface BuildPhaseState {
162
+ activeOutDirs: Set<string>
163
+ tasks: Map<string, Promise<void>[]>
164
+ }
165
+
166
+ const BUILD_STATE_KEY = Symbol.for('pru.images.buildState')
167
+
168
+ function buildState(): BuildPhaseState {
169
+ const g = globalThis as Record<symbol, BuildPhaseState | undefined>
170
+ return (g[BUILD_STATE_KEY] ??= { activeOutDirs: new Set(), tasks: new Map() })
171
+ }
172
+
173
+ export function enterBuildPhase(outDir: string): void {
174
+ buildState().activeOutDirs.add(outDir)
175
+ }
176
+
177
+ export function leaveBuildPhase(outDir: string): void {
178
+ const state = buildState()
179
+ state.activeOutDirs.delete(outDir)
180
+ state.tasks.delete(outDir)
181
+ }
182
+
183
+ export function isBuildPhase(outDir: string): boolean {
184
+ return buildState().activeOutDirs.has(outDir)
185
+ }
186
+
187
+ export function queueBuildTask(outDir: string, task: Promise<void>): void {
188
+ const state = buildState()
189
+ let list = state.tasks.get(outDir)
190
+ if (list === undefined) {
191
+ list = []
192
+ state.tasks.set(outDir, list)
193
+ }
194
+ list.push(task)
195
+ }
196
+
197
+ export async function flushBuildPhase(outDir: string): Promise<void> {
198
+ const state = buildState()
199
+ try {
200
+ while (true) {
201
+ const pending = state.tasks.get(outDir)
202
+ if (pending === undefined || pending.length === 0)
203
+ break
204
+ state.tasks.set(outDir, [])
205
+ await Promise.all(pending)
206
+ }
207
+ }
208
+ finally {
209
+ state.activeOutDirs.delete(outDir)
210
+ state.tasks.delete(outDir)
211
+ }
212
+ }
213
+
214
+ export const RSVG_SLOTS = 4
215
+ export const RSVG_TIMEOUT_MS = 15_000
216
+
217
+ let activeRsvgSlots = 0
218
+ const waitingForRsvgSlot: (() => void)[] = []
219
+
220
+ async function takeRsvgSlot(): Promise<void> {
221
+ if (activeRsvgSlots < RSVG_SLOTS) {
222
+ activeRsvgSlots++
223
+ return
224
+ }
225
+ await new Promise<void>(resolve => waitingForRsvgSlot.push(resolve))
226
+ }
227
+
228
+ function releaseRsvgSlot(): void {
229
+ const next = waitingForRsvgSlot.shift()
230
+ if (next !== undefined)
231
+ next()
232
+ else
233
+ activeRsvgSlots--
234
+ }
235
+
236
+ let magickCache: { path: string | undefined, available: boolean } | undefined
237
+ let rsvgCache: { path: string | undefined, available: boolean, bin: string } | undefined
238
+
239
+ export function hasMagick(): boolean {
240
+ const envPath = process.env.PATH
241
+ if (magickCache === undefined || magickCache.path !== envPath)
242
+ magickCache = { path: envPath, available: (envPath ?? '') !== '' && Bun.which('magick', { PATH: envPath! }) !== null }
243
+ return magickCache.available
244
+ }
245
+
246
+ export function hasRsvgConvert(): boolean {
247
+ const envPath = process.env.PATH
248
+ if (rsvgCache === undefined || rsvgCache.path !== envPath) {
249
+ const resolved = (envPath ?? '') !== '' ? Bun.which('rsvg-convert', { PATH: envPath! }) : null
250
+ rsvgCache = { path: envPath, available: resolved !== null, bin: resolved ?? 'rsvg-convert' }
251
+ }
252
+ return rsvgCache.available
253
+ }
254
+
255
+ async function readStreamChunks(reader: ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer>> {
256
+ const chunks: Uint8Array<ArrayBuffer>[] = []
257
+ let total = 0
258
+ while (true) {
259
+ const { done, value } = await reader.read()
260
+ if (done)
261
+ break
262
+ chunks.push(value)
263
+ total += value.byteLength
264
+ }
265
+ if (chunks.length === 1)
266
+ return chunks[0]!
267
+ const out = new Uint8Array(total)
268
+ let offset = 0
269
+ for (const chunk of chunks) {
270
+ out.set(chunk, offset)
271
+ offset += chunk.byteLength
272
+ }
273
+ return out
274
+ }
275
+
276
+ async function runRsvgConvert(svg: string, timeoutMs: number): Promise<Uint8Array<ArrayBuffer> | undefined> {
277
+ const bin = rsvgCache?.bin ?? 'rsvg-convert'
278
+ await takeRsvgSlot()
279
+ try {
280
+ const proc = Bun.spawn([bin], { stdin: new Response(svg), stdout: 'pipe', stderr: 'ignore', timeout: timeoutMs, killSignal: 'SIGKILL' })
281
+ const reader = proc.stdout.getReader()
282
+ let timedOut = false
283
+ const timer = setTimeout(() => {
284
+ timedOut = true
285
+ if (!proc.killed)
286
+ proc.kill('SIGKILL')
287
+ void reader.cancel()
288
+ }, timeoutMs)
289
+ try {
290
+ const [exitCode, bytes] = await Promise.all([
291
+ proc.exited,
292
+ readStreamChunks(reader).catch(() => new Uint8Array(0)),
293
+ ])
294
+ if (!timedOut && proc.signalCode !== 'SIGKILL' && exitCode === 0 && bytes.byteLength > 8)
295
+ return bytes
296
+ return undefined
297
+ }
298
+ finally {
299
+ clearTimeout(timer)
300
+ }
301
+ }
302
+ finally {
303
+ releaseRsvgSlot()
304
+ }
305
+ }
306
+
307
+ /** Non-blocking SVG->PNG rasterization over stdin/stdout pipes (zero temp files, bounded concurrency & timeout). */
308
+ export async function rasterizeSvgToPngBytesAsync(
309
+ svg: string,
310
+ options?: { timeoutMs?: number | undefined },
311
+ ): Promise<Uint8Array<ArrayBuffer> | undefined> {
312
+ if (hasRsvgConvert()) {
313
+ const png = await runRsvgConvert(svg, options?.timeoutMs ?? RSVG_TIMEOUT_MS)
314
+ if (png !== undefined)
315
+ return png
316
+ }
317
+ if (hasMagick()) {
318
+ const result = await runMagick(['svg:-', 'png:-'], new Response(svg))
319
+ if (result.ok && result.stdout.byteLength > 8)
320
+ return result.stdout
321
+ }
322
+ return undefined
323
+ }
324
+
325
+ /** Non-blocking image variant encoding via stdout pipe (zero temp files, works on read-only FS). */
326
+ export async function encodeVariantToBytesAsync(
327
+ srcPath: string,
328
+ width: number,
329
+ format: 'avif' | 'webp',
330
+ quality: number,
331
+ ): Promise<Uint8Array<ArrayBuffer> | undefined> {
332
+ if (!hasMagick())
333
+ return undefined
334
+ const result = await runMagick([`${srcPath}[0]`, '-auto-orient', '-strip', '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
335
+ if (result.ok && result.stdout.byteLength > 0)
336
+ return result.stdout
337
+ return undefined
338
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.