create-cellsweb-rpc-api 1.0.22 → 1.0.24

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/README.md CHANGED
@@ -1,29 +1,66 @@
1
1
  # `create-cellsweb-rpc-api`
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/create-cellsweb-rpc-api.svg)](https://www.npmjs.com/package/create-cellsweb-rpc-api)
4
+ [![license](https://img.shields.io/npm/l/create-cellsweb-rpc-api.svg)](LICENSE)
5
+
3
6
  > Official CLI scaffolder for **CellsWeb RPC API** service projects.
4
7
 
8
+ > [!TIP]
9
+ > **CellsWeb RPC Ecosystem**:
10
+ > - ⚡ **Backend RPC Engine**: [`@cellsweb/rpc-core`](https://www.npmjs.com/package/@cellsweb/rpc-core) ($O(1)$ dispatching, TypeBox schemas, Busboy multipart)
11
+ > - 🌐 **Client SDK & React/RN Hooks**: [`@cellsweb/rpc-client`](https://www.npmjs.com/package/@cellsweb/rpc-client) (Universal fetch & automatic multipart form-data)
12
+
5
13
  ---
6
14
 
7
15
  ## Usage
8
16
 
9
17
  ```bash
10
- # Using npm
18
+ # Interactive setup
11
19
  npm create cellsweb-rpc-api@latest my-app
12
-
13
- # Using npx
20
+ # or
14
21
  npx create-cellsweb-rpc-api@latest my-app
15
-
16
- # Using pnpm
22
+ # or
17
23
  pnpm create cellsweb-rpc-api@latest my-app
18
24
  ```
19
25
 
26
+ ### Non-Interactive & Framework Flags
27
+
28
+ You can specify your preferred base web framework directly using the `--framework` (or `-f`) flag:
29
+
30
+ ```bash
31
+ # 1. Vanilla Node.js (Default — zero extra dependencies, native node:http)
32
+ npx create-cellsweb-rpc-api@latest my-app --framework node
33
+
34
+ # 2. Express (Standard — easiest for adding traditional REST routes & middleware)
35
+ npx create-cellsweb-rpc-api@latest my-app --framework express
36
+
37
+ # 3. Fastify (Modern — high performance & rich plugin ecosystem)
38
+ npx create-cellsweb-rpc-api@latest my-app --framework fastify
39
+
40
+ # 4. Ultimate-Express (Extreme Throughput — uWebSockets.js-backed Express drop-in)
41
+ npx create-cellsweb-rpc-api@latest my-app --framework ultimate-express
42
+ ```
43
+
44
+ ---
45
+
46
+ ## Supported Base Frameworks
47
+
48
+ | Framework | Dependencies | Description |
49
+ | :--- | :--- | :--- |
50
+ | **Vanilla Node.js** *(Default)* | *None (Zero extra deps)* | Highest raw performance directly on native `node:http`. |
51
+ | **Express** | `express`, `@types/express` | Standard Express server; easily mount traditional REST routes alongside `/rpc`. |
52
+ | **Fastify** | `fastify` | Fastify server with raw stream forwarding via `reply.hijack()`. |
53
+ | **Ultimate-Express** | `ultimate-express` | Drop-in Express replacement powered by `uWebSockets.js` for extreme I/O throughput. |
54
+
20
55
  ---
21
56
 
22
57
  ## Features
23
58
 
59
+ - **Multi-Framework Flexibility**: Choose between Vanilla Node.js, Express, Fastify, or Ultimate-Express while keeping RPC function and middleware code 100% identical.
24
60
  - **Pre-wired `@cellsweb/rpc-core`**: High performance $O(1)$ dispatching engine.
25
- - **Interactive Scaffolding**: Built-in CLI scripts for adding new functions (`pnpm run create:function`) and middlewares (`pnpm run create:middleware`).
26
- - **Pre-scaffolded Common Middlewares**: Includes `auth` (JWT verification stub) and `rateLimit` (in-memory rate limiting) with rich step-by-step instructions.
61
+ - **Interactive & Batch Generators**: Built-in CLI scripts for adding new functions (`pnpm run create:function`) and middlewares (`pnpm run create:middleware`).
62
+ - **Pre-scaffolded Common Middlewares**: Includes `auth` (JWT verification stub) and `rateLimit` (in-memory rate limiting).
63
+ - **Security & Integration Audit Testing**: Built-in in-process security audit test harness with HTML/JSON report generation (`pnpm run test:audit`).
27
64
  - **Pluggable Extensions**: Modular application-level `env.ts` (TypeBox), `telemetry.ts` (Sentry), and `storage.ts` (Local/S3 uploads).
28
65
 
29
66
  ---
package/bin/create.js CHANGED
@@ -10,9 +10,9 @@
10
10
  * npx create-cellsweb-rpc-api@latest
11
11
  */
12
12
 
13
+ import { execSync } from "node:child_process";
13
14
  import fs from "node:fs";
14
15
  import path from "node:path";
15
- import { execSync } from "node:child_process";
16
16
  import readline from "node:readline";
17
17
  import { fileURLToPath } from "node:url";
18
18
 
@@ -71,12 +71,36 @@ function copyDir(src, dest) {
71
71
  // ─── Main ─────────────────────────────────────────────────────────────────────
72
72
  async function main() {
73
73
  // ── 1. Inputs ──────────────────────────────────────────────────────────────
74
- const rawArg = process.argv.slice(2).find((arg) => !arg.startsWith("-"));
74
+ const args = process.argv.slice(2);
75
+ const rawArg = args.find((arg) => !arg.startsWith("-"));
75
76
  const isTTY = Boolean(process.stdin.isTTY);
76
77
 
78
+ // Parse --framework or -f flag
79
+ let explicitFramework = null;
80
+ const fwFlagIdx = args.findIndex((arg) => arg === "--framework" || arg === "-f");
81
+ if (fwFlagIdx !== -1 && args[fwFlagIdx + 1]) {
82
+ explicitFramework = args[fwFlagIdx + 1].toLowerCase().trim();
83
+ } else {
84
+ const inlineFw = args.find((arg) => arg.startsWith("--framework="));
85
+ if (inlineFw) {
86
+ explicitFramework = inlineFw.split("=")[1]?.toLowerCase().trim();
87
+ }
88
+ }
89
+
90
+ function normalizeFramework(input) {
91
+ if (!input) return "node";
92
+ const str = String(input).toLowerCase().trim();
93
+ if (str === "1" || str === "node" || str === "vanilla" || str === "vanilla node" || str === "vanilla node.js" || str === "node.js") return "node";
94
+ if (str === "2" || str === "express") return "express";
95
+ if (str === "3" || str === "fastify") return "fastify";
96
+ if (str === "4" || str === "ultimate-express" || str === "ultimate" || str === "ue") return "ultimate-express";
97
+ return "node";
98
+ }
99
+
77
100
  let targetDir;
78
101
  let projectName;
79
102
  let pm;
103
+ let framework = "node";
80
104
 
81
105
  if (rawArg) {
82
106
  targetDir = path.resolve(process.cwd(), rawArg);
@@ -95,11 +119,24 @@ async function main() {
95
119
  if (!isTTY) {
96
120
  projectName = defaultName;
97
121
  pm = "pnpm";
122
+ framework = normalizeFramework(explicitFramework);
98
123
  rl.close();
99
124
  } else {
100
125
  projectName = await ask("Package name", defaultName);
101
126
  const pmAnswer = await ask("Package manager [npm / pnpm / yarn]", "pnpm");
102
127
  pm = ["npm", "pnpm", "yarn"].includes(pmAnswer) ? pmAnswer : "pnpm";
128
+
129
+ if (explicitFramework) {
130
+ framework = normalizeFramework(explicitFramework);
131
+ } else {
132
+ console.log(`\n ${bold("Base web framework:")}`);
133
+ console.log(` ${cyan("1)")} Vanilla Node.js ${dim("(Default — zero extra dependencies, native node:http)")}`);
134
+ console.log(` ${cyan("2)")} Express ${dim("(Standard — easiest for traditional REST routes & middlewares)")}`);
135
+ console.log(` ${cyan("3)")} Fastify ${dim("(High performance & rich plugin ecosystem)")}`);
136
+ console.log(` ${cyan("4)")} Ultimate-Express ${dim("(uWebSockets.js-backed Express drop-in)")}`);
137
+ const fwAnswer = await ask("Choose framework [1/2/3/4]", "1");
138
+ framework = normalizeFramework(fwAnswer);
139
+ }
103
140
  rl.close();
104
141
  }
105
142
 
@@ -114,6 +151,12 @@ async function main() {
114
151
  console.log(`\n ${dim("Scaffolding into")} ${cyan(targetDir)} ...\n`);
115
152
  copyDir(templateDir, targetDir);
116
153
 
154
+ // ── 3.5 Swap server.ts template if non-default framework selected ─────────
155
+ const serverTemplatePath = path.join(__dirname, "..", "templates", "servers", `server.${framework}.ts`);
156
+ if (fs.existsSync(serverTemplatePath)) {
157
+ fs.copyFileSync(serverTemplatePath, path.join(targetDir, "src", "server.ts"));
158
+ }
159
+
117
160
  // ── 4. Write package.json ──────────────────────────────────────────────────
118
161
  const pkg = {
119
162
  name: projectName,
@@ -136,8 +179,8 @@ async function main() {
136
179
  node: ">=20.0.0",
137
180
  },
138
181
  dependencies: {
139
- "@cellsweb/rpc-core": "^1.0.26",
140
- "create-cellsweb-rpc-api": "^1.0.22",
182
+ "@cellsweb/rpc-core": "^1.0.28",
183
+ "create-cellsweb-rpc-api": "^1.0.24",
141
184
  "@aws-sdk/client-s3": "^3.700.0",
142
185
  "@paralleldrive/cuid2": "^2.2.2",
143
186
  "@sentry/node": "^8.40.0",
@@ -166,9 +209,21 @@ async function main() {
166
209
  "vitest": "^3.2.4",
167
210
  },
168
211
  pnpm: {
169
- onlyBuiltDependencies: ["esbuild"],
212
+ onlyBuiltDependencies: ["esbuild", "mongodb-memory-server"],
170
213
  },
171
214
  };
215
+
216
+ // Add framework-specific dependencies
217
+ if (framework === "express") {
218
+ pkg.dependencies["express"] = "^4.21.2";
219
+ pkg.devDependencies["@types/express"] = "^5.0.0";
220
+ } else if (framework === "fastify") {
221
+ pkg.dependencies["fastify"] = "^5.2.1";
222
+ } else if (framework === "ultimate-express") {
223
+ pkg.dependencies["ultimate-express"] = "^2.2.1";
224
+ pkg.devDependencies["@types/express"] = "^5.0.0";
225
+ }
226
+
172
227
  fs.writeFileSync(path.join(targetDir, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
173
228
 
174
229
  // ── 5. Write tsconfig.json ─────────────────────────────────────────────────
@@ -215,11 +270,15 @@ async function main() {
215
270
  fs.mkdirSync(scriptsDir, { recursive: true });
216
271
  fs.writeFileSync(path.join(scriptsDir, "tsconfig.json"), JSON.stringify(scriptsTsconfig, null, 2) + "\n");
217
272
 
218
- // ── 7. Write .gitignore ───────────────────────────────────────────────────
273
+ // ── 7. Write .gitignore & .npmrc ──────────────────────────────────────────
219
274
  const gitignore = ["node_modules", "dist", ".env", "*.log", ".DS_Store"].join("\n") + "\n";
220
275
  const giPath = path.join(targetDir, ".gitignore");
221
276
  if (!fs.existsSync(giPath)) fs.writeFileSync(giPath, gitignore);
222
277
 
278
+ const npmrc = "onlyBuiltDependencies=esbuild,mongodb-memory-server\n";
279
+ const npmrcPath = path.join(targetDir, ".npmrc");
280
+ if (!fs.existsSync(npmrcPath)) fs.writeFileSync(npmrcPath, npmrc);
281
+
223
282
  // ── 7.5 Copy .env.example -> .env ────────────────────────────────────────
224
283
  const envExamplePath = path.join(targetDir, ".env.example");
225
284
  const envPath = path.join(targetDir, ".env");
@@ -231,16 +290,26 @@ async function main() {
231
290
  console.log(` ${dim("Installing dependencies with")} ${bold(pm)} ...\n`);
232
291
  try {
233
292
  const installCmd =
234
- pm === "pnpm" ? "pnpm install --config.onlyBuiltDependencies=esbuild" : `${pm} install`;
293
+ pm === "pnpm" ? "pnpm install && pnpm approve-builds --all" : `${pm} install`;
235
294
  execSync(installCmd, { cwd: targetDir, stdio: "inherit" });
236
295
  } catch {
237
296
  console.log(` ${yellow("⚠")} Install failed — run ${bold(`${pm} install`)} manually.\n`);
238
297
  }
239
298
 
240
299
  // ── 9. Done ───────────────────────────────────────────────────────────────
300
+ const fwNameMap = {
301
+ node: "Vanilla Node.js (node:http)",
302
+ express: "Express",
303
+ fastify: "Fastify",
304
+ "ultimate-express": "Ultimate-Express (uWebSockets.js)",
305
+ };
306
+
241
307
  console.log(`
242
308
  ${green("✔")} ${bold("Done!")} Your RPC API is ready.
243
309
 
310
+ ${dim("Framework:")} ${cyan(fwNameMap[framework] || framework)}
311
+ ${dim("Target dir:")} ${cyan(targetDir)}
312
+
244
313
  ${dim("Next steps:")}
245
314
  ${cyan(`cd ${path.relative(process.cwd(), targetDir) || "."}`)}
246
315
  ${cyan(`${pm} run dev`)} ${dim("→ start dev server with crpc (hot-reload)")}
@@ -251,7 +320,7 @@ async function main() {
251
320
  ${dim("Add your JWT logic in:")}
252
321
  ${cyan("src/middlewares/auth/run.ts")} ${dim("→ verifyToken()")}
253
322
 
254
- ${dim("API endpoint:")} POST ${cyan("http://localhost:4000/api")}
323
+ ${dim("API endpoint:")} POST ${cyan("http://localhost:4000/api")} (or ${cyan("/rpc")})
255
324
  ${dim("Docs:")} GET ${cyan("http://localhost:4000/docs")}
256
325
  `);
257
326
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-cellsweb-rpc-api",
3
- "version": "1.0.22",
3
+ "version": "1.0.24",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -13,7 +13,8 @@
13
13
  },
14
14
  "files": [
15
15
  "bin",
16
- "template"
16
+ "template",
17
+ "templates"
17
18
  ],
18
19
  "scripts": {
19
20
  "test": "echo \"CLI scaffolder test suite\""
@@ -19,7 +19,7 @@ export const app = new CoreRPC({
19
19
 
20
20
  const rpcHandler = await app.createHandler();
21
21
 
22
- const server = http.createServer(async (req, res) => {
22
+ export const server = http.createServer(async (req, res) => {
23
23
  const url = req.url ?? "/";
24
24
  const method = req.method ?? "GET";
25
25
 
@@ -52,8 +52,9 @@ const server = http.createServer(async (req, res) => {
52
52
 
53
53
  // Only start HTTP listener if not running inside test environment (Vitest)
54
54
  if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
55
- server.listen(env.API_PORT, env.API_HOST, () => {
56
- console.log(`Server listening at http://${env.API_HOST}:${env.API_PORT}`);
55
+ const port = env.API_PORT ?? 4000;
56
+ const host = env.API_HOST ?? "0.0.0.0";
57
+ server.listen(port, host, () => {
58
+ console.log(`Server listening at http://${host}:${port}`);
57
59
  });
58
60
  }
59
-
@@ -0,0 +1,50 @@
1
+ /**
2
+ * server.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * CellsWeb RPC API Server Entrypoint — Express
5
+ */
6
+
7
+ import { CoreRPC } from "@cellsweb/rpc-core";
8
+ import express, { type Express } from "express";
9
+ import { env } from "./env";
10
+ import { storage } from "./utils/storage";
11
+
12
+ export const app = new CoreRPC({
13
+ functionsDir: "./src/functions",
14
+ middlewaresDir: "./src/middlewares",
15
+ port: env.API_PORT,
16
+ host: env.API_HOST,
17
+ docs: true,
18
+ });
19
+
20
+ export const server: Express = express();
21
+ const rpcHandler = await app.createHandler();
22
+
23
+ // ── Static Files Route (/uploads/*) ──
24
+ server.get("/uploads/*", async (req, res) => {
25
+ const filePath = decodeURIComponent(req.url.replace(/^\/uploads\//, ""));
26
+ const result = await storage.serve(filePath);
27
+ if (!result) {
28
+ res.status(404).json({
29
+ status: "error",
30
+ code: "not_found",
31
+ message: "File not found",
32
+ });
33
+ return;
34
+ }
35
+ res.setHeader("Content-Type", result.mimeType);
36
+ res.setHeader("Cache-Control", "public, max-age=86400");
37
+ res.send(result.buffer);
38
+ });
39
+
40
+ // ⚠️ IMPORTANT: Mount RPC handler BEFORE any global body parsers (like express.json())!
41
+ server.use(rpcHandler);
42
+
43
+ // Only start HTTP listener if not running inside test environment (Vitest)
44
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
45
+ const port = env.API_PORT ?? 4000;
46
+ const host = env.API_HOST ?? "0.0.0.0";
47
+ server.listen(port, host, () => {
48
+ console.log(`Express server listening at http://${host}:${port}`);
49
+ });
50
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * server.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * CellsWeb RPC API Server Entrypoint — Fastify
5
+ */
6
+
7
+ import { CoreRPC } from "@cellsweb/rpc-core";
8
+ import Fastify from "fastify";
9
+ import { env } from "./env";
10
+ import { storage } from "./utils/storage";
11
+
12
+ export const app = new CoreRPC({
13
+ functionsDir: "./src/functions",
14
+ middlewaresDir: "./src/middlewares",
15
+ port: env.API_PORT,
16
+ host: env.API_HOST,
17
+ docs: true,
18
+ });
19
+
20
+ export const server = Fastify({ logger: false });
21
+
22
+ // ── Static Files Route (/uploads/*) ──
23
+ server.get("/uploads/*", async (req, reply) => {
24
+ const filePath = decodeURIComponent(req.url.replace(/^\/uploads\//, ""));
25
+ const result = await storage.serve(filePath);
26
+ if (!result) {
27
+ reply.code(404).send({
28
+ status: "error",
29
+ code: "not_found",
30
+ message: "File not found",
31
+ });
32
+ return;
33
+ }
34
+ reply.header("Content-Type", result.mimeType);
35
+ reply.header("Cache-Control", "public, max-age=86400");
36
+ reply.send(result.buffer);
37
+ });
38
+
39
+ // ── Register CellsWeb RPC Plugin (Handles /rpc, /docs, and /health) ──
40
+ await server.register(app.createFastifyPlugin());
41
+
42
+ // Only start HTTP listener if not running inside test environment (Vitest)
43
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
44
+ const port = env.API_PORT ?? 4000;
45
+ const host = env.API_HOST ?? "0.0.0.0";
46
+ await server.listen({ port, host });
47
+ console.log(`Fastify server listening at http://${host}:${port}`);
48
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * server.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * CellsWeb RPC API Server Entrypoint — Vanilla Node.js (node:http)
5
+ */
6
+
7
+ import { CoreRPC } from "@cellsweb/rpc-core";
8
+ import http from "node:http";
9
+ import { env } from "./env";
10
+ import { storage } from "./utils/storage";
11
+
12
+ export const app = new CoreRPC({
13
+ functionsDir: "./src/functions",
14
+ middlewaresDir: "./src/middlewares",
15
+ port: env.API_PORT,
16
+ host: env.API_HOST,
17
+ docs: true,
18
+ });
19
+
20
+ const rpcHandler = await app.createHandler();
21
+
22
+ export const server = http.createServer(async (req, res) => {
23
+ const url = req.url ?? "/";
24
+ const method = req.method ?? "GET";
25
+
26
+ // ── Static Files Route (/uploads/*) ──
27
+ if (method === "GET" && url.startsWith("/uploads/")) {
28
+ const filePath = decodeURIComponent(url.replace(/^\/uploads\//, ""));
29
+ const result = await storage.serve(filePath);
30
+ if (!result) {
31
+ res.writeHead(404, { "Content-Type": "application/json" });
32
+ res.end(
33
+ JSON.stringify({
34
+ status: "error",
35
+ code: "not_found",
36
+ message: "File not found",
37
+ }),
38
+ );
39
+ return;
40
+ }
41
+ res.writeHead(200, {
42
+ "Content-Type": result.mimeType,
43
+ "Cache-Control": "public, max-age=86400",
44
+ });
45
+ res.end(result.buffer);
46
+ return;
47
+ }
48
+
49
+ // ── Core RPC Engine Handler (Handles /rpc, /docs, /health) ──
50
+ await rpcHandler(req, res);
51
+ });
52
+
53
+ // Only start HTTP listener if not running inside test environment (Vitest)
54
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
55
+ const port = env.API_PORT ?? 4000;
56
+ const host = env.API_HOST ?? "0.0.0.0";
57
+ server.listen(port, host, () => {
58
+ console.log(`Server listening at http://${host}:${port}`);
59
+ });
60
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * server.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * CellsWeb RPC API Server Entrypoint — Ultimate-Express (uWebSockets.js)
5
+ */
6
+
7
+ import { CoreRPC } from "@cellsweb/rpc-core";
8
+ import express from "ultimate-express";
9
+ import { env } from "./env";
10
+ import { storage } from "./utils/storage";
11
+
12
+ export const app = new CoreRPC({
13
+ functionsDir: "./src/functions",
14
+ middlewaresDir: "./src/middlewares",
15
+ port: env.API_PORT,
16
+ host: env.API_HOST,
17
+ docs: true,
18
+ });
19
+
20
+ export const server = express();
21
+ const rpcHandler = await app.createHandler();
22
+
23
+ // ── Static Files Route (/uploads/*) ──
24
+ server.get("/uploads/*", async (req: any, res: any) => {
25
+ const filePath = decodeURIComponent(req.url.replace(/^\/uploads\//, ""));
26
+ const result = await storage.serve(filePath);
27
+ if (!result) {
28
+ res.status(404).json({
29
+ status: "error",
30
+ code: "not_found",
31
+ message: "File not found",
32
+ });
33
+ return;
34
+ }
35
+ res.setHeader("Content-Type", result.mimeType);
36
+ res.setHeader("Cache-Control", "public, max-age=86400");
37
+ res.send(result.buffer);
38
+ });
39
+
40
+ // ⚠️ IMPORTANT: Mount RPC handler BEFORE any global body parsers
41
+ server.use(rpcHandler);
42
+
43
+ // Only start HTTP listener if not running inside test environment (Vitest)
44
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
45
+ const port = env.API_PORT ?? 4000;
46
+ const host = env.API_HOST ?? "0.0.0.0";
47
+ server.listen(port, host, () => {
48
+ console.log(`Ultimate-Express server listening at http://${host}:${port}`);
49
+ });
50
+ }