@all-the.rest/astro-image-cdn 0.0.0-stage → 0.1.1

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/service.js ADDED
@@ -0,0 +1,468 @@
1
+ import { readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { readdir, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { DEV_ASSET_PREFIX } from "./dev-server.js";
6
+ import { processRequestedImages } from "./processor.js";
7
+
8
+ const manifestCache = new Map();
9
+ const requestBatches = new Map();
10
+ const TRANSFORM_OPTIONS = new Set([
11
+ "src", "width", "height", "format", "quality", "widths", "densities", "layout", "priority",
12
+ "fit", "position", "background", "inferSize", "formats",
13
+ ]);
14
+ const ASTRO_SOURCE_FORMATS = new Set(["avif", "webp", "jpeg", "jpg", "png", "tiff", "gif", "svg"]);
15
+ const CONFIGURED_OUTPUT_FORMATS = new Set(["avif", "webp", "jpeg", "png"]);
16
+ const EXCLUDED_DIRS = new Set([".astro", ".cache", ".git", "dist", "node_modules"]);
17
+
18
+ function normalizeFormat(format) {
19
+ return format === "jpg" ? "jpeg" : format;
20
+ }
21
+
22
+ function isImportedImage(source) {
23
+ return (typeof source === "object" && source !== null) || (typeof source === "function" && "src" in source);
24
+ }
25
+
26
+ function defaultOutputFormat(options) {
27
+ return isImportedImage(options.src) && normalizeFormat(options.src.format) === "svg" ? "svg" : "webp";
28
+ }
29
+
30
+ function rejectRemoteUrlCredentials(source) {
31
+ if (typeof source !== "string") return;
32
+
33
+ const trimmedSource = source.trim();
34
+ if (!/^[a-z][a-z\d+.-]*:\/\//i.test(trimmedSource)) return;
35
+ if (/\s|[\u0000-\u001f\u007f]/u.test(source)) {
36
+ throw new TypeError("Remote image URLs must not contain whitespace or control characters.");
37
+ }
38
+
39
+ const rawAuthority = source.match(/^[a-z][a-z\d+.-]*:\/\/([^/?#]*)/i)?.[1] ?? "";
40
+ let parsedUrl;
41
+ try {
42
+ parsedUrl = new URL(source);
43
+ } catch {
44
+ if (!rawAuthority.includes("@")) return;
45
+ }
46
+
47
+ if (parsedUrl?.username || parsedUrl?.password || rawAuthority.includes("@")) {
48
+ throw new TypeError("Remote image URLs must not include username or password credentials.");
49
+ }
50
+ }
51
+
52
+ function readManifest(imageConfig) {
53
+ const manifestPath = manifestPathFor(imageConfig);
54
+ let mtime;
55
+ try {
56
+ mtime = statSync(manifestPath).mtimeMs;
57
+ } catch (error) {
58
+ throw new Error(`astro-image-cdn manifest not found at ${manifestPath}. Run an Astro build or start its dev server with the integration enabled.`, { cause: error });
59
+ }
60
+
61
+ const cached = manifestCache.get(manifestPath);
62
+ if (cached?.mtime === mtime) return cached.manifest;
63
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
64
+ manifestCache.set(manifestPath, { mtime, manifest });
65
+ return manifest;
66
+ }
67
+
68
+ function manifestPathFor(imageConfig) {
69
+ const cacheDir = path.resolve(imageConfig.service.config.rootDir, imageConfig.service.config.cacheDir);
70
+ return path.join(cacheDir, "manifest.json");
71
+ }
72
+
73
+ function requestBatchKey(config) {
74
+ return [config.rootDir, config.outputDir, config.cacheDir].map((directory) => path.resolve(directory))
75
+ .concat(config.requestSessionId ?? "")
76
+ .join("\0");
77
+ }
78
+
79
+ function scheduleRequestBatch(state, config, logger) {
80
+ if (state.scheduled || state.flushing || state.pending.size === 0) return;
81
+ state.scheduled = true;
82
+ queueMicrotask(async () => {
83
+ state.scheduled = false;
84
+ state.flushing = true;
85
+ const batch = [...state.pending.entries()];
86
+ state.pending.clear();
87
+ try {
88
+ const result = await processRequestedImages(config, batch.map(([sourcePath]) => sourcePath));
89
+ manifestCache.delete(path.join(path.resolve(config.rootDir, config.cacheDir), "manifest.json"));
90
+ logger?.info(`astro-image-cdn: ${result.processed} processed, ${result.skipped} reused; private state at ${result.manifestPath}`);
91
+ if (result.legacyPublicManifestPath && !state.warnedAboutLegacyManifest) {
92
+ state.warnedAboutLegacyManifest = true;
93
+ logger?.warn(`astro-image-cdn found a pre-existing manifest at ${result.legacyPublicManifestPath} and left it untouched. Verify that it belongs to astro-image-cdn, then manually remove it from the public output (or move it outside outputDir) before publishing. The current private manifest is at ${result.manifestPath}.`);
94
+ }
95
+ for (const [, request] of batch) request.resolve();
96
+ } catch (error) {
97
+ for (const [sourcePath, request] of batch) {
98
+ if (state.requests.get(sourcePath) === request) state.requests.delete(sourcePath);
99
+ request.reject(error);
100
+ }
101
+ } finally {
102
+ state.flushing = false;
103
+ scheduleRequestBatch(state, config, logger);
104
+ }
105
+ });
106
+ }
107
+
108
+ async function ensureRequestedImage(options, imageConfig, logger) {
109
+ if (typeof options.src === "string") return Promise.resolve();
110
+ const sourcePath = await requestedSourcePath(options.src, imageConfig.service.config);
111
+ if (typeof sourcePath !== "string") {
112
+ throw new Error(`astro-image-cdn cannot identify the source file for imported image ${JSON.stringify(options.src?.src)}; import the image from a configured source directory.`);
113
+ }
114
+
115
+ const config = imageConfig.service.config;
116
+ const absoluteSourcePath = path.resolve(sourcePath);
117
+ const key = requestBatchKey(config);
118
+ const fileInfo = statSync(absoluteSourcePath, { bigint: true });
119
+ const fingerprint = [fileInfo.dev, fileInfo.ino, fileInfo.size, fileInfo.mtimeNs, fileInfo.ctimeNs].join(":");
120
+ let state = requestBatches.get(key);
121
+ if (!state) {
122
+ state = {
123
+ requests: new Map(),
124
+ pending: new Map(),
125
+ scheduled: false,
126
+ flushing: false,
127
+ warnedAboutLegacyManifest: false,
128
+ };
129
+ requestBatches.set(key, state);
130
+ }
131
+ const existing = state.requests.get(absoluteSourcePath);
132
+ if (existing?.fingerprint === fingerprint) return existing.promise;
133
+ if (existing && state.pending.get(absoluteSourcePath) === existing) {
134
+ // A queued request will read the latest source contents when its batch runs.
135
+ existing.fingerprint = fingerprint;
136
+ return existing.promise;
137
+ }
138
+
139
+ let resolve;
140
+ let reject;
141
+ const promise = new Promise((resolvePromise, rejectPromise) => {
142
+ resolve = resolvePromise;
143
+ reject = rejectPromise;
144
+ });
145
+ const request = { fingerprint, promise, resolve, reject };
146
+ state.requests.set(absoluteSourcePath, request);
147
+ state.pending.set(absoluteSourcePath, request);
148
+ scheduleRequestBatch(state, config, logger);
149
+ return promise;
150
+ }
151
+
152
+ function sourceCandidates(value, rootDir) {
153
+ if (!value || typeof value !== "string") return [];
154
+ const candidates = new Set();
155
+ let decoded = value;
156
+ try {
157
+ if (decoded.startsWith("file:")) decoded = fileURLToPath(decoded);
158
+ else decoded = decodeURIComponent(decoded);
159
+ } catch {}
160
+
161
+ if (decoded.startsWith("/@fs/")) decoded = decoded.slice("/@fs".length);
162
+ if (path.isAbsolute(decoded)) {
163
+ candidates.add(path.resolve(decoded));
164
+ let canonicalPath = path.resolve(decoded);
165
+ try {
166
+ canonicalPath = realpathSync(canonicalPath);
167
+ candidates.add(canonicalPath);
168
+ } catch {}
169
+ const relative = path.relative(rootDir, canonicalPath);
170
+ if (!relative.startsWith(`..${path.sep}`) && relative !== "..") candidates.add(relative.split(path.sep).join("/"));
171
+ } else {
172
+ const cleaned = decoded.replace(/^\/+/, "");
173
+ candidates.add(cleaned.split(path.sep).join("/"));
174
+ candidates.add(path.resolve(rootDir, cleaned));
175
+ }
176
+ return [...candidates];
177
+ }
178
+
179
+ function isInside(parent, candidate) {
180
+ const relative = path.relative(parent, candidate);
181
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
182
+ }
183
+
184
+ function isConfiguredSourcePath(sourcePath, config) {
185
+ const rootDir = path.resolve(config.rootDir);
186
+ const relative = path.relative(rootDir, sourcePath);
187
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return false;
188
+ const sourceDirectories = (config.sources ?? ["src"]).map((source) => path.resolve(rootDir, source));
189
+ return sourceDirectories.some((directory) => isInside(directory, sourcePath));
190
+ }
191
+
192
+ async function findFilesByName(directory, fileName, matches) {
193
+ let entries;
194
+ try {
195
+ entries = await readdir(directory, { withFileTypes: true });
196
+ } catch (error) {
197
+ if (error.code === "ENOENT") return;
198
+ throw error;
199
+ }
200
+
201
+ for (const entry of entries) {
202
+ if (entry.isDirectory()) {
203
+ if (!EXCLUDED_DIRS.has(entry.name)) await findFilesByName(path.join(directory, entry.name), fileName, matches);
204
+ } else if (entry.isFile() && entry.name === fileName) {
205
+ matches.push(path.join(directory, entry.name));
206
+ }
207
+ }
208
+ }
209
+
210
+ async function requestedSourcePath(source, config) {
211
+ if (typeof source?.fsPath === "string") return path.resolve(source.fsPath);
212
+
213
+ const sourceName = typeof source?.src === "string" ? source.src : undefined;
214
+ if (!sourceName) return undefined;
215
+ const rootDir = path.resolve(config.rootDir);
216
+ const sourceNameWithoutQuery = sourceName.split(/[?#]/, 1)[0];
217
+ for (const candidate of sourceCandidates(sourceNameWithoutQuery, rootDir)) {
218
+ const absoluteCandidate = path.resolve(rootDir, candidate);
219
+ if (!isConfiguredSourcePath(absoluteCandidate, config)) continue;
220
+ try {
221
+ if ((await stat(absoluteCandidate)).isFile()) return absoluteCandidate;
222
+ } catch (error) {
223
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
224
+ }
225
+ }
226
+
227
+ // Astro's SVG component wrapper serializes image metadata without its private fsPath.
228
+ // Resolve that requested import by its emitted basename, but reject ambiguous matches.
229
+ const basename = path.posix.basename(sourceNameWithoutQuery)
230
+ .replace(/\.[a-z0-9_-]{8,}(?=\.[^.]+$)/i, "");
231
+ const matches = [];
232
+ for (const directory of (config.sources ?? ["src"]).map((sourceDirectory) => path.resolve(rootDir, sourceDirectory))) {
233
+ await findFilesByName(directory, basename, matches);
234
+ }
235
+ if (matches.length === 1) return matches[0];
236
+ if (matches.length > 1) {
237
+ throw new Error(`astro-image-cdn cannot uniquely match requested image ${JSON.stringify(basename)} to a source file. Use a unique filename or import from a dedicated source directory.`);
238
+ }
239
+ return undefined;
240
+ }
241
+
242
+ function validateAstroOptions(options) {
243
+ if (!options?.src || (typeof options.src !== "string" && !isImportedImage(options.src))) {
244
+ throw new TypeError("Astro image options require an imported image or a remote image source.");
245
+ }
246
+
247
+ if (typeof options.src === "string") {
248
+ const isUrl = /^[a-z][a-z\d+.-]*:/i.test(options.src);
249
+ if (options.src.startsWith("/@fs/") || (!isUrl && !options.src.startsWith("/"))) {
250
+ throw new TypeError(`Local image source ${JSON.stringify(options.src)} must be imported instead of passed as a string.`);
251
+ }
252
+ if (!options.width || !options.height) {
253
+ const missingDimension = !options.width && !options.height ? "width and height" : !options.width ? "width" : "height";
254
+ throw new TypeError(`Remote image sources require ${missingDimension}; provide explicit dimensions for ${JSON.stringify(options.src)}.`);
255
+ }
256
+ return;
257
+ }
258
+
259
+ if (!ASTRO_SOURCE_FORMATS.has(options.src.format)) {
260
+ throw new TypeError(`Astro image service does not support source format ${JSON.stringify(options.src.format)}.`);
261
+ }
262
+ if (options.widths && options.densities) {
263
+ throw new TypeError("Astro image options cannot specify both widths and densities.");
264
+ }
265
+ if (options.src.format !== "svg" && options.format === "svg") {
266
+ throw new TypeError("Astro image service cannot convert a non-SVG source to SVG.");
267
+ }
268
+ }
269
+
270
+ function resolveImage(options, imageConfig) {
271
+ const manifest = readManifest(imageConfig);
272
+ const rootDir = path.resolve(imageConfig.service.config.rootDir);
273
+ const source = options.src;
274
+ const possibleSources = [];
275
+ if (isImportedImage(source)) {
276
+ if (typeof source.fsPath === "string") possibleSources.push(...sourceCandidates(source.fsPath, rootDir));
277
+ possibleSources.push(...sourceCandidates(source.src, rootDir));
278
+ } else {
279
+ possibleSources.push(...sourceCandidates(source, rootDir));
280
+ }
281
+
282
+ for (const candidate of possibleSources) {
283
+ const entry = manifest.images[candidate];
284
+ if (entry) return entry;
285
+ }
286
+
287
+ const sourceName = typeof source === "string" ? source : source?.src;
288
+ if (typeof sourceName === "string") {
289
+ const builtAssetName = path.basename(sourceName).replace(/\.[a-z0-9_-]{8,}(?=\.[^.]+$)/i, "");
290
+ const sameName = Object.values(manifest.images).filter((entry) => path.posix.basename(entry.source) === builtAssetName);
291
+ const sameDimensions = sameName.filter((entry) => entry.width === source?.width && entry.height === source?.height);
292
+ const candidates = sameDimensions.length > 0 ? sameDimensions : sameName;
293
+ if (candidates.length === 1) return candidates[0];
294
+ if (candidates.length > 1 && candidates.every((entry) => entry.fingerprint === candidates[0].fingerprint)) {
295
+ return candidates[0];
296
+ }
297
+ if (candidates.length > 1) {
298
+ throw new Error(
299
+ `astro-image-cdn found multiple files named ${JSON.stringify(builtAssetName)} with matching dimensions. ` +
300
+ `Use unique source filenames or import one file from a dedicated source directory.`
301
+ );
302
+ }
303
+ }
304
+
305
+ throw new Error(
306
+ `astro-image-cdn cannot match Astro image source ${JSON.stringify(sourceName)} to a scanned file. ` +
307
+ `Ensure the imported image is inside one of the configured source directories.`
308
+ );
309
+ }
310
+
311
+ function targetWidth(options, image) {
312
+ if (options.width) return Math.min(image.width, Math.max(1, Math.round(Number(options.width))));
313
+ if (options.height) {
314
+ return Math.min(image.width, Math.max(1, Math.round(Number(options.height) * image.width / image.height)));
315
+ }
316
+ return image.width;
317
+ }
318
+
319
+ function validateStaticTransform(options, config) {
320
+ if (typeof options.src === "string") return;
321
+
322
+ if (options.background != null) {
323
+ throw new Error("astro-image-cdn does not support per-image background flattening; use a pre-flattened source image.");
324
+ }
325
+ if (options.fit != null && !["cover", "contain"].includes(options.fit)) {
326
+ throw new Error(`astro-image-cdn does not support fit="${options.fit}".`);
327
+ }
328
+
329
+ const width = Number(options.width ?? options.src.width);
330
+ const height = Number(options.height ?? (width * options.src.height / options.src.width));
331
+ const targetRatio = width / height;
332
+ const sourceRatio = options.src.width / options.src.height;
333
+ if (Number.isFinite(targetRatio) && Math.abs(targetRatio - sourceRatio) > 0.005) {
334
+ throw new Error("astro-image-cdn generates aspect-preserving variants only; per-image cropping is not supported.");
335
+ }
336
+
337
+ if (options.quality != null) {
338
+ const presets = { low: 25, mid: 50, high: 80, max: 100 };
339
+ const requestedQuality = typeof options.quality === "number"
340
+ ? options.quality
341
+ : presets[options.quality] ?? Number(options.quality);
342
+ if (requestedQuality !== config.quality) {
343
+ throw new Error(`astro-image-cdn uses build-wide quality ${config.quality}; requested per-image quality ${options.quality} (${requestedQuality}) is not available.`);
344
+ }
345
+ }
346
+ }
347
+
348
+ function findVariant(image, width, format) {
349
+ const variants = image.variants.filter((variant) => variant.format === format);
350
+ if (variants.length === 0) return undefined;
351
+ return variants.find((variant) => variant.width >= width) ?? variants.at(-1);
352
+ }
353
+
354
+ function imageUrl(options, imageConfig, width) {
355
+ const config = imageConfig.service.config;
356
+ const image = resolveImage(options, imageConfig);
357
+ const format = normalizeFormat(options.format ?? defaultOutputFormat(options));
358
+ const variant = findVariant(image, width, format);
359
+ if (!variant) {
360
+ throw new Error(`astro-image-cdn has no ${format} variant for ${image.source}. Add the format to the integration's formats option.`);
361
+ }
362
+ const variantPath = variant.file.split("/").map(encodeURIComponent).join("/");
363
+ return config.devMode ? `${DEV_ASSET_PREFIX}${variantPath}` : `${config.baseUrl}/${variantPath}`;
364
+ }
365
+
366
+ const service = {
367
+ validateOptions(options, imageConfig) {
368
+ rejectRemoteUrlCredentials(options?.src);
369
+ const config = imageConfig.service.config;
370
+ validateAstroOptions(options);
371
+ const sourceFormat = isImportedImage(options.src) ? normalizeFormat(options.src.format) : undefined;
372
+ const configuredFormats = config.formats.map(normalizeFormat);
373
+ const invalidFormats = configuredFormats.filter((format) => !CONFIGURED_OUTPUT_FORMATS.has(format));
374
+ if (invalidFormats.length > 0) {
375
+ throw new Error(`astro-image-cdn has unsupported configured output format(s): ${invalidFormats.join(", ")}. Supported output formats are avif, webp, jpeg, or png.`);
376
+ }
377
+ const format = normalizeFormat(options.format ?? defaultOutputFormat(options));
378
+ const isSourceFormat = sourceFormat === format && ["avif", "webp", "jpeg", "png", "svg"].includes(format);
379
+ if (typeof options.src !== "string" && !configuredFormats.includes(format) && !isSourceFormat) {
380
+ if (format === "webp" && options.format == null) {
381
+ throw new Error('Astro 7.4 defaults raster images to "webp", but "webp" is not configured. Add "webp" to astroImageCdn({ formats }) or set an explicit configured format on the image.');
382
+ }
383
+ throw new Error(`astro-image-cdn format "${format}" is not configured for generation`);
384
+ }
385
+ if (sourceFormat === "svg" && format !== "svg" && !config.dangerouslyProcessSVG) {
386
+ throw new Error("SVG image processing is disabled. Set image.dangerouslyProcessSVG: true only if you trust the SVG source.");
387
+ }
388
+ validateStaticTransform(options, config);
389
+ const validatedOptions = { ...options, format };
390
+ if (validatedOptions.width) validatedOptions.width = Math.round(validatedOptions.width);
391
+ if (validatedOptions.height) validatedOptions.height = Math.round(validatedOptions.height);
392
+ delete validatedOptions.layout;
393
+ if (validatedOptions.fit === "none") delete validatedOptions.fit;
394
+ return validatedOptions;
395
+ },
396
+
397
+ async getURL(options, imageConfig, logger) {
398
+ if (typeof options.src === "string") return options.src;
399
+ await ensureRequestedImage(options, imageConfig, logger);
400
+ const image = resolveImage(options, imageConfig);
401
+ return imageUrl(options, imageConfig, targetWidth(options, image));
402
+ },
403
+
404
+ async getSrcSet(options, imageConfig, logger) {
405
+ if (typeof options.src === "string") return [];
406
+ await ensureRequestedImage(options, imageConfig, logger);
407
+ const image = resolveImage(options, imageConfig);
408
+ const format = normalizeFormat(options.format ?? defaultOutputFormat(options));
409
+ const variants = image.variants.filter((variant) => variant.format === format);
410
+ const maximumWidth = targetWidth(options, image);
411
+ let candidates;
412
+
413
+ if (Array.isArray(options.widths) && options.widths.length > 0) {
414
+ candidates = options.widths
415
+ .map((width) => findVariant(image, Math.min(image.width, Math.round(width)), format))
416
+ .filter(Boolean);
417
+ } else if (Array.isArray(options.densities) && options.densities.length > 0) {
418
+ candidates = options.densities
419
+ .map((density) => {
420
+ const multiplier = typeof density === "string" ? Number.parseFloat(density) : Number(density);
421
+ return findVariant(image, Math.min(image.width, Math.round(maximumWidth * multiplier)), format);
422
+ })
423
+ .filter(Boolean);
424
+ } else {
425
+ candidates = [];
426
+ }
427
+
428
+ const unique = [...new Map(candidates.map((variant) => [variant.width, variant])).values()]
429
+ .filter((variant) => variant.width <= image.width)
430
+ .sort((a, b) => a.width - b.width);
431
+ return unique.map((variant) => ({
432
+ transform: { ...options, width: variant.width, height: variant.height, format },
433
+ descriptor: Array.isArray(options.densities) && options.densities.length > 0
434
+ ? `${Number((variant.width / maximumWidth).toFixed(2))}x`
435
+ : `${variant.width}w`,
436
+ attributes: { type: `image/${format}` },
437
+ }));
438
+ },
439
+
440
+ async getHTMLAttributes(options, imageConfig, logger) {
441
+ const attributes = Object.fromEntries(Object.entries(options).filter(([key]) => !TRANSFORM_OPTIONS.has(key)));
442
+ if (typeof options.src === "string") {
443
+ return {
444
+ ...attributes,
445
+ width: options.width,
446
+ height: options.height,
447
+ loading: attributes.loading ?? (options.priority ? "eager" : "lazy"),
448
+ decoding: attributes.decoding ?? "async",
449
+ ...(options.priority ? { fetchpriority: "high" } : {}),
450
+ };
451
+ }
452
+
453
+ await ensureRequestedImage(options, imageConfig, logger);
454
+ const image = resolveImage(options, imageConfig);
455
+ const width = targetWidth(options, image);
456
+ const height = Math.max(1, Math.round(width * image.height / image.width));
457
+ return {
458
+ ...attributes,
459
+ width,
460
+ height,
461
+ loading: attributes.loading ?? (options.priority ? "eager" : "lazy"),
462
+ decoding: attributes.decoding ?? "async",
463
+ ...(options.priority ? { fetchpriority: "high" } : {}),
464
+ };
465
+ },
466
+ };
467
+
468
+ export default service;