-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsystem.ts
More file actions
2018 lines (1808 loc) · 64 KB
/
Copy pathsystem.ts
File metadata and controls
2018 lines (1808 loc) · 64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* Unified Build System
*
* Framework-agnostic build orchestration.
* Framework-specific functionality (like React Server Components) is provided
* through the FrameworkPlugin interface.
*/
import {
type FsWatcher,
runtime,
toPosix,
} from "@eserstack/standards/cross-runtime";
import * as logging from "@eserstack/logging";
import * as pkg from "@eserstack/codebase/package";
import { analyzeServerActions } from "@eserstack/codebase/directive-analysis";
import {
JS_FILE_PATTERN,
replaceJsExtension,
} from "@eserstack/standards/patterns";
import { transformServerActions } from "./domain/server-action-transform.ts";
import { generateClientActionStubs } from "./domain/client-action-stub.ts";
const buildLogger = logging.logger.getLogger(["laroux-bundler", "build"]);
import { copy } from "@std/fs"; // copy not available in runtime
import { ulid } from "@std/ulid";
import type {
ClientComponent,
FrameworkPlugin,
ModuleMap,
} from "./domain/framework-plugin.ts";
import { noopPlugin } from "./domain/framework-plugin.ts";
import type { BundlerBackend } from "./config.ts";
import type { BuildConfig, FontDefinition } from "./types.ts";
import type { ChunkManifest } from "./domain/chunk-manifest.ts";
import { processCss } from "./adapters/lightningcss/mod.ts";
import type { CssPlugin } from "./domain/css-plugin.ts";
import type { CSSModuleResult } from "./css-modules.ts";
import { createImportMapResolverPlugin } from "./import-map-resolver-plugin.ts";
import { scanRoutes } from "./domain/route-scanner.ts";
import {
generateApiRouteFile,
generateProxyFile,
generateRouteFile,
} from "./domain/route-generator.ts";
import {
createVirtualSource,
translateClientComponents,
translateToVirtualPath,
} from "./domain/virtual-source.ts";
import { type BuildCache, getGlobalBuildCache } from "./domain/build-cache.ts";
import {
bundle,
bundleServerComponents,
logBundleStats,
} from "./domain/bundler.ts";
import {
generateChunkManifest,
logManifest,
saveChunkManifest,
} from "./domain/chunk-manifest.ts";
import { PRODUCTION_SETTINGS } from "./config.ts";
import { getFontUrls, optimizeGoogleFonts } from "./adapters/fonts/mod.ts";
import { processCSSModules, saveCSSModuleOutputs } from "./css-modules.ts";
import { createServerExternalsPlugin } from "./server-externals-plugin.ts";
// Constants
const MANIFEST_FILENAME = "manifest.json";
const MODULE_MAP_FILENAME = "module-map.json";
const SERVER_DIR = "server";
const CLIENT_DIR = "client";
/**
* Build context with all necessary dependencies
*/
export type BuildContext = {
/** Build configuration */
config: BuildConfig;
/** Project root directory */
projectRoot: string;
/** Source directory */
srcDir: string;
/** Distribution/output directory */
distDir: string;
/** Client entry point path */
clientEntry: string;
/** Chunk manifest file path */
chunkManifestFile: string;
/** Build cache for incremental builds (watch mode) */
cache?: BuildCache;
/** Bundler backend to use (default: "deno-bundler") */
bundlerBackend?: BundlerBackend;
/** Framework plugin for framework-specific build functionality */
plugin: FrameworkPlugin;
/** CSS plugin for CSS processing (Tailwind, UnoCSS, etc.) */
cssPlugin?: CssPlugin;
};
/**
* Result of a build operation
*/
export type BuildResult = {
/** Whether the build succeeded */
success: boolean;
/** Path to the client bundle */
clientBundle: string;
/** Module map for client components */
moduleMap: ModuleMap;
/** Number of client components found */
clientComponents: number;
/** Build duration in milliseconds */
duration: number;
/** Build timestamp */
timestamp: number;
/** Files that changed (for watch mode HMR) */
changedFiles?: string[];
};
/**
* Build plugins configuration
* Users pass these explicitly when calling bundle functions
*/
export type BuildPlugins = {
/** Framework plugin for framework-specific build functionality (React, Vue, etc.) */
framework?: FrameworkPlugin;
/** CSS plugin for CSS processing (Tailwind, UnoCSS, etc.) */
css?: CssPlugin;
/** Bundler backend to use (default: "deno-bundler") */
bundlerBackend?: BundlerBackend;
};
/**
* Create build context from configuration
* @param config - Build configuration
* @param plugins - Plugins for framework, CSS, and bundler (explicit composition)
* @returns Build context with all paths and dependencies
*/
export function createBuildContext(
config: BuildConfig,
plugins?: BuildPlugins,
): BuildContext {
const projectRoot = config.projectRoot;
const srcDir = config.srcDir;
const distDir = config.distDir;
// Client entry is no longer hardcoded - provided by the plugin
const clientEntry = "";
const chunkManifestFile = runtime.path.resolve(distDir, MANIFEST_FILENAME);
return {
config,
projectRoot,
srcDir,
distDir,
clientEntry,
chunkManifestFile,
bundlerBackend: plugins?.bundlerBackend,
plugin: plugins?.framework ?? noopPlugin,
cssPlugin: plugins?.css,
};
}
/**
* Main build function
* Performs complete build: analyze → transform → bundle → generate maps
* @param context - Build context with configuration and paths
* @param options - Build options
* - skipCss: skip CSS processing for JS-only changes
* - cssOnly: only process CSS, skip all JS steps (for CSS-only HMR)
* - changedFiles: set of changed file paths for incremental builds
* @returns Build result with success status and metrics
*/
export async function build(
context: BuildContext,
options?: {
skipCss?: boolean;
cssOnly?: boolean;
changedFiles?: Set<string>;
},
): Promise<BuildResult> {
const { srcDir, distDir, projectRoot } = context;
const startTime = performance.now();
// Generate unique build ID
const buildId = ulid();
buildLogger.info(`🚀 Starting RSC build...`);
buildLogger.debug(`🆔 Build ID: ${buildId}`);
try {
// CSS-only fast path for HMR - skip all JS steps
if (options?.cssOnly) {
buildLogger.debug("⚡ CSS-only rebuild (fast path)");
const buildTimestamp = Date.now();
const clientOutputDir = runtime.path.resolve(distDir, CLIENT_DIR);
// Use provided CSS plugin or skip CSS processing if none
const cssPlugin = context.cssPlugin;
if (!cssPlugin) {
buildLogger.warn("⚠️ No CSS plugin provided, skipping CSS processing");
return {
success: true,
clientBundle: "",
moduleMap: {},
clientComponents: 0,
duration: performance.now() - startTime,
timestamp: buildTimestamp,
};
}
// Scan CSS modules once for this build
const cssModulePaths = await scanCssModuleFiles(srcDir);
// Only process CSS files
await processCssFiles(cssPlugin, srcDir, projectRoot, clientOutputDir);
// Process CSS Modules (pass pre-scanned paths and cache)
if (cssModulePaths.length > 0) {
await processCssModulesFiles(
projectRoot,
clientOutputDir,
context.config,
{ cssModulePaths, cache: context.cache },
);
}
const duration = performance.now() - startTime;
buildLogger.info(`⚡ CSS rebuild completed (${duration.toFixed(0)}ms)`);
return {
success: true,
clientBundle: "", // Preserved from previous build
moduleMap: {}, // Preserved from previous build
clientComponents: 0,
duration,
timestamp: buildTimestamp,
};
}
// Step 1: Clean if requested (preserve CSS files when skipCss is true)
await cleanBuildDir(distDir, options?.skipCss);
// Step 2: Ensure dist directory exists
await runtime.fs.ensureDir(distDir);
// Build timestamp will be written to chunk manifest at the end
const buildTimestamp = Date.now();
// Step 3: Parallel scan - routes, client components, and CSS modules
// These operations are independent and can run concurrently for faster builds
buildLogger.debug(
"🔍 Step 3: Parallel scanning (routes, components, CSS modules)...",
);
const routesDir = runtime.path.resolve(srcDir, "app/routes");
const { plugin } = context;
const [scanResult, clientComponents, cssModulePaths] = await Promise.all([
scanRoutes(routesDir, projectRoot),
plugin.analyzeClientComponents
? plugin.analyzeClientComponents(srcDir, projectRoot, context.cache)
: Promise.resolve([]),
scanCssModuleFiles(srcDir),
]);
// Generate route files to dist/server/ (NOT src/) for build isolation
const serverDir = runtime.path.resolve(distDir, SERVER_DIR);
await runtime.fs.ensureDir(serverDir);
const generatedRoutesPath = runtime.path.resolve(
serverDir,
"_generated-routes.ts",
);
// Get srcDir name relative to project root (e.g., "src")
const srcDirName = runtime.path.relative(projectRoot, srcDir);
await generateRouteFile({
scanResult,
outputPath: generatedRoutesPath,
projectRoot,
srcDirName,
});
buildLogger.debug(
`✓ Generated ${scanResult.routes.length} page route(s) to dist/`,
);
// Generate API routes file if any exist
if (scanResult.apiRoutes.length > 0) {
const apiRoutesPath = runtime.path.resolve(
distDir,
"server",
"api-routes.ts",
);
await runtime.fs.ensureDir(runtime.path.dirname(apiRoutesPath));
await generateApiRouteFile(scanResult, apiRoutesPath, projectRoot);
buildLogger.debug(
`✓ Generated ${scanResult.apiRoutes.length} API route(s)`,
);
}
// Generate proxy registry if any exist
if (scanResult.proxies.length > 0) {
const proxyPath = runtime.path.resolve(
distDir,
"server",
"proxy-registry.ts",
);
await runtime.fs.ensureDir(runtime.path.dirname(proxyPath));
await generateProxyFile(scanResult, proxyPath, projectRoot);
buildLogger.debug(
`✓ Generated ${scanResult.proxies.length} proxy definition(s)`,
);
}
if (clientComponents.length === 0) {
buildLogger.warn("⚠️ Warning: No client components found!");
}
// Step 4: Transform client components (proxies)
buildLogger.debug("🔄 Step 4: Transforming client components...");
const transformResults = plugin.transformClientComponents
? await plugin.transformClientComponents(
clientComponents,
runtime.path.resolve(distDir, SERVER_DIR),
projectRoot,
)
: [];
// Generate transform manifest
if (plugin.generateTransformManifest) {
await plugin.generateTransformManifest(
transformResults,
runtime.path.resolve(distDir, "transform-manifest.json"),
projectRoot,
);
}
// Step 5: Rewrite server component imports
buildLogger.debug(
"✏️ Step 5: Rewriting server component imports...",
);
const allComponents = plugin.getAllComponents
? await plugin.getAllComponents(srcDir)
: [];
const clientComponentPaths = new Set(
clientComponents.map((c) => c.filePath),
);
const serverComponentPaths = allComponents.filter((path) =>
!clientComponentPaths.has(path)
);
if (plugin.rewriteServerComponents) {
await plugin.rewriteServerComponents(
serverComponentPaths,
transformResults,
cssModulePaths,
runtime.path.resolve(distDir, SERVER_DIR),
projectRoot,
);
}
// Step 5b: Transform server actions to add React server reference symbols
// This must happen AFTER server components are copied but BEFORE bundling
buildLogger.debug(
"🔄 Step 5b: Transforming server actions with React symbols...",
);
const serverDistDir = runtime.path.resolve(distDir, SERVER_DIR);
const serverActionResults = await transformServerActions(serverDistDir);
if (serverActionResults.length > 0) {
const totalActions = serverActionResults.reduce(
(sum, r) => sum + r.transformedActions.length,
0,
);
buildLogger.info(
` ✅ Transformed ${serverActionResults.length} file(s) with ${totalActions} action(s)`,
);
}
// Step 6: Generate module map
buildLogger.debug("🗺️ Step 6: Generating module map...");
const clientOutputDir = runtime.path.resolve(distDir, CLIENT_DIR);
await runtime.fs.ensureDir(clientOutputDir);
const moduleMap = plugin.createModuleMap
? await plugin.createModuleMap(clientComponents)
: {};
if (plugin.saveModuleMap) {
await plugin.saveModuleMap(
moduleMap,
runtime.path.resolve(clientOutputDir, MODULE_MAP_FILENAME),
);
}
if (plugin.createClientManifest) {
await plugin.createClientManifest(clientComponents);
}
// Use provided CSS plugin (or skip CSS if none)
const cssPlugin = context.cssPlugin;
// Step 7: Process global CSS with CSS plugin (skippable for JS-only changes)
if (!options?.skipCss && cssPlugin) {
buildLogger.debug(
"🎨 Step 7: Processing CSS with CSS plugin + Lightning CSS...",
);
await processCssFiles(cssPlugin, srcDir, projectRoot, clientOutputDir);
} else if (!cssPlugin) {
buildLogger.debug("⏭️ No CSS plugin provided, skipping CSS processing");
} else {
buildLogger.debug("⏭️ Skipping CSS processing (JS-only change)");
}
// Step 8: Create virtual source for bundling (build isolation)
// This copies src/ to dist/_bundle_src/ so we can modify imports without touching original source
// In watch mode, only copy changed files for faster rebuilds
buildLogger.debug("📁 Step 8: Creating virtual source for bundling...");
const virtualSource = await createVirtualSource({
projectRoot,
distDir,
srcDir,
changedFiles: options?.changedFiles,
});
const virtualSrcDir = virtualSource.virtualSrcDir;
// Step 8b: Generate client stubs for "use server" files in virtual source
// This replaces server action files with client-side stubs that call /action
// Must happen BEFORE client bundling so imports resolve to stubs
buildLogger.debug(
"🔌 Step 8b: Generating client action stubs in virtual source...",
);
const virtualSrcSubdirForStubs = runtime.path.join(
virtualSrcDir,
srcDirName,
);
const clientStubResults = await generateClientActionStubs(
virtualSrcSubdirForStubs,
virtualSrcDir,
);
if (clientStubResults.length > 0) {
const totalActions = clientStubResults.reduce(
(sum, r) => sum + r.exportedActions.length,
0,
);
buildLogger.info(
` ✅ Generated ${clientStubResults.length} stub file(s) with ${totalActions} action(s)`,
);
}
// Step 9: Process CSS Modules to virtual source (NOT original src/)
// Generate JSON files in the virtual source directory
// Map to store pre-processed CSS module results (translated to original paths)
let cssModuleResults: Map<string, CSSModuleResult> | undefined;
if (!options?.skipCss) {
buildLogger.debug(
"🎨 Step 9: Processing CSS Modules to virtual source...",
);
// Translate CSS module paths to virtual source
const virtualCssModulePaths = cssModulePaths.map((p) =>
translateToVirtualPath(p, srcDir, virtualSrcDir)
);
// Process and generate JSON files in virtual source
// Use real projectRoot for Tailwind (needs node_modules for @import "tailwindcss")
// Pass pre-translated virtual paths to avoid redundant scan
const virtualResults = await processCssModulesFiles(
projectRoot,
virtualSrcDir,
context.config,
{
skipCss: true,
cssModulePaths: virtualCssModulePaths,
cache: context.cache,
},
);
// Translate virtual paths back to original paths for reuse in appendCssModulesToStyles
// This avoids duplicate CSS module processing
cssModuleResults = new Map();
// Use srcDirName computed from config (e.g., "src") for virtual path translation
const virtualSrcSubdir = runtime.path.join(virtualSrcDir, srcDirName);
for (const [virtualPath, result] of virtualResults) {
// Convert virtual path back to original path
const relativePath = runtime.path.relative(
virtualSrcSubdir,
virtualPath,
);
const originalPath = runtime.path.resolve(srcDir, relativePath);
cssModuleResults.set(originalPath, result);
}
// Rewrite CSS imports in virtual source (NOT original src/)
if (virtualCssModulePaths.length > 0) {
buildLogger.debug(
"✏️ Step 10: Rewriting CSS module imports in virtual source...",
);
if (plugin.rewriteCssModuleImports) {
await plugin.rewriteCssModuleImports(
virtualSrcSubdir,
virtualCssModulePaths,
projectRoot,
);
}
}
}
// Step 11: Bundle client code from virtual source
// Translate component paths to use virtual source
buildLogger.debug(
"📦 Step 11: Bundling client code from virtual source...",
);
const virtualClientComponents = translateClientComponents(
clientComponents,
srcDir,
virtualSrcDir,
);
const clientBundle = await bundleClient(
{ ...context, srcDir: virtualSrcDir },
virtualClientComponents,
buildId,
buildTimestamp,
);
// Step 12: Copy CSS Module JSON files from virtual source to dist/
if (!options?.skipCss && cssModulePaths.length > 0) {
// Copy JSON files from virtual source to dist/client/
buildLogger.debug(
`📋 Step 12: Copying ${cssModulePaths.length} CSS Module JSON file(s) to client/...`,
);
await copyCssModuleJsonFilesFromSrc(
cssModulePaths.map((p) =>
translateToVirtualPath(p, srcDir, virtualSrcDir)
),
virtualSrcDir,
clientOutputDir,
);
// Copy JSON files from virtual source to dist/server/
buildLogger.debug(
`📋 Step 13: Copying ${cssModulePaths.length} CSS Module JSON file(s) to server/...`,
);
await copyCssModuleJsonFilesFromSrc(
cssModulePaths.map((p) =>
translateToVirtualPath(p, srcDir, virtualSrcDir)
),
virtualSrcDir,
runtime.path.resolve(distDir, SERVER_DIR),
);
// Append CSS module styles to main styles.css bundle
// Pass pre-processed results to avoid duplicate processing
buildLogger.debug("🎨 Step 14: Appending CSS modules to styles.css...");
await appendCssModulesToStyles(
cssModulePaths,
projectRoot,
clientOutputDir,
cssModuleResults,
);
}
// Step 15: Clean up virtual source
buildLogger.debug("🧹 Step 15: Cleaning up virtual source...");
await virtualSource.cleanup();
// Step 16: Extract critical CSS for faster initial render (requires CSS plugin)
if (cssPlugin) {
buildLogger.debug("✨ Step 16: Extracting critical CSS...");
const criticalCssResult = await extractCriticalPageCssFiles(
cssPlugin,
clientOutputDir,
);
if (criticalCssResult) {
buildLogger.debug(
` Critical: ${criticalCssResult.criticalPath}, Deferred: ${criticalCssResult.deferredPath}`,
);
}
// Step 17: Generate universal CSS (base/theme styles)
buildLogger.debug("🎨 Step 17: Generating universal CSS...");
const universalCssPath = await generateCriticalUniversalCssFile(
cssPlugin,
clientOutputDir,
);
if (universalCssPath) {
buildLogger.debug(` Universal: ${universalCssPath}`);
}
}
// Step 18: Optimize fonts for self-hosting (output to client/)
buildLogger.debug("🔤 Step 18: Optimizing Fonts...");
await optimizeFonts(clientOutputDir, context.config.fonts);
// Step 19: Optimize images (WebP, AVIF, responsive variants)
buildLogger.debug("🖼️ Step 19: Optimizing Images...");
await optimizeImagesStep(projectRoot, clientOutputDir, context.config);
// Step 20: Copy translation JSON files to server directory
buildLogger.debug("🌐 Step 20: Copying translation files...");
await copyTranslationFiles(
srcDir,
runtime.path.resolve(distDir, SERVER_DIR),
projectRoot,
);
// Step 21: Copy import maps to dist/server for dev mode dynamic imports
// In dev mode, Deno dynamically imports files from dist/server.
// These files have bare imports (e.g., "lucide-react") that need resolution.
// Copying the project's config files ensures import maps apply.
const serverOutputDir = runtime.path.resolve(distDir, SERVER_DIR);
await copyConfigFilesWithImportMaps(projectRoot, serverOutputDir);
// Step 22: Bundle server components
// This resolves all bare specifiers (react, lucide-react, etc.) via the bundler
// instead of manual rewriting to npm: specifiers (which breaks Node.js)
// NOTE: Always use rolldown for server bundling because deno-bundler doesn't support
// custom resolver plugins needed for npm: specifiers
buildLogger.info(
`📦 Step 22: Server bundling check - components: ${serverComponentPaths.length}`,
);
if (serverComponentPaths.length > 0) {
buildLogger.info(
`📦 Step 22: Bundling ${serverComponentPaths.length} server component(s) with rolldown...`,
);
// Get server component files from dist/server (already copied with rewrites)
// Files are in dist/server/src/... (preserving source directory structure)
const serverEntrypoints: string[] = [];
for (const srcPath of serverComponentPaths) {
// Get path relative to project root (e.g., "src/app/page.tsx")
const relativePath = runtime.path.relative(projectRoot, srcPath);
// Join with serverOutputDir (e.g., "dist/server/src/app/page.tsx")
const distPath = runtime.path.join(serverOutputDir, relativePath);
const exists = await runtime.fs.exists(distPath);
if (exists) {
serverEntrypoints.push(distPath);
}
}
buildLogger.info(
` Found ${serverEntrypoints.length} server entrypoints to bundle`,
);
if (serverEntrypoints.length > 0) {
// Server externals from config (default: @eserstack/laroux, @eserstack/laroux-server)
// These resolve from the app's node_modules at current.
// Everything else (react, lucide-react, etc.) gets bundled.
// See ADR: 0002-bundler-external-import-specifiers.md
const serverExternals = context.config.serverExternals;
// Create server externals plugin with prefix matching for subpath imports
// e.g., "@eserstack/laroux-server" matches "@eserstack/laroux-server/action-registry"
// This ensures singleton modules like action-registry are shared between
// bundled server components and the laroux-server current.
const serverExternalsPlugin = createServerExternalsPlugin({
externals: serverExternals,
});
// Use the configured bundler backend for server bundling
// - deno-bundler: outputs browser-targeted ESM, but works in Deno runtime
// - rolldown: supports platform: "node" for Node.js-compatible output
const serverBundleResult = await bundleServerComponents(
{
entrypoints: serverEntrypoints,
outputDir: serverOutputDir,
projectRoot: serverOutputDir,
sourcemap: false,
minify: false,
externals: serverExternals,
plugins: [serverExternalsPlugin],
},
context.bundlerBackend ?? "deno-bundler",
);
buildLogger.info(
` ✅ Bundled ${serverBundleResult.fileCount} server file(s)`,
);
}
}
// Step 22b: Generate server actions manifest
// Use analyzeServerActions which scans ALL files for "use server" directive
// This finds action files regardless of naming (not just actions.ts)
buildLogger.debug("📋 Step 22b: Generating server actions manifest...");
const serverActionMatches = await analyzeServerActions(srcDir, {
projectRoot,
});
// Convert source paths to bundled output paths:
// Preserves full path structure (src/app/actions.ts → src/app/actions.js)
const actionFiles = serverActionMatches.map((match) =>
replaceJsExtension(match.relativePath, ".js")
);
// Write actions manifest
const actionsManifestPath = runtime.path.resolve(
serverOutputDir,
"actions-manifest.json",
);
await runtime.fs.writeTextFile(
actionsManifestPath,
JSON.stringify({ actions: actionFiles }, null, 2),
);
buildLogger.debug(
`✓ Generated actions manifest: ${actionFiles.length} action file(s)`,
);
// Step 23: Copy public assets to dist root (server expects them there)
await copyPublicAssets(projectRoot, distDir);
const duration = performance.now() - startTime;
buildLogger.info(`📊 Build Summary:`);
buildLogger.info(` Client components: ${clientComponents.length}`);
buildLogger.info(` Build time: ${duration.toFixed(0)}ms`);
return {
success: true,
clientBundle,
moduleMap,
clientComponents: clientComponents.length,
duration,
timestamp: buildTimestamp,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
const errorStack = error instanceof Error ? error.stack : null;
buildLogger.error("❌ Build failed:");
buildLogger.error(` Error: ${errorMessage}`);
if (errorStack !== null) {
buildLogger.error(` Stack trace:\n${errorStack}`);
}
return {
success: false,
clientBundle: "",
moduleMap: {},
clientComponents: 0,
duration: performance.now() - startTime,
timestamp: Date.now(),
};
}
}
/**
* Ensure build is ready - builds if needed, skips if up-to-date
* @param context - Build context with configuration and paths
* @returns Build result
*/
export async function ensureBuildIsReady(
context: BuildContext,
): Promise<BuildResult> {
if (await needsRebuild(context)) {
buildLogger.info("🔄 Build needed, running build...");
return await build(context);
} else {
buildLogger.info("✅ Build is up-to-date, skipping...");
return await loadExistingBuild(context);
}
}
/**
* Check if rebuild is needed based on file timestamps
* @param context - Build context
* @returns True if rebuild is needed
*/
async function needsRebuild(context: BuildContext): Promise<boolean> {
const { distDir, chunkManifestFile, srcDir, clientEntry, projectRoot } =
context;
// Check if dist directory exists
if (!(await runtime.fs.exists(distDir))) {
return true;
}
// Check if chunk manifest file exists
if (!(await runtime.fs.exists(chunkManifestFile))) {
return true;
}
// Get build timestamp from chunk manifest
const manifestContent = await runtime.fs.readTextFile(chunkManifestFile);
const manifest: ChunkManifest = JSON.parse(manifestContent);
const buildTimestamp = manifest.timestamp;
// Check if any source file is newer than build
const sourceFiles = [];
for await (const entry of runtime.fs.readDir(srcDir)) {
if (entry.isFile && JS_FILE_PATTERN.test(entry.name)) {
sourceFiles.push(runtime.path.resolve(srcDir, entry.name));
}
}
// Check client entry
sourceFiles.push(clientEntry);
for (const file of sourceFiles) {
try {
const fileStat = await runtime.fs.stat(file);
if (fileStat.mtime && fileStat.mtime.getTime() > buildTimestamp) {
buildLogger.debug(
` Changed: ${runtime.path.relative(projectRoot, file)}`,
);
return true;
}
} catch {
// File might not exist, skip
}
}
return false;
}
/**
* Load existing build result
*/
/**
* Load existing build result from manifest files
* @param context - Build context
* @returns Build result from previous successful build
*/
async function loadExistingBuild(context: BuildContext): Promise<BuildResult> {
const { chunkManifestFile, distDir } = context;
const manifestContent = await runtime.fs.readTextFile(chunkManifestFile);
const manifest: ChunkManifest = JSON.parse(manifestContent);
const moduleMapContent = await runtime.fs.readTextFile(
runtime.path.resolve(distDir, MODULE_MAP_FILENAME),
);
const moduleMap: ModuleMap = JSON.parse(moduleMapContent);
return {
success: true,
clientBundle: runtime.path.resolve(distDir, "client.js"),
moduleMap,
clientComponents: Object.keys(moduleMap).length,
duration: 0,
timestamp: manifest.timestamp,
};
}
/**
* Watch mode for Hot Module Replacement (HMR)
* Monitors source files and rebuilds on changes
* @param context - Build context
* @param onChange - Callback invoked when rebuild completes
* @returns File system watcher
*/
export function watch(
context: BuildContext,
onChange: (result: BuildResult) => void,
): FsWatcher {
const { srcDir, distDir, projectRoot } = context;
buildLogger.debug(
"👁️ Watch mode enabled, monitoring for changes...",
);
// Get or create the global build cache for incremental builds
const cache = getGlobalBuildCache();
const contextWithCache = { ...context, cache };
// Compute relative dist directory path for filtering
const relativeDistDir = runtime.path.relative(projectRoot, distDir);
// Build list of paths to watch
const watchPaths: string[] = [srcDir];
const watcher = runtime.fs.watch(watchPaths);
let building = false;
let pendingRebuild = false;
const changedFiles: Set<string> = new Set();
// Debounce timer to batch rapid file changes
let debounceTimer: number | null = null;
const DEBOUNCE_MS = 50;
/**
* Trigger a build with proper handling of pending rebuilds
* Uses do-while loop to ensure pending rebuilds are processed immediately
*/
async function triggerBuild() {
if (building) {
pendingRebuild = true;
return;
}
building = true;
// Keep rebuilding while there are pending changes
do {
pendingRebuild = false;
try {
// Check what types of files changed
const changedFilesList = Array.from(changedFiles);
// Invalidate cache entries for changed files
cache.invalidateFiles(
changedFilesList.map((f) => runtime.path.resolve(projectRoot, f)),
);
const hasCssChanges = changedFilesList.some((file) =>
file.endsWith(".css")
);
const hasJsChanges = changedFilesList.some((file) =>
file.match(/\.(tsx?|jsx?)$/)
);
// Determine build mode:
// - cssOnly: only CSS changed, use fast path (no JS rebuild)
// - skipCss: only JS changed, skip CSS processing
// - full build: both changed
const cssOnly = hasCssChanges && !hasJsChanges;
const skipCss = !hasCssChanges && hasJsChanges;
// Convert changed files to absolute paths for incremental virtual source
const changedFilesAbsolute = new Set(
changedFilesList.map((f) => runtime.path.resolve(projectRoot, f)),
);
const result = await build(contextWithCache, {
skipCss,
cssOnly,
changedFiles: changedFilesAbsolute,
});
// Attach changed files to the build result
result.changedFiles = Array.from(changedFiles);
buildLogger.debug(
`✅ Rebuild complete (${result.duration.toFixed(0)}ms)`,
);
onChange(result);
// Clear changed files after successful build
changedFiles.clear();
} catch (error) {
buildLogger.error("❌ Rebuild failed:", { error });
// Keep changed files on error so they can be retried
}
} while (pendingRebuild);
building = false;
}
(async () => {
for await (const event of watcher) {
if (
event.kind === "modify" || event.kind === "create" ||
event.kind === "remove"
) {
const eventPath = event.paths[0];
if (!eventPath) continue;
const changedFile = runtime.path.relative(projectRoot, eventPath);
// Skip non-source files (tsx/jsx/css)
if (!changedFile.match(/\.(tsx?|jsx?|css)$/)) continue;
// Skip dist directory (build outputs shouldn't trigger rebuilds)
// Convert to POSIX format for cross-platform path comparison
const normalizedChangedFile = toPosix(changedFile);
const normalizedDistDir = toPosix(relativeDistDir);
if (normalizedChangedFile.startsWith(`${normalizedDistDir}/`)) {
continue;
}
// Skip temporary files (e.g., .temp.css from CSS module processing)
if (changedFile.includes(".temp.")) continue;
buildLogger.debug(`🔄 File changed: ${changedFile}`);
// Collect changed files for this rebuild
changedFiles.add(changedFile);
// Debounce: clear existing timer and set a new one
// This batches rapid file changes (e.g., editor save operations)
if (debounceTimer !== null) {
clearTimeout(debounceTimer);
}
debounceTimer = setTimeout(() => {
debounceTimer = null;
triggerBuild();
}, DEBOUNCE_MS) as unknown as number;
}
}
})();
return watcher;
}
/**
* Bundle client code using Deno's native bundler with code splitting
* @param context - Build context
* @param clientComponents - Array of client components to bundle
* @param buildId - Unique build identifier
* @param timestamp - Build timestamp
* @returns Path to the generated entry point
*/
async function bundleClient(
context: BuildContext,
clientComponents: ClientComponent[],
buildId: string,
timestamp: number,