@eserstack/laroux-bundler 0.0.0-bootstrap.0 → 5.0.0
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/LICENSE +13 -0
- package/README.md +432 -0
- package/dist/adapters/fonts/font-optimizer.d.ts +28 -0
- package/dist/adapters/fonts/font-optimizer.js +74 -0
- package/dist/adapters/fonts/index.d.ts +18 -0
- package/dist/adapters/fonts/index.js +78 -0
- package/dist/adapters/fonts/mod.d.ts +6 -0
- package/dist/adapters/fonts/mod.js +7 -0
- package/dist/adapters/lightningcss/css-processor.d.ts +39 -0
- package/dist/adapters/lightningcss/css-processor.js +103 -0
- package/dist/adapters/lightningcss/mod.d.ts +5 -0
- package/dist/adapters/lightningcss/mod.js +6 -0
- package/dist/adapters/mod.d.ts +13 -0
- package/dist/adapters/mod.js +21 -0
- package/dist/adapters/prebuilt-bundler/mod.d.ts +5 -0
- package/dist/adapters/prebuilt-bundler/mod.js +6 -0
- package/dist/adapters/prebuilt-bundler/prebuilt-bundler.d.ts +22 -0
- package/dist/adapters/prebuilt-bundler/prebuilt-bundler.js +60 -0
- package/dist/adapters/react/mod.d.ts +10 -0
- package/dist/adapters/react/mod.js +16 -0
- package/dist/adapters/react/plugin.d.ts +17 -0
- package/dist/adapters/react/plugin.js +62 -0
- package/dist/adapters/react/rsc-analyze.d.ts +29 -0
- package/dist/adapters/react/rsc-analyze.js +116 -0
- package/dist/adapters/react/rsc-client-entry.d.ts +26 -0
- package/dist/adapters/react/rsc-client-entry.js +145 -0
- package/dist/adapters/react/rsc-module-map.d.ts +41 -0
- package/dist/adapters/react/rsc-module-map.js +81 -0
- package/dist/adapters/react/rsc-rewrite-imports.d.ts +38 -0
- package/dist/adapters/react/rsc-rewrite-imports.js +409 -0
- package/dist/adapters/react/rsc-transform.d.ts +26 -0
- package/dist/adapters/react/rsc-transform.js +101 -0
- package/dist/adapters/runtime-bundler/mod.d.ts +6 -0
- package/dist/adapters/runtime-bundler/mod.js +6 -0
- package/dist/adapters/runtime-bundler/runtime-bundler.d.ts +85 -0
- package/dist/adapters/runtime-bundler/runtime-bundler.js +244 -0
- package/dist/adapters/sharp/image-optimizer.d.ts +52 -0
- package/dist/adapters/sharp/image-optimizer.js +261 -0
- package/dist/adapters/sharp/mod.d.ts +6 -0
- package/dist/adapters/sharp/mod.js +6 -0
- package/dist/adapters/tailwindcss/compile.d.ts +22 -0
- package/dist/adapters/tailwindcss/compile.js +29 -0
- package/dist/adapters/tailwindcss/critical-css-config.d.ts +46 -0
- package/dist/adapters/tailwindcss/critical-css-config.js +78 -0
- package/dist/adapters/tailwindcss/critical-page-css.d.ts +61 -0
- package/dist/adapters/tailwindcss/critical-page-css.js +431 -0
- package/dist/adapters/tailwindcss/critical-universal-css.d.ts +68 -0
- package/dist/adapters/tailwindcss/critical-universal-css.js +250 -0
- package/dist/adapters/tailwindcss/mod.d.ts +10 -0
- package/dist/adapters/tailwindcss/mod.js +11 -0
- package/dist/adapters/tailwindcss/plugin.d.ts +16 -0
- package/dist/adapters/tailwindcss/plugin.js +107 -0
- package/dist/adapters/tailwindcss/stylesheet-loader.d.ts +15 -0
- package/dist/adapters/tailwindcss/stylesheet-loader.js +83 -0
- package/dist/config.d.ts +27 -0
- package/dist/config.js +31 -0
- package/dist/css-modules.d.ts +49 -0
- package/dist/css-modules.js +146 -0
- package/dist/domain/build-cache.d.ts +107 -0
- package/dist/domain/build-cache.js +128 -0
- package/dist/domain/build-validator.d.ts +68 -0
- package/dist/domain/build-validator.js +207 -0
- package/dist/domain/bundler.d.ts +136 -0
- package/dist/domain/bundler.js +225 -0
- package/dist/domain/chunk-manifest.d.ts +40 -0
- package/dist/domain/chunk-manifest.js +188 -0
- package/dist/domain/client-action-stub.d.ts +30 -0
- package/dist/domain/client-action-stub.js +167 -0
- package/dist/domain/copy-path.d.ts +15 -0
- package/dist/domain/copy-path.js +29 -0
- package/dist/domain/css-plugin.d.ts +91 -0
- package/dist/domain/css-plugin.js +6 -0
- package/dist/domain/css-processor.d.ts +57 -0
- package/dist/domain/css-processor.js +33 -0
- package/dist/domain/font-optimizer.d.ts +46 -0
- package/dist/domain/font-optimizer.js +17 -0
- package/dist/domain/framework-plugin.d.ts +106 -0
- package/dist/domain/framework-plugin.js +20 -0
- package/dist/domain/image-optimizer.d.ts +74 -0
- package/dist/domain/image-optimizer.js +16 -0
- package/dist/domain/import-map.d.ts +90 -0
- package/dist/domain/import-map.js +187 -0
- package/dist/domain/mod.d.ts +32 -0
- package/dist/domain/mod.js +20 -0
- package/dist/domain/route-generator.d.ts +34 -0
- package/dist/domain/route-generator.js +305 -0
- package/dist/domain/route-scanner.d.ts +72 -0
- package/dist/domain/route-scanner.js +282 -0
- package/dist/domain/server-action-transform.d.ts +28 -0
- package/dist/domain/server-action-transform.js +147 -0
- package/dist/domain/virtual-source.d.ts +63 -0
- package/dist/domain/virtual-source.js +238 -0
- package/dist/import-map-resolver-plugin.d.ts +47 -0
- package/dist/import-map-resolver-plugin.js +109 -0
- package/dist/mod.d.ts +57 -0
- package/dist/mod.js +56 -0
- package/dist/server-externals-plugin.d.ts +29 -0
- package/dist/server-externals-plugin.js +63 -0
- package/dist/system.d.ts +157 -0
- package/dist/system.js +1401 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.js +38 -0
- package/package.json +86 -1
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Runtime Bundler for Dev Mode
|
|
4
|
+
* Performs in-memory transformations without requiring dist/ directory
|
|
5
|
+
*
|
|
6
|
+
* NOTE: This bundler requires a React plugin to function.
|
|
7
|
+
* The RSC functionality is provided by @eserstack/laroux-bundler/adapters/react.
|
|
8
|
+
*/
|
|
9
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
10
|
+
import * as logging from "@eserstack/logging";
|
|
11
|
+
import * as larouxConfig from "@eserstack/laroux/config";
|
|
12
|
+
import * as bundler from "../../domain/bundler.js";
|
|
13
|
+
import * as settings from "../../config.js";
|
|
14
|
+
import * as importMapResolverPlugin from "../../import-map-resolver-plugin.js";
|
|
15
|
+
import * as backends from "@eserstack/bundler/backends";
|
|
16
|
+
const runtimeLogger = logging.logger.getLogger([
|
|
17
|
+
"laroux-bundler",
|
|
18
|
+
"runtime-bundler",
|
|
19
|
+
]);
|
|
20
|
+
/**
|
|
21
|
+
* In-memory cache for dev mode
|
|
22
|
+
*/
|
|
23
|
+
class RuntimeCache {
|
|
24
|
+
clientComponents = new Map();
|
|
25
|
+
moduleMap = null;
|
|
26
|
+
bundleCode = null;
|
|
27
|
+
chunkManifest = null;
|
|
28
|
+
lastScan = 0;
|
|
29
|
+
scanInterval = 1000; // Re-scan at most once per second
|
|
30
|
+
config;
|
|
31
|
+
async getOrCreateBundle() {
|
|
32
|
+
const now = Date.now();
|
|
33
|
+
// Re-scan if cache is stale
|
|
34
|
+
if (now - this.lastScan > this.scanInterval || !this.bundleCode) {
|
|
35
|
+
await this.rebuild();
|
|
36
|
+
this.lastScan = now;
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
clientCode: this.bundleCode,
|
|
40
|
+
moduleMap: this.moduleMap,
|
|
41
|
+
clientComponents: this.clientComponents,
|
|
42
|
+
chunkManifest: this.chunkManifest,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
constructor(config) {
|
|
46
|
+
this.config = config;
|
|
47
|
+
}
|
|
48
|
+
async rebuild() {
|
|
49
|
+
const { plugin } = this.config;
|
|
50
|
+
// Step 1: Analyze for "use client" components
|
|
51
|
+
const clientComponentList = plugin.analyzeClientComponents
|
|
52
|
+
? await plugin.analyzeClientComponents(this.config.srcDir, this.config.projectRoot)
|
|
53
|
+
: [];
|
|
54
|
+
// Step 2: Store client components in-memory (no transformation needed for dev mode)
|
|
55
|
+
this.clientComponents.clear();
|
|
56
|
+
for (const component of clientComponentList) {
|
|
57
|
+
this.clientComponents.set(component.filePath, component);
|
|
58
|
+
}
|
|
59
|
+
// Step 3: Generate module map using plugin
|
|
60
|
+
this.moduleMap = plugin.createModuleMap
|
|
61
|
+
? await plugin.createModuleMap(clientComponentList)
|
|
62
|
+
: {};
|
|
63
|
+
// Step 4: Bundle client code in-memory and generate chunk manifest
|
|
64
|
+
const bundleResult = await this.bundleClientCode(clientComponentList);
|
|
65
|
+
this.bundleCode = bundleResult.code;
|
|
66
|
+
this.chunkManifest = bundleResult.manifest;
|
|
67
|
+
}
|
|
68
|
+
async bundleClientCode(clientComponents) {
|
|
69
|
+
const { plugin, projectRoot } = this.config;
|
|
70
|
+
// Create a temporary directory for this bundling process inside project root
|
|
71
|
+
// This allows the bundler to resolve node_modules correctly
|
|
72
|
+
const tempDir = await runtime.fs.makeTempDir({
|
|
73
|
+
prefix: "rsc-runtime-",
|
|
74
|
+
dir: projectRoot, // Create temp dir in project root so node_modules can be found
|
|
75
|
+
});
|
|
76
|
+
try {
|
|
77
|
+
// Generate entry file using plugin
|
|
78
|
+
if (!plugin.createClientEntry) {
|
|
79
|
+
throw new Error("Framework plugin does not provide createClientEntry");
|
|
80
|
+
}
|
|
81
|
+
const generatedEntry = await plugin.createClientEntry(clientComponents, projectRoot, tempDir);
|
|
82
|
+
// The same backend and import map resolver plugin as a production
|
|
83
|
+
// client build, so the browser shims apply here too and the FFI-backed
|
|
84
|
+
// logger stays out of the browser bundle.
|
|
85
|
+
const clientBundler = backends.createBundler(bundler.CLIENT_BUNDLER_BACKEND, { entryName: "client" });
|
|
86
|
+
// One entry: the generated entry imports every client component, and
|
|
87
|
+
// the server sends the result as one file, so no chunk may split off.
|
|
88
|
+
const bundlerConfig = {
|
|
89
|
+
entrypoints: { client: generatedEntry },
|
|
90
|
+
outputDir: tempDir,
|
|
91
|
+
projectRoot,
|
|
92
|
+
format: "esm",
|
|
93
|
+
platform: "browser",
|
|
94
|
+
codeSplitting: settings.DEVELOPMENT_SETTINGS.codeSplitting,
|
|
95
|
+
minify: settings.DEVELOPMENT_SETTINGS.minify,
|
|
96
|
+
sourcemap: false,
|
|
97
|
+
plugins: [
|
|
98
|
+
importMapResolverPlugin.createImportMapResolverPlugin({
|
|
99
|
+
projectRoot,
|
|
100
|
+
browserShims: this.config.browserShims ?? larouxConfig.DEFAULT_BROWSER_SHIMS,
|
|
101
|
+
autoMarkExternal: false,
|
|
102
|
+
}),
|
|
103
|
+
],
|
|
104
|
+
define: settings.DEVELOPMENT_SETTINGS.define,
|
|
105
|
+
};
|
|
106
|
+
const result = await clientBundler.bundle(bundlerConfig);
|
|
107
|
+
if (!result.success) {
|
|
108
|
+
const errorMsg = result.errors?.map((e) => e.message).join(", ") ?? "Unknown error";
|
|
109
|
+
throw new Error(`Bundle failed: ${errorMsg}`);
|
|
110
|
+
}
|
|
111
|
+
// Get the main bundle from outputs; the backend names the entry's
|
|
112
|
+
// output after entryName
|
|
113
|
+
const mainOutput = result.outputs.get("client.js");
|
|
114
|
+
if (!mainOutput) {
|
|
115
|
+
throw new Error("Bundle output 'client.js' not found in bundle result");
|
|
116
|
+
}
|
|
117
|
+
// Decode bundle code from Uint8Array
|
|
118
|
+
const bundleCode = new TextDecoder().decode(mainOutput.code);
|
|
119
|
+
// Generate chunk manifest for runtime mode
|
|
120
|
+
// In runtime mode, all components are bundled together
|
|
121
|
+
const chunkManifest = {
|
|
122
|
+
version: "1.0",
|
|
123
|
+
buildId: "runtime",
|
|
124
|
+
timestamp: Date.now(),
|
|
125
|
+
logLevel: "debug",
|
|
126
|
+
entrypoint: "__runtime_bundle.js",
|
|
127
|
+
hmrEnabled: true, // HMR is enabled in runtime bundler mode
|
|
128
|
+
chunks: {},
|
|
129
|
+
files: {},
|
|
130
|
+
};
|
|
131
|
+
// Add each client component to the manifest
|
|
132
|
+
for (const component of clientComponents) {
|
|
133
|
+
const relativePath = component.relativePath;
|
|
134
|
+
chunkManifest.chunks[relativePath] = {
|
|
135
|
+
main: "__runtime_bundle", // All components are in the runtime bundle
|
|
136
|
+
deps: [],
|
|
137
|
+
size: 0, // Size unknown in runtime mode
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
code: bundleCode,
|
|
142
|
+
manifest: chunkManifest,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
147
|
+
// Handled here: logged once, then served as an error bundle
|
|
148
|
+
runtimeLogger.with({ error }).error("❌ Runtime bundling failed");
|
|
149
|
+
// Fallback: return error code and empty manifest
|
|
150
|
+
// Properly escape for HTML context to prevent XSS
|
|
151
|
+
const escapeHtml = (str) => str
|
|
152
|
+
.replace(/&/g, "&")
|
|
153
|
+
.replace(/</g, "<")
|
|
154
|
+
.replace(/>/g, ">")
|
|
155
|
+
.replace(/"/g, """)
|
|
156
|
+
.replace(/'/g, "'")
|
|
157
|
+
.replace(/\n/g, "\\n")
|
|
158
|
+
.replace(/\r/g, "\\r");
|
|
159
|
+
const errorCode = `
|
|
160
|
+
console.error("Runtime bundling failed:", ${JSON.stringify(errorMessage)});
|
|
161
|
+
document.getElementById("root").innerHTML = '<div class="error"><h2>Bundle Error</h2><pre>${escapeHtml(errorMessage)}</pre></div>';
|
|
162
|
+
`;
|
|
163
|
+
const errorManifest = {
|
|
164
|
+
version: "1.0",
|
|
165
|
+
buildId: "runtime-error",
|
|
166
|
+
timestamp: Date.now(),
|
|
167
|
+
logLevel: "error",
|
|
168
|
+
entrypoint: "__runtime_bundle.js",
|
|
169
|
+
hmrEnabled: false,
|
|
170
|
+
chunks: {},
|
|
171
|
+
files: {},
|
|
172
|
+
};
|
|
173
|
+
return {
|
|
174
|
+
code: errorCode,
|
|
175
|
+
manifest: errorManifest,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
finally {
|
|
179
|
+
// Clean up temporary directory
|
|
180
|
+
try {
|
|
181
|
+
await runtime.fs.remove(tempDir, { recursive: true });
|
|
182
|
+
}
|
|
183
|
+
catch (cleanupError) {
|
|
184
|
+
// Cleanup failure is non-critical - temp files will be cleaned on next run
|
|
185
|
+
runtimeLogger
|
|
186
|
+
.with({ error: cleanupError })
|
|
187
|
+
.debug(`remove temp directory ${tempDir}`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
clear() {
|
|
192
|
+
this.clientComponents.clear();
|
|
193
|
+
this.moduleMap = null;
|
|
194
|
+
this.bundleCode = null;
|
|
195
|
+
this.lastScan = 0;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Create a runtime cache instance with injected config
|
|
200
|
+
* Factory function to enable dependency injection
|
|
201
|
+
*/
|
|
202
|
+
export function createRuntimeCache(config) {
|
|
203
|
+
return new RuntimeCache(config);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Runtime bundler facade with dependency injection
|
|
207
|
+
*/
|
|
208
|
+
export class RuntimeBundler {
|
|
209
|
+
cache;
|
|
210
|
+
constructor(config) {
|
|
211
|
+
this.cache = new RuntimeCache(config);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Get runtime bundle (cached, in-memory)
|
|
215
|
+
* Implements Bundler interface
|
|
216
|
+
*/
|
|
217
|
+
async getBundle() {
|
|
218
|
+
const bundle = await this.cache.getOrCreateBundle();
|
|
219
|
+
return {
|
|
220
|
+
clientCode: bundle.clientCode,
|
|
221
|
+
moduleMap: bundle.moduleMap,
|
|
222
|
+
chunkManifest: bundle.chunkManifest,
|
|
223
|
+
entrypoint: "/__runtime_bundle.js", // Runtime bundle endpoint
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Get the full runtime bundle data (legacy method for internal use)
|
|
228
|
+
*/
|
|
229
|
+
async getRuntimeBundle() {
|
|
230
|
+
return await this.cache.getOrCreateBundle();
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Force rebuild of runtime bundle
|
|
234
|
+
*/
|
|
235
|
+
async rebuild() {
|
|
236
|
+
await this.cache.rebuild();
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Clear runtime cache
|
|
240
|
+
*/
|
|
241
|
+
clear() {
|
|
242
|
+
this.cache.clear();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Image Optimization for Laroux
|
|
3
|
+
* Build-time image processing with format conversion and responsive variants
|
|
4
|
+
*/
|
|
5
|
+
import type { ImageManifest, ImageOptimizer, ImageVariant, OptimizedImage } from "../../domain/image-optimizer.ts";
|
|
6
|
+
/**
|
|
7
|
+
* Image optimization configuration
|
|
8
|
+
*/
|
|
9
|
+
export type ImageOptimizationConfig = {
|
|
10
|
+
/** Output formats to generate */
|
|
11
|
+
formats?: ("webp" | "avif" | "original")[];
|
|
12
|
+
/** Responsive widths to generate */
|
|
13
|
+
widths?: number[];
|
|
14
|
+
/** Quality settings per format */
|
|
15
|
+
quality?: {
|
|
16
|
+
webp?: number;
|
|
17
|
+
avif?: number;
|
|
18
|
+
jpeg?: number;
|
|
19
|
+
png?: number;
|
|
20
|
+
};
|
|
21
|
+
/** Whether to generate blur placeholder data URLs */
|
|
22
|
+
generateBlurPlaceholder?: boolean;
|
|
23
|
+
/** Placeholder width (for blur data URL) */
|
|
24
|
+
placeholderWidth?: number;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Scan for images in a directory
|
|
28
|
+
*/
|
|
29
|
+
export declare function scanImages(dir: string): Promise<string[]>;
|
|
30
|
+
/**
|
|
31
|
+
* Optimize a single image
|
|
32
|
+
*/
|
|
33
|
+
export declare function optimizeImage(imagePath: string, outputDir: string, publicBasePath: string, config?: ImageOptimizationConfig): Promise<OptimizedImage>;
|
|
34
|
+
/**
|
|
35
|
+
* Optimize all images in a directory
|
|
36
|
+
*/
|
|
37
|
+
export declare function optimizeImages(inputDir: string, outputDir: string, publicBasePath?: string, config?: ImageOptimizationConfig): Promise<ImageManifest>;
|
|
38
|
+
/**
|
|
39
|
+
* Generate srcset string for an optimized image
|
|
40
|
+
*/
|
|
41
|
+
export declare function generateSrcset(image: OptimizedImage, format?: string): string;
|
|
42
|
+
/**
|
|
43
|
+
* Get the best variant for a given width
|
|
44
|
+
*/
|
|
45
|
+
export declare function getBestVariant(image: OptimizedImage, targetWidth: number, format?: string): ImageVariant | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* Image optimizer that encodes the images with sharp: responsive variants in
|
|
48
|
+
* the configured formats, widths and quality, a blur placeholder when the
|
|
49
|
+
* config's placeholder is "blur", and image-manifest.json in the output
|
|
50
|
+
* directory. Pass it to the build as `imageOptimizer`.
|
|
51
|
+
*/
|
|
52
|
+
export declare const sharpImageOptimizer: ImageOptimizer;
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Image Optimization for Laroux
|
|
4
|
+
* Build-time image processing with format conversion and responsive variants
|
|
5
|
+
*/
|
|
6
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
7
|
+
import * as patterns from "@eserstack/standards/patterns";
|
|
8
|
+
import * as logging from "@eserstack/logging";
|
|
9
|
+
const imageLogger = logging.logger.getLogger(["laroux", "image-optimizer"]);
|
|
10
|
+
// sharp is a native module, so it loads on first use instead of at import.
|
|
11
|
+
// The dynamic import is untyped; typing it would need sharp's types here.
|
|
12
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
13
|
+
let sharpModule = null;
|
|
14
|
+
// Returns the untyped module held in sharpModule
|
|
15
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
16
|
+
async function getSharp() {
|
|
17
|
+
if (sharpModule === null) {
|
|
18
|
+
sharpModule = await import("sharp");
|
|
19
|
+
}
|
|
20
|
+
return sharpModule.default ?? sharpModule;
|
|
21
|
+
}
|
|
22
|
+
const DEFAULT_CONFIG = {
|
|
23
|
+
formats: ["webp", "original"],
|
|
24
|
+
widths: [640, 768, 1024, 1280, 1920],
|
|
25
|
+
quality: {
|
|
26
|
+
webp: 80,
|
|
27
|
+
avif: 75,
|
|
28
|
+
jpeg: 85,
|
|
29
|
+
png: 90,
|
|
30
|
+
},
|
|
31
|
+
generateBlurPlaceholder: true,
|
|
32
|
+
placeholderWidth: 10,
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Scan for images in a directory
|
|
36
|
+
*/
|
|
37
|
+
export async function scanImages(dir) {
|
|
38
|
+
const images = [];
|
|
39
|
+
const imageExtensions = ["jpg", "jpeg", "png", "gif", "webp"];
|
|
40
|
+
async function scan(currentDir) {
|
|
41
|
+
try {
|
|
42
|
+
for await (const entry of runtime.fs.readDir(currentDir)) {
|
|
43
|
+
const fullPath = runtime.path.resolve(currentDir, entry.name);
|
|
44
|
+
if (entry.isDirectory) {
|
|
45
|
+
await scan(fullPath);
|
|
46
|
+
}
|
|
47
|
+
else if (entry.isFile) {
|
|
48
|
+
if (patterns.hasExtension(entry.name.toLowerCase(), imageExtensions)) {
|
|
49
|
+
images.push(fullPath);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// Directory might not exist
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
await scan(dir);
|
|
59
|
+
return images;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Generate blur placeholder data URL
|
|
63
|
+
*/
|
|
64
|
+
async function generateBlurPlaceholder(imagePath, width) {
|
|
65
|
+
const sharp = await getSharp();
|
|
66
|
+
const image = sharp(imagePath);
|
|
67
|
+
const buffer = await image
|
|
68
|
+
.resize(width, undefined, { fit: "inside" })
|
|
69
|
+
.blur(5)
|
|
70
|
+
.webp({ quality: 20 })
|
|
71
|
+
.toBuffer();
|
|
72
|
+
return `data:image/webp;base64,${buffer.toString("base64")}`;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Encode one variant and write it to disk
|
|
76
|
+
* @returns The size of the written file in bytes
|
|
77
|
+
*/
|
|
78
|
+
async function writeVariant(
|
|
79
|
+
// sharp is loaded lazily through getSharp(), which returns it untyped
|
|
80
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
81
|
+
processedImage, outputPath) {
|
|
82
|
+
const outputBuffer = await processedImage.toBuffer();
|
|
83
|
+
await runtime.fs.writeFile(outputPath, outputBuffer);
|
|
84
|
+
return outputBuffer.length;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Optimize a single image
|
|
88
|
+
*/
|
|
89
|
+
export async function optimizeImage(imagePath, outputDir, publicBasePath, config = {}) {
|
|
90
|
+
const sharp = await getSharp();
|
|
91
|
+
const mergedConfig = { ...DEFAULT_CONFIG, ...config };
|
|
92
|
+
const image = sharp(imagePath);
|
|
93
|
+
const metadata = await image.metadata();
|
|
94
|
+
if (metadata.width === undefined || metadata.height === undefined) {
|
|
95
|
+
throw new Error(`Could not read image dimensions: ${imagePath}`);
|
|
96
|
+
}
|
|
97
|
+
const originalWidth = metadata.width;
|
|
98
|
+
const originalHeight = metadata.height;
|
|
99
|
+
const aspectRatio = originalWidth / originalHeight;
|
|
100
|
+
const originalExt = runtime.path.extname(imagePath);
|
|
101
|
+
const originalExtBare = originalExt.slice(1).toLowerCase();
|
|
102
|
+
const basename = runtime.path.basename(imagePath, originalExt);
|
|
103
|
+
const publicPath = `${publicBasePath}/${basename}`;
|
|
104
|
+
const variants = [];
|
|
105
|
+
// Every variant is written straight into outputDir
|
|
106
|
+
await runtime.fs.ensureDir(outputDir);
|
|
107
|
+
// Generate variants for each width and format
|
|
108
|
+
for (const width of mergedConfig.widths) {
|
|
109
|
+
// Skip widths larger than original
|
|
110
|
+
if (width > originalWidth)
|
|
111
|
+
continue;
|
|
112
|
+
const height = Math.round(width / aspectRatio);
|
|
113
|
+
for (const format of mergedConfig.formats) {
|
|
114
|
+
let outputPath;
|
|
115
|
+
let outputFormat;
|
|
116
|
+
if (format === "original") {
|
|
117
|
+
outputFormat = originalExtBare;
|
|
118
|
+
outputPath = runtime.path.resolve(outputDir, `${basename}-${width}w.${originalExtBare}`);
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
outputFormat = format;
|
|
122
|
+
outputPath = runtime.path.resolve(outputDir, `${basename}-${width}w.${format}`);
|
|
123
|
+
}
|
|
124
|
+
// Process and save
|
|
125
|
+
let processedImage = image.clone().resize(width, height, {
|
|
126
|
+
fit: "cover",
|
|
127
|
+
});
|
|
128
|
+
if (format === "webp") {
|
|
129
|
+
processedImage = processedImage.webp({
|
|
130
|
+
quality: mergedConfig.quality.webp,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
else if (format === "avif") {
|
|
134
|
+
processedImage = processedImage.avif({
|
|
135
|
+
quality: mergedConfig.quality.avif,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
else if (outputFormat === "jpg" || outputFormat === "jpeg") {
|
|
139
|
+
processedImage = processedImage.jpeg({
|
|
140
|
+
quality: mergedConfig.quality.jpeg,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
else if (outputFormat === "png") {
|
|
144
|
+
processedImage = processedImage.png({
|
|
145
|
+
quality: mergedConfig.quality.png,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
// Variants are encoded one at a time so only one encoded buffer is in
|
|
149
|
+
// memory; sharp already spreads each encode over its own thread pool.
|
|
150
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
151
|
+
const size = await writeVariant(processedImage, outputPath);
|
|
152
|
+
variants.push({
|
|
153
|
+
path: outputPath,
|
|
154
|
+
format: outputFormat,
|
|
155
|
+
width,
|
|
156
|
+
height,
|
|
157
|
+
size,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// Generate blur placeholder if enabled
|
|
162
|
+
let blurDataUrl;
|
|
163
|
+
if (mergedConfig.generateBlurPlaceholder) {
|
|
164
|
+
blurDataUrl = await generateBlurPlaceholder(imagePath, mergedConfig.placeholderWidth);
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
originalPath: imagePath,
|
|
168
|
+
publicPath,
|
|
169
|
+
originalWidth,
|
|
170
|
+
originalHeight,
|
|
171
|
+
variants,
|
|
172
|
+
blurDataUrl,
|
|
173
|
+
aspectRatio,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Optimize all images in a directory
|
|
178
|
+
*/
|
|
179
|
+
export async function optimizeImages(inputDir, outputDir, publicBasePath = "/images", config = {}) {
|
|
180
|
+
imageLogger.info(`Scanning for images in ${inputDir}...`);
|
|
181
|
+
const imagePaths = await scanImages(inputDir);
|
|
182
|
+
if (imagePaths.length === 0) {
|
|
183
|
+
imageLogger.debug("No images found to optimize");
|
|
184
|
+
return {
|
|
185
|
+
timestamp: Date.now(),
|
|
186
|
+
images: {},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
imageLogger.info(`Found ${imagePaths.length} image(s) to optimize`);
|
|
190
|
+
const images = {};
|
|
191
|
+
let totalOriginalSize = 0;
|
|
192
|
+
let totalOptimizedSize = 0;
|
|
193
|
+
for (const imagePath of imagePaths) {
|
|
194
|
+
try {
|
|
195
|
+
// Images are optimized one at a time to bound memory: each holds its
|
|
196
|
+
// decoded pixels and encoded variants until it finishes.
|
|
197
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
198
|
+
const originalStat = await runtime.fs.stat(imagePath);
|
|
199
|
+
totalOriginalSize += originalStat.size;
|
|
200
|
+
// Sequential for the same memory bound as the stat above
|
|
201
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
202
|
+
const optimized = await optimizeImage(imagePath, outputDir, publicBasePath, config);
|
|
203
|
+
images[imagePath] = optimized;
|
|
204
|
+
const variantSize = optimized.variants.reduce((sum, v) => sum + v.size, 0);
|
|
205
|
+
totalOptimizedSize += variantSize;
|
|
206
|
+
imageLogger.debug(`Optimized: ${runtime.path.basename(imagePath)} → ${optimized.variants.length} variants`);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
imageLogger
|
|
210
|
+
.with({ error })
|
|
211
|
+
.warn(`optimize ${imagePath}; leaving it out of the image manifest`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const manifest = {
|
|
215
|
+
timestamp: Date.now(),
|
|
216
|
+
images,
|
|
217
|
+
};
|
|
218
|
+
// Save manifest
|
|
219
|
+
const manifestPath = runtime.path.resolve(outputDir, "image-manifest.json");
|
|
220
|
+
await runtime.fs.ensureDir(runtime.path.dirname(manifestPath));
|
|
221
|
+
await runtime.fs.writeTextFile(manifestPath, JSON.stringify(manifest, null, 2));
|
|
222
|
+
const savedPercent = totalOriginalSize > 0
|
|
223
|
+
? ((1 - totalOptimizedSize / totalOriginalSize) * 100).toFixed(1)
|
|
224
|
+
: 0;
|
|
225
|
+
imageLogger.info(`Image optimization complete: ${imagePaths.length} images, ${savedPercent}% size reduction`);
|
|
226
|
+
return manifest;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Generate srcset string for an optimized image
|
|
230
|
+
*/
|
|
231
|
+
export function generateSrcset(image, format = "webp") {
|
|
232
|
+
const variants = image.variants
|
|
233
|
+
.filter((v) => v.format === format)
|
|
234
|
+
.sort((a, b) => a.width - b.width);
|
|
235
|
+
return variants.map((v) => `${v.path} ${v.width}w`).join(", ");
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Get the best variant for a given width
|
|
239
|
+
*/
|
|
240
|
+
export function getBestVariant(image, targetWidth, format = "webp") {
|
|
241
|
+
const variants = image.variants
|
|
242
|
+
.filter((v) => v.format === format)
|
|
243
|
+
.sort((a, b) => a.width - b.width);
|
|
244
|
+
// Find the smallest variant that's at least as wide as target
|
|
245
|
+
return variants.find((v) => v.width >= targetWidth) ?? variants.at(-1);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Image optimizer that encodes the images with sharp: responsive variants in
|
|
249
|
+
* the configured formats, widths and quality, a blur placeholder when the
|
|
250
|
+
* config's placeholder is "blur", and image-manifest.json in the output
|
|
251
|
+
* directory. Pass it to the build as `imageOptimizer`.
|
|
252
|
+
*/
|
|
253
|
+
export const sharpImageOptimizer = {
|
|
254
|
+
name: "sharp",
|
|
255
|
+
optimize: (request) => optimizeImages(request.inputDir, request.outputDir, request.publicPath, {
|
|
256
|
+
formats: request.config.formats,
|
|
257
|
+
widths: request.config.widths,
|
|
258
|
+
quality: request.config.quality,
|
|
259
|
+
generateBlurPlaceholder: request.config.placeholder === "blur",
|
|
260
|
+
}),
|
|
261
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sharp Image Optimizer Adapter
|
|
3
|
+
* Image processing with Sharp library
|
|
4
|
+
*/
|
|
5
|
+
export type { ImageManifest, ImageVariant, OptimizedImage, } from "../../domain/image-optimizer.ts";
|
|
6
|
+
export { generateSrcset, getBestVariant, type ImageOptimizationConfig, optimizeImage, optimizeImages, scanImages, sharpImageOptimizer, } from "./image-optimizer.ts";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Sharp Image Optimizer Adapter
|
|
4
|
+
* Image processing with Sharp library
|
|
5
|
+
*/
|
|
6
|
+
export { generateSrcset, getBestVariant, optimizeImage, optimizeImages, scanImages, sharpImageOptimizer, } from "./image-optimizer.js";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tailwind CSS Compile Wrapper
|
|
3
|
+
* Wraps Tailwind's programmatic compile() API
|
|
4
|
+
*/
|
|
5
|
+
export type TailwindCompileOptions = {
|
|
6
|
+
/** Base directory for relative imports */
|
|
7
|
+
base: string;
|
|
8
|
+
/** Utility class candidates to include */
|
|
9
|
+
candidates?: string[];
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Compile CSS with Tailwind
|
|
13
|
+
* @param css - CSS content to compile
|
|
14
|
+
* @param options - Compile options
|
|
15
|
+
* @returns Compiled CSS
|
|
16
|
+
*/
|
|
17
|
+
export declare function compileTailwind(css: string, options: TailwindCompileOptions): Promise<string>;
|
|
18
|
+
/**
|
|
19
|
+
* Expand @apply directives in CSS
|
|
20
|
+
* Compiles CSS with empty candidates to just expand @apply
|
|
21
|
+
*/
|
|
22
|
+
export declare function expandApplyDirectives(css: string, base: string): Promise<string>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Tailwind CSS Compile Wrapper
|
|
4
|
+
* Wraps Tailwind's programmatic compile() API
|
|
5
|
+
*/
|
|
6
|
+
import * as tailwindcss from "tailwindcss";
|
|
7
|
+
import * as stylesheetLoader from "./stylesheet-loader.js";
|
|
8
|
+
/**
|
|
9
|
+
* Compile CSS with Tailwind
|
|
10
|
+
* @param css - CSS content to compile
|
|
11
|
+
* @param options - Compile options
|
|
12
|
+
* @returns Compiled CSS
|
|
13
|
+
*/
|
|
14
|
+
export async function compileTailwind(css, options) {
|
|
15
|
+
const compiled = await tailwindcss.compile(css, {
|
|
16
|
+
base: options.base,
|
|
17
|
+
loadStylesheet: stylesheetLoader.loadStylesheet,
|
|
18
|
+
});
|
|
19
|
+
// Build with candidates (or empty array for just @apply expansion)
|
|
20
|
+
const candidates = options.candidates ?? [];
|
|
21
|
+
return compiled.build(candidates);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Expand @apply directives in CSS
|
|
25
|
+
* Compiles CSS with empty candidates to just expand @apply
|
|
26
|
+
*/
|
|
27
|
+
export function expandApplyDirectives(css, base) {
|
|
28
|
+
return compileTailwind(css, { base, candidates: [] });
|
|
29
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Critical CSS Configuration for Tailwind CSS v4
|
|
3
|
+
*
|
|
4
|
+
* This configuration defines which CSS rules should be included in critical CSS
|
|
5
|
+
* for optimal initial page render. Since this is Tailwind-specific, it's bundled
|
|
6
|
+
* with the Tailwind plugin.
|
|
7
|
+
*
|
|
8
|
+
* Key concepts:
|
|
9
|
+
* - @layer theme: Contains CSS variables (--spacing, --color-*, etc.)
|
|
10
|
+
* - @layer base: Contains reset/preflight styles
|
|
11
|
+
* - @layer utilities: Contains utility classes (split based on usage)
|
|
12
|
+
* - @property: CSS Houdini properties (needed for gradients, transforms)
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* CSS layers that MUST always be in critical CSS
|
|
16
|
+
* These contain foundational styles that all utilities depend on
|
|
17
|
+
*/
|
|
18
|
+
export declare const CRITICAL_LAYERS: readonly string[];
|
|
19
|
+
/**
|
|
20
|
+
* Heuristics for above-the-fold utility classes
|
|
21
|
+
* These patterns match classes that are likely needed for initial render
|
|
22
|
+
* to prevent Cumulative Layout Shift (CLS)
|
|
23
|
+
*/
|
|
24
|
+
export declare const ABOVE_FOLD_PATTERNS: RegExp[];
|
|
25
|
+
/**
|
|
26
|
+
* CSS features that require @property declarations
|
|
27
|
+
* These must be in critical CSS for the features to work on initial render
|
|
28
|
+
*/
|
|
29
|
+
export declare const CRITICAL_PROPERTY_PATTERNS: readonly RegExp[];
|
|
30
|
+
/**
|
|
31
|
+
* Configuration type for critical CSS extraction
|
|
32
|
+
*/
|
|
33
|
+
export type CriticalCssConfig = {
|
|
34
|
+
/** Layers to always include in critical CSS */
|
|
35
|
+
criticalLayers: readonly string[];
|
|
36
|
+
/** Patterns for above-the-fold utilities */
|
|
37
|
+
aboveFoldPatterns: RegExp[];
|
|
38
|
+
/** Patterns to always include in critical CSS */
|
|
39
|
+
forceInclude?: (string | RegExp)[];
|
|
40
|
+
/** Patterns to always exclude from critical CSS */
|
|
41
|
+
forceExclude?: (string | RegExp)[];
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Get the default critical CSS configuration for Tailwind v4
|
|
45
|
+
*/
|
|
46
|
+
export declare function getDefaultCriticalCssConfig(): CriticalCssConfig;
|