@seip/bluebird-js 0.1.0 → 0.1.2

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/AGENTS.md CHANGED
@@ -306,18 +306,46 @@ For complete deployment details including Nginx reverse proxy configuration and
306
306
 
307
307
  Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
308
308
 
309
- - Automatically routes SQLite database files, `logs/`, and `app/cache/` to a writable OS user data directory (`Config.userDataDir()`), copying initial bundled SQLite databases on first run.
310
- - Binds strictly to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
309
+ - **Base Directory Resolution (`appPath`)**: Accepts `appPath: electronApp.getAppPath()` (or `Config.setAppDir()`) to ensure views (`app/views/`) and static assets (`public/`) resolve accurately regardless of shortcut launch locations (`process.cwd()`).
310
+ - **Writable User Data (`userDataPath`)**: Automatically routes SQLite database files, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`electronApp.getPath("userData")`), copying bundled initial SQLite template databases from `appPath`, `process.resourcesPath`, or `.asar.unpacked` on first launch.
311
+ - **Dynamic Port & LAN / QR Access**:
312
+ - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
313
+ - When `{ allowLan: true }` is enabled, binds to `0.0.0.0` and returns `{ server, port, url, lanUrl, lanIp }` ready for mobile QR code access on local WiFi.
314
+ - **Uploads & Static Serving**:
315
+ - In desktop mode, `Upload.storage()` writes to `userDataDir/uploads` and `App` automatically mounts `/uploads` to serve uploaded files statically without read-only filesystem errors.
316
+ - **Clean Shutdown & WAL Checkpoint**:
317
+ - Invoking `await app.close()` (e.g. in Electron `app.on("before-quit")`) automatically checkpoints SQLite WAL (`PRAGMA wal_checkpoint(TRUNCATE)`), closes open database handles via `Database.closeAll()`, and frees Windows file locks cleanly.
318
+ - **Packaging with electron-builder**:
319
+ - Recommended `electron-builder` configuration in `package.json`:
320
+ ```json
321
+ "build": {
322
+ "asar": true,
323
+ "asarUnpack": ["app/views/**/*", "database/**/*"]
324
+ }
325
+ ```
311
326
 
312
327
  ```javascript
328
+ import App from "@seip/bluebird-js/core/app.js";
329
+ import { app as electronApp, BrowserWindow } from "electron";
330
+ import routerApi from "./app/routes/api.js";
331
+ import routerWeb from "./app/routes/web.js";
332
+
313
333
  const app = new App({
314
334
  desktop: true,
335
+ appPath: electronApp.getAppPath(),
315
336
  userDataPath: electronApp.getPath("userData"),
316
337
  routes: [routerWeb, routerApi],
317
338
  });
318
339
 
319
- const { url, port } = await app.runDesktop();
320
- mainWindow.loadURL(url);
340
+ electronApp.whenReady().then(async () => {
341
+ const { url, port, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
342
+ const mainWindow = new BrowserWindow({ width: 1200, height: 800 });
343
+ mainWindow.loadURL(url);
344
+
345
+ electronApp.on("before-quit", async () => {
346
+ await app.close();
347
+ });
348
+ });
321
349
  ```
322
350
 
323
351
  ## 14. Developer Tooling CLI
package/README.md CHANGED
@@ -256,6 +256,66 @@ routerWeb.get("/terms", (req, res) => Render.html(res, "legal/terms.html", { ttl
256
256
 
257
257
  ---
258
258
 
259
+ ## Desktop Applications (Electron & Desktop Mode)
260
+
261
+ Bluebird.js runs natively embedded inside **Electron** applications with zero child processes, ultra-fast boot (<200ms), and minimal RAM consumption (~25–40 MB vs ~300 MB with Nextron/Next.js):
262
+
263
+ - **Automatic Writable Paths:** Routes SQLite database, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`app.getPath("userData")`) to avoid read-only errors inside `.asar` archives.
264
+ - **Dynamic Port & LAN / QR Access:** Binds to dynamic port `0` and generates LAN URLs (`allowLan: true`) for companion mobile/QR code access.
265
+ - **Clean WAL Shutdown:** `await app.close()` truncates SQLite WAL and frees file locks cleanly on Windows/Mac/Linux.
266
+
267
+ ### Scaffold with a Single Command:
268
+ ```bash
269
+ npx bluebird-js add electron
270
+ ```
271
+ This installs `electron` and `electron-builder`, generates `desktop.js`, and configures build scripts in your `package.json`.
272
+
273
+ ### `desktop.js` Entrypoint:
274
+ ```javascript
275
+ import { app as electronApp, BrowserWindow, shell } from "electron";
276
+ import App from "@seip/bluebird-js/core/app.js";
277
+ import routerWeb from "./app/routes/web.js";
278
+ import routerApi from "./app/routes/api.js";
279
+
280
+ const app = new App({
281
+ desktop: true,
282
+ appPath: electronApp.getAppPath(),
283
+ userDataPath: electronApp.getPath("userData"),
284
+ routes: [routerWeb, routerApi],
285
+ });
286
+
287
+ electronApp.whenReady().then(async () => {
288
+ const { url, lanUrl } = await app.runDesktop({ allowLan: true });
289
+
290
+ const mainWindow = new BrowserWindow({
291
+ width: 1280,
292
+ height: 800,
293
+ minWidth: 900,
294
+ minHeight: 600,
295
+ webPreferences: {
296
+ nodeIntegration: false,
297
+ contextIsolation: true,
298
+ },
299
+ });
300
+
301
+ mainWindow.loadURL(url);
302
+
303
+ mainWindow.webContents.setWindowOpenHandler(({ url }) => {
304
+ if (!url.startsWith("http://127.0.0.1") && !url.startsWith("http://localhost")) {
305
+ shell.openExternal(url);
306
+ return { action: "deny" };
307
+ }
308
+ return { action: "allow" };
309
+ });
310
+
311
+ electronApp.on("before-quit", async () => {
312
+ await app.close();
313
+ });
314
+ });
315
+ ```
316
+
317
+ ---
318
+
259
319
  ## Production Deployment
260
320
 
261
321
  Bluebird.js supports direct Node.js execution and PM2 process clustering out of the box:
@@ -281,6 +341,7 @@ npx bluebird-js migrate # Executes pending migrati
281
341
  npx bluebird-js seed # Executes database seeds
282
342
  npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx reverse proxy configuration
283
343
  npx bluebird-js make:ecosystem [--start] # Generates PM2 clustering config
344
+ npx bluebird-js add electron # Scaffolds Electron desktop app, desktop.js & build config
284
345
  npx bluebird-js add react-islands # Scaffolds React Islands, Vite & Client Router
285
346
  npx bluebird-js add <module> # Installs optional on-demand package
286
347
  ```
package/core/app.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import http from "node:http";
2
2
  import express from "express";
3
3
  import path from "node:path";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
4
6
  import colors from "./util/colors.js";
5
7
  import Config from "./config.js";
6
8
  import Logger from "./logger.js";
@@ -9,10 +11,25 @@ import WebSocketManager from "./ws.js";
9
11
  import RateLimit from "./ratelimit.js";
10
12
  import Seo from "./seo.js";
11
13
 
12
- const __dirname = Config.dirname();
13
14
  const props = Config.props();
14
15
  const SERVER_BOOT_ID = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
15
16
 
17
+ /**
18
+ * Detects the primary local network IPv4 address.
19
+ * @returns {string}
20
+ */
21
+ function getLanIp() {
22
+ const interfaces = os.networkInterfaces();
23
+ for (const name of Object.keys(interfaces)) {
24
+ for (const iface of interfaces[name] || []) {
25
+ if (iface.family === "IPv4" && !iface.internal) {
26
+ return iface.address;
27
+ }
28
+ }
29
+ }
30
+ return "127.0.0.1";
31
+ }
32
+
16
33
  /**
17
34
  * Lightweight native cookie parser middleware.
18
35
  * @param {import('express').Request} req
@@ -171,8 +188,13 @@ class App {
171
188
  * @param {boolean} [options.trustProxy=true] - Enable Express trust proxy for accurate IP behind reverse proxies.
172
189
  * @param {boolean} [options.desktop=false] - Enable Electron/Desktop mode (binds 127.0.0.1 and uses writable userDataDir).
173
190
  * @param {string} [options.userDataPath] - Custom writable directory path for SQLite, logs, and file cache in Electron.
191
+ * @param {string} [options.appPath] - Custom application root directory for views and static assets (ideal for Electron app.getAppPath()).
192
+ * @param {boolean} [options.allowLan=false] - Whether to allow local network / mobile access (binds 0.0.0.0 in desktop mode).
174
193
  */
175
194
  constructor(options = {}) {
195
+ if (options.appPath) {
196
+ Config.setAppDir(options.appPath);
197
+ }
176
198
  if (options.userDataPath) {
177
199
  Config.setUserDataDir(options.userDataPath);
178
200
  } else if (options.desktop) {
@@ -188,8 +210,9 @@ class App {
188
210
  this.cors = options.cors || {};
189
211
  this.middlewares = options.middlewares || [];
190
212
  this.desktop = options.desktop ?? Config.isDesktop();
213
+ this.allowLan = Boolean(options.allowLan);
191
214
  this.port = options.port !== undefined ? options.port : (this.desktop && !process.env.PORT ? 0 : props.port);
192
- this.host = options.host || (this.desktop ? "http://127.0.0.1" : props.host);
215
+ this.host = options.host || (this.desktop ? (this.allowLan ? "http://0.0.0.0" : "http://127.0.0.1") : props.host);
193
216
  this.appUrl = options.appUrl || props.appUrl;
194
217
  this.logger = options.logger ?? false;
195
218
  this.notFound = options.notFound ?? true;
@@ -371,9 +394,12 @@ class App {
371
394
  const staticPath = this.static?.path || "public";
372
395
  const staticOptions = this.static?.options || {};
373
396
  const isDebug = this.debug;
397
+ const resolvedStaticDir = path.isAbsolute(staticPath)
398
+ ? staticPath
399
+ : path.resolve(Config.appDir(), staticPath);
374
400
 
375
401
  this.app.use(
376
- express.static(path.join(__dirname, staticPath), {
402
+ express.static(resolvedStaticDir, {
377
403
  ...staticOptions,
378
404
  setHeaders: (res) => {
379
405
  res.setHeader("X-Powered-By", "Blue Bird");
@@ -385,6 +411,16 @@ class App {
385
411
  })
386
412
  );
387
413
 
414
+ if (this.desktop) {
415
+ const uploadsDir = path.join(Config.userDataDir(), "uploads");
416
+ if (!fs.existsSync(uploadsDir)) {
417
+ try {
418
+ fs.mkdirSync(uploadsDir, { recursive: true });
419
+ } catch {}
420
+ }
421
+ this.app.use("/uploads", express.static(uploadsDir));
422
+ }
423
+
388
424
  this.middlewares.forEach((middleware) => {
389
425
  this.app.use(middleware);
390
426
  });
@@ -519,7 +555,7 @@ class App {
519
555
 
520
556
  /**
521
557
  * Starts the HTTP server and listens for incoming connections.
522
- * In desktop mode, binds exclusively to 127.0.0.1 for local security.
558
+ * In desktop mode, binds to 127.0.0.1 (or 0.0.0.0 if allowLan is true).
523
559
  * @returns {Promise<import('http').Server>}
524
560
  */
525
561
  async run() {
@@ -532,23 +568,33 @@ class App {
532
568
  if (this.desktop) {
533
569
  this.appUrl = `http://127.0.0.1:${activePort}`;
534
570
  }
535
- console.log(
571
+ let banner =
536
572
  colors.bold.blue("Blue Bird Server Online\n") +
537
573
  colors.bold.cyan("App URL: ") +
538
574
  colors.green(`${this.appUrl}`) +
539
575
  "\n" +
540
576
  colors.bold.cyan("Internal: ") +
541
577
  colors.green(`${this.host}:${activePort}`) +
542
- "\n" +
543
- colors.gray("────────────────────────────────")
544
- );
578
+ "\n";
579
+
580
+ if (this.desktop && this.allowLan) {
581
+ const lanIp = getLanIp();
582
+ banner +=
583
+ colors.bold.cyan("LAN / QR: ") +
584
+ colors.yellow(`http://${lanIp}:${activePort}`) +
585
+ "\n";
586
+ }
587
+
588
+ banner += colors.gray("────────────────────────────────");
589
+ console.log(banner);
545
590
  resolve(this.server);
546
591
  };
547
592
 
548
593
  this.server.on("error", reject);
549
594
 
550
595
  if (this.desktop) {
551
- this.server.listen(this.port, "127.0.0.1", onListening);
596
+ const bindAddress = this.allowLan ? "0.0.0.0" : "127.0.0.1";
597
+ this.server.listen(this.port, bindAddress, onListening);
552
598
  } else {
553
599
  this.server.listen(this.port, onListening);
554
600
  }
@@ -556,29 +602,58 @@ class App {
556
602
  }
557
603
 
558
604
  /**
559
- * Starts the server in Electron / Desktop mode, binding to 127.0.0.1 (using a dynamic port if port is 0)
560
- * and returning the server, resolved port, and local URL ready for Electron's mainWindow.loadURL(url).
605
+ * Starts the server in Electron / Desktop mode, binding to 127.0.0.1 (or 0.0.0.0 if allowLan is true),
606
+ * using a dynamic port if port is 0, and returning the server, resolved port, local URL, and optional LAN URL
607
+ * ready for Electron's mainWindow.loadURL(url) and mobile QR code access.
561
608
  * @param {Object} [options={}]
609
+ * @param {string} [options.appPath] - Optional path from Electron app.getAppPath().
562
610
  * @param {string} [options.userDataPath] - Optional path from Electron app.getPath("userData").
563
- * @returns {Promise<{server: import('http').Server, port: number, url: string}>}
611
+ * @param {boolean} [options.allowLan=false] - Whether to allow local network / mobile access (binds 0.0.0.0).
612
+ * @param {string} [options.host] - Optional custom host override.
613
+ * @param {number} [options.port] - Optional custom port override.
614
+ * @returns {Promise<{server: import('http').Server, port: number, url: string, lanUrl?: string, lanIp?: string}>}
564
615
  */
565
616
  async runDesktop(options = {}) {
617
+ if (options.appPath) {
618
+ Config.setAppDir(options.appPath);
619
+ }
566
620
  if (options.userDataPath) {
567
621
  Config.setUserDataDir(options.userDataPath);
568
622
  }
623
+ if (options.port !== undefined) {
624
+ this.port = options.port;
625
+ }
626
+ if (options.allowLan !== undefined) {
627
+ this.allowLan = Boolean(options.allowLan);
628
+ }
569
629
  this.desktop = true;
570
- this.host = "http://127.0.0.1";
630
+ this.host = options.host || (this.allowLan ? "http://0.0.0.0" : "http://127.0.0.1");
571
631
  await this.run();
572
632
  const port = this.getPort();
573
633
  const url = `http://127.0.0.1:${port}`;
574
- return { server: this.server, port, url };
634
+ const result = { server: this.server, port, url };
635
+ if (this.allowLan) {
636
+ const lanIp = getLanIp();
637
+ result.lanIp = lanIp;
638
+ result.lanUrl = `http://${lanIp}:${port}`;
639
+ }
640
+ return result;
575
641
  }
576
642
 
577
643
  /**
578
- * Closes the running HTTP server.
644
+ * Closes the running HTTP server and cleans up database connections.
579
645
  * @returns {Promise<void>}
580
646
  */
581
- close() {
647
+ async close() {
648
+ try {
649
+ const { Database } = await import("./database.js");
650
+ await Database.closeAll();
651
+ } catch {}
652
+ try {
653
+ const { default: Model } = await import("./model.js");
654
+ await Model.close();
655
+ } catch {}
656
+
582
657
  return new Promise((resolve, reject) => {
583
658
  if (this.server) {
584
659
  this.server.close((err) => (err ? reject(err) : resolve()));
package/core/auth.js CHANGED
@@ -266,7 +266,7 @@ class Auth {
266
266
  const defaultCookieOptions = {
267
267
  maxAge: ttl * 1000,
268
268
  httpOnly: true,
269
- secure: production,
269
+ secure: Config.isDesktop() ? false : production,
270
270
  sameSite: "lax",
271
271
  path: "/",
272
272
  };
package/core/cli/init.js CHANGED
@@ -638,6 +638,129 @@ export default function LiveCounter({ initial = 0, label = "Interactive Counter"
638
638
  console.log(colors.bold(' routerWeb.get("/islands-demo", Render.view("islands-demo", { title: "Islands Demo", description: "Bluebird React Islands" }));\n'));
639
639
  }
640
640
 
641
+ /**
642
+ * Scaffolds Electron desktop integration, desktop.js entrypoint, and build configuration.
643
+ */
644
+ function setupElectron() {
645
+ const appDir = process.cwd();
646
+ console.log(colors.cyan("[INFO] Setting up Electron Desktop integration for Bluebird.js..."));
647
+
648
+ try {
649
+ console.log(colors.cyan("[INFO] Installing electron and electron-builder as devDependencies..."));
650
+ execSync("npm install --save-dev electron electron-builder", { stdio: "inherit", cwd: appDir });
651
+ console.log(colors.green("[OK] Successfully installed electron and electron-builder."));
652
+ } catch (err) {
653
+ console.warn(colors.yellow(`[WARN] Could not install electron automatically: ${err.message}`));
654
+ console.log("You can install them manually via: npm install --save-dev electron electron-builder");
655
+ }
656
+
657
+ const desktopFilePath = path.join(appDir, "desktop.js");
658
+ if (!fs.existsSync(desktopFilePath)) {
659
+ const desktopContent = `import { app as electronApp, BrowserWindow, shell } from "electron";
660
+ import App from "@seip/bluebird-js/core/app.js";
661
+ import routerWeb from "./app/routes/web.js";
662
+ import routerApi from "./app/routes/api.js";
663
+
664
+ const app = new App({
665
+ desktop: true,
666
+ appPath: electronApp.getAppPath(),
667
+ userDataPath: electronApp.getPath("userData"),
668
+ routes: [routerWeb, routerApi],
669
+ });
670
+
671
+ electronApp.whenReady().then(async () => {
672
+ const { url, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
673
+
674
+ const mainWindow = new BrowserWindow({
675
+ width: 1280,
676
+ height: 800,
677
+ minWidth: 900,
678
+ minHeight: 600,
679
+ webPreferences: {
680
+ nodeIntegration: false,
681
+ contextIsolation: true,
682
+ },
683
+ });
684
+
685
+ mainWindow.loadURL(url);
686
+
687
+ mainWindow.webContents.setWindowOpenHandler(({ url }) => {
688
+ if (!url.startsWith("http://127.0.0.1") && !url.startsWith("http://localhost")) {
689
+ shell.openExternal(url);
690
+ return { action: "deny" };
691
+ }
692
+ return { action: "allow" };
693
+ });
694
+
695
+ electronApp.on("before-quit", async () => {
696
+ await app.close();
697
+ });
698
+ });
699
+ `;
700
+ fs.writeFileSync(desktopFilePath, desktopContent, "utf-8");
701
+ console.log(colors.green("[OK] Created desktop.js"));
702
+ } else {
703
+ console.log(colors.yellow("[SKIP] desktop.js already exists."));
704
+ }
705
+
706
+ const pkgPath = path.join(appDir, "package.json");
707
+ if (fs.existsSync(pkgPath)) {
708
+ try {
709
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
710
+ pkg.scripts = pkg.scripts || {};
711
+ pkg.scripts["desktop"] = "electron desktop.js";
712
+ pkg.scripts["desktop:build"] = "electron-builder --win";
713
+ pkg.scripts["desktop:portable"] = "electron-builder --win portable";
714
+ pkg.scripts["desktop:dist"] = "electron-builder";
715
+ pkg.scripts["desktop:all"] = "electron-builder -mwl";
716
+
717
+ if (!pkg.build) {
718
+ const appName = (pkg.name || "bluebird-app").replace(/^@.+\//, "");
719
+ pkg.build = {
720
+ appId: `com.${appName.replace(/[^a-zA-Z0-9]/g, "")}.app`,
721
+ productName: appName.charAt(0).toUpperCase() + appName.slice(1),
722
+ asar: true,
723
+ asarUnpack: [
724
+ "app/views/**/*",
725
+ "database/**/*"
726
+ ],
727
+ directories: {
728
+ output: "dist-desktop"
729
+ },
730
+ files: [
731
+ "**/*",
732
+ "!dist-desktop/**/*"
733
+ ],
734
+ win: {
735
+ target: ["nsis", "portable"]
736
+ },
737
+ mac: {
738
+ target: ["dmg", "zip"]
739
+ },
740
+ linux: {
741
+ target: ["AppImage", "deb"]
742
+ }
743
+ };
744
+ } else {
745
+ pkg.build.asarUnpack = pkg.build.asarUnpack || ["app/views/**/*", "database/**/*"];
746
+ }
747
+
748
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), "utf-8");
749
+ console.log(colors.green("[OK] Configured desktop scripts and electron-builder build in package.json"));
750
+ } catch (err) {
751
+ console.warn(colors.yellow(`[WARN] Could not update package.json: ${err.message}`));
752
+ }
753
+ }
754
+
755
+ console.log(colors.bold.green("\nElectron Desktop integration complete!"));
756
+ console.log(colors.white("Commands available:"));
757
+ console.log(colors.cyan(" npm run desktop - Runs the Electron desktop application locally"));
758
+ console.log(colors.cyan(" npm run desktop:build - Builds Windows installer (.exe)"));
759
+ console.log(colors.cyan(" npm run desktop:portable - Builds standalone Windows portable (.exe)"));
760
+ console.log(colors.cyan(" npm run desktop:dist - Builds for current host platform"));
761
+ console.log(colors.cyan(" npm run desktop:all - Builds for Windows, Mac & Linux\n"));
762
+ }
763
+
641
764
  /**
642
765
  * Handles adding on-demand modules and dependencies.
643
766
  * @param {string} [feature]
@@ -646,6 +769,7 @@ function addCommand(feature) {
646
769
  if (!feature) {
647
770
  console.log(colors.yellow("Usage: npx bluebird-js add <feature>"));
648
771
  console.log("Available features:");
772
+ console.log(" electron | desktop - Configures Electron desktop mode, desktop.js & electron-builder");
649
773
  console.log(" react | islands - Installs React + Vite with Islands architecture");
650
774
  console.log(" upload | multer - Installs multer for file uploads");
651
775
  console.log(" ws | websocket - Installs ws for WebSockets");
@@ -662,6 +786,14 @@ function addCommand(feature) {
662
786
 
663
787
  const cleanFeature = feature.toLowerCase().trim();
664
788
 
789
+ if (
790
+ cleanFeature === "electron" ||
791
+ cleanFeature === "desktop"
792
+ ) {
793
+ setupElectron();
794
+ return;
795
+ }
796
+
665
797
  if (
666
798
  cleanFeature === "react" ||
667
799
  cleanFeature === "react-islands" ||
@@ -734,6 +866,7 @@ function showHelp() {
734
866
  console.log(` ${colors.green("npx bluebird-js nginx:conf [domain] [port] [root]")} Generates Host Nginx reverse proxy`);
735
867
  console.log(` ${colors.green("npx bluebird-js make:ecosystem [--start]")} Generates PM2 cluster config`);
736
868
  console.log(` ${colors.green("npx bluebird-js add <module>")} Installs optional on-demand package
869
+ ${colors.green("npx bluebird-js add electron")} Scaffolds Electron desktop app, desktop.js & build config
737
870
  ${colors.green("npx bluebird-js add react-islands")} Installs React + Vite with Islands architecture`);
738
871
  console.log(colors.gray("────────────────────────────────────────────────────────────\n"));
739
872
  }
package/core/config.js CHANGED
@@ -3,6 +3,7 @@ import os from "node:os";
3
3
 
4
4
  let _cachedProps = null;
5
5
  let _customUserDataDir = null;
6
+ let _customAppDir = null;
6
7
 
7
8
  /**
8
9
  * Configuration class to manage application-wide settings, environment variables,
@@ -10,13 +11,34 @@ let _customUserDataDir = null;
10
11
  */
11
12
  class Config {
12
13
  /**
13
- * Returns the base directory of the application (process.cwd()).
14
+ * Sets a custom base directory for application assets and views (e.g. Electron app.getAppPath()).
15
+ * @param {string} dirPath
16
+ */
17
+ static setAppDir(dirPath) {
18
+ _customAppDir = dirPath ? path.resolve(dirPath) : null;
19
+ _cachedProps = null;
20
+ }
21
+
22
+ /**
23
+ * Returns the base directory of the application package.
24
+ * In Electron or when appDir is customized, returns the configured application directory.
25
+ * Otherwise falls back to APP_DIR environment variable or process.cwd().
14
26
  * @returns {string}
15
27
  */
16
- static dirname() {
28
+ static appDir() {
29
+ if (_customAppDir) return _customAppDir;
30
+ if (process.env.APP_DIR) return path.resolve(process.env.APP_DIR);
17
31
  return process.cwd();
18
32
  }
19
33
 
34
+ /**
35
+ * Returns the base directory of the application package.
36
+ * @returns {string}
37
+ */
38
+ static dirname() {
39
+ return this.appDir();
40
+ }
41
+
20
42
  /**
21
43
  * Checks whether the application is running in Electron or Desktop mode.
22
44
  * @returns {boolean}
@@ -26,7 +48,8 @@ class Config {
26
48
  process.versions?.electron ||
27
49
  process.env.DESKTOP_MODE === "true" ||
28
50
  process.env.ELECTRON_RUN_AS_NODE ||
29
- _customUserDataDir
51
+ _customUserDataDir ||
52
+ _customAppDir
30
53
  );
31
54
  }
32
55
 
@@ -51,7 +74,13 @@ class Config {
51
74
  if (process.env.USER_DATA_PATH) return path.resolve(process.env.USER_DATA_PATH);
52
75
 
53
76
  const cwd = process.cwd();
54
- if (cwd.includes(".asar") || process.versions?.electron || process.env.DESKTOP_MODE === "true") {
77
+ const appDir = this.appDir();
78
+ if (
79
+ cwd.includes(".asar") ||
80
+ appDir.includes(".asar") ||
81
+ process.versions?.electron ||
82
+ process.env.DESKTOP_MODE === "true"
83
+ ) {
55
84
  const appName = (process.env.TITLE || "bluebird-app").toLowerCase().replace(/[^a-z0-9_-]/g, "-");
56
85
  const baseAppData =
57
86
  process.env.APPDATA ||
@@ -67,7 +96,7 @@ class Config {
67
96
  /**
68
97
  * Retrieves application properties from environment variables.
69
98
  * Results are cached after the first call.
70
- * @returns {{debug: boolean, desktop: boolean, userDataDir: string, title: string, description: string, version: string, host: string, appUrl: string, port: number, jwtSecret: string, langMeta: string, static: {path: string, options: Object}}} Configuration object.
99
+ * @returns {{debug: boolean, desktop: boolean, userDataDir: string, appDir: string, title: string, description: string, version: string, host: string, appUrl: string, port: number, jwtSecret: string, langMeta: string, static: {path: string, options: Object}}} Configuration object.
71
100
  */
72
101
  static props() {
73
102
  if (_cachedProps) return _cachedProps;
@@ -78,6 +107,7 @@ class Config {
78
107
  debug: process.env.DEBUG === "true",
79
108
  desktop: this.isDesktop(),
80
109
  userDataDir: this.userDataDir(),
110
+ appDir: this.appDir(),
81
111
  descriptionMeta: process.env.DESCRIPTION_META || "",
82
112
  keywordsMeta: process.env.KEYWORDS_META || "",
83
113
  titleMeta: process.env.TITLE_META || "",
package/core/csrf.js CHANGED
@@ -79,7 +79,7 @@ class Csrf {
79
79
  res.cookie(cookieName, token, {
80
80
  httpOnly: false,
81
81
  sameSite: "lax",
82
- secure: Boolean(!propsConfig.debug),
82
+ secure: Config.isDesktop() ? false : Boolean(!propsConfig.debug),
83
83
  path: "/",
84
84
  });
85
85
  }
package/core/database.js CHANGED
@@ -132,6 +132,8 @@ function toPostgresSql(sql) {
132
132
  return result;
133
133
  }
134
134
 
135
+ const _activeDatabases = new Set();
136
+
135
137
  /**
136
138
  * Database class wrapping native node:sqlite, mysql2, and pg with pooling and multi-level caching.
137
139
  */
@@ -224,6 +226,8 @@ class Database {
224
226
  console.error("[DATABASE ERROR] Failed to parse DATABASE_URL:", err.message);
225
227
  }
226
228
  }
229
+
230
+ _activeDatabases.add(this);
227
231
  }
228
232
 
229
233
  /**
@@ -270,12 +274,24 @@ class Database {
270
274
  fs.mkdirSync(dir, { recursive: true });
271
275
  }
272
276
 
273
- if (userDataBase !== process.cwd() && !fs.existsSync(dbFilePath)) {
274
- const bundledDbPath = path.resolve(process.cwd(), this.sqliteConfig.filename);
275
- if (fs.existsSync(bundledDbPath)) {
276
- try {
277
- fs.copyFileSync(bundledDbPath, dbFilePath);
278
- } catch {}
277
+ if (!fs.existsSync(dbFilePath)) {
278
+ const candidatePaths = [
279
+ path.resolve(Config.appDir(), this.sqliteConfig.filename),
280
+ process.resourcesPath ? path.join(process.resourcesPath, this.sqliteConfig.filename) : null,
281
+ process.resourcesPath ? path.join(process.resourcesPath, "database", path.basename(this.sqliteConfig.filename)) : null,
282
+ Config.appDir().includes(".asar")
283
+ ? path.resolve(Config.appDir().replace(/\.asar(?=[\/\\]|$)/, ".asar.unpacked"), this.sqliteConfig.filename)
284
+ : null,
285
+ path.resolve(process.cwd(), this.sqliteConfig.filename),
286
+ ].filter(Boolean);
287
+
288
+ for (const candidate of candidatePaths) {
289
+ if (fs.existsSync(candidate) && path.resolve(candidate) !== path.resolve(dbFilePath)) {
290
+ try {
291
+ fs.copyFileSync(candidate, dbFilePath);
292
+ break;
293
+ } catch {}
294
+ }
279
295
  }
280
296
  }
281
297
  }
@@ -615,11 +631,18 @@ class Database {
615
631
  }
616
632
 
617
633
  /**
618
- * Closes the database connection pool or SQLite instance.
634
+ * Closes the database connection pool or SQLite instance, checkpointing WAL if SQLite.
619
635
  */
620
636
  async close() {
621
637
  this._stmtCache.clear();
622
638
  if (this.db) {
639
+ try {
640
+ if (this._sqliteDriver === "node:sqlite") {
641
+ this.db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
642
+ } else if (this._sqliteDriver === "better-sqlite3") {
643
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
644
+ }
645
+ } catch {}
623
646
  this.db.close();
624
647
  this.db = null;
625
648
  }
@@ -629,6 +652,22 @@ class Database {
629
652
  }
630
653
  this.pool = null;
631
654
  }
655
+ _activeDatabases.delete(this);
656
+ }
657
+
658
+ /**
659
+ * Closes all active database instances across the application.
660
+ * @returns {Promise<void>}
661
+ */
662
+ static async closeAll() {
663
+ const list = Array.from(_activeDatabases);
664
+ for (const db of list) {
665
+ try {
666
+ await db.close();
667
+ } catch (err) {
668
+ console.error("[DATABASE] Error closing database connection:", err.message);
669
+ }
670
+ }
632
671
  }
633
672
  }
634
673
 
package/core/index.d.ts CHANGED
@@ -258,6 +258,8 @@ export interface AppOptions {
258
258
  rateLimit?: boolean | RateLimitOptions;
259
259
  desktop?: boolean;
260
260
  userDataPath?: string;
261
+ appPath?: string;
262
+ allowLan?: boolean;
261
263
  trustProxy?: boolean | number | string;
262
264
  }
263
265
 
@@ -274,6 +276,7 @@ export class App {
274
276
  logger: boolean;
275
277
  notFound: boolean;
276
278
  desktop: boolean;
279
+ allowLan: boolean;
277
280
  trustProxy: boolean | number | string;
278
281
 
279
282
  constructor(options?: AppOptions);
@@ -288,7 +291,13 @@ export class App {
288
291
  getPort(): number;
289
292
  getUrl(): string;
290
293
  run(): Promise<any>;
291
- runDesktop(): Promise<{ server: HttpServer; port: number; url: string }>;
294
+ runDesktop(options?: {
295
+ appPath?: string;
296
+ userDataPath?: string;
297
+ allowLan?: boolean;
298
+ host?: string;
299
+ port?: number;
300
+ }): Promise<{ server: HttpServer; port: number; url: string; lanUrl?: string; lanIp?: string }>;
292
301
  close(): Promise<void>;
293
302
 
294
303
  static helmet(options?: any): (req: Request, res: Response, next: NextFunction) => void;
@@ -581,6 +590,7 @@ export class Database {
581
590
  transaction<T = any>(callback: (tx: DatabaseTransactionClient) => Promise<T>): Promise<T>;
582
591
  executeTransaction<T = any>(callback: (tx: DatabaseTransactionClient) => Promise<T>): Promise<T>;
583
592
  close(): Promise<void>;
593
+ static closeAll(): Promise<void>;
584
594
  }
585
595
 
586
596
  /**
@@ -701,6 +711,7 @@ export class Model {
701
711
 
702
712
  static getDatabase(): Database;
703
713
  static setDatabase(db: Database): void;
714
+ static close(): Promise<void>;
704
715
  static query<T = any>(sql: string, params?: any[], options?: any): Promise<T>;
705
716
  static transaction<T = any>(callback: (tx: DatabaseTransactionClient | any) => Promise<T>): Promise<T>;
706
717
  static invalidateCache(): Promise<void>;
@@ -760,6 +771,7 @@ export interface AppProps {
760
771
  debug: boolean;
761
772
  desktop: boolean;
762
773
  userDataDir: string;
774
+ appDir: string;
763
775
  title: string;
764
776
  description: string;
765
777
  version: string;
@@ -777,6 +789,8 @@ export interface AppProps {
777
789
 
778
790
  export class Config {
779
791
  static dirname(): string;
792
+ static appDir(): string;
793
+ static setAppDir(dirPath: string): void;
780
794
  static isDesktop(): boolean;
781
795
  static setUserDataDir(customDir: string): void;
782
796
  static userDataDir(): string;
package/core/model.js CHANGED
@@ -95,6 +95,17 @@ class Model {
95
95
  this._dbInstance = db;
96
96
  }
97
97
 
98
+ /**
99
+ * Closes the shared Model database connection.
100
+ * @returns {Promise<void>}
101
+ */
102
+ static async close() {
103
+ if (this._dbInstance) {
104
+ await this._dbInstance.close();
105
+ this._dbInstance = null;
106
+ }
107
+ }
108
+
98
109
  /**
99
110
  * Executes a direct SQL query through the model's database connection.
100
111
  * @param {string} sql - SQL query string.
package/core/queue.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import Config from "./config.js";
3
5
  import { getRedisClient } from "./cache.js";
4
6
 
5
7
  /**
@@ -143,9 +145,9 @@ class QueueManager {
143
145
  async loadJobs(jobsDir) {
144
146
  const targetDir =
145
147
  jobsDir ||
146
- (fs.existsSync(path.resolve(process.cwd(), "app/jobs"))
147
- ? path.resolve(process.cwd(), "app/jobs")
148
- : path.resolve(process.cwd(), "backend/jobs"));
148
+ (fs.existsSync(path.resolve(Config.appDir(), "app/jobs"))
149
+ ? path.resolve(Config.appDir(), "app/jobs")
150
+ : path.resolve(Config.appDir(), "backend/jobs"));
149
151
 
150
152
  if (!fs.existsSync(targetDir)) return;
151
153
 
@@ -156,7 +158,8 @@ class QueueManager {
156
158
  for (const file of files) {
157
159
  const fullPath = path.join(targetDir, file);
158
160
  try {
159
- const module = await import(`file://${fullPath}`);
161
+ const fileUrl = pathToFileURL(fullPath).href;
162
+ const module = await import(fileUrl);
160
163
  if (typeof module.default === "function") {
161
164
  const jobName = path.basename(file, path.extname(file));
162
165
  this.process(jobName, module.default);
package/core/upload.js CHANGED
@@ -28,6 +28,7 @@ class Upload {
28
28
 
29
29
  /**
30
30
  * Configures storage for uploaded files.
31
+ * In desktop mode, redirects destination to writable userDataDir() to avoid EROFS inside .asar archives.
31
32
  * @param {string} folder - The destination folder within the static path.
32
33
  * @returns {import('multer').StorageEngine}
33
34
  * @example
@@ -35,7 +36,12 @@ class Upload {
35
36
  */
36
37
  static storage(folder = "uploads") {
37
38
  this._ensureMulter();
38
- const dest = path.join(__dirname, props.static.path, folder);
39
+ const isDesktop = Config.isDesktop();
40
+ const dest = isDesktop
41
+ ? (folder.startsWith("uploads")
42
+ ? path.join(Config.userDataDir(), folder)
43
+ : path.join(Config.userDataDir(), "uploads", folder))
44
+ : path.resolve(Config.appDir(), props.static?.path || "public", folder);
39
45
 
40
46
  if (!fs.existsSync(dest)) {
41
47
  fs.mkdirSync(dest, { recursive: true });
@@ -5,7 +5,14 @@ import Config from "./config.js";
5
5
 
6
6
  const props = Config.props();
7
7
  const DEBUG = props.debug;
8
- const VIEWS_DIR = path.resolve(process.cwd(), process.env.VIEWS_PATH || "app/views");
8
+
9
+ /**
10
+ * Returns the base views directory dynamically relative to Config.appDir().
11
+ * @returns {string}
12
+ */
13
+ function getViewsDir() {
14
+ return path.resolve(Config.appDir(), process.env.VIEWS_PATH || "app/views");
15
+ }
9
16
 
10
17
  /**
11
18
  * Module and raw file cache for production mode.
@@ -20,12 +27,14 @@ const moduleCache = new Map();
20
27
  * @returns {boolean}
21
28
  */
22
29
  function isSafePath(candidatePath) {
23
- const resolved = path.resolve(VIEWS_DIR, candidatePath);
24
- return resolved.startsWith(VIEWS_DIR);
30
+ const viewsDir = getViewsDir();
31
+ const resolved = path.resolve(viewsDir, candidatePath);
32
+ return resolved.startsWith(viewsDir);
25
33
  }
26
34
 
27
35
  /**
28
- * Loads a JavaScript view module with development cache-busting or production memoization.
36
+ * Loads a JavaScript view module with development cache-busting, .asar unpacked fallback,
37
+ * data URL ESM import inside .asar archives, or production memoization.
29
38
  * @param {string} absolutePath
30
39
  * @returns {Promise<Object>}
31
40
  */
@@ -34,11 +43,31 @@ async function importModule(absolutePath) {
34
43
  return moduleCache.get(absolutePath);
35
44
  }
36
45
 
37
- const stats = fs.statSync(absolutePath);
38
- const fileUrl = pathToFileURL(absolutePath).href;
46
+ let targetPath = absolutePath;
47
+ if (absolutePath.includes(".asar")) {
48
+ const unpackedPath = absolutePath.replace(/\.asar(?=[\/\\]|$)/, ".asar.unpacked");
49
+ if (fs.existsSync(unpackedPath)) {
50
+ targetPath = unpackedPath;
51
+ }
52
+ }
53
+
54
+ const stats = fs.statSync(targetPath);
55
+ const fileUrl = pathToFileURL(targetPath).href;
39
56
  const targetUrl = DEBUG ? `${fileUrl}?t=${stats.mtimeMs}` : fileUrl;
40
57
 
41
- const mod = await import(targetUrl);
58
+ let mod;
59
+ try {
60
+ mod = await import(targetUrl);
61
+ } catch (err) {
62
+ if (absolutePath.includes(".asar")) {
63
+ const code = fs.readFileSync(absolutePath, "utf-8");
64
+ const dataUrl = `data:text/javascript;base64,${Buffer.from(code).toString("base64")}`;
65
+ mod = await import(dataUrl);
66
+ } else {
67
+ throw err;
68
+ }
69
+ }
70
+
42
71
  if (!DEBUG) {
43
72
  moduleCache.set(absolutePath, mod);
44
73
  }
@@ -56,7 +85,7 @@ export class ViewLoader {
56
85
  * @returns {string}
57
86
  */
58
87
  static getViewsDir() {
59
- return VIEWS_DIR;
88
+ return getViewsDir();
60
89
  }
61
90
 
62
91
  /**
@@ -92,10 +121,11 @@ export class ViewLoader {
92
121
  path.join("layouts", `${clean}.html`),
93
122
  ];
94
123
 
124
+ const viewsDir = getViewsDir();
95
125
  for (const candidate of candidates) {
96
126
  if (!isSafePath(candidate)) continue;
97
127
 
98
- const fullPath = path.resolve(VIEWS_DIR, candidate);
128
+ const fullPath = path.resolve(viewsDir, candidate);
99
129
  if (fs.existsSync(fullPath)) {
100
130
  if (candidate.endsWith(".js")) {
101
131
  const mod = await importModule(fullPath);
@@ -131,10 +161,11 @@ export class ViewLoader {
131
161
  path.join("layouts", `${clean}.html`),
132
162
  ];
133
163
 
164
+ const viewsDir = getViewsDir();
134
165
  for (const candidate of candidates) {
135
166
  if (!isSafePath(candidate)) continue;
136
167
 
137
- const fullPath = path.resolve(VIEWS_DIR, candidate);
168
+ const fullPath = path.resolve(viewsDir, candidate);
138
169
  if (fs.existsSync(fullPath)) {
139
170
  if (candidate.endsWith(".js")) {
140
171
  const mod = await importModule(fullPath);
package/core/vite.js CHANGED
@@ -36,7 +36,7 @@ class Vite {
36
36
  * @private
37
37
  */
38
38
  static getManifestPath() {
39
- const root = process.cwd();
39
+ const root = Config.appDir();
40
40
  const viteManifest = path.join(root, "public/dist/.vite/manifest.json");
41
41
  if (fs.existsSync(viteManifest)) return viteManifest;
42
42
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seip/bluebird-js",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Performance-first Node.js API and web framework with built-in JWT auth, HTML rendering, validation, BaseModel, and multi-level caching",
5
5
  "type": "module",
6
6
  "main": "core/app.js",
@@ -39,7 +39,7 @@
39
39
  "bugs": {
40
40
  "url": "https://github.com/seip25/bluebird-js/issues"
41
41
  },
42
- "homepage": "https://seip25.github.io/Blue-bird/",
42
+ "homepage": "https://seip25.github.io/bluebird-js/",
43
43
  "engines": {
44
44
  "node": ">=22.18.0"
45
45
  },