create-cellsweb-rpc-api 1.0.25 → 1.0.28

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
@@ -39,8 +39,22 @@ npx create-cellsweb-rpc-api@latest my-app --framework fastify
39
39
 
40
40
  # 4. Ultimate-Express (Extreme Throughput — uWebSockets.js-backed Express drop-in)
41
41
  npx create-cellsweb-rpc-api@latest my-app --framework ultimate-express
42
+
43
+ # 5. Hono (Ultra-fast Web Standards & multi-runtime: Bun, Node.js, Deno)
44
+ npx create-cellsweb-rpc-api@latest my-app --framework hono
45
+
46
+ # 6. Elysia.js (Bun-native & TypeBox first-class)
47
+ npx create-cellsweb-rpc-api@latest my-app --framework elysia
48
+
49
+ # 7. Bun Native (Zero extra dependencies, native Bun.serve)
50
+ bun create cellsweb-rpc-api@latest my-app --framework bun
42
51
  ```
43
52
 
53
+ ### Automation & CI Flags
54
+ - `--skip-install` / `--no-install`: Skip automated package installation.
55
+ - `--yes` / `-y`: Non-interactive mode using defaults.
56
+ - `--pm [npm|pnpm|yarn|bun]`: Specify package manager explicitly.
57
+
44
58
  ---
45
59
 
46
60
  ## Supported Base Frameworks
@@ -49,8 +63,11 @@ npx create-cellsweb-rpc-api@latest my-app --framework ultimate-express
49
63
  | :--- | :--- | :--- |
50
64
  | **Vanilla Node.js** *(Default)* | *None (Zero extra deps)* | Highest raw performance directly on native `node:http`. |
51
65
  | **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()`. |
66
+ | **Fastify** | `fastify` | Fastify server with built-in plugin adapter (`app.createFastifyPlugin()`). |
53
67
  | **Ultimate-Express** | `ultimate-express` | Drop-in Express replacement powered by `uWebSockets.js` for extreme I/O throughput. |
68
+ | **Hono** | `hono`, `@hono/node-server` | Universal Web Standards engine running seamlessly across Bun, Node.js, and Edge runtimes. |
69
+ | **Elysia.js** | `elysia` | Bun-first web framework with native TypeBox alignment and high developer ergonomics. |
70
+ | **Bun Native** | *None (Zero extra deps)* | Ultra-fast execution on native `Bun.serve` with zero third-party web framework overhead. |
54
71
 
55
72
  ---
56
73
 
@@ -1,19 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * scripts/create-function.ts
3
+ * bin/create-function.js
4
4
  * ─────────────────────────────────────────────────────────────────────────────
5
- * Scaffolds a new API function with constants, run, optional middlewares, and comprehensive audit test files.
5
+ * Built-in CellsWeb RPC function generator.
6
+ * Scaffolds a new API function with constants, run, optional middlewares, and tests.
6
7
  *
7
8
  * SUPPORTED MODES:
8
9
  * 1. Interactive Mode (Default in TTY):
9
- * pnpm create:function
10
+ * crpc create:function
10
11
  *
11
12
  * 2. Single CLI Flag Mode (Non-interactive for AI Coders & Devs):
12
- * pnpm create:function --ns admin.products --name create --contentType json --middlewares auth,rateLimit
13
+ * crpc create:function --ns admin.products --name create --contentType json --middlewares auth,rateLimit
13
14
  *
14
15
  * 3. Batch Mode (Scaffold multiple functions in one command):
15
- * pnpm create:function --batch '[{"ns":"admin.products","name":"create","middlewares":["auth"]},{"ns":"admin.products","name":"delete"}]'
16
- * pnpm create:function --file specs/functions.json
16
+ * crpc create:function --batch '[{"ns":"admin.products","name":"create","middlewares":["auth"]}]'
17
+ * crpc create:function --file specs/functions.json
17
18
  */
18
19
 
19
20
  import * as p from "@clack/prompts";
@@ -23,18 +24,65 @@ import { glob } from "tinyglobby";
23
24
 
24
25
  const MAX_RETRIES = 5;
25
26
  const ROOT = process.cwd();
26
- const FUNCTIONS_DIR = path.join(ROOT, "src", "functions");
27
- const MIDDLEWARES_DIR = path.join(ROOT, "src", "middlewares");
28
-
29
- export interface ScaffoldFunctionOptions {
30
- namespace: string;
31
- name: string;
32
- contentType?: "application/json" | "multipart/form-data" | "json" | "multipart";
33
- middlewares?: string[];
34
- description?: string;
27
+
28
+ export function detectConfiguredDirs(rootDir = process.cwd()) {
29
+ let functionsDir = null;
30
+ let middlewaresDir = null;
31
+
32
+ if (process.env.RPC_FUNCTIONS_DIR) functionsDir = process.env.RPC_FUNCTIONS_DIR;
33
+ if (process.env.RPC_MIDDLEWARES_DIR) middlewaresDir = process.env.RPC_MIDDLEWARES_DIR;
34
+
35
+ if (!functionsDir || !middlewaresDir) {
36
+ const pkgPath = path.join(rootDir, "package.json");
37
+ if (fs.existsSync(pkgPath)) {
38
+ try {
39
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
40
+ if (!functionsDir && pkg.crpc?.functionsDir) functionsDir = pkg.crpc.functionsDir;
41
+ if (!middlewaresDir && pkg.crpc?.middlewaresDir) middlewaresDir = pkg.crpc.middlewaresDir;
42
+ } catch {}
43
+ }
44
+ }
45
+
46
+ if (!functionsDir || !middlewaresDir) {
47
+ const candidates = [
48
+ "src/server.ts",
49
+ "src/index.ts",
50
+ "src/app.ts",
51
+ "src/main.ts",
52
+ "server.ts",
53
+ "index.ts",
54
+ "app.ts",
55
+ ];
56
+ for (const file of candidates) {
57
+ const fullPath = path.join(rootDir, file);
58
+ if (fs.existsSync(fullPath)) {
59
+ try {
60
+ const content = fs.readFileSync(fullPath, "utf-8");
61
+ if (!functionsDir) {
62
+ const fnMatch = content.match(/functionsDir\s*:\s*["']([^"']+)["']/);
63
+ if (fnMatch) functionsDir = fnMatch[1];
64
+ }
65
+ if (!middlewaresDir) {
66
+ const mwMatch = content.match(/middlewaresDir\s*:\s*["']([^"']+)["']/);
67
+ if (mwMatch) middlewaresDir = mwMatch[1];
68
+ }
69
+ if (functionsDir && middlewaresDir) break;
70
+ } catch {}
71
+ }
72
+ }
73
+ }
74
+
75
+ return {
76
+ functionsDir: path.resolve(rootDir, functionsDir || "src/functions"),
77
+ middlewaresDir: path.resolve(rootDir, middlewaresDir || "src/middlewares"),
78
+ };
35
79
  }
36
80
 
37
- export async function getExistingNamespaces(): Promise<string[]> {
81
+ const configuredDirs = detectConfiguredDirs(ROOT);
82
+ const FUNCTIONS_DIR = configuredDirs.functionsDir;
83
+ const MIDDLEWARES_DIR = configuredDirs.middlewaresDir;
84
+
85
+ export async function getExistingNamespaces() {
38
86
  if (!fs.existsSync(FUNCTIONS_DIR)) return [];
39
87
 
40
88
  const runFiles = await glob("**/run.ts", {
@@ -43,7 +91,7 @@ export async function getExistingNamespaces(): Promise<string[]> {
43
91
  ignore: ["**/*.spec.ts", "**/__tests__/**"],
44
92
  });
45
93
 
46
- const namespaces = new Set<string>();
94
+ const namespaces = new Set();
47
95
  for (const f of runFiles) {
48
96
  const parts = f.split("/");
49
97
  if (parts.length < 3) continue;
@@ -54,7 +102,7 @@ export async function getExistingNamespaces(): Promise<string[]> {
54
102
  return Array.from(namespaces).sort();
55
103
  }
56
104
 
57
- export function getAvailableMiddlewares(): string[] {
105
+ export function getAvailableMiddlewares() {
58
106
  if (!fs.existsSync(MIDDLEWARES_DIR)) return [];
59
107
  return fs
60
108
  .readdirSync(MIDDLEWARES_DIR, { withFileTypes: true })
@@ -66,7 +114,7 @@ export function getAvailableMiddlewares(): string[] {
66
114
  const identifierRe = /^[a-zA-Z][a-zA-Z0-9]*$/;
67
115
  const namespaceRe = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/;
68
116
 
69
- function tplConstants(ns: string, fn: string, isMultipart: boolean, desc?: string): string {
117
+ function tplConstants(ns, fn, isMultipart, desc) {
70
118
  const nsPath = ns.replace(/\./g, "/");
71
119
  const descriptionStr = desc || `TODO: describe ${fn}`;
72
120
 
@@ -154,7 +202,7 @@ export const outputSchema = Type.Object({
154
202
  `;
155
203
  }
156
204
 
157
- function tplRun(ns: string, fn: string, isMultipart: boolean, mws: string[]): string {
205
+ function tplRun(ns, fn, isMultipart, mws) {
158
206
  const nsPath = ns.replace(/\./g, "/");
159
207
  let contextTypeStr = "MiddlewareContext";
160
208
  let importContextStr = 'import type { MiddlewareContext } from "@cellsweb/rpc-core";';
@@ -237,7 +285,7 @@ export const run = async (
237
285
  `;
238
286
  }
239
287
 
240
- function tplMiddlewares(ns: string, fn: string, mws: string[]): string {
288
+ function tplMiddlewares(ns, fn, mws) {
241
289
  const nsPath = ns.replace(/\./g, "/");
242
290
  const entries = mws
243
291
  .map((mw) => {
@@ -267,8 +315,9 @@ ${entries}
267
315
  `;
268
316
  }
269
317
 
270
- function tplTest(ns: string, fn: string, isMultipart: boolean): string {
318
+ function tplTest(ns, fn, isMultipart, mws = []) {
271
319
  const nsPath = ns.replace(/\./g, "/");
320
+ const hasAuth = mws.includes("auth");
272
321
 
273
322
  if (isMultipart) {
274
323
  return `/**
@@ -349,7 +398,7 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
349
398
  });
350
399
 
351
400
  it("enforces security guards and blocks unprivileged access", async () => {
352
- if (!metadata.isPublic) {
401
+ if (${hasAuth}) {
353
402
  const guestActor = await createTestActor({ role: "unprivileged_guest" });
354
403
  const res = await guestActor.callRaw("${ns}.${fn}", { title: "Unauthorized Attempt" });
355
404
  expect(res.status).toBe("error");
@@ -432,7 +481,7 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
432
481
  });
433
482
 
434
483
  it("enforces security guards and blocks unprivileged access", async () => {
435
- if (!metadata.isPublic) {
484
+ if (${hasAuth}) {
436
485
  const guestActor = await createTestActor({ role: "unprivileged_guest" });
437
486
  const res = await guestActor.callRaw("${ns}.${fn}", { example: "Unauthorized attempt" });
438
487
  expect(res.status).toBe("error");
@@ -455,28 +504,27 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
455
504
  /**
456
505
  * Programmatic function scaffolder.
457
506
  */
458
- export async function scaffoldFunction(
459
- options: ScaffoldFunctionOptions | Record<string, any>,
460
- ): Promise<string> {
461
- const namespace = options.namespace || (options as any).ns;
462
- const name = options.name || (options as any).fn || (options as any).functionName;
507
+ export async function scaffoldFunction(options) {
508
+ const namespace = options.namespace || options.ns;
509
+ const name = options.name || options.fn || options.functionName;
463
510
  if (!namespace || !name) {
464
511
  throw new Error(`Both namespace and name are required. Received: ${JSON.stringify(options)}`);
465
512
  }
466
513
 
467
514
  const middlewares = options.middlewares || [];
468
515
  const description = options.description;
469
- const contentType = options.contentType || (options as any).type;
516
+ const contentType = options.contentType || options.type;
470
517
  const isMultipart =
471
518
  contentType === "multipart/form-data" || contentType === "multipart";
472
519
 
473
- const nsDir = path.join(FUNCTIONS_DIR, namespace.replace(/\./g, path.sep));
520
+ const targetDir = options.targetDir || FUNCTIONS_DIR;
521
+ const nsDir = path.join(targetDir, namespace.replace(/\./g, path.sep));
474
522
  const fnDir = path.join(nsDir, name);
475
523
 
476
524
  fs.mkdirSync(fnDir, { recursive: true });
477
525
  fs.writeFileSync(path.join(fnDir, "constants.ts"), tplConstants(namespace, name, isMultipart, description));
478
526
  fs.writeFileSync(path.join(fnDir, "run.ts"), tplRun(namespace, name, isMultipart, middlewares));
479
- fs.writeFileSync(path.join(fnDir, "test.ts"), tplTest(namespace, name, isMultipart));
527
+ fs.writeFileSync(path.join(fnDir, "test.ts"), tplTest(namespace, name, isMultipart, middlewares));
480
528
 
481
529
  if (middlewares.length > 0) {
482
530
  fs.writeFileSync(path.join(fnDir, "middlewares.ts"), tplMiddlewares(namespace, name, middlewares));
@@ -485,20 +533,17 @@ export async function scaffoldFunction(
485
533
  return fnDir;
486
534
  }
487
535
 
488
- function parseCliArgs(): {
489
- isCli: boolean;
490
- batch?: ScaffoldFunctionOptions[];
491
- single?: ScaffoldFunctionOptions;
492
- } {
536
+ function parseCliArgs() {
493
537
  const args = process.argv.slice(2);
494
538
  if (args.length === 0) return { isCli: false };
495
539
 
496
- let batchJson: string | undefined;
497
- let filePath: string | undefined;
498
- let namespace: string | undefined;
499
- let name: string | undefined;
500
- let contentType: "json" | "multipart" | undefined;
501
- let middlewares: string[] = [];
540
+ let batchJson;
541
+ let filePath;
542
+ let namespace;
543
+ let name;
544
+ let contentType;
545
+ let middlewares = [];
546
+ let targetDir = FUNCTIONS_DIR;
502
547
 
503
548
  for (let i = 0; i < args.length; i++) {
504
549
  const arg = args[i];
@@ -515,19 +560,23 @@ function parseCliArgs(): {
515
560
  contentType = ct.includes("multipart") ? "multipart" : "json";
516
561
  } else if (arg === "--middlewares" && args[i + 1]) {
517
562
  middlewares = args[++i].split(",").map((s) => s.trim()).filter(Boolean);
563
+ } else if ((arg === "--functionsDir" || arg === "--dir") && args[i + 1]) {
564
+ targetDir = path.resolve(ROOT, args[++i]);
518
565
  }
519
566
  }
520
567
 
521
568
  if (filePath) {
522
569
  const fileContent = fs.readFileSync(path.resolve(ROOT, filePath), "utf-8");
523
570
  const parsed = JSON.parse(fileContent);
524
- const batch = Array.isArray(parsed) ? parsed : [parsed];
571
+ const list = Array.isArray(parsed) ? parsed : [parsed];
572
+ const batch = list.map((item) => (targetDir ? { targetDir, ...item } : item));
525
573
  return { isCli: true, batch };
526
574
  }
527
575
 
528
576
  if (batchJson) {
529
577
  const parsed = JSON.parse(batchJson);
530
- const batch = Array.isArray(parsed) ? parsed : [parsed];
578
+ const list = Array.isArray(parsed) ? parsed : [parsed];
579
+ const batch = list.map((item) => (targetDir ? { targetDir, ...item } : item));
531
580
  return { isCli: true, batch };
532
581
  }
533
582
 
@@ -539,6 +588,7 @@ function parseCliArgs(): {
539
588
  name,
540
589
  contentType,
541
590
  middlewares,
591
+ targetDir,
542
592
  },
543
593
  };
544
594
  }
@@ -546,7 +596,7 @@ function parseCliArgs(): {
546
596
  return { isCli: false };
547
597
  }
548
598
 
549
- async function main(): Promise<void> {
599
+ async function main() {
550
600
  const cliArgs = parseCliArgs();
551
601
 
552
602
  // ── 1. Batch or CLI Flags Mode (Non-interactive) ──
@@ -555,8 +605,8 @@ async function main(): Promise<void> {
555
605
  console.log(`Scaffolding batch of ${cliArgs.batch.length} functions...`);
556
606
  for (const item of cliArgs.batch) {
557
607
  const fnDir = await scaffoldFunction(item);
558
- const nsName = item.namespace || (item as any).ns;
559
- const fName = item.name || (item as any).fn || (item as any).functionName;
608
+ const nsName = item.namespace || item.ns;
609
+ const fName = item.name || item.fn || item.functionName;
560
610
  console.log(` ✔ Created: ${nsName}.${fName} -> ${path.relative(ROOT, fnDir)}`);
561
611
  }
562
612
  console.log("Batch function scaffolding complete.");
@@ -586,7 +636,7 @@ async function main(): Promise<void> {
586
636
  });
587
637
  if (p.isCancel(nsPick)) { p.cancel("Cancelled."); process.exit(0); }
588
638
 
589
- let namespace: string;
639
+ let namespace;
590
640
  if (nsPick === "__new__") {
591
641
  const custom = await p.text({
592
642
  message: "New namespace",
@@ -597,9 +647,9 @@ async function main(): Promise<void> {
597
647
  },
598
648
  });
599
649
  if (p.isCancel(custom)) { p.cancel("Cancelled."); process.exit(0); }
600
- namespace = (custom as string).trim();
650
+ namespace = custom.trim();
601
651
  } else {
602
- namespace = nsPick as string;
652
+ namespace = nsPick;
603
653
  }
604
654
 
605
655
  const nsDir = path.join(FUNCTIONS_DIR, namespace.replace(/\./g, path.sep));
@@ -617,7 +667,7 @@ async function main(): Promise<void> {
617
667
  });
618
668
  if (p.isCancel(raw)) { p.cancel("Cancelled."); process.exit(0); }
619
669
 
620
- const name = (raw as string).trim();
670
+ const name = raw.trim();
621
671
  if (fs.existsSync(path.join(nsDir, name))) {
622
672
  const remaining = MAX_RETRIES - attempt - 1;
623
673
  if (remaining === 0) {
@@ -643,7 +693,7 @@ async function main(): Promise<void> {
643
693
  const isMultipart = contentTypePick === "multipart/form-data";
644
694
 
645
695
  const available = getAvailableMiddlewares();
646
- let selectedMws: string[] = [];
696
+ let selectedMws = [];
647
697
 
648
698
  if (available.length > 0) {
649
699
  const pick = await p.multiselect({
@@ -652,7 +702,7 @@ async function main(): Promise<void> {
652
702
  required: false,
653
703
  });
654
704
  if (p.isCancel(pick)) { p.cancel("Cancelled."); process.exit(0); }
655
- selectedMws = pick as string[];
705
+ selectedMws = pick;
656
706
  }
657
707
 
658
708
  const fnDir = path.join(nsDir, functionName);
@@ -669,7 +719,7 @@ async function main(): Promise<void> {
669
719
  spin.stop("Done");
670
720
  } catch (err) {
671
721
  spin.stop("Failed");
672
- p.log.error((err as Error).message);
722
+ p.log.error(err.message);
673
723
  process.exit(1);
674
724
  }
675
725
 
@@ -1,19 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * scripts/create-middleware.ts
3
+ * bin/create-middleware.js
4
4
  * ─────────────────────────────────────────────────────────────────────────────
5
+ * Built-in CellsWeb RPC middleware generator.
5
6
  * Scaffolds new central middlewares with constants, run, and unit tests.
6
7
  *
7
8
  * SUPPORTED MODES:
8
9
  * 1. Interactive Mode (Default in TTY):
9
- * pnpm create:middleware
10
+ * crpc create:middleware
10
11
  *
11
12
  * 2. Single CLI Flag Mode (Non-interactive for AI Coders & Devs):
12
- * pnpm create:middleware --name tenantResolver --description "Resolves organization tenant"
13
+ * crpc create:middleware --name tenantResolver --description "Resolves organization tenant"
13
14
  *
14
15
  * 3. Batch Mode:
15
- * pnpm create:middleware --batch '["auth","rateLimit","tenantResolver"]'
16
- * pnpm create:middleware --file specs/middlewares.json
16
+ * crpc create:middleware --batch '["auth","rateLimit","tenantResolver"]'
17
+ * crpc create:middleware --file specs/middlewares.json
17
18
  */
18
19
 
19
20
  import * as p from "@clack/prompts";
@@ -22,16 +23,66 @@ import path from "node:path";
22
23
 
23
24
  const MAX_RETRIES = 5;
24
25
  const ROOT = process.cwd();
25
- const MIDDLEWARES_DIR = path.join(ROOT, "src", "middlewares");
26
26
 
27
- export interface ScaffoldMiddlewareOptions {
28
- name: string;
29
- description?: string;
27
+ export function detectConfiguredDirs(rootDir = process.cwd()) {
28
+ let functionsDir = null;
29
+ let middlewaresDir = null;
30
+
31
+ if (process.env.RPC_FUNCTIONS_DIR) functionsDir = process.env.RPC_FUNCTIONS_DIR;
32
+ if (process.env.RPC_MIDDLEWARES_DIR) middlewaresDir = process.env.RPC_MIDDLEWARES_DIR;
33
+
34
+ if (!functionsDir || !middlewaresDir) {
35
+ const pkgPath = path.join(rootDir, "package.json");
36
+ if (fs.existsSync(pkgPath)) {
37
+ try {
38
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
39
+ if (!functionsDir && pkg.crpc?.functionsDir) functionsDir = pkg.crpc.functionsDir;
40
+ if (!middlewaresDir && pkg.crpc?.middlewaresDir) middlewaresDir = pkg.crpc.middlewaresDir;
41
+ } catch {}
42
+ }
43
+ }
44
+
45
+ if (!functionsDir || !middlewaresDir) {
46
+ const candidates = [
47
+ "src/server.ts",
48
+ "src/index.ts",
49
+ "src/app.ts",
50
+ "src/main.ts",
51
+ "server.ts",
52
+ "index.ts",
53
+ "app.ts",
54
+ ];
55
+ for (const file of candidates) {
56
+ const fullPath = path.join(rootDir, file);
57
+ if (fs.existsSync(fullPath)) {
58
+ try {
59
+ const content = fs.readFileSync(fullPath, "utf-8");
60
+ if (!functionsDir) {
61
+ const fnMatch = content.match(/functionsDir\s*:\s*["']([^"']+)["']/);
62
+ if (fnMatch) functionsDir = fnMatch[1];
63
+ }
64
+ if (!middlewaresDir) {
65
+ const mwMatch = content.match(/middlewaresDir\s*:\s*["']([^"']+)["']/);
66
+ if (mwMatch) middlewaresDir = mwMatch[1];
67
+ }
68
+ if (functionsDir && middlewaresDir) break;
69
+ } catch {}
70
+ }
71
+ }
72
+ }
73
+
74
+ return {
75
+ functionsDir: path.resolve(rootDir, functionsDir || "src/functions"),
76
+ middlewaresDir: path.resolve(rootDir, middlewaresDir || "src/middlewares"),
77
+ };
30
78
  }
31
79
 
80
+ const configuredDirs = detectConfiguredDirs(ROOT);
81
+ const MIDDLEWARES_DIR = configuredDirs.middlewaresDir;
82
+
32
83
  const identifierRe = /^[a-zA-Z][a-zA-Z0-9]*$/;
33
84
 
34
- function tplConstants(name: string, desc?: string): string {
85
+ function tplConstants(name, desc) {
35
86
  const descriptionStr = desc || `Enforces security policies or request transformations for ${name}`;
36
87
 
37
88
  return `/**
@@ -62,7 +113,7 @@ export const optionsSchema = Type.Object({
62
113
  `;
63
114
  }
64
115
 
65
- function tplRun(name: string): string {
116
+ function tplRun(name) {
66
117
  return `/**
67
118
  * middlewares/${name}/run.ts
68
119
  * ─────────────────────────────────────────────────────────────────────────────
@@ -102,7 +153,7 @@ export const run: MiddlewareFn<Options, { ${name}: string }> = async (
102
153
  `;
103
154
  }
104
155
 
105
- function tplTest(name: string): string {
156
+ function tplTest(name) {
106
157
  return `/**
107
158
  * middlewares/${name}/test.ts
108
159
  * ─────────────────────────────────────────────────────────────────────────────
@@ -140,9 +191,10 @@ describe("middleware: ${name}", () => {
140
191
  /**
141
192
  * Programmatic middleware scaffolder.
142
193
  */
143
- export async function scaffoldMiddleware(options: ScaffoldMiddlewareOptions): Promise<string> {
194
+ export async function scaffoldMiddleware(options) {
144
195
  const { name, description } = options;
145
- const mwDir = path.join(MIDDLEWARES_DIR, name);
196
+ const targetDir = options.targetDir || MIDDLEWARES_DIR;
197
+ const mwDir = path.join(targetDir, name);
146
198
 
147
199
  fs.mkdirSync(mwDir, { recursive: true });
148
200
  fs.writeFileSync(path.join(mwDir, "constants.ts"), tplConstants(name, description));
@@ -152,18 +204,15 @@ export async function scaffoldMiddleware(options: ScaffoldMiddlewareOptions): Pr
152
204
  return mwDir;
153
205
  }
154
206
 
155
- function parseCliArgs(): {
156
- isCli: boolean;
157
- batch?: ScaffoldMiddlewareOptions[];
158
- single?: ScaffoldMiddlewareOptions;
159
- } {
207
+ function parseCliArgs() {
160
208
  const args = process.argv.slice(2);
161
209
  if (args.length === 0) return { isCli: false };
162
210
 
163
- let batchJson: string | undefined;
164
- let filePath: string | undefined;
165
- let name: string | undefined;
166
- let description: string | undefined;
211
+ let batchJson;
212
+ let filePath;
213
+ let name;
214
+ let description;
215
+ let targetDir = MIDDLEWARES_DIR;
167
216
 
168
217
  for (let i = 0; i < args.length; i++) {
169
218
  const arg = args[i];
@@ -175,6 +224,8 @@ function parseCliArgs(): {
175
224
  name = args[++i];
176
225
  } else if ((arg === "--description" || arg === "-d") && args[i + 1]) {
177
226
  description = args[++i];
227
+ } else if ((arg === "--middlewaresDir" || arg === "--dir") && args[i + 1]) {
228
+ targetDir = path.resolve(ROOT, args[++i]);
178
229
  }
179
230
  }
180
231
 
@@ -182,28 +233,34 @@ function parseCliArgs(): {
182
233
  const fileContent = fs.readFileSync(path.resolve(ROOT, filePath), "utf-8");
183
234
  const parsed = JSON.parse(fileContent);
184
235
  const list = Array.isArray(parsed) ? parsed : [parsed];
185
- const batch = list.map((item) => (typeof item === "string" ? { name: item } : item));
236
+ const batch = list.map((item) => {
237
+ const obj = typeof item === "string" ? { name: item } : item;
238
+ return targetDir ? { targetDir, ...obj } : obj;
239
+ });
186
240
  return { isCli: true, batch };
187
241
  }
188
242
 
189
243
  if (batchJson) {
190
244
  const parsed = JSON.parse(batchJson);
191
245
  const list = Array.isArray(parsed) ? parsed : [parsed];
192
- const batch = list.map((item) => (typeof item === "string" ? { name: item } : item));
246
+ const batch = list.map((item) => {
247
+ const obj = typeof item === "string" ? { name: item } : item;
248
+ return targetDir ? { targetDir, ...obj } : obj;
249
+ });
193
250
  return { isCli: true, batch };
194
251
  }
195
252
 
196
253
  if (name) {
197
254
  return {
198
255
  isCli: true,
199
- single: { name, description },
256
+ single: { name, description, targetDir },
200
257
  };
201
258
  }
202
259
 
203
260
  return { isCli: false };
204
261
  }
205
262
 
206
- async function main(): Promise<void> {
263
+ async function main() {
207
264
  const cliArgs = parseCliArgs();
208
265
 
209
266
  // ── 1. Batch or CLI Flags Mode (Non-interactive) ──
@@ -244,7 +301,7 @@ async function main(): Promise<void> {
244
301
  });
245
302
  if (p.isCancel(raw)) { p.cancel("Cancelled."); process.exit(0); }
246
303
 
247
- const name = (raw as string).trim();
304
+ const name = raw.trim();
248
305
  if (fs.existsSync(path.join(MIDDLEWARES_DIR, name))) {
249
306
  const remaining = MAX_RETRIES - attempt - 1;
250
307
  if (remaining === 0) {
@@ -268,7 +325,7 @@ async function main(): Promise<void> {
268
325
  spin.stop("Done");
269
326
  } catch (err) {
270
327
  spin.stop("Failed");
271
- p.log.error((err as Error).message);
328
+ p.log.error(err.message);
272
329
  process.exit(1);
273
330
  }
274
331
 
package/bin/create.js CHANGED
@@ -93,6 +93,10 @@ async function main() {
93
93
  args.includes("--yes") ||
94
94
  args.includes("--non-interactive");
95
95
 
96
+ const skipInstall =
97
+ args.includes("--skip-install") ||
98
+ args.includes("--no-install");
99
+
96
100
  let explicitName = null;
97
101
  const nameFlagIdx = args.findIndex((arg) => arg === "--name" || arg === "-n");
98
102
  if (nameFlagIdx !== -1 && args[nameFlagIdx + 1]) {
@@ -122,6 +126,9 @@ async function main() {
122
126
  if (str === "2" || str === "express") return "express";
123
127
  if (str === "3" || str === "fastify") return "fastify";
124
128
  if (str === "4" || str === "ultimate-express" || str === "ultimate" || str === "ue") return "ultimate-express";
129
+ if (str === "5" || str === "hono") return "hono";
130
+ if (str === "6" || str === "elysia" || str === "elysiajs" || str === "elysia.js") return "elysia";
131
+ if (str === "7" || str === "bun" || str === "bun-native" || str === "bun native") return "bun";
125
132
  return "node";
126
133
  }
127
134
 
@@ -154,8 +161,8 @@ async function main() {
154
161
  } else {
155
162
  projectName = explicitName || (await ask("Package name", defaultName));
156
163
  const pmAnswer =
157
- explicitPm || (await ask("Package manager [npm / pnpm / yarn]", "pnpm"));
158
- pm = ["npm", "pnpm", "yarn"].includes(pmAnswer) ? pmAnswer : "pnpm";
164
+ explicitPm || (await ask("Package manager [npm / pnpm / yarn / bun]", "pnpm"));
165
+ pm = ["npm", "pnpm", "yarn", "bun"].includes(pmAnswer) ? pmAnswer : "pnpm";
159
166
 
160
167
  if (explicitFramework) {
161
168
  framework = normalizeFramework(explicitFramework);
@@ -165,7 +172,10 @@ async function main() {
165
172
  console.log(` ${cyan("2)")} Express ${dim("(Standard — easiest for traditional REST routes & middlewares)")}`);
166
173
  console.log(` ${cyan("3)")} Fastify ${dim("(High performance & rich plugin ecosystem)")}`);
167
174
  console.log(` ${cyan("4)")} Ultimate-Express ${dim("(uWebSockets.js-backed Express drop-in)")}`);
168
- const fwAnswer = await ask("Choose framework [1/2/3/4]", "1");
175
+ console.log(` ${cyan("5)")} Hono ${dim("(Ultra-fast Web Standards & multi-runtime: Bun, Deno, Node)")}`);
176
+ console.log(` ${cyan("6)")} Elysia.js ${dim("(Bun-native & TypeBox first-class)")}`);
177
+ console.log(` ${cyan("7)")} Bun Native ${dim("(Zero extra dependencies, native Bun.serve)")}`);
178
+ const fwAnswer = await ask("Choose framework [1/2/3/4/5/6/7]", "1");
169
179
  framework = normalizeFramework(fwAnswer);
170
180
  }
171
181
  rl.close();
@@ -210,8 +220,7 @@ async function main() {
210
220
  node: ">=20.0.0",
211
221
  },
212
222
  dependencies: {
213
- "@cellsweb/rpc-core": "^1.0.29",
214
- "create-cellsweb-rpc-api": "^1.0.25",
223
+ "@cellsweb/rpc-core": "^1.0.32",
215
224
  "@aws-sdk/client-s3": "^3.700.0",
216
225
  "@paralleldrive/cuid2": "^2.2.2",
217
226
  "@sentry/node": "^8.40.0",
@@ -226,7 +235,6 @@ async function main() {
226
235
  "tinyglobby": "^0.2.12",
227
236
  },
228
237
  devDependencies: {
229
- "@clack/prompts": "^1.4.0",
230
238
  "@types/busboy": "^1.5.4",
231
239
  "@types/mime-types": "^3.0.1",
232
240
  "@types/node": "^22.15.18",
@@ -252,6 +260,13 @@ async function main() {
252
260
  } else if (framework === "ultimate-express") {
253
261
  pkg.dependencies["ultimate-express"] = "^2.2.1";
254
262
  pkg.devDependencies["@types/express"] = "^5.0.0";
263
+ } else if (framework === "hono") {
264
+ pkg.dependencies["hono"] = "^4.7.0";
265
+ pkg.dependencies["@hono/node-server"] = "^1.13.8";
266
+ } else if (framework === "elysia") {
267
+ pkg.dependencies["elysia"] = "^1.2.0";
268
+ } else if (framework === "bun") {
269
+ // Bun native requires zero extra dependencies!
255
270
  }
256
271
 
257
272
  fs.writeFileSync(path.join(targetDir, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
@@ -279,29 +294,7 @@ async function main() {
279
294
  };
280
295
  fs.writeFileSync(path.join(targetDir, "tsconfig.json"), JSON.stringify(tsconfig, null, 2) + "\n");
281
296
 
282
- // ── 6. Write scripts/tsconfig.json ────────────────────────────────────────
283
- const scriptsTsconfig = {
284
- compilerOptions: {
285
- target: "ES2023",
286
- module: "nodenext",
287
- moduleResolution: "nodenext",
288
- lib: ["ES2023"],
289
- types: ["node"],
290
- strict: true,
291
- esModuleInterop: true,
292
- skipLibCheck: true,
293
- resolveJsonModule: true,
294
- noEmit: true,
295
- paths: { "@/*": ["../src/*"] },
296
- },
297
- include: ["./**/*"],
298
- exclude: ["node_modules"],
299
- };
300
- const scriptsDir = path.join(targetDir, "scripts");
301
- fs.mkdirSync(scriptsDir, { recursive: true });
302
- fs.writeFileSync(path.join(scriptsDir, "tsconfig.json"), JSON.stringify(scriptsTsconfig, null, 2) + "\n");
303
-
304
- // ── 7. Write .gitignore & .npmrc ──────────────────────────────────────────
297
+ // ── 6. Write .gitignore & .npmrc ──────────────────────────────────────────
305
298
  const gitignore = ["node_modules", "dist", ".env", "*.log", ".DS_Store"].join("\n") + "\n";
306
299
  const giPath = path.join(targetDir, ".gitignore");
307
300
  if (!fs.existsSync(giPath)) fs.writeFileSync(giPath, gitignore);
@@ -318,15 +311,19 @@ async function main() {
318
311
  }
319
312
 
320
313
  // ── 8. Install ────────────────────────────────────────────────────────────
321
- console.log(` ${dim("Installing dependencies with")} ${bold(pm)} ...\n`);
322
- try {
323
- const installCmd =
324
- pm === "pnpm"
325
- ? "pnpm install || (pnpm approve-builds esbuild && pnpm install)"
326
- : `${pm} install`;
327
- execSync(installCmd, { cwd: targetDir, stdio: "inherit" });
328
- } catch {
329
- console.log(` ${yellow("⚠")} Install failed — run ${bold(`${pm} install`)} manually.\n`);
314
+ if (!skipInstall) {
315
+ console.log(` ${dim("Installing dependencies with")} ${bold(pm)} ...\n`);
316
+ try {
317
+ const installCmd =
318
+ pm === "pnpm"
319
+ ? "pnpm install || (pnpm approve-builds esbuild && pnpm install)"
320
+ : `${pm} install`;
321
+ execSync(installCmd, { cwd: targetDir, stdio: "inherit" });
322
+ } catch {
323
+ console.log(` ${yellow("⚠")} Install failed — run ${bold(`${pm} install`)} manually.\n`);
324
+ }
325
+ } else {
326
+ console.log(` ${dim("Skipping dependency installation (--skip-install).")}\n`);
330
327
  }
331
328
 
332
329
  // ── 9. Done ───────────────────────────────────────────────────────────────
@@ -335,6 +332,9 @@ async function main() {
335
332
  express: "Express",
336
333
  fastify: "Fastify",
337
334
  "ultimate-express": "Ultimate-Express (uWebSockets.js)",
335
+ hono: "Hono (Web Standards & Multi-Runtime)",
336
+ elysia: "Elysia.js (Bun-Native & TypeBox)",
337
+ bun: "Bun Native (native Bun.serve)",
338
338
  };
339
339
 
340
340
  console.log(`
package/bin/crpc.js CHANGED
@@ -5,15 +5,18 @@
5
5
  * CellsWeb RPC Universal Framework CLI (crpc)
6
6
  *
7
7
  * Provides a unified, zero-config CLI for development, building, testing,
8
- * security auditing, and production serving with flexible entrypoint detection.
8
+ * security auditing, and code scaffolding with flexible runtime detection.
9
9
  */
10
10
 
11
11
  import { spawn } from "node:child_process";
12
12
  import fs from "node:fs";
13
13
  import path from "node:path";
14
+ import { fileURLToPath } from "node:url";
14
15
 
16
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
17
  const [,, command, ...args] = process.argv;
16
18
  const rootDir = process.cwd();
19
+ const isBun = typeof process.versions.bun !== "undefined";
17
20
 
18
21
  function getPackageJson() {
19
22
  const pkgPath = path.join(rootDir, "package.json");
@@ -131,12 +134,13 @@ async function main() {
131
134
  const remainingArgs = explicitArg ? args.filter((a) => a !== explicitArg) : args;
132
135
  const entryFile = resolveDevEntry(explicitArg);
133
136
 
134
- console.log(`⚡ Starting CellsWeb RPC Development Server (${entryFile})...`);
135
- const code = await runChild(
136
- "npx",
137
- ["tsx", "watch", "--clear-screen=false", entryFile, ...remainingArgs],
138
- { NODE_ENV: "development" },
139
- );
137
+ console.log(`⚡ Starting CellsWeb RPC Development Server (${entryFile})${isBun ? " [Bun]" : ""}...`);
138
+ const runner = isBun ? "bun" : "npx";
139
+ const runnerArgs = isBun
140
+ ? ["--watch", entryFile, ...remainingArgs]
141
+ : ["tsx", "watch", "--clear-screen=false", entryFile, ...remainingArgs];
142
+
143
+ const code = await runChild(runner, runnerArgs, { NODE_ENV: "development" });
140
144
  process.exit(code);
141
145
  break;
142
146
  }
@@ -161,8 +165,9 @@ async function main() {
161
165
  const remainingArgs = explicitArg ? args.filter((a) => a !== explicitArg) : args;
162
166
  const entryFile = resolveStartEntry(explicitArg);
163
167
 
164
- console.log(`🚀 Starting CellsWeb RPC Production Server (${entryFile})...`);
165
- const code = await runChild("node", [entryFile, ...remainingArgs], {
168
+ console.log(`🚀 Starting CellsWeb RPC Production Server (${entryFile})${isBun ? " [Bun]" : ""}...`);
169
+ const runner = isBun ? "bun" : "node";
170
+ const code = await runChild(runner, [entryFile, ...remainingArgs], {
166
171
  NODE_ENV: "production",
167
172
  });
168
173
  process.exit(code);
@@ -209,14 +214,38 @@ async function main() {
209
214
  }
210
215
 
211
216
  case "create:function": {
212
- const code = await runChild("npx", ["tsx", "scripts/create-function.ts", ...args]);
213
- process.exit(code);
217
+ // 1. Check for project-level custom override (backward compatibility)
218
+ const localScript = path.join(rootDir, "scripts", "create-function.ts");
219
+ if (fs.existsSync(localScript)) {
220
+ const runner = isBun ? "bun" : "npx";
221
+ const runnerArgs = isBun ? [localScript, ...args] : ["tsx", localScript, ...args];
222
+ const code = await runChild(runner, runnerArgs);
223
+ process.exit(code);
224
+ } else {
225
+ // 2. Built-in generator
226
+ const builtinScript = path.join(__dirname, "create-function.js");
227
+ const runner = isBun ? "bun" : "node";
228
+ const code = await runChild(runner, [builtinScript, ...args]);
229
+ process.exit(code);
230
+ }
214
231
  break;
215
232
  }
216
233
 
217
234
  case "create:middleware": {
218
- const code = await runChild("npx", ["tsx", "scripts/create-middleware.ts", ...args]);
219
- process.exit(code);
235
+ // 1. Check for project-level custom override (backward compatibility)
236
+ const localScript = path.join(rootDir, "scripts", "create-middleware.ts");
237
+ if (fs.existsSync(localScript)) {
238
+ const runner = isBun ? "bun" : "npx";
239
+ const runnerArgs = isBun ? [localScript, ...args] : ["tsx", localScript, ...args];
240
+ const code = await runChild(runner, runnerArgs);
241
+ process.exit(code);
242
+ } else {
243
+ // 2. Built-in generator
244
+ const builtinScript = path.join(__dirname, "create-middleware.js");
245
+ const runner = isBun ? "bun" : "node";
246
+ const code = await runChild(runner, [builtinScript, ...args]);
247
+ process.exit(code);
248
+ }
220
249
  break;
221
250
  }
222
251
 
@@ -225,9 +254,9 @@ async function main() {
225
254
  CellsWeb RPC CLI (crpc)
226
255
 
227
256
  Usage:
228
- crpc dev [entry] Start live development server with auto-reload (auto-resolves src/server.ts, src/index.ts, etc.)
229
- crpc build Compile TypeScript to production JavaScript with full ESM resolution
230
- crpc start [entry] Run compiled production server (auto-resolves package.json main / dist/server.js, etc.)
257
+ crpc dev [entry] Start live development server with auto-reload (src/server.ts, etc.)
258
+ crpc build Compile TypeScript with production ESM resolution (tsc + tsc-alias -f)
259
+ crpc start [entry] Run compiled production server (dist/server.js, etc.)
231
260
  crpc test Run Vitest unit and integration test suites
232
261
  crpc test:watch Run Vitest in watch mode
233
262
  crpc test:coverage Run Vitest with code coverage report
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-cellsweb-rpc-api",
3
- "version": "1.0.25",
3
+ "version": "1.0.28",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -0,0 +1,75 @@
1
+ /**
2
+ * server.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * CellsWeb RPC API Server Entrypoint — Bun Native
5
+ */
6
+
7
+ import { CoreRPC } from "@cellsweb/rpc-core";
8
+ import { env } from "./env";
9
+ import { storage } from "./utils/storage";
10
+
11
+ export const app = new CoreRPC({
12
+ functionsDir: "./src/functions",
13
+ middlewaresDir: "./src/middlewares",
14
+ port: env.API_PORT,
15
+ host: env.API_HOST,
16
+ docs: true,
17
+ });
18
+
19
+ export const fetchHandler = async (req: Request): Promise<Response> => {
20
+ const url = new URL(req.url);
21
+
22
+ // ── Static Files Route (/uploads/*) ──
23
+ if (url.pathname.startsWith("/uploads/")) {
24
+ const filePath = decodeURIComponent(url.pathname.replace(/^\/uploads\//, ""));
25
+ const result = await storage.serve(filePath);
26
+ if (!result) {
27
+ return new Response(
28
+ JSON.stringify({
29
+ status: "error",
30
+ code: "not_found",
31
+ message: "File not found",
32
+ }),
33
+ {
34
+ status: 404,
35
+ headers: { "Content-Type": "application/json" },
36
+ },
37
+ );
38
+ }
39
+ return new Response(result.buffer, {
40
+ status: 200,
41
+ headers: {
42
+ "Content-Type": result.mimeType,
43
+ "Cache-Control": "public, max-age=86400",
44
+ },
45
+ });
46
+ }
47
+
48
+ // ── Dispatch to CellsWeb RPC (Handles /rpc, /docs, /health, OPTIONS) ──
49
+ return await app.fetch(req);
50
+ };
51
+
52
+ // Bun default export supports `bun run src/server.ts`
53
+ export default {
54
+ port: env.API_PORT ?? 4000,
55
+ hostname: env.API_HOST ?? "0.0.0.0",
56
+ fetch: fetchHandler,
57
+ };
58
+
59
+ // Start server if executed directly in Bun runtime
60
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
61
+ const port = env.API_PORT ?? 4000;
62
+ const host = env.API_HOST ?? "0.0.0.0";
63
+ if (typeof (globalThis as any).Bun !== "undefined") {
64
+ (globalThis as any).Bun.serve({
65
+ port,
66
+ hostname: host,
67
+ fetch: fetchHandler,
68
+ });
69
+ console.log(`Bun native server listening at http://${host}:${port}`);
70
+ } else {
71
+ // Fallback if started on Node.js
72
+ console.log(`Starting via app.start() fallback on Node.js...`);
73
+ await app.start();
74
+ }
75
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * server.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * CellsWeb RPC API Server Entrypoint — Elysia.js
5
+ */
6
+
7
+ import { CoreRPC, createElysiaPlugin } from "@cellsweb/rpc-core";
8
+ import { Elysia } from "elysia";
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 = new Elysia();
21
+
22
+ // ── Static Files Route (/uploads/*) ──
23
+ server.get("/uploads/*", async ({ path }) => {
24
+ const filePath = decodeURIComponent(path.replace(/^\/uploads\//, ""));
25
+ const result = await storage.serve(filePath);
26
+ if (!result) {
27
+ return new Response(
28
+ JSON.stringify({
29
+ status: "error",
30
+ code: "not_found",
31
+ message: "File not found",
32
+ }),
33
+ {
34
+ status: 404,
35
+ headers: { "Content-Type": "application/json" },
36
+ },
37
+ );
38
+ }
39
+ return new Response(result.buffer, {
40
+ status: 200,
41
+ headers: {
42
+ "Content-Type": result.mimeType,
43
+ "Cache-Control": "public, max-age=86400",
44
+ },
45
+ });
46
+ });
47
+
48
+ // ── Register CellsWeb RPC Plugin (Handles /rpc, /docs, /health) ──
49
+ server.use(createElysiaPlugin(app));
50
+
51
+ // Start server if executed directly
52
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
53
+ const port = env.API_PORT ?? 4000;
54
+ const host = env.API_HOST ?? "0.0.0.0";
55
+ server.listen({ port, hostname: host }, () => {
56
+ console.log(`Elysia server listening at http://${host}:${port}`);
57
+ });
58
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * server.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * CellsWeb RPC API Server Entrypoint — Hono (Web Standards)
5
+ */
6
+
7
+ import { CoreRPC, createHonoMiddleware } from "@cellsweb/rpc-core";
8
+ import { Hono } from "hono";
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 = new Hono();
21
+
22
+ // ── Static Files Route (/uploads/*) ──
23
+ server.get("/uploads/*", async (c) => {
24
+ const filePath = decodeURIComponent(c.req.path.replace(/^\/uploads\//, ""));
25
+ const result = await storage.serve(filePath);
26
+ if (!result) {
27
+ return c.json(
28
+ {
29
+ status: "error",
30
+ code: "not_found",
31
+ message: "File not found",
32
+ },
33
+ 404,
34
+ );
35
+ }
36
+ return new Response(result.buffer, {
37
+ status: 200,
38
+ headers: {
39
+ "Content-Type": result.mimeType,
40
+ "Cache-Control": "public, max-age=86400",
41
+ },
42
+ });
43
+ });
44
+
45
+ // ── Register CellsWeb RPC Middleware (Handles /rpc, /docs, /health) ──
46
+ createHonoMiddleware(app)(server);
47
+
48
+ // Start server if executed directly (Node.js or Bun)
49
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
50
+ const port = env.API_PORT ?? 4000;
51
+ const host = env.API_HOST ?? "0.0.0.0";
52
+
53
+ // Check if running on native Bun
54
+ if (typeof (globalThis as any).Bun !== "undefined") {
55
+ (globalThis as any).Bun.serve({
56
+ port,
57
+ hostname: host,
58
+ fetch: server.fetch,
59
+ });
60
+ console.log(`Hono server listening at http://${host}:${port} (Bun runtime)`);
61
+ } else {
62
+ // Run on Node.js via @hono/node-server
63
+ const { serve } = await import("@hono/node-server");
64
+ serve({ fetch: server.fetch, port, hostname: host }, () => {
65
+ console.log(`Hono server listening at http://${host}:${port} (Node.js runtime)`);
66
+ });
67
+ }
68
+ }
@@ -1,19 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2023",
4
- "module": "nodenext",
5
- "moduleResolution": "nodenext",
6
- "lib": ["ES2023"],
7
- "types": ["node"],
8
- "strict": true,
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "resolveJsonModule": true,
12
- "noEmit": true,
13
- "paths": {
14
- "@/*": ["../src/*"]
15
- }
16
- },
17
- "include": ["./**/*"],
18
- "exclude": ["node_modules"]
19
- }