@all-the.rest/astro-image-cdn 0.2.0 → 0.2.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/processor.js +79 -29
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@all-the.rest/astro-image-cdn",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Persistent, incremental image variants for Astro's native image components",
5
5
  "type": "module",
6
6
  "license": "ISC",
package/src/processor.js CHANGED
@@ -19,6 +19,12 @@ function normalizeFormat(format) {
19
19
  return format === "jpg" ? "jpeg" : format;
20
20
  }
21
21
 
22
+ function normalizeVariantFormat(metadata) {
23
+ return metadata.format === "heif" && metadata.mediaType === "image/avif"
24
+ ? "avif"
25
+ : normalizeFormat(metadata.format);
26
+ }
27
+
22
28
  function normalizeRelativePath(value) {
23
29
  return value.split(path.sep).join("/");
24
30
  }
@@ -104,6 +110,10 @@ function validatePositiveInteger(value, label) {
104
110
  }
105
111
  }
106
112
 
113
+ function heightMatchesExpected(expected, actual) {
114
+ return Number.isSafeInteger(actual) && Math.abs(actual - expected) <= 1;
115
+ }
116
+
107
117
  function resolveOptions(options) {
108
118
  if (!options || typeof options.rootDir !== "string") {
109
119
  throw new TypeError("processImages requires an absolute rootDir");
@@ -301,10 +311,10 @@ function expectedVariants(fingerprint, dimensions, sourceFormat, options) {
301
311
  })));
302
312
  }
303
313
 
304
- async function variantMatches(outputDir, variant) {
305
- if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
314
+ async function readMatchingVariant(outputDir, variant) {
315
+ if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return undefined;
306
316
  const filePath = path.resolve(outputDir, variant.file);
307
- if (!isInside(outputDir, filePath) || filePath === outputDir) return false;
317
+ if (!isInside(outputDir, filePath) || filePath === outputDir) return undefined;
308
318
 
309
319
  try {
310
320
  const relative = path.relative(outputDir, filePath);
@@ -313,20 +323,35 @@ async function variantMatches(outputDir, variant) {
313
323
  for (const segment of segments.slice(0, -1)) {
314
324
  directory = path.join(directory, segment);
315
325
  const directoryInfo = await lstat(directory);
316
- if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return false;
326
+ if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return undefined;
317
327
  }
318
328
  const fileInfo = await lstat(filePath);
319
- if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) return false;
320
- return digest(await readFile(filePath)) === variant.digest;
329
+ if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) return undefined;
330
+ const buffer = await readFile(filePath);
331
+ return digest(buffer) === variant.digest ? buffer : undefined;
321
332
  } catch (error) {
322
- if (error.code === "ENOENT" || error.code === "ENOTDIR") return false;
333
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
323
334
  throw error;
324
335
  }
325
336
  }
326
337
 
327
- async function outputExists(outputDir, variants) {
328
- const matches = await Promise.all(variants.map((variant) => variantMatches(outputDir, variant)));
329
- return matches.every(Boolean);
338
+ async function variantMatches(outputDir, variant) {
339
+ return (await readMatchingVariant(outputDir, variant)) !== undefined;
340
+ }
341
+
342
+ async function verifiedVariantHeight(outputDir, variant, expectedVariant) {
343
+ const buffer = await readMatchingVariant(outputDir, variant);
344
+ if (!buffer) return undefined;
345
+ let metadata;
346
+ try {
347
+ metadata = await sharp(buffer, { failOn: "none" }).metadata();
348
+ } catch {
349
+ return undefined;
350
+ }
351
+ if (normalizeVariantFormat(metadata) !== expectedVariant.format
352
+ || metadata.width !== expectedVariant.width
353
+ || !heightMatchesExpected(expectedVariant.height, metadata.height)) return undefined;
354
+ return metadata.height;
330
355
  }
331
356
 
332
357
  function variantKey(variant) {
@@ -344,10 +369,23 @@ function hasCompleteVariantSet(actual, expected) {
344
369
  }
345
370
  return expected.every((variant) => {
346
371
  const actualVariant = byKey.get(variantKey(variant));
347
- return actualVariant?.file === variant.file && actualVariant.height === variant.height;
372
+ return actualVariant?.file === variant.file && heightMatchesExpected(variant.height, actualVariant.height);
348
373
  });
349
374
  }
350
375
 
376
+ async function verifiedOutputVariants(outputDir, actual, expected) {
377
+ if (!hasCompleteVariantSet(actual, expected)) return undefined;
378
+ const actualByKey = new Map(actual.map((variant) => [variantKey(variant), variant]));
379
+ const verified = [];
380
+ for (const expectedVariant of expected) {
381
+ const variant = actualByKey.get(variantKey(expectedVariant));
382
+ const height = await verifiedVariantHeight(outputDir, variant, expectedVariant);
383
+ if (height === undefined) return undefined;
384
+ verified.push({ ...variant, height });
385
+ }
386
+ return verified;
387
+ }
388
+
351
389
  function carryForwardVariantDigests(expected, previous) {
352
390
  const previousByKey = new Map();
353
391
  if (Array.isArray(previous)) {
@@ -360,8 +398,8 @@ function carryForwardVariantDigests(expected, previous) {
360
398
 
361
399
  return expected.map((variant) => {
362
400
  const previousVariant = previousByKey.get(variantKey(variant));
363
- if (previousVariant?.file === variant.file && previousVariant.height === variant.height) {
364
- return { ...variant, digest: previousVariant.digest };
401
+ if (previousVariant?.file === variant.file && heightMatchesExpected(variant.height, previousVariant.height)) {
402
+ return { ...variant, height: previousVariant.height, digest: previousVariant.digest };
365
403
  }
366
404
  return variant;
367
405
  });
@@ -394,10 +432,10 @@ async function ensureVariantDirectory(outputDir, file) {
394
432
  return filePath;
395
433
  }
396
434
 
397
- async function writeVariant(buffer, filePath, width, format, quality, autoRotate) {
435
+ async function writeVariant(buffer, filePath, width, format, quality, autoRotate, expectedHeight) {
398
436
  if (format === "svg") {
399
437
  await atomicWrite(filePath, buffer);
400
- return digest(buffer);
438
+ return { digest: digest(buffer), width, height: expectedHeight };
401
439
  }
402
440
  const image = sharp(buffer, { failOn: "none" });
403
441
  if (autoRotate) image.rotate();
@@ -407,9 +445,9 @@ async function writeVariant(buffer, filePath, width, format, quality, autoRotate
407
445
  else if (format === "jpeg") image.jpeg({ quality });
408
446
  else image.png({ quality });
409
447
 
410
- const result = await image.toBuffer();
411
- await atomicWrite(filePath, result);
412
- return digest(result);
448
+ const { data, info } = await image.toBuffer({ resolveWithObject: true });
449
+ await atomicWrite(filePath, data);
450
+ return { digest: digest(data), width: info.width, height: info.height };
413
451
  }
414
452
 
415
453
  async function mapConcurrent(items, concurrency, callback) {
@@ -538,28 +576,39 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
538
576
  const dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
539
577
  const sourceFormat = normalizeFormat(dimensions.format);
540
578
  const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
579
+ const expectedByKey = new Map(expected.map((variant) => [variantKey(variant), variant]));
541
580
 
542
- const isWarm = cacheEntry?.fingerprint === fingerprint
581
+ const canReuse = cacheEntry?.fingerprint === fingerprint
543
582
  && previousEntry?.fingerprint === fingerprint
544
583
  && previousEntry.sourceHash === sourceHash
545
584
  && previousEntry.width === dimensions.width
546
585
  && previousEntry.height === dimensions.height
547
- && previousEntry.sourceFormat === dimensions.format
548
- && hasCompleteVariantSet(previousEntry.variants, expected)
549
- && await outputExists(outputDir, previousEntry.variants);
586
+ && previousEntry.sourceFormat === dimensions.format;
587
+ const verifiedVariants = canReuse
588
+ ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected)
589
+ : undefined;
590
+ const isWarm = verifiedVariants !== undefined;
550
591
  let variants;
551
592
  if (isWarm) {
552
- variants = previousEntry.variants;
593
+ variants = verifiedVariants;
553
594
  skipped++;
554
595
  } else {
555
596
  variants = carryForwardVariantDigests(expected, previousEntry?.variants);
556
597
  const missingVariants = [];
557
598
  for (const variant of variants) {
558
- if (!await variantMatches(outputDir, variant)) missingVariants.push(variant);
599
+ const height = await verifiedVariantHeight(outputDir, variant, expectedByKey.get(variantKey(variant)));
600
+ if (height === undefined) missingVariants.push(variant);
601
+ else variant.height = height;
559
602
  }
560
603
  await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
561
604
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
562
- variant.digest = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality, autoRotate);
605
+ const expectedVariant = expectedByKey.get(variantKey(variant));
606
+ const output = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality, autoRotate, expectedVariant.height);
607
+ if (output.width !== expectedVariant.width || !heightMatchesExpected(expectedVariant.height, output.height)) {
608
+ throw new Error(`Generated ${variant.width}.${variant.format} has unexpected dimensions ${output.width}x${output.height}`);
609
+ }
610
+ variant.height = output.height;
611
+ variant.digest = output.digest;
563
612
  });
564
613
  processed++;
565
614
  }
@@ -706,16 +755,17 @@ export async function adoptImageVariants(rawOptions, adoption) {
706
755
  } catch (error) {
707
756
  throw new Error(`Unable to read adopted variant ${inputPath}: ${error.message}`, { cause: error });
708
757
  }
709
- const actualFormat = normalizeFormat(metadata.format);
710
- const actualHeight = Math.max(1, Math.round(expectedVariant.width * dimensions.height / dimensions.width));
711
- if (actualFormat !== expectedVariant.format || metadata.width !== expectedVariant.width || metadata.height !== actualHeight) {
758
+ const actualFormat = normalizeVariantFormat(metadata);
759
+ const expectedHeight = expectedVariant.height;
760
+ if (actualFormat !== expectedVariant.format || metadata.width !== expectedVariant.width || !heightMatchesExpected(expectedHeight, metadata.height)) {
712
761
  throw new Error(
713
- `Adopted variant ${inputPath} does not match expected ${expectedVariant.width}x${actualHeight} ${expectedVariant.format}; ` +
762
+ `Adopted variant ${inputPath} does not match expected ${expectedVariant.width}x${expectedHeight}±1 ${expectedVariant.format}; ` +
714
763
  `received ${metadata.width}x${metadata.height} ${actualFormat}.`,
715
764
  );
716
765
  }
717
766
  validated.push({
718
767
  ...expectedVariant,
768
+ height: metadata.height,
719
769
  digest: digest(buffer),
720
770
  buffer,
721
771
  });