@all-the.rest/astro-image-cdn 0.4.0 → 0.4.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/README.md +37 -1
- package/package.json +1 -1
- package/src/index.d.ts +38 -0
- package/src/index.js +1 -1
- package/src/processor.js +261 -63
package/README.md
CHANGED
|
@@ -97,7 +97,7 @@ Image identity is the project-relative file path; no frontmatter, YAML sidecars,
|
|
|
97
97
|
- Each manifest is checked against the complete set of variants expected for its source and current options, so empty or partial entries trigger repair rather than a false cache hit.
|
|
98
98
|
- The private cache and manifest are updated atomically and only when their contents change. Concurrent native image requests are deduplicated and batched per event-loop turn; batches are serialized through one writer queue, while the configured concurrency controls processing within each batch. A pre-existing `manifest.json` in `outputDir` is detected, reported in the processing result, and warned about when an Astro-requested image or standalone bulk run processes images; it is never modified. Verify its ownership, then manually move it outside public output or remove it before publishing. A filesystem lock allows only one process to write a given output/cache pair; overlapping processes fail with the lock path instead of racing. If a process is interrupted, verify it has stopped and remove any leftover `.astro-image-cdn.lock` file before retrying; the next run can rebuild missing variants.
|
|
99
99
|
- Warm runs skip Sharp transformations when the fingerprint and every expected output still match. They also skip source reads when the recorded source stat still matches.
|
|
100
|
-
- Old content-addressed files are intentionally retained. Request-driven Astro processing preserves unrelated manifest entries; an explicit standalone `processImages()` run reconciles the manifest with the files found under its source directories. Neither mode deletes historical output files.
|
|
100
|
+
- Old content-addressed files are intentionally retained. Request-driven Astro processing preserves unrelated manifest entries; an explicit standalone `processImages()` run reconciles the manifest with the files found under its source directories. Neither mode deletes historical output files; use `pruneImages()` when reclaiming that space is intended.
|
|
101
101
|
- Astro's `dist/` remains Astro-owned; this package does not copy into, clean, or deploy it.
|
|
102
102
|
|
|
103
103
|
### Adopting existing variants
|
|
@@ -130,6 +130,40 @@ await adoptImageVariants({
|
|
|
130
130
|
|
|
131
131
|
The helper verifies the current source hash and each required output's actual format and dimensions before writing. It requires the complete variant set implied by the options; extras (such as legacy native-width files) are ignored. Outputs are atomically written under `outputDir`, and the private manifest/cache are updated only after validation. Under the default `verification: "stat"`, a repeated call whose targets and manifest already match returns without reading the supplied legacy files or copying bytes; `verification: "digest"` re-validates every supplied variant. Failures leave the prior manifest and existing outputs untouched, and old source variants are never removed. Supply the source hash recorded when the existing outputs were produced so a changed source cannot accidentally adopt stale files.
|
|
132
132
|
|
|
133
|
+
### Pruning stale variants
|
|
134
|
+
|
|
135
|
+
Because old variants are retained, `outputDir` keeps growing after style or pipeline changes. `pruneImages()` deletes files under `outputDir` that the private manifest does not reference and removes directories that become empty. It never reads, writes, or deletes sources, and it takes the same writer lock as `processImages()`/the integration, so it refuses to run while a build holds that lock.
|
|
136
|
+
|
|
137
|
+
```js
|
|
138
|
+
import { pruneImages } from "@all-the.rest/astro-image-cdn";
|
|
139
|
+
|
|
140
|
+
const preview = await pruneImages({
|
|
141
|
+
rootDir: process.cwd(),
|
|
142
|
+
outputDir: ".imagedist",
|
|
143
|
+
cacheDir: ".astro-image-cdn",
|
|
144
|
+
dryRun: true,
|
|
145
|
+
});
|
|
146
|
+
console.log(preview);
|
|
147
|
+
|
|
148
|
+
const result = await pruneImages({
|
|
149
|
+
rootDir: process.cwd(),
|
|
150
|
+
outputDir: ".imagedist",
|
|
151
|
+
cacheDir: ".astro-image-cdn",
|
|
152
|
+
});
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Pruning is intended for the point after a successful pipeline run or build has written the manifest and outputs that should be kept, and before publishing `outputDir`. Run it only when the private manifest is current: variants referenced by the manifest are always kept, so a stale manifest can keep stale variants, while a manifest from a different configuration cannot protect variants it does not know about. Start with `dryRun: true` to inspect the counts. The operation is not a substitute for running `processImages()` first.
|
|
156
|
+
|
|
157
|
+
- The private manifest is mandatory and is the sole authority for what is kept. `pruneImages()` refuses to start when `cacheDir/manifest.json` is missing, malformed, or contains an entry whose variant file is missing, unsafe, symlinked, or outside `outputDir`; refusing is deliberate, so a bad manifest cannot cause an unbounded delete. Referenced variants are checked before anything is deleted.
|
|
158
|
+
- An **empty manifest is not a no-op**: when `images` is `{}`, every file under `outputDir` is unreferenced and will be deleted. This can happen after `processImages()` ran against an empty source tree or a `sources` setting that contains no images. Confirm that is intended before pruning.
|
|
159
|
+
- `outputDir` must be a dedicated variants directory. It must not equal or contain `rootDir`, and it must not overlap Astro's `publicDir`, any configured `sources` directory, or `cacheDir`. The `rootDir` check applies even when `sources: []`, so a misconfigured absolute `outputDir` cannot prune the project itself.
|
|
160
|
+
- Only regular files under `outputDir` are deleted. Symlinks are never followed or unlinked, other special files are left untouched, and the writer lock file at the output root is ignored (a nested file with the same name is ordinary output). Kept files are never modified.
|
|
161
|
+
- Empty directories below `outputDir` are removed; `outputDir` itself and `cacheDir` are kept.
|
|
162
|
+
- A legacy public `manifest.json` in `outputDir` is reported in `legacyPublicManifestPath` and kept by default. Set `removeLegacyPublicManifest: true` to delete it (it is then included in `removed`/`bytesFreed`). Verify ownership before enabling this, as with the warning emitted during processing.
|
|
163
|
+
- `removed` counts deleted variant files, `kept` counts regular files and symlinks left in `outputDir` (the writer lock is not counted), `bytesFreed` sums the deleted files' sizes, and `removedDirectories` counts removed empty directories. With `dryRun: true`, all four report what would happen while nothing is deleted; `legacyPublicManifestRemoved` then means it would be removed.
|
|
164
|
+
|
|
165
|
+
The writer lock serializes this package's writers, not arbitrary processes. Pruning re-checks each directory and file immediately before descending or unlinking and never follows symlinks, but path-based filesystem APIs cannot make `outputDir` immutable. If another process concurrently renames or replaces entries inside `outputDir`, behavior is outside the guarantee. Run pruning as a build step on a quiescent output directory, or against a snapshot where external mutation cannot occur.
|
|
166
|
+
|
|
133
167
|
## API
|
|
134
168
|
|
|
135
169
|
The default export is the Astro integration. Its image processor runs only when a native Astro image API requests an imported local image. The exported `processImages()` API is a separate, explicit bulk operation for standalone build scripts; calling it scans every supported image under `sources`:
|
|
@@ -148,6 +182,8 @@ console.log(result);
|
|
|
148
182
|
|
|
149
183
|
The returned counts distinguish newly processed images from warm-cache reuses. `manifestPath` points into the configured private `cacheDir`; `legacyPublicManifestPath` is set when a pre-existing public manifest was found. This API only generates files and a manifest; it performs no deployment.
|
|
150
184
|
|
|
185
|
+
The exported `pruneImages()` API complements `processImages()` by reclaiming space from variants the manifest no longer references (see [Pruning stale variants](#pruning-stale-variants)). It accepts the same directory options plus `dryRun` and `removeLegacyPublicManifest`, and returns `removed`, `kept`, `bytesFreed`, `removedDirectories`, `dryRun`, `manifestPath`, `legacyPublicManifestPath`, and `legacyPublicManifestRemoved`. It never deploys and never touches `dist/`.
|
|
186
|
+
|
|
151
187
|
The standalone processor rejects `outputDir` or `cacheDir` inside Astro's `publicDir`, including symlink aliases. It assumes `rootDir/public` by default; pass `publicDir` when the Astro project customizes that directory. The integration supplies Astro's configured `publicDir` automatically.
|
|
152
188
|
|
|
153
189
|
## Development and verification
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -63,6 +63,43 @@ export interface ProcessImagesResult {
|
|
|
63
63
|
legacyPublicManifestPath?: string;
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
export interface PruneImagesOptions {
|
|
67
|
+
rootDir: string;
|
|
68
|
+
/** Directories that contain image sources; used only to reject unsafe overlaps. Defaults to ["src"]. */
|
|
69
|
+
sources?: string[];
|
|
70
|
+
/** Astro's public directory, relative to rootDir. Defaults to "public". */
|
|
71
|
+
publicDir?: string;
|
|
72
|
+
/**
|
|
73
|
+
* Persistent generated image directory, relative to rootDir. Defaults to ".imagedist".
|
|
74
|
+
* Must not equal or contain rootDir, and must not overlap publicDir, sources, or cacheDir.
|
|
75
|
+
*/
|
|
76
|
+
outputDir?: string;
|
|
77
|
+
/** Incremental state directory, relative to rootDir. Defaults to ".astro-image-cdn". */
|
|
78
|
+
cacheDir?: string;
|
|
79
|
+
/** Report what would be removed without deleting anything. Defaults to false. */
|
|
80
|
+
dryRun?: boolean;
|
|
81
|
+
/** Also remove a legacy public manifest.json in outputDir. Defaults to false. */
|
|
82
|
+
removeLegacyPublicManifest?: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface PruneImagesResult {
|
|
86
|
+
/** Variant files deleted; in a dry run, files that would be deleted. */
|
|
87
|
+
removed: number;
|
|
88
|
+
/** Regular files and symlinks left in outputDir. The writer lock is not counted. */
|
|
89
|
+
kept: number;
|
|
90
|
+
/** Sum of the deleted files' sizes in bytes; in a dry run, bytes that would be freed. */
|
|
91
|
+
bytesFreed: number;
|
|
92
|
+
/** Empty directories removed; in a dry run, directories that would be removed. */
|
|
93
|
+
removedDirectories: number;
|
|
94
|
+
dryRun: boolean;
|
|
95
|
+
/** Private manifest that was used as the reference, inside cacheDir. */
|
|
96
|
+
manifestPath: string;
|
|
97
|
+
/** Legacy public manifest found in outputDir, if any. */
|
|
98
|
+
legacyPublicManifestPath?: string;
|
|
99
|
+
/** Whether the legacy public manifest was removed; in a dry run, whether it would be removed. */
|
|
100
|
+
legacyPublicManifestRemoved: boolean;
|
|
101
|
+
}
|
|
102
|
+
|
|
66
103
|
export interface AdoptImageVariant {
|
|
67
104
|
/** Existing encoded output path; relative paths are resolved from rootDir. */
|
|
68
105
|
path: string;
|
|
@@ -89,6 +126,7 @@ export interface AdoptImageVariantsResult {
|
|
|
89
126
|
export default function astroImageCdn(options: AstroImageCdnOptions): AstroIntegration;
|
|
90
127
|
|
|
91
128
|
export declare function processImages(options: ProcessImagesOptions): Promise<ProcessImagesResult>;
|
|
129
|
+
export declare function pruneImages(options: PruneImagesOptions): Promise<PruneImagesResult>;
|
|
92
130
|
export declare function adoptImageVariants(
|
|
93
131
|
options: ProcessImagesOptions,
|
|
94
132
|
input: AdoptImageVariantsInput,
|
package/src/index.js
CHANGED
package/src/processor.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { open, readdir, readFile, realpath, rename, mkdir, lstat, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { open, readdir, readFile, realpath, rename, mkdir, lstat, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import sharp from "sharp";
|
|
5
5
|
|
|
@@ -61,6 +61,44 @@ async function canonicalizePath(value) {
|
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
async function resolveCanonicalDirectories(options) {
|
|
65
|
+
const { rootDir, sourceDirectories, publicDir } = options;
|
|
66
|
+
const canonicalRoot = await canonicalizePath(rootDir);
|
|
67
|
+
const canonicalSources = [];
|
|
68
|
+
for (const sourceDirectory of sourceDirectories) {
|
|
69
|
+
const relative = path.relative(rootDir, sourceDirectory);
|
|
70
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
71
|
+
throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
|
|
72
|
+
}
|
|
73
|
+
const canonicalSource = await canonicalizePath(sourceDirectory);
|
|
74
|
+
if (!isInside(canonicalRoot, canonicalSource)) {
|
|
75
|
+
throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
|
|
76
|
+
}
|
|
77
|
+
canonicalSources.push(canonicalSource);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const canonicalOutputDir = await canonicalizePath(options.outputDir);
|
|
81
|
+
const canonicalCacheDir = await canonicalizePath(options.cacheDir);
|
|
82
|
+
const canonicalPublicDir = await canonicalizePath(publicDir);
|
|
83
|
+
if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
|
|
84
|
+
throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
|
|
85
|
+
}
|
|
86
|
+
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
87
|
+
if (isInside(canonicalPublicDir, directory)) {
|
|
88
|
+
throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
for (const canonicalSource of canonicalSources) {
|
|
92
|
+
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
93
|
+
if (pathsOverlap(canonicalSource, directory)) {
|
|
94
|
+
throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return { canonicalRoot, canonicalSources, canonicalOutputDir, canonicalCacheDir, canonicalPublicDir };
|
|
100
|
+
}
|
|
101
|
+
|
|
64
102
|
async function releaseWriterLocks(locks) {
|
|
65
103
|
for (const { lockPath, token } of [...locks].reverse()) {
|
|
66
104
|
try {
|
|
@@ -200,6 +238,25 @@ function resolveOptions(options) {
|
|
|
200
238
|
};
|
|
201
239
|
}
|
|
202
240
|
|
|
241
|
+
function resolvePruneOptions(options) {
|
|
242
|
+
if (!options || typeof options.rootDir !== "string") {
|
|
243
|
+
throw new TypeError("pruneImages requires an absolute rootDir");
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const rootDir = path.resolve(options.rootDir);
|
|
247
|
+
const sourceDirectories = (options.sources ?? ["src"]).map((source) => path.resolve(rootDir, source));
|
|
248
|
+
const publicDir = path.resolve(rootDir, options.publicDir ?? "public");
|
|
249
|
+
const outputDir = path.resolve(rootDir, options.outputDir ?? ".imagedist");
|
|
250
|
+
const cacheDir = path.resolve(rootDir, options.cacheDir ?? ".astro-image-cdn");
|
|
251
|
+
const dryRun = options.dryRun ?? false;
|
|
252
|
+
const removeLegacyPublicManifest = options.removeLegacyPublicManifest ?? false;
|
|
253
|
+
for (const [label, value] of Object.entries({ dryRun, removeLegacyPublicManifest })) {
|
|
254
|
+
if (typeof value !== "boolean") throw new TypeError(`${label} must be a boolean`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return { rootDir, sourceDirectories, publicDir, outputDir, cacheDir, dryRun, removeLegacyPublicManifest };
|
|
258
|
+
}
|
|
259
|
+
|
|
203
260
|
async function walk(directory, output, excludedPaths) {
|
|
204
261
|
let entries;
|
|
205
262
|
try {
|
|
@@ -567,41 +624,10 @@ async function mapConcurrent(items, concurrency, callback) {
|
|
|
567
624
|
|
|
568
625
|
async function processImagesFromFiles(rawOptions, requestedFiles) {
|
|
569
626
|
const options = resolveOptions(rawOptions);
|
|
570
|
-
const { rootDir, sourceDirectories,
|
|
627
|
+
const { rootDir, sourceDirectories, concurrency, autoRotate, verification } = options;
|
|
571
628
|
let { outputDir, cacheDir } = options;
|
|
572
629
|
const reportedManifestPath = path.join(cacheDir, "manifest.json");
|
|
573
|
-
const canonicalRoot = await
|
|
574
|
-
const canonicalSources = [];
|
|
575
|
-
for (const sourceDirectory of sourceDirectories) {
|
|
576
|
-
const relative = path.relative(rootDir, sourceDirectory);
|
|
577
|
-
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
578
|
-
throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
|
|
579
|
-
}
|
|
580
|
-
const canonicalSource = await canonicalizePath(sourceDirectory);
|
|
581
|
-
if (!isInside(canonicalRoot, canonicalSource)) {
|
|
582
|
-
throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
|
|
583
|
-
}
|
|
584
|
-
canonicalSources.push(canonicalSource);
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
const canonicalOutputDir = await canonicalizePath(outputDir);
|
|
588
|
-
const canonicalCacheDir = await canonicalizePath(cacheDir);
|
|
589
|
-
const canonicalPublicDir = await canonicalizePath(publicDir);
|
|
590
|
-
if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
|
|
591
|
-
throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
|
|
592
|
-
}
|
|
593
|
-
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
594
|
-
if (isInside(canonicalPublicDir, directory)) {
|
|
595
|
-
throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
|
-
for (const canonicalSource of canonicalSources) {
|
|
599
|
-
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
600
|
-
if (pathsOverlap(canonicalSource, directory)) {
|
|
601
|
-
throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
}
|
|
630
|
+
const { canonicalRoot, canonicalSources } = await resolveCanonicalDirectories(options);
|
|
605
631
|
|
|
606
632
|
await mkdir(outputDir, { recursive: true });
|
|
607
633
|
await mkdir(cacheDir, { recursive: true });
|
|
@@ -797,26 +823,14 @@ export async function adoptImageVariants(rawOptions, adoption) {
|
|
|
797
823
|
throw new TypeError("adoptImageVariants requires a variants array");
|
|
798
824
|
}
|
|
799
825
|
|
|
800
|
-
const { rootDir,
|
|
826
|
+
const { rootDir, verification, autoRotate } = options;
|
|
801
827
|
const sourcePath = path.resolve(rootDir, adoption.sourcePath);
|
|
802
828
|
const relativePath = path.relative(rootDir, sourcePath);
|
|
803
829
|
if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
|
|
804
830
|
throw new Error(`Adopted source must remain inside rootDir: ${sourcePath}`);
|
|
805
831
|
}
|
|
806
832
|
|
|
807
|
-
const canonicalRoot = await
|
|
808
|
-
const canonicalSources = [];
|
|
809
|
-
for (const sourceDirectory of sourceDirectories) {
|
|
810
|
-
const relative = path.relative(rootDir, sourceDirectory);
|
|
811
|
-
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
812
|
-
throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
|
|
813
|
-
}
|
|
814
|
-
const canonicalSource = await canonicalizePath(sourceDirectory);
|
|
815
|
-
if (!isInside(canonicalRoot, canonicalSource)) {
|
|
816
|
-
throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
|
|
817
|
-
}
|
|
818
|
-
canonicalSources.push(canonicalSource);
|
|
819
|
-
}
|
|
833
|
+
const { canonicalRoot, canonicalSources } = await resolveCanonicalDirectories(options);
|
|
820
834
|
|
|
821
835
|
const sourceInfo = await lstat(sourcePath);
|
|
822
836
|
if (!sourceInfo.isFile() || sourceInfo.isSymbolicLink()) {
|
|
@@ -827,21 +841,6 @@ export async function adoptImageVariants(rawOptions, adoption) {
|
|
|
827
841
|
throw new Error(`Adopted source must be inside one of the configured image source directories: ${sourcePath}`);
|
|
828
842
|
}
|
|
829
843
|
|
|
830
|
-
const canonicalOutputDir = await canonicalizePath(options.outputDir);
|
|
831
|
-
const canonicalCacheDir = await canonicalizePath(options.cacheDir);
|
|
832
|
-
const canonicalPublicDir = await canonicalizePath(publicDir);
|
|
833
|
-
if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
|
|
834
|
-
throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
|
|
835
|
-
}
|
|
836
|
-
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
837
|
-
if (isInside(canonicalPublicDir, directory)) {
|
|
838
|
-
throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
|
|
839
|
-
}
|
|
840
|
-
if (canonicalSources.some((sourceDirectory) => pathsOverlap(sourceDirectory, directory))) {
|
|
841
|
-
throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
|
|
845
844
|
for (const [index, variant] of adoption.variants.entries()) {
|
|
846
845
|
if (!variant || typeof variant.path !== "string") {
|
|
847
846
|
throw new TypeError(`Adopted variant ${index} requires a path`);
|
|
@@ -1067,5 +1066,204 @@ export async function processImages(rawOptions) {
|
|
|
1067
1066
|
return processImagesFromFiles(rawOptions, undefined);
|
|
1068
1067
|
}
|
|
1069
1068
|
|
|
1069
|
+
async function readManifestForPrune(manifestPath) {
|
|
1070
|
+
let contents;
|
|
1071
|
+
try {
|
|
1072
|
+
contents = await readFile(manifestPath, "utf8");
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
if (error.code === "ENOENT") {
|
|
1075
|
+
throw new Error(`Refusing to prune image variants: no manifest at ${manifestPath}. Run processImages() first.`, { cause: error });
|
|
1076
|
+
}
|
|
1077
|
+
throw new Error(`Could not read JSON file ${manifestPath}: ${error.message}`, { cause: error });
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
let manifest;
|
|
1081
|
+
try {
|
|
1082
|
+
manifest = JSON.parse(contents);
|
|
1083
|
+
} catch (error) {
|
|
1084
|
+
throw new Error(`Could not read JSON file ${manifestPath}: ${error.message}`, { cause: error });
|
|
1085
|
+
}
|
|
1086
|
+
if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)
|
|
1087
|
+
|| !manifest.images || typeof manifest.images !== "object" || Array.isArray(manifest.images)) {
|
|
1088
|
+
throw new Error(`Refusing to prune image variants: manifest ${manifestPath} has no images object.`);
|
|
1089
|
+
}
|
|
1090
|
+
return manifest;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
function assertPruneDirectories(canonicalOutputDir, canonicalRoot, canonicalPublicDir) {
|
|
1094
|
+
if (isInside(canonicalOutputDir, canonicalRoot)) {
|
|
1095
|
+
throw new Error(`Refusing to prune image variants: outputDir must not equal or contain rootDir: ${canonicalOutputDir}`);
|
|
1096
|
+
}
|
|
1097
|
+
if (pathsOverlap(canonicalOutputDir, canonicalPublicDir)) {
|
|
1098
|
+
throw new Error(`Refusing to prune image variants: outputDir must not overlap Astro's public directory: ${canonicalOutputDir}`);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
function referencedOutputFiles(manifest, outputDir, manifestPath) {
|
|
1103
|
+
const referenced = new Set();
|
|
1104
|
+
for (const [source, entry] of Object.entries(manifest.images)) {
|
|
1105
|
+
if (!entry || typeof entry !== "object" || !Array.isArray(entry.variants)) {
|
|
1106
|
+
throw new Error(`Refusing to prune image variants: manifest ${manifestPath} has an unexpected entry for ${source}.`);
|
|
1107
|
+
}
|
|
1108
|
+
for (const variant of entry.variants) {
|
|
1109
|
+
if (!variant || typeof variant.file !== "string" || variant.file === "") {
|
|
1110
|
+
throw new Error(`Refusing to prune image variants: manifest ${manifestPath} has an invalid variant file for ${source}.`);
|
|
1111
|
+
}
|
|
1112
|
+
const filePath = path.resolve(outputDir, variant.file);
|
|
1113
|
+
if (!isInside(outputDir, filePath) || filePath === outputDir) {
|
|
1114
|
+
throw new Error(`Refusing to prune image variants: manifest ${manifestPath} references ${JSON.stringify(variant.file)} for ${source}, which is outside outputDir.`);
|
|
1115
|
+
}
|
|
1116
|
+
referenced.add(normalizeRelativePath(path.relative(outputDir, filePath)));
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
return referenced;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
async function assertReferencedVariantsExist(outputDir, referenced, manifestPath) {
|
|
1123
|
+
for (const file of referenced) {
|
|
1124
|
+
if (!(await inspectVariantFile(outputDir, file))) {
|
|
1125
|
+
throw new Error(`Refusing to prune image variants: manifest ${manifestPath} references missing or unsafe file ${file}. Run processImages() first.`);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
async function pruneOutputDirectory(outputDir, referenced, options) {
|
|
1131
|
+
const lockPath = path.join(outputDir, ".astro-image-cdn.lock");
|
|
1132
|
+
const legacyManifestPath = path.join(outputDir, "manifest.json");
|
|
1133
|
+
let removed = 0;
|
|
1134
|
+
let kept = 0;
|
|
1135
|
+
let bytesFreed = 0;
|
|
1136
|
+
const removableDirectories = [];
|
|
1137
|
+
|
|
1138
|
+
async function visit(directory) {
|
|
1139
|
+
let entries;
|
|
1140
|
+
try {
|
|
1141
|
+
if (directory !== outputDir) {
|
|
1142
|
+
// Defense in depth against a directory being replaced by a symlink: never descend through it.
|
|
1143
|
+
const info = await lstat(directory);
|
|
1144
|
+
if (!info.isDirectory() || info.isSymbolicLink()) return true;
|
|
1145
|
+
}
|
|
1146
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
1147
|
+
} catch (error) {
|
|
1148
|
+
if (error.code === "ENOENT") return false;
|
|
1149
|
+
throw error;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
let retained = 0;
|
|
1153
|
+
for (const entry of entries) {
|
|
1154
|
+
const entryPath = path.join(directory, entry.name);
|
|
1155
|
+
if (entryPath === lockPath) {
|
|
1156
|
+
// The writer lock is ours and still held; it is not part of the output inventory.
|
|
1157
|
+
retained++;
|
|
1158
|
+
continue;
|
|
1159
|
+
}
|
|
1160
|
+
if (entryPath === legacyManifestPath) {
|
|
1161
|
+
// Handled separately so it can be kept or explicitly removed, even when it is a symlink.
|
|
1162
|
+
if (!options.removeLegacyPublicManifest) kept++;
|
|
1163
|
+
retained++;
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
if (entry.isDirectory()) {
|
|
1167
|
+
if (await visit(entryPath)) retained++;
|
|
1168
|
+
else removableDirectories.push(entryPath);
|
|
1169
|
+
continue;
|
|
1170
|
+
}
|
|
1171
|
+
// Symlinks and special files are never followed, unlinked, or counted as freed bytes.
|
|
1172
|
+
if (!entry.isFile()) {
|
|
1173
|
+
kept++;
|
|
1174
|
+
retained++;
|
|
1175
|
+
continue;
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
const relative = normalizeRelativePath(path.relative(outputDir, entryPath));
|
|
1179
|
+
if (referenced.has(relative)) {
|
|
1180
|
+
kept++;
|
|
1181
|
+
retained++;
|
|
1182
|
+
continue;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
const info = await lstat(entryPath);
|
|
1186
|
+
if (!info.isFile() || info.isSymbolicLink()) {
|
|
1187
|
+
kept++;
|
|
1188
|
+
retained++;
|
|
1189
|
+
continue;
|
|
1190
|
+
}
|
|
1191
|
+
if (!options.dryRun) await unlink(entryPath);
|
|
1192
|
+
removed++;
|
|
1193
|
+
bytesFreed += info.size;
|
|
1194
|
+
}
|
|
1195
|
+
return retained > 0;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
await visit(outputDir);
|
|
1199
|
+
|
|
1200
|
+
let removedDirectories = 0;
|
|
1201
|
+
for (const directory of removableDirectories) {
|
|
1202
|
+
if (options.dryRun) {
|
|
1203
|
+
removedDirectories++;
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
try {
|
|
1207
|
+
await rmdir(directory);
|
|
1208
|
+
removedDirectories++;
|
|
1209
|
+
} catch (error) {
|
|
1210
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTEMPTY") throw error;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
return { removed, kept, bytesFreed, removedDirectories };
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/**
|
|
1218
|
+
* Delete generated variants under outputDir that the private manifest no longer references.
|
|
1219
|
+
* Never follows symlinks, never touches sources, and runs under the writer lock.
|
|
1220
|
+
*/
|
|
1221
|
+
export async function pruneImages(rawOptions) {
|
|
1222
|
+
const options = resolvePruneOptions(rawOptions);
|
|
1223
|
+
const manifestPath = path.join(options.cacheDir, "manifest.json");
|
|
1224
|
+
const { canonicalRoot, canonicalOutputDir, canonicalPublicDir } = await resolveCanonicalDirectories(options);
|
|
1225
|
+
assertPruneDirectories(canonicalOutputDir, canonicalRoot, canonicalPublicDir);
|
|
1226
|
+
|
|
1227
|
+
await mkdir(options.outputDir, { recursive: true });
|
|
1228
|
+
await mkdir(options.cacheDir, { recursive: true });
|
|
1229
|
+
const outputDir = await realpath(options.outputDir);
|
|
1230
|
+
const cacheDir = await realpath(options.cacheDir);
|
|
1231
|
+
const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
|
|
1232
|
+
try {
|
|
1233
|
+
const lockedManifestPath = path.join(cacheDir, "manifest.json");
|
|
1234
|
+
const manifest = await readManifestForPrune(lockedManifestPath);
|
|
1235
|
+
const referenced = referencedOutputFiles(manifest, outputDir, lockedManifestPath);
|
|
1236
|
+
await assertReferencedVariantsExist(outputDir, referenced, lockedManifestPath);
|
|
1237
|
+
const legacyPublicManifestPath = await detectLegacyPublicManifest(outputDir);
|
|
1238
|
+
const legacyInfo = legacyPublicManifestPath ? await lstat(legacyPublicManifestPath) : undefined;
|
|
1239
|
+
if (legacyInfo && options.removeLegacyPublicManifest && !legacyInfo.isFile() && !legacyInfo.isSymbolicLink()) {
|
|
1240
|
+
throw new Error(`Refusing to prune image variants: legacy manifest path ${legacyPublicManifestPath} is not a file.`);
|
|
1241
|
+
}
|
|
1242
|
+
const stats = await pruneOutputDirectory(outputDir, referenced, options);
|
|
1243
|
+
|
|
1244
|
+
let { removed, kept, bytesFreed } = stats;
|
|
1245
|
+
let legacyPublicManifestRemoved = false;
|
|
1246
|
+
if (legacyInfo && options.removeLegacyPublicManifest) {
|
|
1247
|
+
if (legacyInfo.isFile() && !legacyInfo.isSymbolicLink()) bytesFreed += legacyInfo.size;
|
|
1248
|
+
if (!options.dryRun) await unlink(legacyPublicManifestPath);
|
|
1249
|
+
removed++;
|
|
1250
|
+
legacyPublicManifestRemoved = true;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
return {
|
|
1254
|
+
removed,
|
|
1255
|
+
kept,
|
|
1256
|
+
bytesFreed,
|
|
1257
|
+
removedDirectories: stats.removedDirectories,
|
|
1258
|
+
dryRun: options.dryRun,
|
|
1259
|
+
manifestPath,
|
|
1260
|
+
legacyPublicManifestPath,
|
|
1261
|
+
legacyPublicManifestRemoved,
|
|
1262
|
+
};
|
|
1263
|
+
} finally {
|
|
1264
|
+
await releaseLocks();
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1070
1268
|
export const DEFAULT_IMAGE_WIDTHS = DEFAULT_WIDTHS;
|
|
1071
1269
|
export const DEFAULT_IMAGE_FORMATS = DEFAULT_FORMATS;
|