json-api-builder-add-route 0.0.0-stage → 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.
package/bin/index.js ADDED
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ import { addRoute } from "../src/index.js";
5
+
6
+ const specArg = process.argv[2] ?? "v2.json";
7
+ const targetDir = process.cwd();
8
+ const specPath = path.resolve(targetDir, specArg);
9
+
10
+ console.log("=============================================================");
11
+ console.log(" JSON API Builder Add Route CLI ");
12
+ console.log("=============================================================");
13
+
14
+ if (!fs.existsSync(specPath)) {
15
+ console.error(`\n❌ Error: Spec file not found: ${specPath}`);
16
+ console.error(`Usage: npx json-api-builder-add-route [spec-file.json]\n`);
17
+ process.exit(1);
18
+ }
19
+
20
+ try {
21
+ console.log(`- Working Directory: ${targetDir}`);
22
+ console.log(`- Route Spec File: ${specPath}`);
23
+
24
+ const result = addRoute({
25
+ targetDir,
26
+ specFile: specArg
27
+ });
28
+
29
+ console.log("\n[Result]");
30
+ console.log(`✔ Subtree '${result.routeName}' created successfully!`);
31
+ console.log(`- Subtree Directory: ${result.subtreeDir}`);
32
+ console.log(`- Generated Files: ${result.createdFiles.length}`);
33
+ if (result.hookResult) {
34
+ console.log(`- Hooked Router: ${result.parentRouterPath} (updated: ${!result.hookResult.alreadyHooked})`);
35
+ }
36
+ console.log("=============================================================\n");
37
+ } catch (err) {
38
+ console.error("\n❌ Add Route failed:", err.message);
39
+ process.exit(1);
40
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "json-api-builder-add-route",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Scoped subtree generator and parent router hooker for JSON API Builder.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "bin": {
8
+ "json-api-builder-add-route": "./bin/index.js"
9
+ },
10
+ "exports": {
11
+ ".": "./src/index.js"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "scripts": {
20
+ "test": "node --test \"test/**/*.test.js\""
21
+ },
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "dependencies": {
29
+ "acorn": "^8.15.0",
30
+ "astring": "^1.9.0"
31
+ },
32
+ "license": "MIT",
33
+ "author": "KeshavSoft",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/keshavsoft/json-api-builder-add-route.git"
37
+ },
38
+ "bugs": {
39
+ "url": "https://github.com/keshavsoft/json-api-builder-add-route/issues"
40
+ },
41
+ "homepage": "https://keshavsoft.github.io/json-api-builder-add-route/"
42
+ }
@@ -0,0 +1,123 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import * as acorn from "acorn";
4
+ import { generate } from "astring";
5
+
6
+ function getCrudRouteSource(dataRelativePath, idField = "id") {
7
+ return `import { Hono } from "hono";
8
+ import { readFile, writeFile } from "node:fs/promises";
9
+ import { fileURLToPath } from "node:url";
10
+ import path from "node:path";
11
+
12
+ const routes = new Hono();
13
+ const dataPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ${JSON.stringify(dataRelativePath)});
14
+ const readRows = async () => JSON.parse(await readFile(dataPath, "utf8"));
15
+ const writeRows = async rows => writeFile(dataPath, JSON.stringify(rows, null, 2) + "\\n");
16
+
17
+ routes.get("/", async c => c.json(await readRows()));
18
+
19
+ routes.post("/", async c => {
20
+ const row = await c.req.json();
21
+ const rows = await readRows();
22
+ if (row[${JSON.stringify(idField)}] == null) row[${JSON.stringify(idField)}] = Date.now();
23
+ rows.push(row);
24
+ await writeRows(rows);
25
+ return c.json(row, 201);
26
+ });
27
+
28
+ routes.get("/:id", async c => {
29
+ const row = (await readRows()).find(item => String(item[${JSON.stringify(idField)}]) === c.req.param("id"));
30
+ return row ? c.json(row) : c.json({ error: "Not found" }, 404);
31
+ });
32
+
33
+ routes.put("/:id", async c => {
34
+ const rows = await readRows();
35
+ const index = rows.findIndex(item => String(item[${JSON.stringify(idField)}]) === c.req.param("id"));
36
+ if (index < 0) return c.json({ error: "Not found" }, 404);
37
+ rows[index] = { ...rows[index], ...await c.req.json(), [${JSON.stringify(idField)}]: rows[index][${JSON.stringify(idField)}] };
38
+ await writeRows(rows);
39
+ return c.json(rows[index]);
40
+ });
41
+
42
+ routes.delete("/:id", async c => {
43
+ const rows = await readRows();
44
+ const index = rows.findIndex(item => String(item[${JSON.stringify(idField)}]) === c.req.param("id"));
45
+ if (index < 0) return c.json({ error: "Not found" }, 404);
46
+ rows.splice(index, 1);
47
+ await writeRows(rows);
48
+ return c.json({ deleted: true });
49
+ });
50
+
51
+ export default routes;
52
+ `;
53
+ }
54
+
55
+ function getSubtreeRouterSource(resourceNames) {
56
+ const imports = [
57
+ 'import { Hono } from "hono";',
58
+ ...resourceNames.map(r => `import ${r}Routes from "./${r}/routes.js";`)
59
+ ].join("\n");
60
+
61
+ const mounts = resourceNames.map(r => `routes.route("/${r}", ${r}Routes);`).join("\n");
62
+
63
+ return `${imports}
64
+
65
+ const routes = new Hono();
66
+
67
+ ${mounts}
68
+
69
+ export default routes;
70
+ `;
71
+ }
72
+
73
+ export function generateSubtree(targetDir, spec) {
74
+ const routeName = spec.name ?? "v2";
75
+ const resources = spec.routes ?? spec.resources ?? {};
76
+ const subtreeDir = path.join(targetDir, routeName);
77
+ fs.mkdirSync(subtreeDir, { recursive: true });
78
+
79
+ const resourceNames = [];
80
+ const createdFiles = [];
81
+
82
+ for (const [resKey, resVal] of Object.entries(resources)) {
83
+ const resourceDir = path.join(subtreeDir, resKey);
84
+ fs.mkdirSync(resourceDir, { recursive: true });
85
+
86
+ const dataRelative = resVal.dataFile ?? `../../data/${resKey}.json`;
87
+ const idField = resVal.idField ?? "id";
88
+
89
+ // Generate AST and serialize via astring
90
+ const rawSource = getCrudRouteSource(dataRelative, idField);
91
+ const ast = acorn.parse(rawSource, { ecmaVersion: "latest", sourceType: "module" });
92
+ const code = generate(ast);
93
+
94
+ const resourceRoutesPath = path.join(resourceDir, "routes.js");
95
+ fs.writeFileSync(resourceRoutesPath, code.trim() + "\n", "utf8");
96
+ createdFiles.push(resourceRoutesPath);
97
+
98
+ // Ensure data file exists
99
+ const dataFullPath = path.resolve(resourceDir, dataRelative);
100
+ if (!fs.existsSync(dataFullPath)) {
101
+ fs.mkdirSync(path.dirname(dataFullPath), { recursive: true });
102
+ fs.writeFileSync(dataFullPath, "[]\n", "utf8");
103
+ createdFiles.push(dataFullPath);
104
+ }
105
+
106
+ resourceNames.push(resKey);
107
+ }
108
+
109
+ // Generate subtree routes.js via AST and serialize via astring
110
+ const rawRouterSource = getSubtreeRouterSource(resourceNames);
111
+ const routerAst = acorn.parse(rawRouterSource, { ecmaVersion: "latest", sourceType: "module" });
112
+ const routerCode = generate(routerAst);
113
+
114
+ const subtreeRoutesPath = path.join(subtreeDir, "routes.js");
115
+ fs.writeFileSync(subtreeRoutesPath, routerCode.trim() + "\n", "utf8");
116
+ createdFiles.push(subtreeRoutesPath);
117
+
118
+ return {
119
+ routeName,
120
+ subtreeDir,
121
+ createdFiles
122
+ };
123
+ }
@@ -0,0 +1,109 @@
1
+ import fs from "node:fs";
2
+ import * as acorn from "acorn";
3
+ import { generate } from "astring";
4
+
5
+ export function hookParentRouter(parentRouterPath, routeName) {
6
+ if (!fs.existsSync(parentRouterPath)) {
7
+ throw new Error(`Parent router file not found: ${parentRouterPath}`);
8
+ }
9
+
10
+ const source = fs.readFileSync(parentRouterPath, "utf8");
11
+ const ast = acorn.parse(source, { ecmaVersion: "latest", sourceType: "module" });
12
+
13
+ const importSource = `./${routeName}/routes.js`;
14
+ const variableName = `${routeName}Routes`;
15
+ const routeMountPath = `/${routeName}`;
16
+
17
+ // 1. Check if import already exists
18
+ let hasImport = false;
19
+ let lastImportIndex = -1;
20
+
21
+ for (let i = 0; i < ast.body.length; i++) {
22
+ const node = ast.body[i];
23
+ if (node.type === "ImportDeclaration") {
24
+ lastImportIndex = i;
25
+ if (node.source.value === importSource) {
26
+ hasImport = true;
27
+ }
28
+ }
29
+ }
30
+
31
+ // 2. Check if mount already exists
32
+ let hasMount = false;
33
+ let lastMountIndex = -1;
34
+
35
+ for (let i = 0; i < ast.body.length; i++) {
36
+ const node = ast.body[i];
37
+ if (
38
+ node.type === "ExpressionStatement" &&
39
+ node.expression?.type === "CallExpression" &&
40
+ node.expression.callee?.type === "MemberExpression" &&
41
+ node.expression.callee.property?.name === "route"
42
+ ) {
43
+ lastMountIndex = i;
44
+ const firstArg = node.expression.arguments?.[0];
45
+ if (firstArg?.value === routeMountPath) {
46
+ hasMount = true;
47
+ }
48
+ }
49
+ }
50
+
51
+ if (hasImport && hasMount) {
52
+ return { alreadyHooked: true, parentRouterPath };
53
+ }
54
+
55
+ // 3. Inject Import if missing
56
+ if (!hasImport) {
57
+ const newImportNode = {
58
+ type: "ImportDeclaration",
59
+ specifiers: [
60
+ {
61
+ type: "ImportDefaultSpecifier",
62
+ local: { type: "Identifier", name: variableName }
63
+ }
64
+ ],
65
+ source: {
66
+ type: "Literal",
67
+ value: importSource,
68
+ raw: JSON.stringify(importSource)
69
+ }
70
+ };
71
+
72
+ const insertAt = lastImportIndex >= 0 ? lastImportIndex + 1 : 0;
73
+ ast.body.splice(insertAt, 0, newImportNode);
74
+ if (lastMountIndex >= insertAt) {
75
+ lastMountIndex++;
76
+ }
77
+ }
78
+
79
+ // 4. Inject Route Mount if missing
80
+ if (!hasMount) {
81
+ const newMountNode = {
82
+ type: "ExpressionStatement",
83
+ expression: {
84
+ type: "CallExpression",
85
+ callee: {
86
+ type: "MemberExpression",
87
+ object: { type: "Identifier", name: "routes" },
88
+ property: { type: "Identifier", name: "route" }
89
+ },
90
+ arguments: [
91
+ { type: "Literal", value: routeMountPath, raw: JSON.stringify(routeMountPath) },
92
+ { type: "Identifier", name: variableName }
93
+ ]
94
+ }
95
+ };
96
+
97
+ const insertAt = lastMountIndex >= 0 ? lastMountIndex + 1 : ast.body.length - 1;
98
+ ast.body.splice(insertAt, 0, newMountNode);
99
+ }
100
+
101
+ const updatedCode = generate(ast).trim() + "\n";
102
+ fs.writeFileSync(parentRouterPath, updatedCode, "utf8");
103
+
104
+ return {
105
+ alreadyHooked: false,
106
+ parentRouterPath,
107
+ updated: true
108
+ };
109
+ }
package/src/index.js ADDED
@@ -0,0 +1,41 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { generateSubtree } from "./generate-subtree.js";
4
+ import { hookParentRouter } from "./hook-parent-router.js";
5
+
6
+ export function addRoute(options = {}) {
7
+ const targetDir = path.resolve(options.targetDir ?? process.cwd());
8
+ let spec = options.spec;
9
+
10
+ if (!spec) {
11
+ const specFile = options.specFile ?? "v2.json";
12
+ const specPath = path.resolve(targetDir, specFile);
13
+ if (!fs.existsSync(specPath)) {
14
+ throw new Error(`Route specification file not found: ${specPath}`);
15
+ }
16
+ spec = JSON.parse(fs.readFileSync(specPath, "utf8"));
17
+ }
18
+
19
+ const parentRouterName = options.parentRouterName ?? "routes.js";
20
+ const parentRouterPath = path.join(targetDir, parentRouterName);
21
+
22
+ // 1. Generate new subtree
23
+ const subtreeResult = generateSubtree(targetDir, spec);
24
+
25
+ // 2. Hook into parent router if it exists
26
+ let hookResult = null;
27
+ if (fs.existsSync(parentRouterPath)) {
28
+ hookResult = hookParentRouter(parentRouterPath, subtreeResult.routeName);
29
+ }
30
+
31
+ return {
32
+ targetDir,
33
+ routeName: subtreeResult.routeName,
34
+ subtreeDir: subtreeResult.subtreeDir,
35
+ createdFiles: subtreeResult.createdFiles,
36
+ parentRouterPath: fs.existsSync(parentRouterPath) ? parentRouterPath : null,
37
+ hookResult
38
+ };
39
+ }
40
+
41
+ export default { addRoute };
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.