@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,16 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Image Optimizer Port
4
+ *
5
+ * Turns the images under public/images into responsive variants in modern
6
+ * formats, with optional blur placeholders, and describes them in an image
7
+ * manifest. The sharp adapter (adapters/sharp) implements it.
8
+ */
9
+ /**
10
+ * Image optimizer for builds that pass none: it optimizes nothing, so the
11
+ * images are served as they are in public/images.
12
+ */
13
+ export const noopImageOptimizer = {
14
+ name: "noop",
15
+ optimize: () => Promise.resolve(null),
16
+ };
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Import Map Loader
3
+ *
4
+ * Reads the dependencies a project declares in its package.json. A declared
5
+ * package is a bare specifier that resolves from the project's node_modules
6
+ * (ADR 0004), so the map records which packages the project declares and
7
+ * never rewrites a specifier.
8
+ *
9
+ * @module
10
+ */
11
+ /**
12
+ * Extract protocol from a specifier if present.
13
+ * Works for both standard URLs (http, https, file) and other prefixes such
14
+ * as node: or workspace:.
15
+ *
16
+ * @param specifier - The specifier to extract protocol from
17
+ * @returns The protocol with trailing colon (e.g., "node:") or null
18
+ */
19
+ export declare function getProtocol(specifier: string): string | null;
20
+ /**
21
+ * Check if specifier is a relative or absolute path.
22
+ */
23
+ export declare function isPathSpecifier(specifier: string): boolean;
24
+ /**
25
+ * Check if a specifier is a bare package import.
26
+ * Bare imports have no protocol prefix and are not relative/absolute paths.
27
+ *
28
+ * @param specifier - The specifier to check
29
+ * @returns true if the specifier is a bare import
30
+ */
31
+ export declare function isBareSpecifier(specifier: string): boolean;
32
+ /**
33
+ * A package the project declares in package.json.
34
+ */
35
+ export type ImportMapEntry = {
36
+ /** The bare specifier (e.g., "react", "lucide-react") */
37
+ specifier: string;
38
+ /** What the specifier resolves to: the same bare specifier (ADR 0004) */
39
+ target: string;
40
+ /** The version range package.json declares (e.g., "^19.0.0") */
41
+ version: string;
42
+ };
43
+ /**
44
+ * The packages a project declares in package.json.
45
+ */
46
+ export type ImportMap = {
47
+ /** All declared packages, keyed by specifier */
48
+ entries: Map<string, ImportMapEntry>;
49
+ /** The declared registry packages, which may stay external */
50
+ externals: string[];
51
+ /** Project root directory */
52
+ projectRoot: string;
53
+ /** Whether package.json was found */
54
+ hasPackageJson: boolean;
55
+ };
56
+ /**
57
+ * Load the packages a project declares in package.json: dependencies,
58
+ * devDependencies and peerDependencies, where dependencies win.
59
+ *
60
+ * @param projectRoot - Project root directory
61
+ * @returns The project's import map
62
+ */
63
+ export declare function loadImportMap(projectRoot: string): Promise<ImportMap>;
64
+ /**
65
+ * Resolve a bare specifier against the declared packages. A declared package
66
+ * resolves to the specifier itself, which the bundler and the runtime then
67
+ * find in node_modules.
68
+ *
69
+ * @param specifier - Bare specifier to resolve (e.g., "react", "react-dom/client")
70
+ * @param importMap - Import map to use for resolution
71
+ * @returns The specifier, or null when no declared package provides it
72
+ */
73
+ export declare function resolveSpecifier(specifier: string, importMap: ImportMap): string | null;
74
+ /**
75
+ * Get all external package specifiers for bundler configuration.
76
+ * These packages should be marked as external in the bundler.
77
+ *
78
+ * @param importMap - Import map to extract externals from
79
+ * @returns Array of external specifier patterns
80
+ */
81
+ export declare function getExternals(importMap: ImportMap): string[];
82
+ /**
83
+ * Check if a specifier should be treated as external: a node: built-in or a
84
+ * declared registry package.
85
+ *
86
+ * @param specifier - Specifier to check
87
+ * @param importMap - Import map to check against
88
+ * @returns True if the specifier should be external
89
+ */
90
+ export declare function isExternal(specifier: string, importMap: ImportMap): boolean;
@@ -0,0 +1,187 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Import Map Loader
4
+ *
5
+ * Reads the dependencies a project declares in its package.json. A declared
6
+ * package is a bare specifier that resolves from the project's node_modules
7
+ * (ADR 0004), so the map records which packages the project declares and
8
+ * never rewrites a specifier.
9
+ *
10
+ * @module
11
+ */
12
+ import { runtime } from "@eserstack/standards/cross-runtime";
13
+ import * as logging from "@eserstack/logging";
14
+ const importMapLogger = logging.logger.getLogger([
15
+ "laroux-bundler",
16
+ "import-map",
17
+ ]);
18
+ /** Protocol prefixes of specifiers that are never bundled. */
19
+ const EXTERNAL_PROTOCOLS = new Set(["node:"]);
20
+ /** Protocol prefixes of specifiers that are not bare package imports. */
21
+ const KNOWN_PROTOCOLS = new Set(["node:", "http:", "https:", "file:", "data:"]);
22
+ /** Version protocols of dependencies that are not registry packages. */
23
+ const LOCAL_VERSION_PROTOCOLS = new Set(["workspace:", "file:", "link:"]);
24
+ /**
25
+ * Maximum length of a protocol prefix (e.g., "workspace:" is 10 chars).
26
+ * Used to avoid false positives when checking for protocols in paths.
27
+ */
28
+ const MAX_PROTOCOL_LENGTH = 12;
29
+ /**
30
+ * Extract protocol from a specifier if present.
31
+ * Works for both standard URLs (http, https, file) and other prefixes such
32
+ * as node: or workspace:.
33
+ *
34
+ * @param specifier - The specifier to extract protocol from
35
+ * @returns The protocol with trailing colon (e.g., "node:") or null
36
+ */
37
+ export function getProtocol(specifier) {
38
+ // For standard URLs, use URL API
39
+ if (URL.canParse(specifier)) {
40
+ return new URL(specifier).protocol;
41
+ }
42
+ // For other prefixes, extract manually
43
+ const colonIndex = specifier.indexOf(":");
44
+ if (colonIndex > 0 && colonIndex < MAX_PROTOCOL_LENGTH) {
45
+ return specifier.slice(0, colonIndex + 1);
46
+ }
47
+ return null;
48
+ }
49
+ /**
50
+ * Check if specifier is a relative or absolute path.
51
+ */
52
+ export function isPathSpecifier(specifier) {
53
+ return (specifier.startsWith("./") ||
54
+ specifier.startsWith("../") ||
55
+ specifier.startsWith("/"));
56
+ }
57
+ /**
58
+ * Check if a specifier is a bare package import.
59
+ * Bare imports have no protocol prefix and are not relative/absolute paths.
60
+ *
61
+ * @param specifier - The specifier to check
62
+ * @returns true if the specifier is a bare import
63
+ */
64
+ export function isBareSpecifier(specifier) {
65
+ const protocol = getProtocol(specifier);
66
+ if (protocol !== null && KNOWN_PROTOCOLS.has(protocol)) {
67
+ return false;
68
+ }
69
+ return !isPathSpecifier(specifier);
70
+ }
71
+ /**
72
+ * Turn package.json dependencies into entries, skipping workspace, file and
73
+ * link references, which are not registry packages.
74
+ */
75
+ function parsePackageJsonDependencies(deps) {
76
+ const entries = [];
77
+ for (const [name, version] of Object.entries(deps)) {
78
+ const protocol = getProtocol(version);
79
+ if (protocol !== null && LOCAL_VERSION_PROTOCOLS.has(protocol)) {
80
+ continue;
81
+ }
82
+ entries.push({ specifier: name, target: name, version });
83
+ }
84
+ return entries;
85
+ }
86
+ /**
87
+ * Load package.json from a directory.
88
+ */
89
+ async function loadPackageJson(projectRoot) {
90
+ const packageJsonPath = runtime.path.join(projectRoot, "package.json");
91
+ try {
92
+ const exists = await runtime.fs.exists(packageJsonPath);
93
+ if (!exists) {
94
+ return null;
95
+ }
96
+ const content = await runtime.fs.readTextFile(packageJsonPath);
97
+ return JSON.parse(content);
98
+ }
99
+ catch (error) {
100
+ importMapLogger
101
+ .with({ error })
102
+ .debug(`load ${packageJsonPath}; resolving without its dependencies`);
103
+ return null;
104
+ }
105
+ }
106
+ /**
107
+ * Load the packages a project declares in package.json: dependencies,
108
+ * devDependencies and peerDependencies, where dependencies win.
109
+ *
110
+ * @param projectRoot - Project root directory
111
+ * @returns The project's import map
112
+ */
113
+ export async function loadImportMap(projectRoot) {
114
+ const entries = new Map();
115
+ const packageJson = await loadPackageJson(projectRoot);
116
+ if (packageJson !== null) {
117
+ const allDeps = {
118
+ ...packageJson.peerDependencies,
119
+ ...packageJson.devDependencies,
120
+ ...packageJson.dependencies, // dependencies override dev/peer
121
+ };
122
+ for (const entry of parsePackageJsonDependencies(allDeps)) {
123
+ entries.set(entry.specifier, entry);
124
+ }
125
+ }
126
+ const externals = [...entries.keys()];
127
+ importMapLogger.debug(`Loaded import map: ${entries.size} entries, ${externals.length} externals`);
128
+ return {
129
+ entries,
130
+ externals,
131
+ projectRoot,
132
+ hasPackageJson: packageJson !== null,
133
+ };
134
+ }
135
+ /**
136
+ * Find the declared package a specifier belongs to: the exact name, or the
137
+ * package of a subpath import such as "react-dom/client".
138
+ */
139
+ function findEntry(specifier, importMap) {
140
+ const entry = importMap.entries.get(specifier);
141
+ if (entry !== undefined) {
142
+ return entry;
143
+ }
144
+ for (const [key, value] of importMap.entries) {
145
+ if (specifier.startsWith(`${key}/`)) {
146
+ return value;
147
+ }
148
+ }
149
+ return null;
150
+ }
151
+ /**
152
+ * Resolve a bare specifier against the declared packages. A declared package
153
+ * resolves to the specifier itself, which the bundler and the runtime then
154
+ * find in node_modules.
155
+ *
156
+ * @param specifier - Bare specifier to resolve (e.g., "react", "react-dom/client")
157
+ * @param importMap - Import map to use for resolution
158
+ * @returns The specifier, or null when no declared package provides it
159
+ */
160
+ export function resolveSpecifier(specifier, importMap) {
161
+ return findEntry(specifier, importMap) === null ? null : specifier;
162
+ }
163
+ /**
164
+ * Get all external package specifiers for bundler configuration.
165
+ * These packages should be marked as external in the bundler.
166
+ *
167
+ * @param importMap - Import map to extract externals from
168
+ * @returns Array of external specifier patterns
169
+ */
170
+ export function getExternals(importMap) {
171
+ return importMap.externals;
172
+ }
173
+ /**
174
+ * Check if a specifier should be treated as external: a node: built-in or a
175
+ * declared registry package.
176
+ *
177
+ * @param specifier - Specifier to check
178
+ * @param importMap - Import map to check against
179
+ * @returns True if the specifier should be external
180
+ */
181
+ export function isExternal(specifier, importMap) {
182
+ const protocol = getProtocol(specifier);
183
+ if (protocol !== null && EXTERNAL_PROTOCOLS.has(protocol)) {
184
+ return true;
185
+ }
186
+ return findEntry(specifier, importMap) !== null;
187
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Domain Layer
3
+ *
4
+ * Contains pure business logic and port interfaces/types.
5
+ * Adapters implement the interfaces defined here.
6
+ */
7
+ export type { ClientComponent, FrameworkPlugin, ModuleMap, ModuleMapEntry, TransformResult, } from "./framework-plugin.ts";
8
+ export { noopPlugin } from "./framework-plugin.ts";
9
+ export type { CriticalCssResult, CssPlugin, CssPluginContext, CssPluginOptions, UniversalCssResult, } from "./css-plugin.ts";
10
+ export type { CssProcessor, CssProcessorOptions } from "./css-processor.ts";
11
+ export { noopCssProcessor } from "./css-processor.ts";
12
+ export type { FontOptimizationOptions, FontOptimizer, OptimizedFonts, } from "./font-optimizer.ts";
13
+ export { noopFontOptimizer } from "./font-optimizer.ts";
14
+ export type { ImageManifest, ImageOptimizationRequest, ImageOptimizer, ImageVariant, OptimizedImage, } from "./image-optimizer.ts";
15
+ export { noopImageOptimizer } from "./image-optimizer.ts";
16
+ export type { BundleData, BundleOptions, BundleOutput, Bundler, BundleResult, ServerBundleOptions, ServerBundleResult, } from "./bundler.ts";
17
+ export { analyzeBundleResult, bundle, bundleServerComponents, logBundleStats, } from "./bundler.ts";
18
+ export type { BaseChunkInfo, BaseChunkManifest, ChunkManifest, ComponentChunkInfo, FileInfo, } from "./chunk-manifest.ts";
19
+ export { ChunkManifestError, generateChunkManifest, loadChunkManifest, logManifest, saveChunkManifest, } from "./chunk-manifest.ts";
20
+ export type { ClientComponentCache, ClientComponentCacheEntry, CSSModuleCacheEntry, RouteCacheEntry, } from "./build-cache.ts";
21
+ export { BuildCache } from "./build-cache.ts";
22
+ export type { RouteScanCache, ScannedProxy, ScannedRoute, ScanResult, ScanRoutesOptions, } from "./route-scanner.ts";
23
+ export { getComponentName, getLayoutName, scanRoutes, } from "./route-scanner.ts";
24
+ export { generateApiRouteFile, generateProxyFile, generateRouteFile, } from "./route-generator.ts";
25
+ export type { VirtualSourceOptions, VirtualSourceResult, } from "./virtual-source.ts";
26
+ export { createVirtualSource, translateClientComponents, translateFromVirtualPath, translateToVirtualPath, VIRTUAL_SRC_DIR, } from "./virtual-source.ts";
27
+ export type { BuildIsolationReport, FileViolation } from "./build-validator.ts";
28
+ export { BuildIsolationError, cleanSrcArtifacts, createIsolatedWriter, isWithinOutputDir, validateBuildIsolation, } from "./build-validator.ts";
29
+ export type { ImportMap, ImportMapEntry } from "./import-map.ts";
30
+ export { getExternals, isExternal, loadImportMap, resolveSpecifier, } from "./import-map.ts";
31
+ export type { ServerActionTransformResult } from "./server-action-transform.ts";
32
+ export { transformServerActionFile, transformServerActions, } from "./server-action-transform.ts";
@@ -0,0 +1,20 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Domain Layer
4
+ *
5
+ * Contains pure business logic and port interfaces/types.
6
+ * Adapters implement the interfaces defined here.
7
+ */
8
+ export { noopPlugin } from "./framework-plugin.js";
9
+ export { noopCssProcessor } from "./css-processor.js";
10
+ export { noopFontOptimizer } from "./font-optimizer.js";
11
+ export { noopImageOptimizer } from "./image-optimizer.js";
12
+ export { analyzeBundleResult, bundle, bundleServerComponents, logBundleStats, } from "./bundler.js";
13
+ export { ChunkManifestError, generateChunkManifest, loadChunkManifest, logManifest, saveChunkManifest, } from "./chunk-manifest.js";
14
+ export { BuildCache } from "./build-cache.js";
15
+ export { getComponentName, getLayoutName, scanRoutes, } from "./route-scanner.js";
16
+ export { generateApiRouteFile, generateProxyFile, generateRouteFile, } from "./route-generator.js";
17
+ export { createVirtualSource, translateClientComponents, translateFromVirtualPath, translateToVirtualPath, VIRTUAL_SRC_DIR, } from "./virtual-source.js";
18
+ export { BuildIsolationError, cleanSrcArtifacts, createIsolatedWriter, isWithinOutputDir, validateBuildIsolation, } from "./build-validator.js";
19
+ export { getExternals, isExternal, loadImportMap, resolveSpecifier, } from "./import-map.js";
20
+ export { transformServerActionFile, transformServerActions, } from "./server-action-transform.js";
@@ -0,0 +1,34 @@
1
+ import type { ScanResult } from "./route-scanner.ts";
2
+ /**
3
+ * Options for generating route files
4
+ */
5
+ export type GenerateRouteOptions = {
6
+ /** Result from scanning routes */
7
+ scanResult: ScanResult;
8
+ /** Path to output the generated file */
9
+ outputPath: string;
10
+ /** Project root directory for relative path calculation */
11
+ projectRoot: string;
12
+ /** Source directory name relative to project root (e.g., "src") */
13
+ srcDirName: string;
14
+ /**
15
+ * Added to each page and layout import as `?v=<moduleVersion>`, such as
16
+ * the build id. The runtime keeps an imported module under its URL until
17
+ * the process exits, so without a new query a dev server that imports the
18
+ * rebuilt routes file again still gets the pages of the first build.
19
+ * Default: imports carry no query.
20
+ */
21
+ moduleVersion?: string;
22
+ };
23
+ /**
24
+ * Generates the _generated-routes.ts file with route definitions
25
+ */
26
+ export declare function generateRouteFile(options: GenerateRouteOptions): Promise<void>;
27
+ /**
28
+ * Generates the api-routes.ts file with API route definitions
29
+ */
30
+ export declare function generateApiRouteFile(scanResult: ScanResult, outputPath: string, projectRoot: string): Promise<void>;
31
+ /**
32
+ * Generates the proxy-registry.ts file with proxy definitions
33
+ */
34
+ export declare function generateProxyFile(scanResult: ScanResult, outputPath: string, projectRoot: string): Promise<void>;
@@ -0,0 +1,305 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ // Route generator for file-based routing
3
+ // Generates _generated-routes.ts, api-routes.ts and proxy-registry.ts from
4
+ // the scanned route files
5
+ import * as crossRuntime from "@eserstack/standards/cross-runtime";
6
+ import * as logging from "@eserstack/logging";
7
+ import * as patterns from "@eserstack/standards/patterns";
8
+ const generatorLogger = logging.logger.getLogger([
9
+ "laroux-bundler",
10
+ "route-generator",
11
+ ]);
12
+ /**
13
+ * Generates the _generated-routes.ts file with route definitions
14
+ */
15
+ export async function generateRouteFile(options) {
16
+ const { scanResult, outputPath, projectRoot, moduleVersion } = options;
17
+ const importQuery = moduleVersion === undefined
18
+ ? ""
19
+ : `?v=${encodeURIComponent(moduleVersion)}`;
20
+ const { routes } = scanResult;
21
+ generatorLogger.debug(`Generating routes file: ${outputPath}`);
22
+ const imports = [];
23
+ const routeDefinitions = [];
24
+ // Track unique imports to avoid duplicates
25
+ const importedComponents = new Map();
26
+ for (const route of routes) {
27
+ // The component path is relative like "src/app/routes/home/page.tsx"
28
+ // We want to import from the bundled file "./src/app/routes/home/page.js"
29
+ // Both bundlers output to dist/server/src/app/* (preserves src/ structure)
30
+ // Strip source extension before adding .js
31
+ const componentImportPath = `./${patterns.replaceJsExtension(route.componentPath, "")}.js${importQuery}`;
32
+ // One route's sources at a time keeps open file handles bounded; a
33
+ // project can have more routes than the open-file limit.
34
+ // oxlint-disable-next-line no-await-in-loop
35
+ const { componentName, layoutName } = await resolveRouteExportNames(route, projectRoot);
36
+ // Add component import if not already imported
37
+ if (!importedComponents.has(route.componentPath)) {
38
+ imports.push(`import { ${componentName} } from "${componentImportPath}";`);
39
+ importedComponents.set(route.componentPath, componentName);
40
+ }
41
+ // Add layout import if exists
42
+ if (route.layoutPath && layoutName) {
43
+ // Import from bundled files in dist/server/src/app/ (both bundlers preserve src/ structure)
44
+ // Strip source extension before adding .js
45
+ const layoutImportPath = `./${patterns.replaceJsExtension(route.layoutPath, "")}.js${importQuery}`;
46
+ if (!importedComponents.has(route.layoutPath)) {
47
+ imports.push(`import { ${layoutName} } from "${layoutImportPath}";`);
48
+ importedComponents.set(route.layoutPath, layoutName);
49
+ }
50
+ }
51
+ // Generate route definition
52
+ const routeDef = generateRouteDefinition(route, componentName, layoutName);
53
+ routeDefinitions.push(routeDef);
54
+ }
55
+ // Generate the file content
56
+ const content = `// AUTO-GENERATED FILE - DO NOT EDIT
57
+ // Generated by laroux-bundler/route-generator.ts
58
+ // Run build to regenerate
59
+
60
+ import type { RouteDefinition } from "@eserstack/laroux/router";
61
+ ${imports.join("\n")}
62
+
63
+ /**
64
+ * Auto-generated routes from file-based routing
65
+ * Routes are sorted by specificity (static > dynamic > catch-all)
66
+ */
67
+ export const generatedRoutes: RouteDefinition[] = [
68
+ ${routeDefinitions.map((r) => ` ${r}`).join(",\n")},
69
+ ];
70
+ `;
71
+ await crossRuntime.runtime.fs.writeTextFile(outputPath, content);
72
+ generatorLogger.debug(`Generated ${routes.length} route(s)`);
73
+ }
74
+ /**
75
+ * Reads the export names of a route's page and layout from their source files
76
+ */
77
+ async function resolveRouteExportNames(route, projectRoot) {
78
+ // Full path to original source file (for reading export names)
79
+ const componentFullPath = crossRuntime.runtime.path.join(projectRoot, route.componentPath);
80
+ // Get actual export name from source file
81
+ const componentName = await getPageExportName(componentFullPath, generateComponentName(route.componentPath));
82
+ // Get layout name if exists
83
+ if (route.layoutPath === undefined) {
84
+ return { componentName, layoutName: undefined };
85
+ }
86
+ const layoutFullPath = crossRuntime.runtime.path.join(projectRoot, route.layoutPath);
87
+ const layoutName = await getLayoutExportName(layoutFullPath, generateLayoutName(route.layoutPath));
88
+ return { componentName, layoutName };
89
+ }
90
+ /**
91
+ * Generates the api-routes.ts file with API route definitions
92
+ */
93
+ export async function generateApiRouteFile(scanResult, outputPath, projectRoot) {
94
+ const { apiRoutes } = scanResult;
95
+ if (apiRoutes.length === 0) {
96
+ generatorLogger.debug("No API routes found, skipping generation");
97
+ return;
98
+ }
99
+ generatorLogger.debug(`Generating API routes file: ${outputPath}`);
100
+ const routeEntries = [];
101
+ for (const route of apiRoutes) {
102
+ // Calculate import path relative to output directory
103
+ const outputDir = crossRuntime.runtime.path.dirname(outputPath);
104
+ const modulePath = getRelativeImportPath(outputDir, crossRuntime.runtime.path.join(projectRoot, route.componentPath));
105
+ routeEntries.push(` { path: "${route.routePath}", modulePath: "${modulePath}" }`);
106
+ }
107
+ const content = `// AUTO-GENERATED FILE - DO NOT EDIT
108
+ // Generated by laroux-bundler/route-generator.ts
109
+
110
+ export type ApiRouteDefinition = {
111
+ path: string;
112
+ modulePath: string;
113
+ };
114
+
115
+ /**
116
+ * Auto-generated API routes from file-based routing
117
+ */
118
+ export const apiRoutes: ApiRouteDefinition[] = [
119
+ ${routeEntries.join(",\n")},
120
+ ];
121
+ `;
122
+ await crossRuntime.runtime.fs.writeTextFile(outputPath, content);
123
+ generatorLogger.debug(`Generated ${apiRoutes.length} API route(s)`);
124
+ }
125
+ /**
126
+ * Generates the proxy-registry.ts file with proxy definitions
127
+ */
128
+ export async function generateProxyFile(scanResult, outputPath, projectRoot) {
129
+ const { proxies } = scanResult;
130
+ if (proxies.length === 0) {
131
+ generatorLogger.debug("No proxies found, skipping generation");
132
+ return;
133
+ }
134
+ generatorLogger.debug(`Generating proxy registry file: ${outputPath}`);
135
+ const proxyEntries = [];
136
+ for (const proxy of proxies) {
137
+ // Calculate import path relative to output directory
138
+ const outputDir = crossRuntime.runtime.path.dirname(outputPath);
139
+ const modulePath = getRelativeImportPath(outputDir, crossRuntime.runtime.path.join(projectRoot, proxy.modulePath));
140
+ proxyEntries.push(` { pathPrefix: "${proxy.pathPrefix}", modulePath: "${modulePath}" }`);
141
+ }
142
+ const content = `// AUTO-GENERATED FILE - DO NOT EDIT
143
+ // Generated by laroux-bundler/route-generator.ts
144
+
145
+ export type ProxyDefinition = {
146
+ pathPrefix: string;
147
+ modulePath: string;
148
+ };
149
+
150
+ /**
151
+ * Auto-generated proxy definitions from file-based routing
152
+ * Sorted by path prefix length (most specific first)
153
+ */
154
+ export const proxyRegistry: ProxyDefinition[] = [
155
+ ${proxyEntries.join(",\n")},
156
+ ];
157
+ `;
158
+ await crossRuntime.runtime.fs.writeTextFile(outputPath, content);
159
+ generatorLogger.debug(`Generated ${proxies.length} proxy definition(s)`);
160
+ }
161
+ /**
162
+ * Extract all export names from a React component file
163
+ * Finds all named exports and default export
164
+ */
165
+ async function extractExportNames(filePath) {
166
+ try {
167
+ const content = await crossRuntime.runtime.fs.readTextFile(filePath);
168
+ const exportNames = [];
169
+ // Match all: export function ComponentName() or export async function ComponentName()
170
+ const namedFunctionMatches = content.matchAll(/export\s+(?:async\s+)?function\s+(\w+)/g);
171
+ for (const match of namedFunctionMatches) {
172
+ if (match[1] !== undefined) {
173
+ exportNames.push(match[1]);
174
+ }
175
+ }
176
+ // Match all: export const ComponentName =
177
+ const namedConstMatches = content.matchAll(/export\s+const\s+(\w+)\s*=/g);
178
+ for (const match of namedConstMatches) {
179
+ if (match[1] !== undefined) {
180
+ exportNames.push(match[1]);
181
+ }
182
+ }
183
+ // Check for default export
184
+ if (content.match(/export\s+default\s+/)) {
185
+ exportNames.push("default");
186
+ }
187
+ // Deduplicate and return
188
+ return [...new Set(exportNames)];
189
+ }
190
+ catch {
191
+ return [];
192
+ }
193
+ }
194
+ /**
195
+ * Gets the main page export name from a file
196
+ * Prefers named exports ending with "Page", falls back to first named export
197
+ */
198
+ async function getPageExportName(filePath, fallbackName) {
199
+ const exports = await extractExportNames(filePath);
200
+ if (exports.length === 0) {
201
+ return fallbackName;
202
+ }
203
+ // Prefer export ending with "Page" (non-default)
204
+ const pageExport = exports.find((e) => e !== "default" && e.endsWith("Page"));
205
+ if (pageExport) {
206
+ return pageExport;
207
+ }
208
+ // Otherwise use first non-default export
209
+ const namedExport = exports.find((e) => e !== "default");
210
+ if (namedExport) {
211
+ return namedExport;
212
+ }
213
+ // Fall back to generated name
214
+ return fallbackName;
215
+ }
216
+ /**
217
+ * Gets the main layout export name from a file
218
+ * Prefers named exports ending with "Layout", falls back to first named export
219
+ */
220
+ async function getLayoutExportName(filePath, fallbackName) {
221
+ const exports = await extractExportNames(filePath);
222
+ if (exports.length === 0) {
223
+ return fallbackName;
224
+ }
225
+ // Prefer export ending with "Layout" (non-default)
226
+ const layoutExport = exports.find((e) => e !== "default" && e.endsWith("Layout"));
227
+ if (layoutExport) {
228
+ return layoutExport;
229
+ }
230
+ // Otherwise use first non-default export
231
+ const namedExport = exports.find((e) => e !== "default");
232
+ if (namedExport) {
233
+ return namedExport;
234
+ }
235
+ // Fall back to generated name
236
+ return fallbackName;
237
+ }
238
+ /**
239
+ * Generates a PascalCase component name from file path (fallback)
240
+ */
241
+ function generateComponentName(componentPath) {
242
+ // Get directory name (e.g., "stories", "[slug]", "home")
243
+ const dirName = crossRuntime.runtime.path.basename(crossRuntime.runtime.path.dirname(componentPath));
244
+ // Convert to PascalCase
245
+ const baseName = toPascalCase(cleanDynamicSegment(dirName));
246
+ return `${baseName}Page`;
247
+ }
248
+ /**
249
+ * Generates a PascalCase layout name from file path (fallback)
250
+ */
251
+ function generateLayoutName(layoutPath) {
252
+ const dirName = crossRuntime.runtime.path.basename(crossRuntime.runtime.path.dirname(layoutPath));
253
+ const baseName = toPascalCase(cleanDynamicSegment(dirName));
254
+ return `${baseName}Layout`;
255
+ }
256
+ /**
257
+ * Cleans dynamic segment brackets from a string
258
+ * [slug] -> slug
259
+ * [...slug] -> slug
260
+ */
261
+ function cleanDynamicSegment(str) {
262
+ // Handle catch-all [...slug]
263
+ if (str.startsWith("[...")) {
264
+ return str.slice(4, -1);
265
+ }
266
+ // Handle dynamic [slug]
267
+ if (str.startsWith("[") && str.endsWith("]")) {
268
+ return str.slice(1, -1);
269
+ }
270
+ return str;
271
+ }
272
+ /**
273
+ * Converts a string to PascalCase
274
+ */
275
+ function toPascalCase(str) {
276
+ return str
277
+ .split(/[-_\s]+/)
278
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
279
+ .join("");
280
+ }
281
+ /**
282
+ * Gets relative import path from output directory to target file
283
+ */
284
+ function getRelativeImportPath(fromDir, toFile) {
285
+ // Get relative path and convert to POSIX format for import specifiers
286
+ const relativePath = crossRuntime.toPosix(crossRuntime.runtime.path.relative(fromDir, toFile));
287
+ // Add ./ prefix if needed for relative imports
288
+ if (!relativePath.startsWith(".")) {
289
+ return `./${relativePath}`;
290
+ }
291
+ return relativePath;
292
+ }
293
+ /**
294
+ * Generates a route definition object string
295
+ */
296
+ function generateRouteDefinition(route, componentName, layoutName) {
297
+ const parts = [
298
+ `path: "${route.routePath}"`,
299
+ `component: ${componentName}`,
300
+ ];
301
+ if (layoutName) {
302
+ parts.push(`layout: ${layoutName}`);
303
+ }
304
+ return `{ ${parts.join(", ")} }`;
305
+ }