@bromscandium/vite-plugin 1.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.
@@ -0,0 +1,205 @@
1
+ /**
2
+ * File system scanner for discovering page routes.
3
+ * @module
4
+ */
5
+ import * as fs from 'fs';
6
+ import * as path from 'path';
7
+ const VALID_EXTENSIONS = ['.tsx', '.jsx', '.ts', '.js'];
8
+ const IGNORED_FILES = ['_app', '_document', '_error', '404', '500'];
9
+ const IGNORED_PREFIXES = ['_', '.'];
10
+ const layoutsMap = new Map();
11
+ /**
12
+ * Scans a pages directory and returns all discovered routes.
13
+ * Supports Next.js-style file-based routing conventions including:
14
+ * - `page.tsx` files for page components
15
+ * - `layout.tsx` files for layout wrappers
16
+ * - `[param]` for dynamic route segments
17
+ * - `[...slug]` for catch-all routes
18
+ * - `(group)` folders for route grouping without URL segments
19
+ *
20
+ * @param pagesDir - The directory to scan for pages
21
+ * @returns An array of scanned route information, sorted by priority
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const routes = scanPages('./src/pages');
26
+ * // Returns routes sorted: static > dynamic > catch-all
27
+ * ```
28
+ */
29
+ export function scanPages(pagesDir) {
30
+ if (!fs.existsSync(pagesDir)) {
31
+ return [];
32
+ }
33
+ layoutsMap.clear();
34
+ scanForLayouts(pagesDir, '');
35
+ const routes = [];
36
+ scanDirectory(pagesDir, '', '', routes);
37
+ for (const route of routes) {
38
+ const layout = findLayoutForRoute(route.fsPath);
39
+ if (layout) {
40
+ route.layoutPath = layout;
41
+ }
42
+ }
43
+ return routes.sort((a, b) => {
44
+ if (a.isCatchAll !== b.isCatchAll) {
45
+ return a.isCatchAll ? 1 : -1;
46
+ }
47
+ if (a.isDynamic !== b.isDynamic) {
48
+ return a.isDynamic ? 1 : -1;
49
+ }
50
+ const aSegments = a.routePath.split('/').filter(Boolean).length;
51
+ const bSegments = b.routePath.split('/').filter(Boolean).length;
52
+ if (aSegments !== bSegments) {
53
+ return aSegments - bSegments;
54
+ }
55
+ return a.routePath.localeCompare(b.routePath);
56
+ });
57
+ }
58
+ function scanForLayouts(dir, fsRelativePath) {
59
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
60
+ for (const entry of entries) {
61
+ const name = entry.name;
62
+ if (IGNORED_PREFIXES.some(prefix => name.startsWith(prefix))) {
63
+ continue;
64
+ }
65
+ const fullPath = path.join(dir, name);
66
+ if (entry.isDirectory()) {
67
+ const newFsPath = fsRelativePath ? `${fsRelativePath}/${name}` : name;
68
+ scanForLayouts(fullPath, newFsPath);
69
+ }
70
+ else if (entry.isFile()) {
71
+ const ext = path.extname(name);
72
+ if (!VALID_EXTENSIONS.includes(ext))
73
+ continue;
74
+ const baseName = path.basename(name, ext);
75
+ if (baseName === 'layout' || baseName === '_layout') {
76
+ const fsPath = '/' + fsRelativePath.replace(/\\/g, '/');
77
+ layoutsMap.set(fsPath.replace(/\/+/g, '/') || '/', fullPath.replace(/\\/g, '/'));
78
+ }
79
+ }
80
+ }
81
+ }
82
+ function findLayoutForRoute(fsPath) {
83
+ let current = fsPath;
84
+ while (current) {
85
+ const layout = layoutsMap.get(current);
86
+ if (layout)
87
+ return layout;
88
+ const lastSlash = current.lastIndexOf('/');
89
+ if (lastSlash <= 0)
90
+ break;
91
+ current = current.substring(0, lastSlash);
92
+ }
93
+ return layoutsMap.get('/');
94
+ }
95
+ function isRouteGroup(name) {
96
+ return name.startsWith('(') && name.endsWith(')');
97
+ }
98
+ function scanDirectory(dir, routeRelativePath, fsRelativePath, routes) {
99
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
100
+ for (const entry of entries) {
101
+ const name = entry.name;
102
+ if (IGNORED_PREFIXES.some(prefix => name.startsWith(prefix))) {
103
+ continue;
104
+ }
105
+ const fullPath = path.join(dir, name);
106
+ if (entry.isDirectory()) {
107
+ const routeSegment = isRouteGroup(name) ? '' : name;
108
+ const newRoutePath = routeSegment
109
+ ? (routeRelativePath ? `${routeRelativePath}/${routeSegment}` : routeSegment)
110
+ : routeRelativePath;
111
+ const newFsPath = fsRelativePath ? `${fsRelativePath}/${name}` : name;
112
+ scanDirectory(fullPath, newRoutePath, newFsPath, routes);
113
+ }
114
+ else if (entry.isFile()) {
115
+ const ext = path.extname(name);
116
+ if (!VALID_EXTENSIONS.includes(ext)) {
117
+ continue;
118
+ }
119
+ const baseName = path.basename(name, ext);
120
+ if (IGNORED_FILES.includes(baseName)) {
121
+ continue;
122
+ }
123
+ if (baseName === '_layout' || baseName === 'layout') {
124
+ continue;
125
+ }
126
+ const route = parseRoute(fullPath, routeRelativePath, fsRelativePath, baseName);
127
+ if (route) {
128
+ routes.push(route);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ function parseRoute(filePath, routeRelativePath, fsRelativePath, baseName) {
134
+ const isPage = baseName === 'page';
135
+ const isLayout = baseName === '_layout' || baseName === 'layout';
136
+ let routePath = '/' + routeRelativePath.replace(/\\/g, '/');
137
+ if (!isPage) {
138
+ routePath = routePath === '/'
139
+ ? `/${baseName}`
140
+ : `${routePath}/${baseName}`;
141
+ }
142
+ const fsPath = '/' + fsRelativePath.replace(/\\/g, '/');
143
+ const params = [];
144
+ let isDynamic = false;
145
+ let isCatchAll = false;
146
+ routePath = routePath.replace(/\[\.\.\.(\w+)]/g, (_, paramName) => {
147
+ params.push(paramName);
148
+ isDynamic = true;
149
+ isCatchAll = true;
150
+ return `:${paramName}*`;
151
+ });
152
+ routePath = routePath.replace(/\[(\w+)]/g, (_, paramName) => {
153
+ params.push(paramName);
154
+ isDynamic = true;
155
+ return `:${paramName}`;
156
+ });
157
+ routePath = routePath.replace(/\/+/g, '/');
158
+ if (routePath.length > 1 && routePath.endsWith('/')) {
159
+ routePath = routePath.slice(0, -1);
160
+ }
161
+ const segments = routePath.split('/').filter(Boolean);
162
+ return {
163
+ filePath: filePath.replace(/\\/g, '/'),
164
+ routePath,
165
+ isDynamic,
166
+ params,
167
+ isPage,
168
+ isLayout,
169
+ isCatchAll,
170
+ segments,
171
+ fsPath: fsPath.replace(/\/+/g, '/') || '/',
172
+ };
173
+ }
174
+ /**
175
+ * Watches a pages directory for changes and invokes a callback when files change.
176
+ *
177
+ * @param pagesDir - The directory to watch
178
+ * @param onChange - Callback invoked when a page file changes
179
+ * @returns A function to stop watching
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * const stop = watchPages('./src/pages', () => {
184
+ * console.log('Pages changed, regenerating routes...');
185
+ * });
186
+ *
187
+ * // Later: stop watching
188
+ * stop();
189
+ * ```
190
+ */
191
+ export function watchPages(pagesDir, onChange) {
192
+ if (!fs.existsSync(pagesDir)) {
193
+ fs.mkdirSync(pagesDir, { recursive: true });
194
+ }
195
+ const watcher = fs.watch(pagesDir, { recursive: true }, (_eventType, filename) => {
196
+ if (!filename)
197
+ return;
198
+ const ext = path.extname(filename);
199
+ if (VALID_EXTENSIONS.includes(ext)) {
200
+ onChange();
201
+ }
202
+ });
203
+ return () => watcher.close();
204
+ }
205
+ //# sourceMappingURL=scanner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner.js","sourceRoot":"","sources":["../src/scanner.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AA4B7B,MAAM,gBAAgB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AACxD,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AACpE,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAEpC,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE7C;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,SAAS,CAAC,QAAgB;IACxC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC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}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@bromscandium/vite-plugin",
3
+ "version": "1.0.0",
4
+ "description": "Vite plugin for BromiumJS file-based routing",
5
+ "author": "bromscandium",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/bromscandium/bromiumjs.git",
10
+ "directory": "packages/vite-plugin"
11
+ },
12
+ "homepage": "https://github.com/bromscandium/bromiumjs#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/bromscandium/bromiumjs/issues"
15
+ },
16
+ "keywords": ["bromium", "bromiumjs", "vite", "vite-plugin", "file-based-routing"],
17
+ "type": "module",
18
+ "main": "./dist/index.js",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "import": "./dist/index.js",
24
+ "types": "./dist/index.d.ts"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "src"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsc",
33
+ "dev": "tsc --watch"
34
+ },
35
+ "peerDependencies": {
36
+ "vite": "^5.0.0 || ^6.0.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^25.0.9",
40
+ "typescript": "^5.9.3",
41
+ "vite": "^7.3.1"
42
+ }
43
+ }
package/src/codegen.ts ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Route code generation utilities.
3
+ * @module
4
+ */
5
+
6
+ import {ScannedRoute} from './scanner.js';
7
+ import * as path from 'path';
8
+
9
+ /**
10
+ * Options for route code generation.
11
+ */
12
+ export interface CodegenOptions {
13
+ /** The pages directory path */
14
+ pagesDir: string;
15
+ /** The output file path for generated routes */
16
+ outputPath: string;
17
+ /** Optional base path for routes */
18
+ base?: string;
19
+ }
20
+
21
+ /**
22
+ * Generates TypeScript code for route configuration from scanned routes.
23
+ * The output exports a `routes` array compatible with the Bromium router.
24
+ *
25
+ * @param routes - Array of scanned route information
26
+ * @param options - Code generation options
27
+ * @returns Generated TypeScript source code
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const routes = scanPages('./src/pages');
32
+ * const code = generateRouteConfig(routes, {
33
+ * pagesDir: './src/pages',
34
+ * outputPath: './src/routes.generated.ts',
35
+ * });
36
+ * fs.writeFileSync('./src/routes.generated.ts', code);
37
+ * ```
38
+ */
39
+ export function generateRouteConfig(
40
+ routes: ScannedRoute[],
41
+ options: CodegenOptions
42
+ ): string {
43
+ const { outputPath } = options;
44
+
45
+ const outputDir = path.dirname(outputPath);
46
+
47
+ const routeObjects: string[] = [];
48
+
49
+ routes.forEach((route) => {
50
+ let relativePath = path.relative(outputDir, route.filePath);
51
+ relativePath = relativePath.replace(/\\/g, '/');
52
+
53
+ relativePath = relativePath.replace(/\.(tsx?|jsx?)$/, '');
54
+
55
+ if (!relativePath.startsWith('.') && !relativePath.startsWith('/')) {
56
+ relativePath = './' + relativePath;
57
+ }
58
+
59
+ let layoutImport = '';
60
+ if (route.layoutPath) {
61
+ let layoutRelativePath = path.relative(outputDir, route.layoutPath);
62
+ layoutRelativePath = layoutRelativePath.replace(/\\/g, '/');
63
+ layoutRelativePath = layoutRelativePath.replace(/\.(tsx?|jsx?)$/, '');
64
+ if (!layoutRelativePath.startsWith('.') && !layoutRelativePath.startsWith('/')) {
65
+ layoutRelativePath = './' + layoutRelativePath;
66
+ }
67
+ layoutImport = `,\n layout: () => import('${layoutRelativePath}')`;
68
+ }
69
+
70
+ const routePath = route.routePath;
71
+
72
+ const routeObj = ` {
73
+ path: '${routePath}',
74
+ component: () => import('${relativePath}')${layoutImport},
75
+ }`;
76
+
77
+ routeObjects.push(routeObj);
78
+ });
79
+
80
+ return `// Auto-generated by @bromscandium/vite-plugin
81
+ // Do not edit manually - changes will be overwritten
82
+
83
+ import type { Route } from '@bromscandium/router';
84
+
85
+ export const routes: Route[] = [
86
+ ${routeObjects.join(',\n')}
87
+ ];
88
+
89
+ export default routes;
90
+ `;
91
+ }
92
+
93
+ /**
94
+ * Generates TypeScript type definitions for routes.
95
+ * Provides type-safe route paths and parameter types.
96
+ *
97
+ * @param routes - Array of scanned route information
98
+ * @returns Generated TypeScript declaration code
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const routes = scanPages('./src/pages');
103
+ * const types = generateRouteTypes(routes);
104
+ * fs.writeFileSync('./src/routes.generated.d.ts', types);
105
+ * ```
106
+ */
107
+ export function generateRouteTypes(routes: ScannedRoute[]): string {
108
+ const routePaths = routes.map(r => ` | '${r.routePath}'`).join('\n');
109
+
110
+ const paramTypes = routes
111
+ .filter(r => r.params.length > 0)
112
+ .map(r => {
113
+ const params = r.params.map(p => ` ${p}: string;`).join('\n');
114
+ return ` '${r.routePath}': {\n${params}\n };`;
115
+ })
116
+ .join('\n');
117
+
118
+ return `// Auto-generated route types
119
+
120
+ export type RoutePath =
121
+ ${routePaths || " | '/'"}
122
+
123
+ export interface RouteParams {
124
+ ${paramTypes || " '/': Record<string, never>;"}
125
+ }
126
+ `;
127
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ // Vite plugin exports
2
+
3
+ import { bromiumPlugin } from './plugin.js';
4
+
5
+ export { bromiumPlugin, type BromiumPluginOptions } from './plugin.js';
6
+ export { scanPages, watchPages, type ScannedRoute } from './scanner.js';
7
+ export { generateRouteConfig, generateRouteTypes, type CodegenOptions } from './codegen.js';
8
+
9
+ export default bromiumPlugin;
package/src/plugin.ts ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Main Vite plugin for BromiumJS file-based routing.
3
+ * @module
4
+ */
5
+
6
+ import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite';
7
+ import * as path from 'path';
8
+ import * as fs from 'fs';
9
+ import { scanPages, watchPages } from './scanner.js';
10
+ import { generateRouteConfig, generateRouteTypes } from './codegen.js';
11
+
12
+ /**
13
+ * Configuration options for the Bromium Vite plugin.
14
+ */
15
+ export interface BromiumPluginOptions {
16
+ /**
17
+ * Directory containing page components.
18
+ * @default 'src/pages'
19
+ */
20
+ pagesDir?: string;
21
+
22
+ /**
23
+ * Output path for generated routes file.
24
+ * @default 'src/routes.generated.ts'
25
+ */
26
+ routesOutput?: string;
27
+
28
+ /**
29
+ * Base path for all routes (e.g., '/app/').
30
+ * @default ''
31
+ */
32
+ base?: string;
33
+
34
+ /**
35
+ * Generate TypeScript type definitions for routes.
36
+ * @default true
37
+ */
38
+ generateTypes?: boolean;
39
+ }
40
+
41
+ /**
42
+ * Creates the Bromium Vite plugin for file-based routing.
43
+ * Automatically scans the pages directory and generates route configuration.
44
+ *
45
+ * @param options - Plugin configuration options
46
+ * @returns A Vite plugin instance
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * // vite.config.ts
51
+ * import { defineConfig } from 'vite';
52
+ * import { bromiumPlugin } from '@bromscandium/vite-plugin';
53
+ *
54
+ * export default defineConfig({
55
+ * plugins: [
56
+ * bromiumPlugin({
57
+ * pagesDir: 'src/pages',
58
+ * base: '/app/',
59
+ * generateTypes: true,
60
+ * }),
61
+ * ],
62
+ * });
63
+ * ```
64
+ */
65
+ export function bromiumPlugin(options: BromiumPluginOptions = {}): Plugin {
66
+ const {
67
+ pagesDir = 'src/pages',
68
+ routesOutput = 'src/routes.generated.ts',
69
+ base = '',
70
+ generateTypes = true,
71
+ } = options;
72
+
73
+ let root: string;
74
+ let fullPagesDir: string;
75
+ let fullRoutesOutput: string;
76
+ let stopWatcher: (() => void) | null = null;
77
+
78
+ async function generateRoutes(): Promise<void> {
79
+ if (!fs.existsSync(fullPagesDir)) {
80
+ fs.mkdirSync(fullPagesDir, { recursive: true });
81
+ }
82
+
83
+ const routes = scanPages(fullPagesDir);
84
+
85
+ const code = generateRouteConfig(routes, {
86
+ pagesDir: fullPagesDir,
87
+ outputPath: fullRoutesOutput,
88
+ base,
89
+ });
90
+
91
+ const outputDir = path.dirname(fullRoutesOutput);
92
+ if (!fs.existsSync(outputDir)) {
93
+ fs.mkdirSync(outputDir, { recursive: true });
94
+ }
95
+
96
+ fs.writeFileSync(fullRoutesOutput, code, 'utf-8');
97
+
98
+ if (generateTypes) {
99
+ const typesPath = fullRoutesOutput.replace(/\.ts$/, '.d.ts');
100
+ const typesCode = generateRouteTypes(routes);
101
+ fs.writeFileSync(typesPath, typesCode, 'utf-8');
102
+ }
103
+
104
+ console.log(`[bromium] Generated routes from ${routes.length} pages`);
105
+ }
106
+
107
+ return {
108
+ name: 'bromium-plugin',
109
+
110
+ configResolved(config: ResolvedConfig) {
111
+ root = config.root;
112
+ fullPagesDir = path.resolve(root, pagesDir);
113
+ fullRoutesOutput = path.resolve(root, routesOutput);
114
+ },
115
+
116
+ async buildStart() {
117
+ await generateRoutes();
118
+ },
119
+
120
+ configureServer(server: ViteDevServer) {
121
+ stopWatcher = watchPages(fullPagesDir, async () => {
122
+ await generateRoutes();
123
+ const module = server.moduleGraph.getModuleById(fullRoutesOutput);
124
+ if (module) {
125
+ server.moduleGraph.invalidateModule(module);
126
+ server.ws.send({
127
+ type: 'full-reload',
128
+ path: '*',
129
+ });
130
+ }
131
+ });
132
+ },
133
+
134
+ buildEnd() {
135
+ if (stopWatcher) {
136
+ stopWatcher();
137
+ stopWatcher = null;
138
+ }
139
+ },
140
+
141
+ transform(_code: string, id: string) {
142
+ if (!id.endsWith('.tsx') && !id.endsWith('.jsx')) {
143
+ return null;
144
+ }
145
+
146
+ return null;
147
+ },
148
+ };
149
+ }
150
+
151
+ export default bromiumPlugin;