@eserstack/laroux-bundler 0.0.0-stage → 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.
Files changed (103) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +431 -2
  3. package/dist/adapters/fonts/font-optimizer.d.ts +28 -0
  4. package/dist/adapters/fonts/font-optimizer.js +74 -0
  5. package/dist/adapters/fonts/index.d.ts +18 -0
  6. package/dist/adapters/fonts/index.js +78 -0
  7. package/dist/adapters/fonts/mod.d.ts +6 -0
  8. package/dist/adapters/fonts/mod.js +7 -0
  9. package/dist/adapters/lightningcss/css-processor.d.ts +39 -0
  10. package/dist/adapters/lightningcss/css-processor.js +103 -0
  11. package/dist/adapters/lightningcss/mod.d.ts +5 -0
  12. package/dist/adapters/lightningcss/mod.js +6 -0
  13. package/dist/adapters/mod.d.ts +13 -0
  14. package/dist/adapters/mod.js +21 -0
  15. package/dist/adapters/prebuilt-bundler/mod.d.ts +5 -0
  16. package/dist/adapters/prebuilt-bundler/mod.js +6 -0
  17. package/dist/adapters/prebuilt-bundler/prebuilt-bundler.d.ts +22 -0
  18. package/dist/adapters/prebuilt-bundler/prebuilt-bundler.js +60 -0
  19. package/dist/adapters/react/mod.d.ts +10 -0
  20. package/dist/adapters/react/mod.js +16 -0
  21. package/dist/adapters/react/plugin.d.ts +17 -0
  22. package/dist/adapters/react/plugin.js +62 -0
  23. package/dist/adapters/react/rsc-analyze.d.ts +29 -0
  24. package/dist/adapters/react/rsc-analyze.js +116 -0
  25. package/dist/adapters/react/rsc-client-entry.d.ts +26 -0
  26. package/dist/adapters/react/rsc-client-entry.js +145 -0
  27. package/dist/adapters/react/rsc-module-map.d.ts +41 -0
  28. package/dist/adapters/react/rsc-module-map.js +81 -0
  29. package/dist/adapters/react/rsc-rewrite-imports.d.ts +38 -0
  30. package/dist/adapters/react/rsc-rewrite-imports.js +409 -0
  31. package/dist/adapters/react/rsc-transform.d.ts +26 -0
  32. package/dist/adapters/react/rsc-transform.js +101 -0
  33. package/dist/adapters/runtime-bundler/mod.d.ts +6 -0
  34. package/dist/adapters/runtime-bundler/mod.js +6 -0
  35. package/dist/adapters/runtime-bundler/runtime-bundler.d.ts +85 -0
  36. package/dist/adapters/runtime-bundler/runtime-bundler.js +244 -0
  37. package/dist/adapters/sharp/image-optimizer.d.ts +52 -0
  38. package/dist/adapters/sharp/image-optimizer.js +261 -0
  39. package/dist/adapters/sharp/mod.d.ts +6 -0
  40. package/dist/adapters/sharp/mod.js +6 -0
  41. package/dist/adapters/tailwindcss/compile.d.ts +22 -0
  42. package/dist/adapters/tailwindcss/compile.js +29 -0
  43. package/dist/adapters/tailwindcss/critical-css-config.d.ts +46 -0
  44. package/dist/adapters/tailwindcss/critical-css-config.js +78 -0
  45. package/dist/adapters/tailwindcss/critical-page-css.d.ts +61 -0
  46. package/dist/adapters/tailwindcss/critical-page-css.js +431 -0
  47. package/dist/adapters/tailwindcss/critical-universal-css.d.ts +68 -0
  48. package/dist/adapters/tailwindcss/critical-universal-css.js +250 -0
  49. package/dist/adapters/tailwindcss/mod.d.ts +10 -0
  50. package/dist/adapters/tailwindcss/mod.js +11 -0
  51. package/dist/adapters/tailwindcss/plugin.d.ts +16 -0
  52. package/dist/adapters/tailwindcss/plugin.js +107 -0
  53. package/dist/adapters/tailwindcss/stylesheet-loader.d.ts +15 -0
  54. package/dist/adapters/tailwindcss/stylesheet-loader.js +83 -0
  55. package/dist/config.d.ts +27 -0
  56. package/dist/config.js +31 -0
  57. package/dist/css-modules.d.ts +49 -0
  58. package/dist/css-modules.js +146 -0
  59. package/dist/domain/build-cache.d.ts +107 -0
  60. package/dist/domain/build-cache.js +128 -0
  61. package/dist/domain/build-validator.d.ts +68 -0
  62. package/dist/domain/build-validator.js +207 -0
  63. package/dist/domain/bundler.d.ts +136 -0
  64. package/dist/domain/bundler.js +225 -0
  65. package/dist/domain/chunk-manifest.d.ts +40 -0
  66. package/dist/domain/chunk-manifest.js +188 -0
  67. package/dist/domain/client-action-stub.d.ts +30 -0
  68. package/dist/domain/client-action-stub.js +167 -0
  69. package/dist/domain/copy-path.d.ts +15 -0
  70. package/dist/domain/copy-path.js +29 -0
  71. package/dist/domain/css-plugin.d.ts +91 -0
  72. package/dist/domain/css-plugin.js +6 -0
  73. package/dist/domain/css-processor.d.ts +57 -0
  74. package/dist/domain/css-processor.js +33 -0
  75. package/dist/domain/font-optimizer.d.ts +46 -0
  76. package/dist/domain/font-optimizer.js +17 -0
  77. package/dist/domain/framework-plugin.d.ts +106 -0
  78. package/dist/domain/framework-plugin.js +20 -0
  79. package/dist/domain/image-optimizer.d.ts +74 -0
  80. package/dist/domain/image-optimizer.js +16 -0
  81. package/dist/domain/import-map.d.ts +90 -0
  82. package/dist/domain/import-map.js +187 -0
  83. package/dist/domain/mod.d.ts +32 -0
  84. package/dist/domain/mod.js +20 -0
  85. package/dist/domain/route-generator.d.ts +34 -0
  86. package/dist/domain/route-generator.js +305 -0
  87. package/dist/domain/route-scanner.d.ts +72 -0
  88. package/dist/domain/route-scanner.js +282 -0
  89. package/dist/domain/server-action-transform.d.ts +28 -0
  90. package/dist/domain/server-action-transform.js +147 -0
  91. package/dist/domain/virtual-source.d.ts +63 -0
  92. package/dist/domain/virtual-source.js +238 -0
  93. package/dist/import-map-resolver-plugin.d.ts +47 -0
  94. package/dist/import-map-resolver-plugin.js +109 -0
  95. package/dist/mod.d.ts +57 -0
  96. package/dist/mod.js +56 -0
  97. package/dist/server-externals-plugin.d.ts +29 -0
  98. package/dist/server-externals-plugin.js +63 -0
  99. package/dist/system.d.ts +157 -0
  100. package/dist/system.js +1401 -0
  101. package/dist/types.d.ts +60 -0
  102. package/dist/types.js +38 -0
  103. package/package.json +83 -3
@@ -0,0 +1,146 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * CSS Modules Handler
4
+ * Re-exports @eserstack/bundler/css CSS modules utilities with laroux-specific caching.
5
+ * The caller's CSS plugin preprocesses each module; the Tailwind plugin
6
+ * injects @reference and expands @apply.
7
+ */
8
+ import { runtime } from "@eserstack/standards/cross-runtime";
9
+ import * as logging from "@eserstack/logging";
10
+ import * as css from "@eserstack/bundler/css";
11
+ const cssModulesLogger = logging.logger.getLogger([
12
+ "laroux-bundler",
13
+ "css-modules",
14
+ ]);
15
+ /**
16
+ * Process a single CSS module file
17
+ * Uses plugin for @reference injection and @apply expansion
18
+ */
19
+ export async function processCSSModule(cssPath, options = {}) {
20
+ const { generateDTS = false, projectRoot, minify = true, plugin, injectReference = true, } = options;
21
+ cssModulesLogger.debug(`Processing CSS module: ${cssPath}`);
22
+ // Read CSS content
23
+ const cssContent = await runtime.fs.readTextFile(cssPath);
24
+ // Create context for plugin
25
+ const context = {
26
+ projectRoot: projectRoot ?? runtime.process.cwd(),
27
+ cssPath,
28
+ isModule: true,
29
+ injectReference,
30
+ };
31
+ // Preprocess with the plugin if there is one and it claims this file
32
+ let processedContent = cssContent;
33
+ if (plugin !== undefined &&
34
+ (plugin.shouldProcess?.(cssContent, context) ?? true)) {
35
+ const preprocessed = plugin.preprocess?.(cssContent, context);
36
+ if (preprocessed !== undefined) {
37
+ processedContent = await Promise.resolve(preprocessed);
38
+ }
39
+ }
40
+ // Write preprocessed content to temp file for eserProcessCssModule
41
+ const tempPath = cssPath.replace(/\.module\.css$/, ".temp.module.css");
42
+ await runtime.fs.writeTextFile(tempPath, processedContent);
43
+ try {
44
+ // Use @eserstack/bundler's processCssModule (no Tailwind root needed - plugin handled @apply)
45
+ const result = await css.processCssModule(tempPath, {
46
+ generateDts: generateDTS,
47
+ minify,
48
+ // No tailwind option - plugin's preprocess already expanded @apply
49
+ });
50
+ const filename = runtime.path.basename(cssPath);
51
+ cssModulesLogger.debug(`Processed ${Object.keys(result.exports).length} class(es) in ${filename}`);
52
+ return result;
53
+ }
54
+ finally {
55
+ // Clean up temp file
56
+ await runtime.fs.remove(tempPath).catch(() => { });
57
+ }
58
+ }
59
+ /**
60
+ * Process multiple CSS modules in parallel with one shared CSS plugin
61
+ */
62
+ export async function processCSSModules(cssPaths, options = {}) {
63
+ const { cache, projectRoot, minify = true, ...moduleOptions } = options;
64
+ cssModulesLogger.debug(`Processing ${cssPaths.length} CSS module(s)`);
65
+ let cacheHits = 0;
66
+ let cacheMisses = 0;
67
+ const results = await Promise.all(cssPaths.map(async (cssPath) => {
68
+ // Check cache first if available
69
+ if (cache !== undefined) {
70
+ try {
71
+ const fileStat = await runtime.fs.stat(cssPath);
72
+ const fileMtime = fileStat.mtime?.getTime() ?? 0;
73
+ const cached = cache.getCssModuleResult(cssPath, fileMtime);
74
+ if (cached !== undefined && cached !== null) {
75
+ cacheHits++;
76
+ return [
77
+ cssPath,
78
+ {
79
+ code: cached.code,
80
+ exports: cached.exports,
81
+ },
82
+ ];
83
+ }
84
+ }
85
+ catch {
86
+ // File might have been deleted, continue with processing
87
+ }
88
+ }
89
+ // Cache miss - process the CSS module
90
+ cacheMisses++;
91
+ const result = await processCSSModule(cssPath, {
92
+ ...moduleOptions,
93
+ projectRoot,
94
+ minify,
95
+ });
96
+ // Cache the result
97
+ if (cache !== undefined) {
98
+ try {
99
+ const fileStat = await runtime.fs.stat(cssPath);
100
+ const fileMtime = fileStat.mtime?.getTime() ?? 0;
101
+ cache.setCssModuleResult(cssPath, result.code, result.exports, fileMtime);
102
+ }
103
+ catch {
104
+ // Ignore caching errors
105
+ }
106
+ }
107
+ return [cssPath, result];
108
+ }));
109
+ if (cache !== undefined && (cacheHits > 0 || cacheMisses > 0)) {
110
+ cssModulesLogger.debug(`CSS modules: ${cacheHits} cache hits, ${cacheMisses} processed`);
111
+ }
112
+ return new Map(results);
113
+ }
114
+ /**
115
+ * Save CSS module outputs to disk
116
+ */
117
+ export async function saveCSSModuleOutputs(cssPath, result, outputDir, options) {
118
+ const basename = runtime.path.basename(cssPath, ".module.css");
119
+ // Determine the correct base directory for relative path calculation
120
+ // If cssPath is under outputDir, use outputDir as base (virtual source case)
121
+ // Otherwise, use projectRoot (real source case)
122
+ const baseDir = cssPath.startsWith(outputDir)
123
+ ? outputDir
124
+ : (options?.projectRoot ?? runtime.process.cwd());
125
+ const relativePath = runtime.path.relative(baseDir, cssPath);
126
+ const relativeDir = runtime.path.dirname(relativePath);
127
+ // Create output directory structure mirroring source
128
+ const moduleOutputDir = runtime.path.resolve(outputDir, relativeDir);
129
+ await runtime.fs.mkdir(moduleOutputDir, { recursive: true });
130
+ // Save processed CSS (skip if only JSON is needed)
131
+ if (options?.skipCss !== true) {
132
+ const cssOutputPath = runtime.path.resolve(moduleOutputDir, `${basename}.module.css`);
133
+ await runtime.fs.writeTextFile(cssOutputPath, result.code);
134
+ }
135
+ // Save exports JSON
136
+ const jsonOutputPath = runtime.path.resolve(moduleOutputDir, `${basename}.module.css.json`);
137
+ await runtime.fs.writeTextFile(jsonOutputPath, JSON.stringify(result.exports, null, 2));
138
+ // Save .d.ts if generated
139
+ if (result.dts !== undefined) {
140
+ const dtsOutputPath = runtime.path.resolve(moduleOutputDir, `${basename}.module.css.d.ts`);
141
+ await runtime.fs.writeTextFile(dtsOutputPath, result.dts);
142
+ }
143
+ cssModulesLogger.debug(`Saved CSS module outputs to ${moduleOutputDir}`);
144
+ }
145
+ // Re-export utility for external use
146
+ export { generateTypeScriptDefinition } from "@eserstack/bundler/css";
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Build Cache for Incremental Builds
3
+ * Provides mtime-based caching for expensive build operations
4
+ */
5
+ import type { RouteScanCache, ScanResult } from "./route-scanner.ts";
6
+ /**
7
+ * Cached client component analysis result
8
+ */
9
+ export type ClientComponentCacheEntry = {
10
+ isClient: boolean;
11
+ exportNames: string[];
12
+ mtime: number;
13
+ };
14
+ /**
15
+ * Cached CSS module processing result
16
+ */
17
+ export type CSSModuleCacheEntry = {
18
+ code: string;
19
+ exports: Record<string, string>;
20
+ mtime: number;
21
+ };
22
+ /**
23
+ * Cached route scan result of one routes directory
24
+ */
25
+ export type RouteCacheEntry = {
26
+ /** The scan result */
27
+ readonly scan: ScanResult;
28
+ /** Modification time of the routes directory when it was scanned */
29
+ readonly mtime: number;
30
+ };
31
+ /**
32
+ * Keeps the "use client" analysis of source files between builds. BuildCache
33
+ * implements it; framework plugins receive it in analyzeClientComponents.
34
+ */
35
+ export type ClientComponentCache = {
36
+ /**
37
+ * The cached analysis of filePath, or null when there is none or the file
38
+ * changed after it (currentMtime is newer than the entry's).
39
+ */
40
+ getClientComponent(filePath: string, currentMtime: number): ClientComponentCacheEntry | null;
41
+ /** Store the analysis of filePath, made when the file had this mtime. */
42
+ setClientComponent(filePath: string, isClient: boolean, exportNames: string[], mtime: number): void;
43
+ };
44
+ /**
45
+ * Build Cache Manager
46
+ * Maintains caches across incremental builds in watch mode. Every entry is
47
+ * keyed by an absolute path, so one cache can serve several projects.
48
+ */
49
+ export declare class BuildCache implements ClientComponentCache, RouteScanCache {
50
+ private clientComponentCache;
51
+ private cssModuleCache;
52
+ private routeScans;
53
+ /**
54
+ * Get cached client component analysis result
55
+ * @param filePath - Absolute path to the component file
56
+ * @param currentMtime - Current file modification time
57
+ * @returns Cached entry if valid, null if cache miss or stale
58
+ */
59
+ getClientComponent(filePath: string, currentMtime: number): ClientComponentCacheEntry | null;
60
+ /**
61
+ * Set client component analysis result in cache
62
+ */
63
+ setClientComponent(filePath: string, isClient: boolean, exportNames: string[], mtime: number): void;
64
+ /**
65
+ * Get cached CSS module processing result
66
+ * @param cssPath - Absolute path to the CSS module file
67
+ * @param currentMtime - Current file modification time
68
+ * @returns Cached entry if valid, null if cache miss or stale
69
+ */
70
+ getCssModuleResult(cssPath: string, currentMtime: number): CSSModuleCacheEntry | null;
71
+ /**
72
+ * Set CSS module processing result in cache
73
+ */
74
+ setCssModuleResult(cssPath: string, code: string, exports: Record<string, string>, mtime: number): void;
75
+ /**
76
+ * Get the cached route scan of a routes directory
77
+ * @param routesDir - Absolute path of the routes directory
78
+ * @param routesDirMtime - Current modification time of the directory
79
+ * @returns The scan if valid, null if cache miss or stale
80
+ */
81
+ getRouteScan(routesDir: string, routesDirMtime: number): ScanResult | null;
82
+ /**
83
+ * Set the route scan of a routes directory in the cache
84
+ */
85
+ setRouteScan(routesDir: string, result: ScanResult, routesDirMtime: number): void;
86
+ /**
87
+ * Invalidate cache entries for a specific file
88
+ * Called when a file changes in watch mode
89
+ */
90
+ invalidateFile(filePath: string): void;
91
+ /**
92
+ * Invalidate all caches for a list of changed files
93
+ */
94
+ invalidateFiles(filePaths: string[]): void;
95
+ /**
96
+ * Clear all caches
97
+ */
98
+ clear(): void;
99
+ /**
100
+ * Get cache statistics for debugging
101
+ */
102
+ getStats(): {
103
+ clientComponents: number;
104
+ cssModules: number;
105
+ hasRoutes: boolean;
106
+ };
107
+ }
@@ -0,0 +1,128 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Build Cache for Incremental Builds
4
+ * Provides mtime-based caching for expensive build operations
5
+ */
6
+ import * as logging from "@eserstack/logging";
7
+ import * as buildValidator from "./build-validator.js";
8
+ const cacheLogger = logging.logger.getLogger(["laroux-bundler", "build-cache"]);
9
+ /**
10
+ * Build Cache Manager
11
+ * Maintains caches across incremental builds in watch mode. Every entry is
12
+ * keyed by an absolute path, so one cache can serve several projects.
13
+ */
14
+ export class BuildCache {
15
+ clientComponentCache = new Map();
16
+ cssModuleCache = new Map();
17
+ routeScans = new Map();
18
+ /**
19
+ * Get cached client component analysis result
20
+ * @param filePath - Absolute path to the component file
21
+ * @param currentMtime - Current file modification time
22
+ * @returns Cached entry if valid, null if cache miss or stale
23
+ */
24
+ getClientComponent(filePath, currentMtime) {
25
+ const cached = this.clientComponentCache.get(filePath);
26
+ if (cached && cached.mtime >= currentMtime) {
27
+ cacheLogger.debug(`Cache hit: client component ${filePath}`);
28
+ return cached;
29
+ }
30
+ return null;
31
+ }
32
+ /**
33
+ * Set client component analysis result in cache
34
+ */
35
+ setClientComponent(filePath, isClient, exportNames, mtime) {
36
+ this.clientComponentCache.set(filePath, { isClient, exportNames, mtime });
37
+ }
38
+ /**
39
+ * Get cached CSS module processing result
40
+ * @param cssPath - Absolute path to the CSS module file
41
+ * @param currentMtime - Current file modification time
42
+ * @returns Cached entry if valid, null if cache miss or stale
43
+ */
44
+ getCssModuleResult(cssPath, currentMtime) {
45
+ const cached = this.cssModuleCache.get(cssPath);
46
+ if (cached && cached.mtime >= currentMtime) {
47
+ cacheLogger.debug(`Cache hit: CSS module ${cssPath}`);
48
+ return cached;
49
+ }
50
+ return null;
51
+ }
52
+ /**
53
+ * Set CSS module processing result in cache
54
+ */
55
+ setCssModuleResult(cssPath, code, exports, mtime) {
56
+ this.cssModuleCache.set(cssPath, { code, exports, mtime });
57
+ }
58
+ /**
59
+ * Get the cached route scan of a routes directory
60
+ * @param routesDir - Absolute path of the routes directory
61
+ * @param routesDirMtime - Current modification time of the directory
62
+ * @returns The scan if valid, null if cache miss or stale
63
+ */
64
+ getRouteScan(routesDir, routesDirMtime) {
65
+ const cached = this.routeScans.get(routesDir);
66
+ if (cached !== undefined && cached.mtime >= routesDirMtime) {
67
+ cacheLogger.debug(`Cache hit: route scan of ${routesDir}`);
68
+ return cached.scan;
69
+ }
70
+ return null;
71
+ }
72
+ /**
73
+ * Set the route scan of a routes directory in the cache
74
+ */
75
+ setRouteScan(routesDir, result, routesDirMtime) {
76
+ this.routeScans.set(routesDir, { scan: result, mtime: routesDirMtime });
77
+ }
78
+ /**
79
+ * Invalidate cache entries for a specific file
80
+ * Called when a file changes in watch mode
81
+ */
82
+ invalidateFile(filePath) {
83
+ // Invalidate client component cache
84
+ if (this.clientComponentCache.has(filePath)) {
85
+ this.clientComponentCache.delete(filePath);
86
+ cacheLogger.debug(`Invalidated: client component ${filePath}`);
87
+ }
88
+ // Invalidate CSS module cache
89
+ if (this.cssModuleCache.has(filePath)) {
90
+ this.cssModuleCache.delete(filePath);
91
+ cacheLogger.debug(`Invalidated: CSS module ${filePath}`);
92
+ }
93
+ // Invalidate the scan of every routes directory that holds the file
94
+ for (const routesDir of this.routeScans.keys()) {
95
+ if (buildValidator.isWithinOutputDir(filePath, routesDir)) {
96
+ this.routeScans.delete(routesDir);
97
+ cacheLogger.debug(`Invalidated: route scan of ${routesDir}`);
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * Invalidate all caches for a list of changed files
103
+ */
104
+ invalidateFiles(filePaths) {
105
+ for (const filePath of filePaths) {
106
+ this.invalidateFile(filePath);
107
+ }
108
+ }
109
+ /**
110
+ * Clear all caches
111
+ */
112
+ clear() {
113
+ this.clientComponentCache.clear();
114
+ this.cssModuleCache.clear();
115
+ this.routeScans.clear();
116
+ cacheLogger.debug("All caches cleared");
117
+ }
118
+ /**
119
+ * Get cache statistics for debugging
120
+ */
121
+ getStats() {
122
+ return {
123
+ clientComponents: this.clientComponentCache.size,
124
+ cssModules: this.cssModuleCache.size,
125
+ hasRoutes: this.routeScans.size > 0,
126
+ };
127
+ }
128
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Build Isolation Validator
3
+ *
4
+ * Ensures the build process only writes to the designated output directory (dist/).
5
+ * This is critical for:
6
+ * - Docker/container deployments with read-only source volumes
7
+ * - Runtime permission scoping (write access to dist/ only)
8
+ * - CI/CD pipelines (clean git status after build)
9
+ * - Build reproducibility
10
+ */
11
+ export interface BuildIsolationReport {
12
+ valid: boolean;
13
+ violations: FileViolation[];
14
+ checkedAt: Date;
15
+ distDir: string;
16
+ projectRoot: string;
17
+ }
18
+ export interface FileViolation {
19
+ filePath: string;
20
+ relativePath: string;
21
+ type: "created" | "modified";
22
+ timestamp: Date;
23
+ }
24
+ /**
25
+ * The build wrote outside the output directory while strict validation was on.
26
+ */
27
+ export declare class BuildIsolationError extends Error {
28
+ readonly violations: readonly FileViolation[];
29
+ constructor(violations: readonly FileViolation[]);
30
+ }
31
+ /**
32
+ * Validate that the build only wrote to the output directory
33
+ *
34
+ * @param projectRoot - The project root directory
35
+ * @param distDir - The designated output directory
36
+ * @param buildStartTime - Timestamp when the build started
37
+ * @param options - Validation options
38
+ * @returns Validation report
39
+ */
40
+ export declare function validateBuildIsolation(projectRoot: string, distDir: string, buildStartTime: Date, options?: {
41
+ strict?: boolean;
42
+ warnOnly?: boolean;
43
+ ignorePatterns?: string[];
44
+ }): Promise<BuildIsolationReport>;
45
+ /**
46
+ * Check if a path is within the allowed output directory
47
+ */
48
+ export declare function isWithinOutputDir(filePath: string, distDir: string): boolean;
49
+ /**
50
+ * Isolated writer interface for build output
51
+ */
52
+ export type IsolatedWriter = {
53
+ writeTextFile(filePath: string, content: string): Promise<void>;
54
+ copy(src: string, dest: string): Promise<void>;
55
+ };
56
+ /**
57
+ * Create a safe write function that only allows writes to dist/
58
+ * Use this to wrap file writes for strict isolation
59
+ */
60
+ export declare function createIsolatedWriter(distDir: string): IsolatedWriter;
61
+ /**
62
+ * Clean up known build artifacts from src/ directory
63
+ * Use before implementing full isolation to start fresh
64
+ */
65
+ export declare function cleanSrcArtifacts(projectRoot: string): Promise<{
66
+ deleted: string[];
67
+ failed: string[];
68
+ }>;
@@ -0,0 +1,207 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Build Isolation Validator
4
+ *
5
+ * Ensures the build process only writes to the designated output directory (dist/).
6
+ * This is critical for:
7
+ * - Docker/container deployments with read-only source volumes
8
+ * - Runtime permission scoping (write access to dist/ only)
9
+ * - CI/CD pipelines (clean git status after build)
10
+ * - Build reproducibility
11
+ */
12
+ import { runtime } from "@eserstack/standards/cross-runtime";
13
+ import * as collector from "@eserstack/collector";
14
+ import * as logging from "@eserstack/logging";
15
+ import * as copyPath from "./copy-path.js";
16
+ // Pattern to ignore node_modules and hidden directories
17
+ const IGNORE_PATTERN = /(?:node_modules|\/\.|\\\.)/;
18
+ const validatorLogger = logging.logger.getLogger([
19
+ "laroux-bundler",
20
+ "build-validator",
21
+ ]);
22
+ /**
23
+ * The build wrote outside the output directory while strict validation was on.
24
+ */
25
+ export class BuildIsolationError extends Error {
26
+ violations;
27
+ // Explicit assignment, not parameter properties: Node's erase-only type
28
+ // stripping cannot emit the assignment a parameter property implies.
29
+ constructor(violations) {
30
+ super(`build isolation: ${violations.length} file(s) modified outside dist/: ${violations
31
+ .map((violation) => `${violation.relativePath} (${violation.type})`)
32
+ .join(", ")}. Fix the build to write only to dist/, or validate without strict.`);
33
+ this.name = "BuildIsolationError";
34
+ this.violations = violations;
35
+ }
36
+ }
37
+ /**
38
+ * Files that are intentionally generated in src/ (grandfathered but should be migrated)
39
+ * These generate warnings but don't fail the build
40
+ */
41
+ const KNOWN_SRC_ARTIFACTS = [
42
+ "_generated.ts", // Route generation (to be moved to dist/)
43
+ ".module.css.json", // CSS module mappings (to be moved to dist/)
44
+ ".module.css.d.ts", // CSS module TypeScript definitions
45
+ ];
46
+ /**
47
+ * Directories that should never have build artifacts
48
+ */
49
+ const PROTECTED_DIRECTORIES = ["src", "public", "packages"];
50
+ /**
51
+ * Validate that the build only wrote to the output directory
52
+ *
53
+ * @param projectRoot - The project root directory
54
+ * @param distDir - The designated output directory
55
+ * @param buildStartTime - Timestamp when the build started
56
+ * @param options - Validation options
57
+ * @returns Validation report
58
+ */
59
+ export async function validateBuildIsolation(projectRoot, distDir, buildStartTime, options = {}) {
60
+ const resolvedDistDir = runtime.path.resolve(projectRoot, distDir);
61
+ validatorLogger.debug("Validating build isolation...");
62
+ validatorLogger.debug(` Project root: ${projectRoot}`);
63
+ validatorLogger.debug(` Dist dir: ${resolvedDistDir}`);
64
+ validatorLogger.debug(` Build start: ${buildStartTime.toISOString()}`);
65
+ // Check each protected directory for modifications; the scans are
66
+ // independent and their results are joined in directory order
67
+ const violationsPerDirectory = await Promise.all(PROTECTED_DIRECTORIES.map(async (protectedDir) => {
68
+ const dirPath = runtime.path.resolve(projectRoot, protectedDir);
69
+ if (!(await runtime.fs.exists(dirPath))) {
70
+ return [];
71
+ }
72
+ return await scanForViolations(dirPath, projectRoot, buildStartTime, options.ignorePatterns ?? []);
73
+ }));
74
+ const violations = violationsPerDirectory.flat();
75
+ const report = {
76
+ valid: violations.length === 0,
77
+ violations,
78
+ checkedAt: new Date(),
79
+ distDir: resolvedDistDir,
80
+ projectRoot,
81
+ };
82
+ if (violations.length === 0) {
83
+ validatorLogger.debug("Build isolation validated successfully");
84
+ return report;
85
+ }
86
+ // A failing strict check throws, and the caller that handles the error logs
87
+ // it; only the outcomes that do not throw are logged here
88
+ if (options.strict === true && options.warnOnly !== true) {
89
+ throw new BuildIsolationError(violations);
90
+ }
91
+ const level = options.strict === true ? "error" : "warn";
92
+ validatorLogger[level](`Build isolation violations detected: ${violations.length} file(s) modified outside dist/`);
93
+ for (const violation of violations) {
94
+ const isKnown = KNOWN_SRC_ARTIFACTS.some((artifact) => violation.relativePath.includes(artifact));
95
+ if (isKnown) {
96
+ validatorLogger.warn(` Known artifact: ${violation.relativePath} (${violation.type})`);
97
+ }
98
+ else {
99
+ validatorLogger[level](` VIOLATION: ${violation.relativePath} (${violation.type})`);
100
+ }
101
+ }
102
+ return report;
103
+ }
104
+ /**
105
+ * Scan a directory for files modified after the build start time
106
+ */
107
+ async function scanForViolations(dirPath, projectRoot, buildStartTime, ignorePatterns) {
108
+ const violations = [];
109
+ try {
110
+ for await (const relPath of collector.walkFiles(dirPath, undefined, IGNORE_PATTERN)) {
111
+ const filePath = runtime.path.join(dirPath, relPath);
112
+ // Check if file matches ignore patterns
113
+ const relativePath = runtime.path.relative(projectRoot, filePath);
114
+ if (ignorePatterns.some((pattern) => relativePath.includes(pattern))) {
115
+ continue;
116
+ }
117
+ try {
118
+ const stat = await runtime.fs.stat(filePath);
119
+ if (stat.mtime !== null && stat.mtime > buildStartTime) {
120
+ violations.push({
121
+ filePath,
122
+ relativePath,
123
+ type: "modified",
124
+ timestamp: stat.mtime,
125
+ });
126
+ }
127
+ }
128
+ catch {
129
+ // File may have been deleted, skip
130
+ }
131
+ }
132
+ }
133
+ catch (error) {
134
+ validatorLogger
135
+ .with({ error })
136
+ .debug(`scan ${dirPath} for files changed during the build; skipping it`);
137
+ }
138
+ return violations;
139
+ }
140
+ /**
141
+ * Check if a path is within the allowed output directory
142
+ */
143
+ export function isWithinOutputDir(filePath, distDir) {
144
+ const resolvedFilePath = runtime.path.resolve(filePath);
145
+ const resolvedDistDir = runtime.path.resolve(distDir);
146
+ return (resolvedFilePath.startsWith(resolvedDistDir + runtime.path.sep) ||
147
+ resolvedFilePath === resolvedDistDir);
148
+ }
149
+ /**
150
+ * Create a safe write function that only allows writes to dist/
151
+ * Use this to wrap file writes for strict isolation
152
+ */
153
+ export function createIsolatedWriter(distDir) {
154
+ const resolvedDistDir = runtime.path.resolve(distDir);
155
+ return {
156
+ async writeTextFile(filePath, content) {
157
+ if (!isWithinOutputDir(filePath, resolvedDistDir)) {
158
+ throw new Error(`Build isolation violation: Cannot write to ${filePath} (outside ${resolvedDistDir})`);
159
+ }
160
+ // Ensure directory exists
161
+ await runtime.fs.ensureDir(runtime.path.dirname(filePath));
162
+ await runtime.fs.writeTextFile(filePath, content);
163
+ },
164
+ async copy(src, dest) {
165
+ if (!isWithinOutputDir(dest, resolvedDistDir)) {
166
+ throw new Error(`Build isolation violation: Cannot copy to ${dest} (outside ${resolvedDistDir})`);
167
+ }
168
+ await copyPath.copyPath(src, dest);
169
+ },
170
+ };
171
+ }
172
+ /**
173
+ * Clean up known build artifacts from src/ directory
174
+ * Use before implementing full isolation to start fresh
175
+ */
176
+ export async function cleanSrcArtifacts(projectRoot) {
177
+ const deleted = [];
178
+ const failed = [];
179
+ const srcDir = runtime.path.resolve(projectRoot, "src");
180
+ validatorLogger.debug("Cleaning build artifacts from src/...");
181
+ try {
182
+ for await (const relPath of collector.walkFiles(srcDir, undefined, /node_modules/)) {
183
+ const filePath = runtime.path.join(srcDir, relPath);
184
+ const isArtifact = KNOWN_SRC_ARTIFACTS.some((pattern) => filePath.endsWith(pattern));
185
+ if (isArtifact) {
186
+ try {
187
+ await runtime.fs.remove(filePath);
188
+ deleted.push(runtime.path.relative(projectRoot, filePath));
189
+ validatorLogger.debug(` Deleted: ${filePath}`);
190
+ }
191
+ catch (error) {
192
+ failed.push(runtime.path.relative(projectRoot, filePath));
193
+ validatorLogger
194
+ .with({ error })
195
+ .warn(`delete build artifact ${filePath}; delete it by hand`);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ catch (error) {
201
+ validatorLogger.with({ error }).error("scan src/ for build artifacts");
202
+ }
203
+ if (deleted.length > 0) {
204
+ validatorLogger.debug(`Cleaned ${deleted.length} artifact(s) from src/`);
205
+ }
206
+ return { deleted, failed };
207
+ }