@samadhi1311/router 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ default: () => router
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+ var import_fs = __toESM(require("fs"), 1);
37
+ var import_path = __toESM(require("path"), 1);
38
+ function router(options = {}) {
39
+ const appDir = options.appDir || "app";
40
+ const virtualModuleId = "virtual:router";
41
+ const resolvedVirtualModuleId = "\0" + virtualModuleId;
42
+ function scanDirectory(dir, basePath = "") {
43
+ const routes = [];
44
+ const fullDir = import_path.default.join(process.cwd(), appDir, dir);
45
+ if (!import_fs.default.existsSync(fullDir)) return routes;
46
+ const entries = import_fs.default.readdirSync(fullDir, { withFileTypes: true });
47
+ let pagePath;
48
+ let layoutPath;
49
+ let loadingPath;
50
+ let notFoundPath;
51
+ for (const entry of entries) {
52
+ if (!entry.isFile()) continue;
53
+ const nameWithoutExt = entry.name.replace(/\.(tsx?|jsx?)$/, "");
54
+ const fullPath = import_path.default.join(dir, entry.name);
55
+ if (nameWithoutExt === "page") {
56
+ pagePath = fullPath;
57
+ } else if (nameWithoutExt === "layout") {
58
+ layoutPath = fullPath;
59
+ } else if (nameWithoutExt === "loading") {
60
+ loadingPath = fullPath;
61
+ } else if (nameWithoutExt === "not-found") {
62
+ notFoundPath = fullPath;
63
+ }
64
+ }
65
+ const children = [];
66
+ for (const entry of entries) {
67
+ if (!entry.isDirectory()) continue;
68
+ const dirName = entry.name;
69
+ const isDynamic = dirName.startsWith("[") && dirName.endsWith("]");
70
+ const param = isDynamic ? dirName.slice(1, -1) : dirName;
71
+ const routePath = isDynamic ? `:${param}` : dirName;
72
+ const nestedRoutes = scanDirectory(import_path.default.join(dir, dirName), routePath);
73
+ children.push(...nestedRoutes);
74
+ }
75
+ if (pagePath) {
76
+ routes.push({
77
+ path: basePath || "/",
78
+ componentPath: pagePath,
79
+ layoutPath,
80
+ loadingPath,
81
+ notFoundPath,
82
+ isDynamic: basePath.includes(":"),
83
+ params: basePath.match(/:\w+/g)?.map((p) => p.slice(1)) || [],
84
+ children: children.length > 0 ? children : void 0
85
+ });
86
+ } else if (layoutPath || children.length > 0) {
87
+ routes.push({
88
+ path: basePath || "/",
89
+ componentPath: "",
90
+ layoutPath,
91
+ loadingPath,
92
+ notFoundPath,
93
+ isDynamic: basePath.includes(":"),
94
+ params: basePath.match(/:\w+/g)?.map((p) => p.slice(1)) || [],
95
+ children: children.length > 0 ? children : void 0
96
+ });
97
+ }
98
+ return routes;
99
+ }
100
+ function generateRouteCode(routes) {
101
+ let imports = 'import { createElement, Suspense } from "react";\nimport { Outlet } from "react-router";\n';
102
+ let routeConfigs = "";
103
+ let importCounter = 0;
104
+ function processRoute(route, depth = 0) {
105
+ const indent = " ".repeat(depth + 1);
106
+ const componentId = route.componentPath ? `Page${importCounter++}` : null;
107
+ const layoutId = route.layoutPath ? `Layout${importCounter++}` : null;
108
+ const loadingId = route.loadingPath ? `Loading${importCounter++}` : null;
109
+ const notFoundId = route.notFoundPath ? `NotFound${importCounter++}` : null;
110
+ if (componentId && route.componentPath) {
111
+ imports += `import ${componentId} from '/${appDir}/${route.componentPath}';
112
+ `;
113
+ }
114
+ if (layoutId && route.layoutPath) {
115
+ imports += `import ${layoutId} from '/${appDir}/${route.layoutPath}';
116
+ `;
117
+ }
118
+ if (loadingId && route.loadingPath) {
119
+ imports += `import ${loadingId} from '/${appDir}/${route.loadingPath}';
120
+ `;
121
+ }
122
+ if (notFoundId && route.notFoundPath) {
123
+ imports += `import ${notFoundId} from '/${appDir}/${route.notFoundPath}';
124
+ `;
125
+ }
126
+ let config = `${indent}{
127
+ `;
128
+ config += `${indent} path: '${route.path}',
129
+ `;
130
+ if (layoutId) {
131
+ config += `${indent} element: createElement(${layoutId}, null, createElement(Outlet)),
132
+ `;
133
+ } else if (componentId) {
134
+ const element = loadingId ? `createElement(Suspense, { fallback: createElement(${loadingId}) }, createElement(${componentId}))` : `createElement(${componentId})`;
135
+ config += `${indent} element: ${element},
136
+ `;
137
+ } else {
138
+ config += `${indent} element: createElement(Outlet),
139
+ `;
140
+ }
141
+ if (notFoundId) {
142
+ config += `${indent} errorElement: createElement(${notFoundId}),
143
+ `;
144
+ }
145
+ if (route.children && route.children.length > 0) {
146
+ config += `${indent} children: [
147
+ `;
148
+ route.children.forEach((child) => {
149
+ config += processRoute(child, depth + 1);
150
+ });
151
+ config += `${indent} ],
152
+ `;
153
+ }
154
+ config += `${indent}},
155
+ `;
156
+ return config;
157
+ }
158
+ routes.forEach((route) => {
159
+ routeConfigs += processRoute(route, 0);
160
+ });
161
+ return `${imports}
162
+ export const routes = [
163
+ ${routeConfigs}];
164
+ `;
165
+ }
166
+ return {
167
+ name: "router",
168
+ enforce: "pre",
169
+ resolveId(id) {
170
+ if (id === virtualModuleId) {
171
+ return resolvedVirtualModuleId;
172
+ }
173
+ },
174
+ load(id) {
175
+ if (id === resolvedVirtualModuleId) {
176
+ const routes = scanDirectory("");
177
+ return generateRouteCode(routes);
178
+ }
179
+ },
180
+ handleHotUpdate({ file, server }) {
181
+ if (file.includes(`/${appDir}/`)) {
182
+ const module2 = server.moduleGraph.getModuleById(resolvedVirtualModuleId);
183
+ if (module2) {
184
+ server.moduleGraph.invalidateModule(module2);
185
+ server.ws.send({ type: "full-reload" });
186
+ }
187
+ }
188
+ }
189
+ };
190
+ }
@@ -0,0 +1,7 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ declare function router(options?: {
4
+ appDir?: string;
5
+ }): Plugin;
6
+
7
+ export { router as default };
@@ -0,0 +1,7 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ declare function router(options?: {
4
+ appDir?: string;
5
+ }): Plugin;
6
+
7
+ export { router as default };
package/dist/index.js ADDED
@@ -0,0 +1,159 @@
1
+ // src/index.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ function router(options = {}) {
5
+ const appDir = options.appDir || "app";
6
+ const virtualModuleId = "virtual:router";
7
+ const resolvedVirtualModuleId = "\0" + virtualModuleId;
8
+ function scanDirectory(dir, basePath = "") {
9
+ const routes = [];
10
+ const fullDir = path.join(process.cwd(), appDir, dir);
11
+ if (!fs.existsSync(fullDir)) return routes;
12
+ const entries = fs.readdirSync(fullDir, { withFileTypes: true });
13
+ let pagePath;
14
+ let layoutPath;
15
+ let loadingPath;
16
+ let notFoundPath;
17
+ for (const entry of entries) {
18
+ if (!entry.isFile()) continue;
19
+ const nameWithoutExt = entry.name.replace(/\.(tsx?|jsx?)$/, "");
20
+ const fullPath = path.join(dir, entry.name);
21
+ if (nameWithoutExt === "page") {
22
+ pagePath = fullPath;
23
+ } else if (nameWithoutExt === "layout") {
24
+ layoutPath = fullPath;
25
+ } else if (nameWithoutExt === "loading") {
26
+ loadingPath = fullPath;
27
+ } else if (nameWithoutExt === "not-found") {
28
+ notFoundPath = fullPath;
29
+ }
30
+ }
31
+ const children = [];
32
+ for (const entry of entries) {
33
+ if (!entry.isDirectory()) continue;
34
+ const dirName = entry.name;
35
+ const isDynamic = dirName.startsWith("[") && dirName.endsWith("]");
36
+ const param = isDynamic ? dirName.slice(1, -1) : dirName;
37
+ const routePath = isDynamic ? `:${param}` : dirName;
38
+ const nestedRoutes = scanDirectory(path.join(dir, dirName), routePath);
39
+ children.push(...nestedRoutes);
40
+ }
41
+ if (pagePath) {
42
+ routes.push({
43
+ path: basePath || "/",
44
+ componentPath: pagePath,
45
+ layoutPath,
46
+ loadingPath,
47
+ notFoundPath,
48
+ isDynamic: basePath.includes(":"),
49
+ params: basePath.match(/:\w+/g)?.map((p) => p.slice(1)) || [],
50
+ children: children.length > 0 ? children : void 0
51
+ });
52
+ } else if (layoutPath || children.length > 0) {
53
+ routes.push({
54
+ path: basePath || "/",
55
+ componentPath: "",
56
+ layoutPath,
57
+ loadingPath,
58
+ notFoundPath,
59
+ isDynamic: basePath.includes(":"),
60
+ params: basePath.match(/:\w+/g)?.map((p) => p.slice(1)) || [],
61
+ children: children.length > 0 ? children : void 0
62
+ });
63
+ }
64
+ return routes;
65
+ }
66
+ function generateRouteCode(routes) {
67
+ let imports = 'import { createElement, Suspense } from "react";\nimport { Outlet } from "react-router";\n';
68
+ let routeConfigs = "";
69
+ let importCounter = 0;
70
+ function processRoute(route, depth = 0) {
71
+ const indent = " ".repeat(depth + 1);
72
+ const componentId = route.componentPath ? `Page${importCounter++}` : null;
73
+ const layoutId = route.layoutPath ? `Layout${importCounter++}` : null;
74
+ const loadingId = route.loadingPath ? `Loading${importCounter++}` : null;
75
+ const notFoundId = route.notFoundPath ? `NotFound${importCounter++}` : null;
76
+ if (componentId && route.componentPath) {
77
+ imports += `import ${componentId} from '/${appDir}/${route.componentPath}';
78
+ `;
79
+ }
80
+ if (layoutId && route.layoutPath) {
81
+ imports += `import ${layoutId} from '/${appDir}/${route.layoutPath}';
82
+ `;
83
+ }
84
+ if (loadingId && route.loadingPath) {
85
+ imports += `import ${loadingId} from '/${appDir}/${route.loadingPath}';
86
+ `;
87
+ }
88
+ if (notFoundId && route.notFoundPath) {
89
+ imports += `import ${notFoundId} from '/${appDir}/${route.notFoundPath}';
90
+ `;
91
+ }
92
+ let config = `${indent}{
93
+ `;
94
+ config += `${indent} path: '${route.path}',
95
+ `;
96
+ if (layoutId) {
97
+ config += `${indent} element: createElement(${layoutId}, null, createElement(Outlet)),
98
+ `;
99
+ } else if (componentId) {
100
+ const element = loadingId ? `createElement(Suspense, { fallback: createElement(${loadingId}) }, createElement(${componentId}))` : `createElement(${componentId})`;
101
+ config += `${indent} element: ${element},
102
+ `;
103
+ } else {
104
+ config += `${indent} element: createElement(Outlet),
105
+ `;
106
+ }
107
+ if (notFoundId) {
108
+ config += `${indent} errorElement: createElement(${notFoundId}),
109
+ `;
110
+ }
111
+ if (route.children && route.children.length > 0) {
112
+ config += `${indent} children: [
113
+ `;
114
+ route.children.forEach((child) => {
115
+ config += processRoute(child, depth + 1);
116
+ });
117
+ config += `${indent} ],
118
+ `;
119
+ }
120
+ config += `${indent}},
121
+ `;
122
+ return config;
123
+ }
124
+ routes.forEach((route) => {
125
+ routeConfigs += processRoute(route, 0);
126
+ });
127
+ return `${imports}
128
+ export const routes = [
129
+ ${routeConfigs}];
130
+ `;
131
+ }
132
+ return {
133
+ name: "router",
134
+ enforce: "pre",
135
+ resolveId(id) {
136
+ if (id === virtualModuleId) {
137
+ return resolvedVirtualModuleId;
138
+ }
139
+ },
140
+ load(id) {
141
+ if (id === resolvedVirtualModuleId) {
142
+ const routes = scanDirectory("");
143
+ return generateRouteCode(routes);
144
+ }
145
+ },
146
+ handleHotUpdate({ file, server }) {
147
+ if (file.includes(`/${appDir}/`)) {
148
+ const module = server.moduleGraph.getModuleById(resolvedVirtualModuleId);
149
+ if (module) {
150
+ server.moduleGraph.invalidateModule(module);
151
+ server.ws.send({ type: "full-reload" });
152
+ }
153
+ }
154
+ }
155
+ };
156
+ }
157
+ export {
158
+ router as default
159
+ };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@samadhi1311/router",
3
+ "version": "0.1.0",
4
+ "description": "A simple router for Vite inspired by Next.JS App Router",
5
+ "author": {
6
+ "name": "Samadhi Gunasinghe",
7
+ "email": "samadhi@hyperreal.cloud"
8
+ },
9
+ "contributors": [
10
+ {
11
+ "name": "Samadhi Gunasinghe",
12
+ "email": "samadhi@hyperreal.cloud",
13
+ "url": "https://github.com/samadhi1311"
14
+ },
15
+ {
16
+ "name": "Nipuni Gamage",
17
+ "email": "nipuni@hyperreal.cloud",
18
+ "url": "https://github.com/nipunigamage"
19
+ }
20
+ ],
21
+ "type": "module",
22
+ "main": "./dist/index.cjs",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js",
29
+ "require": "./dist/index.cjs"
30
+ }
31
+ },
32
+ "files": ["dist"],
33
+ "peerDependencies": {
34
+ "vite": "^5 || ^6",
35
+ "react": "^18",
36
+ "react-router": "^6"
37
+ },
38
+ "keywords": ["vite", "vite-plugin", "react", "router", "nextjs"],
39
+ "scripts": {
40
+ "build": "tsup",
41
+ "prepublishOnly": "pnpm build"
42
+ }
43
+ }