@ecopages/image-processor 0.2.0-alpha.1 → 0.2.0-alpha.10

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/plugin.js CHANGED
@@ -1,13 +1,12 @@
1
1
  import path from "node:path";
2
- import { fileURLToPath } from "node:url";
3
2
  import { deepMerge } from "@ecopages/core/utils/deep-merge";
4
3
  import { GENERATED_BASE_PATHS } from "@ecopages/core/constants";
5
4
  import { fileSystem } from "@ecopages/file-system";
6
5
  import { Processor } from "@ecopages/core/plugins/processor";
7
6
  import { Logger } from "@ecopages/logger";
8
- import { createImagePlugin, createImagePluginBundler } from "./image-plugins";
9
- import { ImageProcessor } from "./image-processor";
10
- import { anyCaseToCamelCase } from "./utils";
7
+ import { createImagePlugin, createImagePluginBundler } from "./image-plugins.js";
8
+ import { ImageProcessor } from "./image-processor.js";
9
+ import { anyCaseToCamelCase } from "./utils.js";
11
10
  function resolveGeneratedPath(type, options) {
12
11
  const { root, module, subPath } = options;
13
12
  const parts = [root, GENERATED_BASE_PATHS[type], module, subPath].filter(Boolean);
@@ -16,8 +15,54 @@ function resolveGeneratedPath(type, options) {
16
15
  const logger = new Logger("[@ecopages/image-processor]", {
17
16
  debug: process.env.ECOPAGES_LOGGER_DEBUG === "true"
18
17
  });
19
- const currentDir = path.dirname(fileURLToPath(import.meta.url));
18
+ const IMAGE_VIRTUAL_MODULE_TYPES = `/**
19
+ * ImageAttributes
20
+ * These are the core attributes for the image element generated by the image processor
21
+ */
22
+ interface ImageAttributes {
23
+ src: string;
24
+ width: number;
25
+ height: number;
26
+ sizes: string;
27
+ srcset?: string;
28
+ }
29
+
30
+ /**
31
+ * This represents a single image variant created using the size configuration
32
+ */
33
+ interface ImageVariant {
34
+ width: number;
35
+ height: number;
36
+ src: string;
37
+ label: string;
38
+ }
39
+
40
+ /**
41
+ * These are the core attributes for the image element and the image variants
42
+ * This is the representation of the image element in the virtual module
43
+ */
44
+ interface ImageSpecifications {
45
+ attributes: ImageAttributes;
46
+ variants: ImageVariant[];
47
+ /**
48
+ * A unique key used to cache the image specifications.
49
+ * This key should uniquely identify the combination of attributes and variants
50
+ * to ensure proper caching behavior.
51
+ */
52
+ cacheKey: string;
53
+ }
54
+
55
+ /**
56
+ * This is the representation of an image breakpoint
57
+ * This is used to generate the srcset attribute
58
+ */
59
+ type ImageSize = {
60
+ width: number;
61
+ label: string;
62
+ };`;
20
63
  class ImageProcessorPlugin extends Processor {
64
+ buildContributionsPrepared = false;
65
+ resolvedConfig;
21
66
  processedImages = {};
22
67
  constructor(config) {
23
68
  const acceptedFormats = config.options?.acceptedFormats ?? ["jpg", "jpeg", "png", "webp"];
@@ -50,20 +95,26 @@ class ImageProcessorPlugin extends Processor {
50
95
  return [createImagePlugin(this.processedImages)];
51
96
  }
52
97
  /**
53
- * Generate dependencies for processor.
54
- * It is ossible to define which one should be included in the final bundle based on the environment.
55
- * @returns
98
+ * Replaces image-map contents without swapping the backing object.
99
+ *
100
+ * @remarks
101
+ * The build/runtime virtual-module plugins close over `processedImages`, so
102
+ * mutating the existing object keeps those plugins live after preparation.
56
103
  */
57
- generateDependencies() {
58
- const deps = [];
59
- if (process.env.NODE_ENV === "development") {
104
+ replaceProcessedImages(images) {
105
+ for (const key of Object.keys(this.processedImages)) {
106
+ delete this.processedImages[key];
60
107
  }
61
- return deps;
108
+ Object.assign(this.processedImages, images);
62
109
  }
63
110
  /**
64
- * Setup the image processor and create the virtual module.
111
+ * Prepares the image virtual-module state before config build seals the app
112
+ * manifest.
65
113
  */
66
- async setup() {
114
+ async prepareBuildContributions() {
115
+ if (this.buildContributionsPrepared) {
116
+ return;
117
+ }
67
118
  if (!this.context) {
68
119
  throw new Error("ImageProcessor requires context to be set");
69
120
  }
@@ -80,16 +131,75 @@ class ImageProcessorPlugin extends Processor {
80
131
  format: "webp"
81
132
  };
82
133
  const config = this.options ? deepMerge(defaultConfig, this.options) : defaultConfig;
134
+ this.resolvedConfig = config;
83
135
  this.processor = new ImageProcessor(config, {
84
136
  readCache: (key) => this.readCache(key),
85
137
  writeCache: (key, data) => this.writeCache(key, data)
86
138
  });
87
- this.processedImages = await this.processor.processDirectory();
139
+ this.replaceProcessedImages(await this.processor.processDirectory());
88
140
  if (this.watchConfig) {
89
141
  this.watchConfig.paths = [config.sourceDir];
90
142
  }
91
143
  this.dependencies = this.generateDependencies();
92
144
  this.generateTypes();
145
+ this.buildContributionsPrepared = true;
146
+ }
147
+ getRuntimeVirtualModulePath() {
148
+ if (!this.context) {
149
+ throw new Error("ImageProcessor requires context to be set");
150
+ }
151
+ return resolveGeneratedPath("cache", {
152
+ root: this.context.distDir,
153
+ module: this.name,
154
+ subPath: "virtual-module.ts"
155
+ });
156
+ }
157
+ getGeneratedOutputPath(src) {
158
+ if (!this.resolvedConfig) {
159
+ throw new Error("ImageProcessor not initialized");
160
+ }
161
+ return path.join(this.resolvedConfig.outputDir, path.basename(src));
162
+ }
163
+ hasGeneratedOutputs() {
164
+ if (!this.resolvedConfig) {
165
+ return false;
166
+ }
167
+ if (!fileSystem.exists(this.resolvedConfig.outputDir) || !fileSystem.exists(this.getRuntimeVirtualModulePath())) {
168
+ return false;
169
+ }
170
+ return Object.values(this.processedImages).every((image) => {
171
+ const outputPaths = [image.attributes.src, ...image.variants.map((variant) => variant.src)];
172
+ return outputPaths.every((src) => fileSystem.exists(this.getGeneratedOutputPath(src)));
173
+ });
174
+ }
175
+ async rehydrateGeneratedOutputs() {
176
+ if (!this.processor) {
177
+ throw new Error("ImageProcessor not initialized");
178
+ }
179
+ if (this.hasGeneratedOutputs()) {
180
+ return;
181
+ }
182
+ this.replaceProcessedImages(await this.processor.processDirectory());
183
+ this.dependencies = this.generateDependencies();
184
+ this.generateTypes();
185
+ }
186
+ /**
187
+ * Generate dependencies for processor.
188
+ * It is ossible to define which one should be included in the final bundle based on the environment.
189
+ * @returns
190
+ */
191
+ generateDependencies() {
192
+ const deps = [];
193
+ if (process.env.NODE_ENV === "development") {
194
+ }
195
+ return deps;
196
+ }
197
+ /**
198
+ * Prepares build contributions if not already done and rehydrates previously generated image outputs.
199
+ */
200
+ async setup() {
201
+ await this.prepareBuildContributions();
202
+ await this.rehydrateGeneratedOutputs();
93
203
  }
94
204
  /**
95
205
  * Process images.
@@ -159,14 +269,13 @@ class ImageProcessorPlugin extends Processor {
159
269
  if (!this.options?.outputDir) {
160
270
  throw new Error("Output directory not set");
161
271
  }
162
- const requiredTypes = fileSystem.readFileSync(path.join(currentDir, "types.ts")).toString().replaceAll("export ", "");
163
272
  const content = `
164
273
  /**
165
274
  * Do not edit manually. This file is auto-generated.
166
275
  * This file contains the type definitions for the virtual module "ecopages:images".
167
276
  */
168
277
 
169
- ${requiredTypes}
278
+ ${IMAGE_VIRTUAL_MODULE_TYPES}
170
279
 
171
280
  declare module "ecopages:images" {
172
281
  ${Object.keys(this.processedImages).map((key) => `export const ${anyCaseToCamelCase(key)}: ImageSpecifications;`).join("\n ")}
@@ -1,59 +0,0 @@
1
- /**
2
- * This file contains the plugins for bundling the image specifications.
3
- * @module @ecopages/image-processor/bun-plugins
4
- */
5
-
6
- import type { EcoBuildOnLoadResult, EcoBuildPlugin } from '@ecopages/core/build/build-types';
7
- import type { ImageMap } from './plugin';
8
- import { anyCaseToCamelCase } from './utils';
9
-
10
- /**
11
- * This function creates the plugin result for the image specifications.
12
- */
13
- function createPluginResult(exports: ImageMap): EcoBuildOnLoadResult {
14
- return {
15
- contents: `${Object.entries(exports)
16
- .map(([key, value]) => `export const ${anyCaseToCamelCase(key)} = ${JSON.stringify(value)};`)
17
- .join('\n')}`,
18
- loader: 'ts',
19
- };
20
- }
21
-
22
- /**
23
- * This function creates a plugin for bundling the image specifications.
24
- * https://bun.sh/docs/runtime/plugins#virtual-modules
25
- * @param exports
26
- * @returns
27
- */
28
- export function createImagePlugin(exports: ImageMap): EcoBuildPlugin {
29
- return {
30
- name: 'ecopages:images',
31
- setup(build) {
32
- build.module('ecopages:images', () => createPluginResult(exports));
33
- },
34
- };
35
- }
36
-
37
- /**
38
- * This function creates a plugin for bundling the image specifications.
39
- * Due to some limitations in the bundler, we need to use a different approach.
40
- * https://bun.sh/docs/runtime/plugins#virtual-modules > bun-v1.2.5
41
- * (This feature is currently only available at runtime with Bun.plugin and not yet supported in the bundler, but you can mimic the behavior using onResolve and onLoad.)
42
- * @param exports
43
- * @returns
44
- */
45
- export function createImagePluginBundler(exports: ImageMap): EcoBuildPlugin {
46
- return {
47
- name: 'ecopages:images',
48
- setup(build) {
49
- build.onResolve({ filter: /^ecopages:images$/ }, () => {
50
- return {
51
- namespace: 'ecopages-images',
52
- path: 'ecopages:images',
53
- };
54
- });
55
-
56
- build.onLoad({ filter: /.*/, namespace: 'ecopages-images' }, () => createPluginResult(exports));
57
- },
58
- };
59
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * Image component that renders the image as a string.
3
- * @module @ecopages/image-processor/component/html
4
- */
5
-
6
- import { type EcoImageProps, renderer } from '../image-renderer';
7
-
8
- /**
9
- * EcoImage
10
- * This component generates the image element based on the provided props as a string
11
- * @param props {@link EcoImageProps}
12
- */
13
- export const EcoImage = (props: EcoImageProps): string => {
14
- return renderer.renderToString(props);
15
- };
@@ -1,20 +0,0 @@
1
- /**
2
- * Image component that renders the image as a string.
3
- * @module @ecopages/image-processor/component/react
4
- */
5
-
6
- import { createElement, type JSX } from 'react';
7
- import { type EcoImageProps, renderer } from '../image-renderer';
8
-
9
- /**
10
- * EcoImage
11
- * This component generates the image element based on the provided props as JSX
12
- * @param props {@link EcoImageProps}
13
- * @returns
14
- */
15
- export const EcoImage = (props: EcoImageProps): JSX.Element => {
16
- return createElement('img', {
17
- ...renderer.generateAttributesJsx(props),
18
- suppressHydrationWarning: true,
19
- });
20
- };
package/src/constants.ts DELETED
@@ -1,7 +0,0 @@
1
- import type { ImageLayout } from './image-renderer';
2
-
3
- /**
4
- * Default image layout
5
- * @constant "constrained"
6
- */
7
- export const DEFAULT_LAYOUT: ImageLayout = 'constrained';
@@ -1,59 +0,0 @@
1
- /**
2
- * This file contains the plugins for bundling the image specifications.
3
- * @module @ecopages/image-processor/image-plugins
4
- */
5
-
6
- import type { EcoBuildOnLoadResult, EcoBuildPlugin } from '@ecopages/core/build/build-types';
7
- import type { ImageMap } from './plugin';
8
- import { anyCaseToCamelCase } from './utils';
9
-
10
- /**
11
- * This function creates the plugin result for the image specifications.
12
- */
13
- function createPluginResult(exports: ImageMap): EcoBuildOnLoadResult {
14
- return {
15
- contents: `${Object.entries(exports)
16
- .map(([key, value]) => `export const ${anyCaseToCamelCase(key)} = ${JSON.stringify(value)};`)
17
- .join('\n')}`,
18
- loader: 'ts',
19
- };
20
- }
21
-
22
- /**
23
- * This function creates a plugin for bundling the image specifications.
24
- * https://bun.sh/docs/runtime/plugins#virtual-modules
25
- * @param exports
26
- * @returns
27
- */
28
- export function createImagePlugin(exports: ImageMap): EcoBuildPlugin {
29
- return {
30
- name: 'ecopages:images',
31
- setup(build) {
32
- build.module('ecopages:images', () => createPluginResult(exports));
33
- },
34
- };
35
- }
36
-
37
- /**
38
- * This function creates a plugin for bundling the image specifications.
39
- * Due to some limitations in the bundler, we need to use a different approach.
40
- * https://bun.sh/docs/runtime/plugins#virtual-modules > bun-v1.2.5
41
- * (This feature is currently only available at runtime with Bun.plugin and not yet supported in the bundler, but you can mimic the behavior using onResolve and onLoad.)
42
- * @param exports
43
- * @returns
44
- */
45
- export function createImagePluginBundler(exports: ImageMap): EcoBuildPlugin {
46
- return {
47
- name: 'ecopages:images',
48
- setup(build) {
49
- build.onResolve({ filter: /^ecopages:images$/ }, () => {
50
- return {
51
- namespace: 'ecopages-images',
52
- path: 'ecopages:images',
53
- };
54
- });
55
-
56
- build.onLoad({ filter: /.*/, namespace: 'ecopages-images' }, () => createPluginResult(exports));
57
- },
58
- };
59
- }
@@ -1,201 +0,0 @@
1
- import path from 'node:path';
2
- import { deepMerge } from '@ecopages/core/utils/deep-merge';
3
- import { fileSystem } from '@ecopages/file-system';
4
- import { Logger } from '@ecopages/logger';
5
- import sharp from 'sharp';
6
- import { ImageUtils } from './image-utils';
7
- import type { ImageMap, ImageProcessorConfig } from './plugin';
8
- import type { ImageAttributes, ImageSpecifications, ImageVariant } from './types';
9
-
10
- const appLogger = new Logger('[@ecopages/image-processor]', {
11
- debug: process.env.ECOPAGES_LOGGER_DEBUG === 'true',
12
- });
13
-
14
- /**
15
- * ImageProcessor
16
- * This is the core class for processing images.
17
- * It uses the sharp library to resize and optimize images.
18
- */
19
- export class ImageProcessor {
20
- private readonly config: ImageProcessorConfig;
21
- private readonly cacheManager: {
22
- readCache: <T>(key: string) => Promise<T | null>;
23
- writeCache: <T>(key: string, data: T) => Promise<void>;
24
- };
25
-
26
- constructor(
27
- config: ImageProcessorConfig,
28
- cacheManager: {
29
- readCache: <T>(key: string) => Promise<T | null>;
30
- writeCache: <T>(key: string, data: T) => Promise<void>;
31
- },
32
- ) {
33
- this.config = deepMerge({ cacheEnabled: true }, config);
34
- this.cacheManager = cacheManager;
35
- fileSystem.ensureDir(this.config.outputDir);
36
- }
37
-
38
- private async calculateDimensions(metadata: sharp.Metadata, targetWidth: number) {
39
- const originalWidth = metadata.width || 0;
40
- const originalHeight = metadata.height || 0;
41
- const aspectRatio = originalHeight / originalWidth;
42
- const width = Math.min(targetWidth, originalWidth);
43
- const height = Math.round(width * aspectRatio);
44
- return { width, height };
45
- }
46
-
47
- private getOutputPath(imagePath: string, width: number) {
48
- const hash = fileSystem.hash(imagePath);
49
- const ext = path.extname(imagePath);
50
- const base = path.basename(imagePath, ext);
51
- const filename = `${base}-${hash}-${width}.${this.config.format}`;
52
- return path.join(this.config.outputDir, filename);
53
- }
54
-
55
- async processImage(imagePath: string): Promise<ImageSpecifications | null> {
56
- try {
57
- const fileHash = fileSystem.hash(imagePath);
58
- const cacheKey = `${path.basename(imagePath)}:${fileHash}`;
59
-
60
- if (this.config.cacheEnabled) {
61
- const cached = await this.cacheManager.readCache<ImageSpecifications>(cacheKey);
62
- if (cached) {
63
- /**
64
- * Verify that the files actually exist
65
- * We construct the absolute path relative to the process current working directory
66
- * since the src in attributes is relative from the root
67
- */
68
- const mainFilePath = path.join(process.cwd(), cached.attributes.src);
69
- const mainFileExists = fileSystem.exists(mainFilePath);
70
- const variantsExist = cached.variants.every((v) =>
71
- fileSystem.exists(path.join(process.cwd(), v.src)),
72
- );
73
-
74
- if (mainFileExists && variantsExist) {
75
- appLogger.debug(`Cache hit for ${imagePath}`);
76
- return cached;
77
- }
78
-
79
- appLogger.debug(`Cache invalid for ${imagePath}, reprocessing`);
80
- }
81
- }
82
-
83
- fileSystem.ensureDir(this.config.outputDir);
84
-
85
- const metadata = await sharp(imagePath).metadata();
86
- const originalWidth = metadata.width || 0;
87
- const originalHeight = metadata.height || 0;
88
-
89
- if (this.config.sizes.length === 0) {
90
- const outputPath = this.getOutputPath(imagePath, originalWidth);
91
-
92
- if (fileSystem.exists(outputPath)) {
93
- appLogger.debug(`Using existing file for ${imagePath}`);
94
- } else {
95
- await sharp(imagePath)
96
- .toFormat(this.config.format, { quality: this.config.quality })
97
- .toFile(outputPath);
98
- }
99
-
100
- const src = path.join(this.config.publicPath, path.basename(outputPath));
101
-
102
- const imageSpecifications: ImageSpecifications = {
103
- attributes: {
104
- src,
105
- width: originalWidth,
106
- height: originalHeight,
107
- sizes: '',
108
- },
109
- variants: [],
110
- cacheKey,
111
- };
112
-
113
- if (this.config.cacheEnabled) {
114
- await this.cacheManager.writeCache(cacheKey, imageSpecifications);
115
- }
116
-
117
- return imageSpecifications;
118
- }
119
-
120
- let applicableSizes = this.config.sizes
121
- .filter((size) => size.width <= originalWidth)
122
- .sort((a, b) => b.width - a.width);
123
-
124
- if (applicableSizes.length === 0) {
125
- applicableSizes = this.config.sizes.sort((a, b) => b.width - a.width).slice(0, 1);
126
- }
127
-
128
- const variants: ImageVariant[] = await Promise.all(
129
- applicableSizes.map(async ({ width: targetWidth, label }) => {
130
- const { width, height } = await this.calculateDimensions(metadata, targetWidth);
131
- const outputPath = this.getOutputPath(imagePath, width);
132
-
133
- if (fileSystem.exists(outputPath)) {
134
- appLogger.debug(`Variant ${width}px already exists for ${imagePath}`);
135
- } else {
136
- await sharp(imagePath)
137
- .resize(width, height)
138
- .toFormat(this.config.format, { quality: this.config.quality })
139
- .toFile(outputPath);
140
- }
141
-
142
- const src = path.join(this.config.publicPath, path.basename(outputPath));
143
-
144
- return {
145
- width,
146
- height,
147
- src,
148
- label,
149
- };
150
- }),
151
- );
152
-
153
- const mainVariant = variants[0];
154
- const attributes: ImageAttributes = {
155
- src: mainVariant.src,
156
- width: mainVariant.width,
157
- height: mainVariant.height,
158
- sizes: ImageUtils.generateSizes(variants),
159
- srcset: ImageUtils.generateSrcset(variants),
160
- };
161
-
162
- const imageSpecifications: ImageSpecifications = {
163
- attributes,
164
- variants,
165
- cacheKey,
166
- };
167
-
168
- if (this.config.cacheEnabled) {
169
- await this.cacheManager.writeCache(cacheKey, imageSpecifications);
170
- }
171
-
172
- return imageSpecifications;
173
- } catch (error) {
174
- appLogger.error(`Failed to process image ${imagePath}:`, error as Error);
175
- return null;
176
- }
177
- }
178
-
179
- async processDirectory(): Promise<ImageMap> {
180
- const acceptedFormats = this.config.acceptedFormats || ['jpg', 'jpeg', 'png', 'webp'];
181
-
182
- const images = await fileSystem.glob([`${this.config.sourceDir}/**/*.{${acceptedFormats.join(',')}}`]);
183
-
184
- appLogger.debugTime('Processing images');
185
-
186
- const results = (
187
- await Promise.all(
188
- images.map(async (file) => {
189
- const processed = await this.processImage(file);
190
- if (!processed) return null;
191
- return [path.basename(file), processed] as [string, ImageSpecifications];
192
- }),
193
- )
194
- ).filter(Boolean) as [string, ImageSpecifications][];
195
-
196
- appLogger.debugTimeEnd('Processing images');
197
- appLogger.info(`Processed ${results.length} images`);
198
-
199
- return Object.fromEntries(results);
200
- }
201
- }