@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.
- package/LICENSE +13 -0
- package/README.md +431 -2
- package/dist/adapters/fonts/font-optimizer.d.ts +28 -0
- package/dist/adapters/fonts/font-optimizer.js +74 -0
- package/dist/adapters/fonts/index.d.ts +18 -0
- package/dist/adapters/fonts/index.js +78 -0
- package/dist/adapters/fonts/mod.d.ts +6 -0
- package/dist/adapters/fonts/mod.js +7 -0
- package/dist/adapters/lightningcss/css-processor.d.ts +39 -0
- package/dist/adapters/lightningcss/css-processor.js +103 -0
- package/dist/adapters/lightningcss/mod.d.ts +5 -0
- package/dist/adapters/lightningcss/mod.js +6 -0
- package/dist/adapters/mod.d.ts +13 -0
- package/dist/adapters/mod.js +21 -0
- package/dist/adapters/prebuilt-bundler/mod.d.ts +5 -0
- package/dist/adapters/prebuilt-bundler/mod.js +6 -0
- package/dist/adapters/prebuilt-bundler/prebuilt-bundler.d.ts +22 -0
- package/dist/adapters/prebuilt-bundler/prebuilt-bundler.js +60 -0
- package/dist/adapters/react/mod.d.ts +10 -0
- package/dist/adapters/react/mod.js +16 -0
- package/dist/adapters/react/plugin.d.ts +17 -0
- package/dist/adapters/react/plugin.js +62 -0
- package/dist/adapters/react/rsc-analyze.d.ts +29 -0
- package/dist/adapters/react/rsc-analyze.js +116 -0
- package/dist/adapters/react/rsc-client-entry.d.ts +26 -0
- package/dist/adapters/react/rsc-client-entry.js +145 -0
- package/dist/adapters/react/rsc-module-map.d.ts +41 -0
- package/dist/adapters/react/rsc-module-map.js +81 -0
- package/dist/adapters/react/rsc-rewrite-imports.d.ts +38 -0
- package/dist/adapters/react/rsc-rewrite-imports.js +409 -0
- package/dist/adapters/react/rsc-transform.d.ts +26 -0
- package/dist/adapters/react/rsc-transform.js +101 -0
- package/dist/adapters/runtime-bundler/mod.d.ts +6 -0
- package/dist/adapters/runtime-bundler/mod.js +6 -0
- package/dist/adapters/runtime-bundler/runtime-bundler.d.ts +85 -0
- package/dist/adapters/runtime-bundler/runtime-bundler.js +244 -0
- package/dist/adapters/sharp/image-optimizer.d.ts +52 -0
- package/dist/adapters/sharp/image-optimizer.js +261 -0
- package/dist/adapters/sharp/mod.d.ts +6 -0
- package/dist/adapters/sharp/mod.js +6 -0
- package/dist/adapters/tailwindcss/compile.d.ts +22 -0
- package/dist/adapters/tailwindcss/compile.js +29 -0
- package/dist/adapters/tailwindcss/critical-css-config.d.ts +46 -0
- package/dist/adapters/tailwindcss/critical-css-config.js +78 -0
- package/dist/adapters/tailwindcss/critical-page-css.d.ts +61 -0
- package/dist/adapters/tailwindcss/critical-page-css.js +431 -0
- package/dist/adapters/tailwindcss/critical-universal-css.d.ts +68 -0
- package/dist/adapters/tailwindcss/critical-universal-css.js +250 -0
- package/dist/adapters/tailwindcss/mod.d.ts +10 -0
- package/dist/adapters/tailwindcss/mod.js +11 -0
- package/dist/adapters/tailwindcss/plugin.d.ts +16 -0
- package/dist/adapters/tailwindcss/plugin.js +107 -0
- package/dist/adapters/tailwindcss/stylesheet-loader.d.ts +15 -0
- package/dist/adapters/tailwindcss/stylesheet-loader.js +83 -0
- package/dist/config.d.ts +27 -0
- package/dist/config.js +31 -0
- package/dist/css-modules.d.ts +49 -0
- package/dist/css-modules.js +146 -0
- package/dist/domain/build-cache.d.ts +107 -0
- package/dist/domain/build-cache.js +128 -0
- package/dist/domain/build-validator.d.ts +68 -0
- package/dist/domain/build-validator.js +207 -0
- package/dist/domain/bundler.d.ts +136 -0
- package/dist/domain/bundler.js +225 -0
- package/dist/domain/chunk-manifest.d.ts +40 -0
- package/dist/domain/chunk-manifest.js +188 -0
- package/dist/domain/client-action-stub.d.ts +30 -0
- package/dist/domain/client-action-stub.js +167 -0
- package/dist/domain/copy-path.d.ts +15 -0
- package/dist/domain/copy-path.js +29 -0
- package/dist/domain/css-plugin.d.ts +91 -0
- package/dist/domain/css-plugin.js +6 -0
- package/dist/domain/css-processor.d.ts +57 -0
- package/dist/domain/css-processor.js +33 -0
- package/dist/domain/font-optimizer.d.ts +46 -0
- package/dist/domain/font-optimizer.js +17 -0
- package/dist/domain/framework-plugin.d.ts +106 -0
- package/dist/domain/framework-plugin.js +20 -0
- package/dist/domain/image-optimizer.d.ts +74 -0
- package/dist/domain/image-optimizer.js +16 -0
- package/dist/domain/import-map.d.ts +90 -0
- package/dist/domain/import-map.js +187 -0
- package/dist/domain/mod.d.ts +32 -0
- package/dist/domain/mod.js +20 -0
- package/dist/domain/route-generator.d.ts +34 -0
- package/dist/domain/route-generator.js +305 -0
- package/dist/domain/route-scanner.d.ts +72 -0
- package/dist/domain/route-scanner.js +282 -0
- package/dist/domain/server-action-transform.d.ts +28 -0
- package/dist/domain/server-action-transform.js +147 -0
- package/dist/domain/virtual-source.d.ts +63 -0
- package/dist/domain/virtual-source.js +238 -0
- package/dist/import-map-resolver-plugin.d.ts +47 -0
- package/dist/import-map-resolver-plugin.js +109 -0
- package/dist/mod.d.ts +57 -0
- package/dist/mod.js +56 -0
- package/dist/server-externals-plugin.d.ts +29 -0
- package/dist/server-externals-plugin.js +63 -0
- package/dist/system.d.ts +157 -0
- package/dist/system.js +1401 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.js +38 -0
- package/package.json +83 -3
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** A page or API route found under the routes directory. */
|
|
2
|
+
export type ScannedRoute = {
|
|
3
|
+
/** URL pattern, such as "/stories/[slug]" */
|
|
4
|
+
routePath: string;
|
|
5
|
+
/** Module path from the project root, such as "src/app/routes/stories/[slug]/page.tsx" */
|
|
6
|
+
componentPath: string;
|
|
7
|
+
/** The page's own layout or its closest parent's, from the project root */
|
|
8
|
+
layoutPath?: string;
|
|
9
|
+
/** True for a route.ts handler, false for a page */
|
|
10
|
+
isApiRoute: boolean;
|
|
11
|
+
/** Proxy module that applies to the route, from the project root */
|
|
12
|
+
proxyPath?: string;
|
|
13
|
+
};
|
|
14
|
+
/** A proxy.ts module found under the routes directory. */
|
|
15
|
+
export type ScannedProxy = {
|
|
16
|
+
/** URL prefix the proxy applies to, such as "/admin" */
|
|
17
|
+
pathPrefix: string;
|
|
18
|
+
/** Module path from the project root, such as "src/app/routes/admin/proxy.ts" */
|
|
19
|
+
modulePath: string;
|
|
20
|
+
};
|
|
21
|
+
/** The routes, API routes and proxies of one routes directory. */
|
|
22
|
+
export type ScanResult = {
|
|
23
|
+
/** Page routes, most specific first */
|
|
24
|
+
routes: ScannedRoute[];
|
|
25
|
+
/** API routes, most specific first */
|
|
26
|
+
apiRoutes: ScannedRoute[];
|
|
27
|
+
/** Proxies, longest prefix first */
|
|
28
|
+
proxies: ScannedProxy[];
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Keeps scan results between builds, per routes directory. BuildCache
|
|
32
|
+
* implements it; watch mode drops an entry when a file under its routes
|
|
33
|
+
* directory changes.
|
|
34
|
+
*/
|
|
35
|
+
export type RouteScanCache = {
|
|
36
|
+
/**
|
|
37
|
+
* The cached scan of routesDir, or null when there is none or the routes
|
|
38
|
+
* directory changed after it (its mtime is newer than the entry's).
|
|
39
|
+
*/
|
|
40
|
+
getRouteScan(routesDir: string, routesDirMtime: number): ScanResult | null;
|
|
41
|
+
/** Store the scan of routesDir, made when the directory had this mtime. */
|
|
42
|
+
setRouteScan(routesDir: string, result: ScanResult, routesDirMtime: number): void;
|
|
43
|
+
};
|
|
44
|
+
/** Options of {@link scanRoutes}. */
|
|
45
|
+
export type ScanRoutesOptions = {
|
|
46
|
+
/**
|
|
47
|
+
* Cache to reuse a scan of the same routes directory from an earlier
|
|
48
|
+
* build. Without one, every call scans the directory.
|
|
49
|
+
*/
|
|
50
|
+
readonly cache?: RouteScanCache;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Scans the routes directory for page, layout, route, and proxy files
|
|
54
|
+
* Test files and anything in or below an `_`-prefixed file or directory are
|
|
55
|
+
* skipped, so `_private/page.tsx` is never routed
|
|
56
|
+
* Uses @eserstack/collector for file walking
|
|
57
|
+
* @param routesDir - The routes directory path (src/app/routes)
|
|
58
|
+
* @param projectRoot - The project root directory
|
|
59
|
+
* @param options - A cache to reuse an earlier scan of the same directory;
|
|
60
|
+
* without one, the directory is scanned every time
|
|
61
|
+
* @returns Scan result containing routes, API routes, and proxies
|
|
62
|
+
*/
|
|
63
|
+
export declare function scanRoutes(routesDir: string, projectRoot: string, options?: ScanRoutesOptions): Promise<ScanResult>;
|
|
64
|
+
/**
|
|
65
|
+
* Gets the exported component name from a page.tsx file
|
|
66
|
+
* Assumes the component is exported as a named export or default export
|
|
67
|
+
*/
|
|
68
|
+
export declare function getComponentName(componentPath: string): string;
|
|
69
|
+
/**
|
|
70
|
+
* Gets the layout component name from a layout.tsx file
|
|
71
|
+
*/
|
|
72
|
+
export declare function getLayoutName(layoutPath: string): string;
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
// Route scanner for file-based routing
|
|
3
|
+
// Scans src/app/routes for page.tsx, layout.tsx, route.ts, and proxy.ts files
|
|
4
|
+
import * as crossRuntime from "@eserstack/standards/cross-runtime";
|
|
5
|
+
import * as patterns from "@eserstack/standards/patterns";
|
|
6
|
+
import * as collector from "@eserstack/collector";
|
|
7
|
+
import * as logging from "@eserstack/logging";
|
|
8
|
+
const scannerLogger = logging.logger.getLogger([
|
|
9
|
+
"laroux-bundler",
|
|
10
|
+
"route-scanner",
|
|
11
|
+
]);
|
|
12
|
+
// Skips test files and every path with a segment that starts with "_": a
|
|
13
|
+
// file such as _helpers.tsx and everything below a directory such as
|
|
14
|
+
// _private/ stay private to the app. The pattern is matched against the path
|
|
15
|
+
// relative to the routes directory, so a "_" above it does not count.
|
|
16
|
+
const IGNORE_PATTERN = /(?:^|[/\\])_|\.test\.[cm]?[jt]sx?$/;
|
|
17
|
+
// Route file base names (without extension)
|
|
18
|
+
const ROUTE_FILE_BASES = ["page", "layout", "route", "proxy"];
|
|
19
|
+
// Generate all valid route file names with supported extensions
|
|
20
|
+
const ROUTE_FILES = new Set(ROUTE_FILE_BASES.flatMap((base) => patterns.JS_FILE_EXTENSIONS.map((ext) => `${base}.${ext}`)));
|
|
21
|
+
/**
|
|
22
|
+
* Get the base name of a route file (without extension)
|
|
23
|
+
*/
|
|
24
|
+
function getRouteFileBase(fileName) {
|
|
25
|
+
for (const base of ROUTE_FILE_BASES) {
|
|
26
|
+
if (fileName.startsWith(`${base}.`) &&
|
|
27
|
+
patterns.JS_FILE_PATTERN.test(fileName)) {
|
|
28
|
+
return base;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Read the modification time of the routes directory, or null when it does
|
|
35
|
+
* not exist or the file system reports none.
|
|
36
|
+
*/
|
|
37
|
+
async function readRoutesDirMtime(routesDir) {
|
|
38
|
+
try {
|
|
39
|
+
const routesDirStat = await crossRuntime.runtime.fs.stat(routesDir);
|
|
40
|
+
return routesDirStat.mtime?.getTime() ?? null;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error instanceof crossRuntime.NotFoundError) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Scans the routes directory for page, layout, route, and proxy files
|
|
51
|
+
* Test files and anything in or below an `_`-prefixed file or directory are
|
|
52
|
+
* skipped, so `_private/page.tsx` is never routed
|
|
53
|
+
* Uses @eserstack/collector for file walking
|
|
54
|
+
* @param routesDir - The routes directory path (src/app/routes)
|
|
55
|
+
* @param projectRoot - The project root directory
|
|
56
|
+
* @param options - A cache to reuse an earlier scan of the same directory;
|
|
57
|
+
* without one, the directory is scanned every time
|
|
58
|
+
* @returns Scan result containing routes, API routes, and proxies
|
|
59
|
+
*/
|
|
60
|
+
export async function scanRoutes(routesDir, projectRoot, options = {}) {
|
|
61
|
+
const { cache } = options;
|
|
62
|
+
const routesDirMtime = cache !== undefined ? await readRoutesDirMtime(routesDir) : null;
|
|
63
|
+
if (cache !== undefined && routesDirMtime !== null) {
|
|
64
|
+
const cached = cache.getRouteScan(routesDir, routesDirMtime);
|
|
65
|
+
if (cached !== null) {
|
|
66
|
+
scannerLogger.debug(`Using cached route scan of ${routesDir}`);
|
|
67
|
+
return cached;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
scannerLogger.debug(`Scanning routes in: ${routesDir}`);
|
|
71
|
+
// Group files by directory
|
|
72
|
+
const dirEntries = new Map();
|
|
73
|
+
// Walk all files using @eserstack/collector
|
|
74
|
+
for await (const relativePath of collector.walkFiles(routesDir, undefined, IGNORE_PATTERN)) {
|
|
75
|
+
const fileName = crossRuntime.runtime.path.basename(relativePath);
|
|
76
|
+
// Only process route files
|
|
77
|
+
if (!ROUTE_FILES.has(fileName)) {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const dirPath = crossRuntime.runtime.path.dirname(relativePath);
|
|
81
|
+
const dirEntry = dirEntries.get(dirPath) ?? {};
|
|
82
|
+
const fullPath = crossRuntime.runtime.path.join(routesDir, relativePath);
|
|
83
|
+
const base = getRouteFileBase(fileName);
|
|
84
|
+
if (base === "page") {
|
|
85
|
+
dirEntry.pagePath = fullPath;
|
|
86
|
+
}
|
|
87
|
+
else if (base === "layout") {
|
|
88
|
+
dirEntry.layoutPath = fullPath;
|
|
89
|
+
}
|
|
90
|
+
else if (base === "route") {
|
|
91
|
+
dirEntry.routePath = fullPath;
|
|
92
|
+
}
|
|
93
|
+
else if (base === "proxy") {
|
|
94
|
+
dirEntry.proxyPath = fullPath;
|
|
95
|
+
}
|
|
96
|
+
dirEntries.set(dirPath, dirEntry);
|
|
97
|
+
}
|
|
98
|
+
// Build routes from grouped entries
|
|
99
|
+
const routes = [];
|
|
100
|
+
const apiRoutes = [];
|
|
101
|
+
const proxies = [];
|
|
102
|
+
// Helper to find closest parent layout for a directory path
|
|
103
|
+
const findParentLayout = (dirPath) => {
|
|
104
|
+
let currentDir = dirPath;
|
|
105
|
+
while (currentDir && currentDir !== ".") {
|
|
106
|
+
const parentDir = crossRuntime.runtime.path.dirname(currentDir);
|
|
107
|
+
if (parentDir === currentDir)
|
|
108
|
+
break; // Reached root
|
|
109
|
+
const parentEntry = dirEntries.get(parentDir);
|
|
110
|
+
if (parentEntry?.layoutPath) {
|
|
111
|
+
return crossRuntime.runtime.path.relative(projectRoot, parentEntry.layoutPath);
|
|
112
|
+
}
|
|
113
|
+
currentDir = parentDir;
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
};
|
|
117
|
+
for (const [dirPath, entries] of dirEntries) {
|
|
118
|
+
const routePath = directoryToRoutePath(dirPath);
|
|
119
|
+
// Add page route
|
|
120
|
+
if (entries.pagePath) {
|
|
121
|
+
const componentPath = crossRuntime.runtime.path.relative(projectRoot, entries.pagePath);
|
|
122
|
+
// Use own layout if present, otherwise inherit from closest parent
|
|
123
|
+
const layoutPath = entries.layoutPath
|
|
124
|
+
? crossRuntime.runtime.path.relative(projectRoot, entries.layoutPath)
|
|
125
|
+
: findParentLayout(dirPath);
|
|
126
|
+
routes.push({
|
|
127
|
+
routePath,
|
|
128
|
+
componentPath,
|
|
129
|
+
layoutPath,
|
|
130
|
+
isApiRoute: false,
|
|
131
|
+
});
|
|
132
|
+
scannerLogger.debug(`Found page: ${routePath} -> ${componentPath}${layoutPath ? ` (layout: ${layoutPath})` : ""}`);
|
|
133
|
+
}
|
|
134
|
+
// Add API route
|
|
135
|
+
if (entries.routePath) {
|
|
136
|
+
const componentPath = crossRuntime.runtime.path.relative(projectRoot, entries.routePath);
|
|
137
|
+
apiRoutes.push({
|
|
138
|
+
routePath,
|
|
139
|
+
componentPath,
|
|
140
|
+
isApiRoute: true,
|
|
141
|
+
});
|
|
142
|
+
scannerLogger.debug(`Found API route: ${routePath} -> ${componentPath}`);
|
|
143
|
+
}
|
|
144
|
+
// Add proxy
|
|
145
|
+
if (entries.proxyPath) {
|
|
146
|
+
const modulePath = crossRuntime.runtime.path.relative(projectRoot, entries.proxyPath);
|
|
147
|
+
// directoryToRoutePath maps the root directory to "/", so the prefix is
|
|
148
|
+
// never empty
|
|
149
|
+
proxies.push({
|
|
150
|
+
pathPrefix: routePath,
|
|
151
|
+
modulePath,
|
|
152
|
+
});
|
|
153
|
+
scannerLogger.debug(`Found proxy: ${routePath} -> ${modulePath}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// Sort routes by specificity (static > dynamic > catch-all)
|
|
157
|
+
const sortedRoutes = sortRoutesBySpecificity(routes);
|
|
158
|
+
const sortedApiRoutes = sortRoutesBySpecificity(apiRoutes);
|
|
159
|
+
const sortedProxies = sortProxiesBySpecificity(proxies);
|
|
160
|
+
scannerLogger.debug(`Found ${sortedRoutes.length} page routes, ${sortedApiRoutes.length} API routes, ${sortedProxies.length} proxies`);
|
|
161
|
+
const result = {
|
|
162
|
+
routes: sortedRoutes,
|
|
163
|
+
apiRoutes: sortedApiRoutes,
|
|
164
|
+
proxies: sortedProxies,
|
|
165
|
+
};
|
|
166
|
+
// A directory without an mtime cannot be checked for changes, so its scan
|
|
167
|
+
// is not cached.
|
|
168
|
+
if (cache !== undefined && routesDirMtime !== null) {
|
|
169
|
+
cache.setRouteScan(routesDir, result, routesDirMtime);
|
|
170
|
+
}
|
|
171
|
+
return result;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Converts a directory path relative to routes dir into a URL route path
|
|
175
|
+
* Examples:
|
|
176
|
+
* "home" -> "/"
|
|
177
|
+
* "stories" -> "/stories"
|
|
178
|
+
* "stories/[slug]" -> "/stories/[slug]"
|
|
179
|
+
* "[slug]/[pageslug]" -> "/[slug]/[pageslug]"
|
|
180
|
+
*/
|
|
181
|
+
function directoryToRoutePath(relativePath) {
|
|
182
|
+
// Handle root directory (empty string)
|
|
183
|
+
if (relativePath === "" || relativePath === ".") {
|
|
184
|
+
return "/";
|
|
185
|
+
}
|
|
186
|
+
// Special case: "home" directory maps to root "/"
|
|
187
|
+
if (relativePath === "home") {
|
|
188
|
+
return "/";
|
|
189
|
+
}
|
|
190
|
+
// Convert to POSIX format and add leading slash
|
|
191
|
+
return `/${crossRuntime.toPosix(relativePath)}`;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Sort routes by specificity:
|
|
195
|
+
* 1. Static routes first (no dynamic segments)
|
|
196
|
+
* 2. Dynamic routes ([param])
|
|
197
|
+
* 3. Catch-all routes ([...slug]) last
|
|
198
|
+
* Within each category, longer paths come first
|
|
199
|
+
*/
|
|
200
|
+
function sortRoutesBySpecificity(routes) {
|
|
201
|
+
return routes.sort((a, b) => {
|
|
202
|
+
const scoreA = getRouteSpecificityScore(a.routePath);
|
|
203
|
+
const scoreB = getRouteSpecificityScore(b.routePath);
|
|
204
|
+
// Higher score = more specific = comes first
|
|
205
|
+
if (scoreA !== scoreB) {
|
|
206
|
+
return scoreB - scoreA;
|
|
207
|
+
}
|
|
208
|
+
// Same specificity, longer path comes first
|
|
209
|
+
return b.routePath.length - a.routePath.length;
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Calculate specificity score for a route
|
|
214
|
+
* Higher score = more specific
|
|
215
|
+
*/
|
|
216
|
+
function getRouteSpecificityScore(routePath) {
|
|
217
|
+
let score = 0;
|
|
218
|
+
// Base score from number of segments (more segments = more specific)
|
|
219
|
+
const segments = routePath.split("/").filter(Boolean);
|
|
220
|
+
score += segments.length * 10;
|
|
221
|
+
// Deduct points for dynamic segments
|
|
222
|
+
for (const segment of segments) {
|
|
223
|
+
if (segment.startsWith("[...")) {
|
|
224
|
+
// Catch-all: large deduction
|
|
225
|
+
score -= 100;
|
|
226
|
+
}
|
|
227
|
+
else if (segment.startsWith("[")) {
|
|
228
|
+
// Dynamic: small deduction
|
|
229
|
+
score -= 5;
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
// Static: bonus
|
|
233
|
+
score += 3;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return score;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Sort proxies by specificity (longer/more specific prefixes first)
|
|
240
|
+
*/
|
|
241
|
+
function sortProxiesBySpecificity(proxies) {
|
|
242
|
+
return proxies.sort((a, b) => {
|
|
243
|
+
// Longer prefix = more specific = comes first
|
|
244
|
+
return b.pathPrefix.length - a.pathPrefix.length;
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Gets the exported component name from a page.tsx file
|
|
249
|
+
* Assumes the component is exported as a named export or default export
|
|
250
|
+
*/
|
|
251
|
+
export function getComponentName(componentPath) {
|
|
252
|
+
// Get parent directory name
|
|
253
|
+
const dirName = crossRuntime.runtime.path.basename(crossRuntime.runtime.path.dirname(componentPath));
|
|
254
|
+
// Generate a PascalCase component name from directory
|
|
255
|
+
const name = dirName === "home" ? "HomePage" : `${toPascalCase(dirName)}Page`;
|
|
256
|
+
return name;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Gets the layout component name from a layout.tsx file
|
|
260
|
+
*/
|
|
261
|
+
export function getLayoutName(layoutPath) {
|
|
262
|
+
const dirName = crossRuntime.runtime.path.basename(crossRuntime.runtime.path.dirname(layoutPath));
|
|
263
|
+
return `${toPascalCase(dirName)}Layout`;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Converts a string to PascalCase
|
|
267
|
+
*/
|
|
268
|
+
function toPascalCase(str) {
|
|
269
|
+
// Handle dynamic segments like [slug]
|
|
270
|
+
if (str.startsWith("[") && str.endsWith("]")) {
|
|
271
|
+
const inner = str.slice(1, -1);
|
|
272
|
+
// Handle catch-all [...slug]
|
|
273
|
+
if (inner.startsWith("...")) {
|
|
274
|
+
return toPascalCase(inner.slice(3));
|
|
275
|
+
}
|
|
276
|
+
return toPascalCase(inner);
|
|
277
|
+
}
|
|
278
|
+
return str
|
|
279
|
+
.split(/[-_\s]+/)
|
|
280
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
|
281
|
+
.join("");
|
|
282
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result of a server action file transformation.
|
|
3
|
+
*/
|
|
4
|
+
export interface ServerActionTransformResult {
|
|
5
|
+
/** Original file path */
|
|
6
|
+
filePath: string;
|
|
7
|
+
/** Relative path from project root */
|
|
8
|
+
relativePath: string;
|
|
9
|
+
/** List of transformed action names */
|
|
10
|
+
transformedActions: string[];
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Transform a single server action file by adding React server reference markers.
|
|
14
|
+
*
|
|
15
|
+
* @param filePath - Path to the file to transform
|
|
16
|
+
* @param relativePath - Relative path for action ID generation
|
|
17
|
+
* @returns List of transformed action names, or null if file doesn't need transformation
|
|
18
|
+
*/
|
|
19
|
+
export declare function transformServerActionFile(filePath: string, relativePath: string): Promise<string[] | null>;
|
|
20
|
+
/**
|
|
21
|
+
* Transform all server action files in a directory.
|
|
22
|
+
*
|
|
23
|
+
* Scans for files with "use server" directive and adds React server reference markers.
|
|
24
|
+
*
|
|
25
|
+
* @param serverOutputDir - Directory containing server files (e.g., dist/server)
|
|
26
|
+
* @returns Array of transform results
|
|
27
|
+
*/
|
|
28
|
+
export declare function transformServerActions(serverOutputDir: string): Promise<ServerActionTransformResult[]>;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Server Action Transform
|
|
4
|
+
*
|
|
5
|
+
* Transforms files with "use server" directive to mark exported functions
|
|
6
|
+
* with React's native server reference symbols.
|
|
7
|
+
*
|
|
8
|
+
* This module injects:
|
|
9
|
+
* 1. Server reference symbol markers ($$typeof, $$id, $$bound)
|
|
10
|
+
*
|
|
11
|
+
* React recognizes these markers and treats the functions as server actions,
|
|
12
|
+
* enabling native <form action={fn}> and useActionState(fn, state) support.
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
17
|
+
import * as logging from "@eserstack/logging";
|
|
18
|
+
import * as directiveAnalysis from "@eserstack/codebase/directive-analysis";
|
|
19
|
+
const transformLogger = logging.logger.getLogger([
|
|
20
|
+
"laroux-bundler",
|
|
21
|
+
"server-action-transform",
|
|
22
|
+
]);
|
|
23
|
+
/**
|
|
24
|
+
* Generate a unique action ID from file path and export name.
|
|
25
|
+
*
|
|
26
|
+
* Action ID format: `path/to/file#exportName`
|
|
27
|
+
* Example: `src/app/actions#addComment`
|
|
28
|
+
*
|
|
29
|
+
* This ensures unique IDs even when multiple files export functions with the same name.
|
|
30
|
+
*/
|
|
31
|
+
function generateActionId(relativePath, exportName) {
|
|
32
|
+
// Strip file extension for cleaner IDs
|
|
33
|
+
const pathWithoutExt = relativePath.replace(/\.[cm]?[jt]sx?$/, "");
|
|
34
|
+
return `${pathWithoutExt}#${exportName}`;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Generate code to mark a function with React's server reference symbols.
|
|
38
|
+
*
|
|
39
|
+
* This adds $$typeof, $$id, and $$bound properties that React uses to
|
|
40
|
+
* identify and serialize server action references.
|
|
41
|
+
*/
|
|
42
|
+
function generateServerReferenceMarker(relativePath, exportName) {
|
|
43
|
+
const actionId = generateActionId(relativePath, exportName);
|
|
44
|
+
// Use Object.defineProperties to add non-enumerable React symbols
|
|
45
|
+
return `Object.defineProperties(${exportName}, {
|
|
46
|
+
$$typeof: { value: Symbol.for("react.server.reference"), enumerable: false },
|
|
47
|
+
$$id: { value: "${actionId}", enumerable: false },
|
|
48
|
+
$$bound: { value: null, enumerable: false, writable: true }
|
|
49
|
+
});`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Transform a single server action file by adding React server reference markers.
|
|
53
|
+
*
|
|
54
|
+
* @param filePath - Path to the file to transform
|
|
55
|
+
* @param relativePath - Relative path for action ID generation
|
|
56
|
+
* @returns List of transformed action names, or null if file doesn't need transformation
|
|
57
|
+
*/
|
|
58
|
+
export async function transformServerActionFile(filePath, relativePath) {
|
|
59
|
+
// Read file content
|
|
60
|
+
let content;
|
|
61
|
+
try {
|
|
62
|
+
content = await runtime.fs.readTextFile(filePath);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
transformLogger
|
|
66
|
+
.with({ error })
|
|
67
|
+
.warn(`read ${filePath}; skipping its server action transform`);
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
// Check if file has "use server" directive at the top (file-level)
|
|
71
|
+
// We only transform file-level "use server" - function-level needs different handling
|
|
72
|
+
if (!directiveAnalysis.hasDirective(content, "use server")) {
|
|
73
|
+
transformLogger.debug(`Skipping ${filePath} - no file-level "use server"`);
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
// Extract exports
|
|
77
|
+
const exports = directiveAnalysis.extractExports(content);
|
|
78
|
+
if (exports.length === 0) {
|
|
79
|
+
transformLogger.debug(`Skipping ${filePath} - no exports found`);
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
// Filter out "default" export - handle it separately if needed
|
|
83
|
+
const namedExports = exports.filter((e) => e !== "default");
|
|
84
|
+
if (namedExports.length === 0) {
|
|
85
|
+
transformLogger.debug(`Skipping ${filePath} - only default export`);
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
transformLogger.debug(`Transforming ${filePath} with ${namedExports.length} export(s)`);
|
|
89
|
+
// Build the server reference markers
|
|
90
|
+
const markers = namedExports
|
|
91
|
+
.map((exportName) => generateServerReferenceMarker(relativePath, exportName))
|
|
92
|
+
.join("\n");
|
|
93
|
+
// Append markers at the end of the file
|
|
94
|
+
const lines = content.split("\n");
|
|
95
|
+
lines.push("");
|
|
96
|
+
lines.push("// Auto-generated React server reference markers");
|
|
97
|
+
lines.push(markers);
|
|
98
|
+
// Write transformed content
|
|
99
|
+
const transformedContent = lines.join("\n");
|
|
100
|
+
await runtime.fs.writeTextFile(filePath, transformedContent);
|
|
101
|
+
transformLogger.debug(`Transformed ${filePath}: marked ${namedExports.length} action(s) with server reference symbols`);
|
|
102
|
+
return namedExports;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Transform all server action files in a directory.
|
|
106
|
+
*
|
|
107
|
+
* Scans for files with "use server" directive and adds React server reference markers.
|
|
108
|
+
*
|
|
109
|
+
* @param serverOutputDir - Directory containing server files (e.g., dist/server)
|
|
110
|
+
* @returns Array of transform results
|
|
111
|
+
*/
|
|
112
|
+
export async function transformServerActions(serverOutputDir) {
|
|
113
|
+
transformLogger.debug(`Scanning for server actions in: ${serverOutputDir}`);
|
|
114
|
+
// Check if directory exists
|
|
115
|
+
const exists = await runtime.fs.exists(serverOutputDir);
|
|
116
|
+
if (!exists) {
|
|
117
|
+
transformLogger.debug(`Directory does not exist: ${serverOutputDir}`);
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
// Find all server action files
|
|
121
|
+
// relativePath will be like "src/app/actions.ts" (full path preserved)
|
|
122
|
+
const actionMatches = await directiveAnalysis.analyzeServerActions(serverOutputDir, {
|
|
123
|
+
projectRoot: serverOutputDir,
|
|
124
|
+
});
|
|
125
|
+
if (actionMatches.length === 0) {
|
|
126
|
+
transformLogger.debug("No server action files found");
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
transformLogger.info(`Found ${actionMatches.length} server action file(s) to transform`);
|
|
130
|
+
const results = [];
|
|
131
|
+
for (const match of actionMatches) {
|
|
132
|
+
// Use relativePath directly for action IDs (e.g., "src/app/actions#addComment").
|
|
133
|
+
// One file at a time keeps open file handles bounded; a project can have
|
|
134
|
+
// more action files than the open-file limit.
|
|
135
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
136
|
+
const transformedActions = await transformServerActionFile(match.filePath, match.relativePath);
|
|
137
|
+
if (transformedActions !== null && transformedActions.length > 0) {
|
|
138
|
+
results.push({
|
|
139
|
+
filePath: match.filePath,
|
|
140
|
+
relativePath: match.relativePath,
|
|
141
|
+
transformedActions,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
transformLogger.info(`Transformed ${results.length} server action file(s)`);
|
|
146
|
+
return results;
|
|
147
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Virtual Source Directory Handler
|
|
3
|
+
*
|
|
4
|
+
* Creates a temporary copy of source files for bundling.
|
|
5
|
+
* This allows CSS module imports to be rewritten without modifying original source.
|
|
6
|
+
*
|
|
7
|
+
* The virtual source is created in dist/_bundle_src/ and cleaned up after bundling.
|
|
8
|
+
*/
|
|
9
|
+
export declare const VIRTUAL_SRC_DIR = "_bundle_src";
|
|
10
|
+
export interface VirtualSourceOptions {
|
|
11
|
+
projectRoot: string;
|
|
12
|
+
distDir: string;
|
|
13
|
+
srcDir: string;
|
|
14
|
+
/** Changed files for incremental update (absolute paths) */
|
|
15
|
+
changedFiles?: Set<string>;
|
|
16
|
+
}
|
|
17
|
+
export interface VirtualSourceResult {
|
|
18
|
+
virtualSrcDir: string;
|
|
19
|
+
cleanup: () => Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Create a virtual source directory by copying src/ to dist/_bundle_src/src/
|
|
23
|
+
*
|
|
24
|
+
* This creates an isolated copy where CSS imports can be rewritten
|
|
25
|
+
* without modifying the original source files.
|
|
26
|
+
*
|
|
27
|
+
* The virtual source maintains the same directory structure as the original project:
|
|
28
|
+
* - dist/_bundle_src/src/app/... (mirrors src/app/...)
|
|
29
|
+
*
|
|
30
|
+
* This allows functions that expect projectRoot/src/ to work correctly.
|
|
31
|
+
*
|
|
32
|
+
* @param options - Virtual source options
|
|
33
|
+
* @returns Virtual source result with cleanup function (virtualSrcDir is the virtual "project root")
|
|
34
|
+
*/
|
|
35
|
+
export declare function createVirtualSource(options: VirtualSourceOptions): Promise<VirtualSourceResult>;
|
|
36
|
+
/**
|
|
37
|
+
* Translate a path from original source to virtual source
|
|
38
|
+
*
|
|
39
|
+
* @param originalPath - Path in original src/ (e.g., /project/src/app/page.tsx)
|
|
40
|
+
* @param srcDir - Original src directory (e.g., /project/src)
|
|
41
|
+
* @param virtualSrcDir - Virtual "project root" (e.g., /project/dist/_bundle_src)
|
|
42
|
+
* @param srcDirName - Name of src directory relative to project (e.g., "src")
|
|
43
|
+
* @returns Path in virtual source (e.g., /project/dist/_bundle_src/src/app/page.tsx)
|
|
44
|
+
*/
|
|
45
|
+
export declare function translateToVirtualPath(originalPath: string, srcDir: string, virtualSrcDir: string, srcDirName?: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* Translate a path from virtual source back to original source
|
|
48
|
+
*
|
|
49
|
+
* @param virtualPath - Path in virtual source (e.g., /project/dist/_bundle_src/src/app/page.tsx)
|
|
50
|
+
* @param srcDir - Original src directory (e.g., /project/src)
|
|
51
|
+
* @param virtualSrcDir - Virtual "project root" (e.g., /project/dist/_bundle_src)
|
|
52
|
+
* @param srcDirName - Name of src directory relative to project (e.g., "src")
|
|
53
|
+
* @returns Path in original src/ (e.g., /project/src/app/page.tsx)
|
|
54
|
+
*/
|
|
55
|
+
export declare function translateFromVirtualPath(virtualPath: string, srcDir: string, virtualSrcDir: string, srcDirName?: string): string;
|
|
56
|
+
/**
|
|
57
|
+
* Translate client component paths to use virtual source
|
|
58
|
+
* Also updates relativePath to match the virtual source structure
|
|
59
|
+
*/
|
|
60
|
+
export declare function translateClientComponents<T extends {
|
|
61
|
+
filePath: string;
|
|
62
|
+
relativePath: string;
|
|
63
|
+
}>(components: T[], srcDir: string, virtualSrcDir: string): T[];
|