@seip/bluebird-js 0.2.1 → 0.2.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 +3 -0
- package/README.md +9 -0
- package/core/cache.js +17 -0
- package/core/cli/migrate.js +57 -31
- package/core/cli/route.js +8 -7
- package/core/index.d.ts +1288 -1286
- package/core/react/client/components.js +4 -1
- package/core/react/client/index.d.ts +1 -0
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -263,9 +263,12 @@ const stats = await Cache.deduplicate("stats-key", async () => {
|
|
|
263
263
|
});
|
|
264
264
|
|
|
265
265
|
await Cache.delete("custom_key");
|
|
266
|
+
await Cache.invalidateRoute("/api/stats");
|
|
266
267
|
await Cache.clear();
|
|
267
268
|
```
|
|
268
269
|
|
|
270
|
+
After mutations, clear responses cached by `Cache.middleware()` with `Cache.invalidateRoute("/api/notes")` (the path, its query variants, and `/api/notes/:id`). `Cache.delete("/api/notes")` does not match route cache keys. `make:route` generates routers on `/api/<name>` with `Csrf.middleware()` and `Cache.invalidateRoute()` already wired.
|
|
271
|
+
|
|
269
272
|
### Render Cache & Query Parameters
|
|
270
273
|
|
|
271
274
|
HTML caches (`Render.cache(ttl)`, `Render.html(..., { cache: 300, cacheQuery: [...] })`, and `router.spa(..., { cache: 300 })`) key entries by **path only**. Requests carrying query parameters bypass the cache unless the parameter is allowlisted, preventing cache flooding with `?random=...` variants:
|
package/README.md
CHANGED
|
@@ -531,8 +531,17 @@ await Cache.set("metrics", { activeUsers: 450 }, 60, { driver: "memory" });
|
|
|
531
531
|
const metrics = await Cache.get("metrics", { driver: "memory" });
|
|
532
532
|
|
|
533
533
|
await Cache.set("report", htmlContent, 300, { driver: "file" });
|
|
534
|
+
|
|
535
|
+
routerApi.get("/notes", Cache.middleware(60), listNotes);
|
|
536
|
+
routerApi.post("/notes", async (req, res) => {
|
|
537
|
+
await Note.create(req.body);
|
|
538
|
+
await Cache.invalidateRoute("/api/notes");
|
|
539
|
+
res.created(null, "Saved");
|
|
540
|
+
});
|
|
534
541
|
```
|
|
535
542
|
|
|
543
|
+
`Cache.invalidateRoute(path)` clears what `Cache.middleware()` cached for a path, its query-string variants, and sub-routes such as `/api/notes/7` (not siblings like `/api/notes-archive`). HTML pages cached by `Render` are cleared with `Render.invalidate(path)`. `npx bluebird-js make:route <name>` generates a CRUD router on `/api/<name>` with `Csrf.middleware()` and this invalidation already wired.
|
|
544
|
+
|
|
536
545
|
HTML render caches (`Render.html(..., { cache: 300 })`, `Render.cache(300)`, `router.spa(..., { cache: 300 })`) are keyed by path. Query strings bypass the cache unless allowlisted (`cacheQuery: ["page"]` or `Render.cache(300, { query: ["page"] })`), preventing cache flooding. Cached pages restore each visitor's own CSRF token and CSP nonce.
|
|
537
546
|
|
|
538
547
|
#### Security Defaults (CORS & CSP)
|
package/core/cache.js
CHANGED
|
@@ -419,6 +419,23 @@ class Cache {
|
|
|
419
419
|
return true;
|
|
420
420
|
}
|
|
421
421
|
|
|
422
|
+
/**
|
|
423
|
+
* Invalidates responses cached by `Cache.middleware()` for a route path and everything below it (query-string
|
|
424
|
+
* variants and sub-routes such as `/:id`), without touching sibling paths like `/api/notes-archive`.
|
|
425
|
+
* Call it after mutations: `await Cache.invalidateRoute("/api/notes")`.
|
|
426
|
+
* @param {string} routePath - Full request path as seen by the browser (including the router prefix).
|
|
427
|
+
* @returns {Promise<boolean>}
|
|
428
|
+
*/
|
|
429
|
+
static async invalidateRoute(routePath) {
|
|
430
|
+
if (isNoneMode || !routePath) return false;
|
|
431
|
+
const clean = String(routePath).replace(/\/+$/, "") || "/";
|
|
432
|
+
const routeKey = `route:${clean}`;
|
|
433
|
+
await this.delete([routeKey, `${routeKey}/`]);
|
|
434
|
+
await this.deletePrefix(`${routeKey}/`);
|
|
435
|
+
await this.deletePrefix(`${routeKey}?`);
|
|
436
|
+
return true;
|
|
437
|
+
}
|
|
438
|
+
|
|
422
439
|
/**
|
|
423
440
|
* Alias for delete().
|
|
424
441
|
* @param {string|string[]} keys
|
package/core/cli/migrate.js
CHANGED
|
@@ -52,6 +52,21 @@ function getTimestamp() {
|
|
|
52
52
|
return `${year}${month}${day}_${hours}${mins}${secs}`;
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
/**
|
|
56
|
+
* Builds a migration file name that never reuses an existing one (two migrations created in the same second
|
|
57
|
+
* get `_2`, `_3`... suffixes, which still sort after the first). Reusing a name would mark the new migration
|
|
58
|
+
* as already applied and silently skip it.
|
|
59
|
+
* @param {string} migrationsDir
|
|
60
|
+
* @param {string} title
|
|
61
|
+
* @returns {string}
|
|
62
|
+
*/
|
|
63
|
+
function uniqueMigrationName(migrationsDir, title) {
|
|
64
|
+
const base = `${getTimestamp()}_${title}`;
|
|
65
|
+
let name = `${base}.sql`;
|
|
66
|
+
for (let i = 2; fs.existsSync(path.join(migrationsDir, name)); i++) name = `${base}_${i}.sql`;
|
|
67
|
+
return name;
|
|
68
|
+
}
|
|
69
|
+
|
|
55
70
|
/**
|
|
56
71
|
* Splits raw SQL content into discrete executable statements,
|
|
57
72
|
* correctly handling single/double quoted strings and stripping line comments.
|
|
@@ -363,7 +378,7 @@ async function makeMigration(name, modelName = null, isAll = false, autoRun = fa
|
|
|
363
378
|
}
|
|
364
379
|
|
|
365
380
|
const migrationTitle = cleanName || "auto_migration";
|
|
366
|
-
const filename =
|
|
381
|
+
const filename = uniqueMigrationName(migrationsDir, migrationTitle);
|
|
367
382
|
const filePath = path.join(migrationsDir, filename);
|
|
368
383
|
|
|
369
384
|
const template = `-- =============================================================\n-- Migration: ${migrationTitle}\n-- Created At: ${new Date().toISOString()}\n-- Driver Compatibility: ${DB_TYPE}\n-- =============================================================\n\n-- Up\n${upBlocks.join("\n\n")}\n\n-- Down\n${downBlocks.join("\n")}\n`;
|
|
@@ -373,7 +388,7 @@ async function makeMigration(name, modelName = null, isAll = false, autoRun = fa
|
|
|
373
388
|
|
|
374
389
|
const shouldRun = autoRun || (await promptConfirm("? Do you want to execute pending migrations now? (Y/n): ", true));
|
|
375
390
|
if (shouldRun) {
|
|
376
|
-
await runMigrations(true);
|
|
391
|
+
await runMigrations(true, false, { skipModelDiff: true });
|
|
377
392
|
}
|
|
378
393
|
return;
|
|
379
394
|
}
|
|
@@ -382,7 +397,7 @@ async function makeMigration(name, modelName = null, isAll = false, autoRun = fa
|
|
|
382
397
|
cleanName = modelName ? `create_${modelName.toLowerCase()}_table` : "custom_migration";
|
|
383
398
|
}
|
|
384
399
|
|
|
385
|
-
const filename =
|
|
400
|
+
const filename = uniqueMigrationName(migrationsDir, cleanName);
|
|
386
401
|
const filePath = path.join(migrationsDir, filename);
|
|
387
402
|
|
|
388
403
|
let idCol = "id INTEGER PRIMARY KEY AUTOINCREMENT";
|
|
@@ -397,7 +412,7 @@ async function makeMigration(name, modelName = null, isAll = false, autoRun = fa
|
|
|
397
412
|
|
|
398
413
|
const shouldRun = autoRun || (await promptConfirm("? Do you want to execute pending migrations now? (Y/n): ", true));
|
|
399
414
|
if (shouldRun) {
|
|
400
|
-
await runMigrations(true);
|
|
415
|
+
await runMigrations(true, false, { skipModelDiff: true });
|
|
401
416
|
}
|
|
402
417
|
}
|
|
403
418
|
|
|
@@ -467,11 +482,13 @@ async function ensureMigrationsTable(db) {
|
|
|
467
482
|
}
|
|
468
483
|
|
|
469
484
|
/**
|
|
470
|
-
* Executes pending database
|
|
485
|
+
* Executes pending database migration files. When nothing is pending, it also compares `app/models/` with the
|
|
486
|
+
* database and offers to generate a migration for missing tables or columns.
|
|
471
487
|
* @param {boolean} [exitOnFinish=true]
|
|
472
488
|
* @param {boolean} [autoYes=false]
|
|
489
|
+
* @param {{ skipModelDiff?: boolean }} [options={}] - `skipModelDiff` is used right after `makeMigration` wrote the file.
|
|
473
490
|
*/
|
|
474
|
-
async function runMigrations(exitOnFinish = true, autoYes = false) {
|
|
491
|
+
async function runMigrations(exitOnFinish = true, autoYes = false, options = {}) {
|
|
475
492
|
const migrationsDir = path.resolve(process.cwd(), "database/migrations");
|
|
476
493
|
if (!fs.existsSync(migrationsDir)) {
|
|
477
494
|
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
@@ -487,33 +504,11 @@ async function runMigrations(exitOnFinish = true, autoYes = false) {
|
|
|
487
504
|
return;
|
|
488
505
|
}
|
|
489
506
|
|
|
490
|
-
const allModels = await loadAllModels();
|
|
491
|
-
if (allModels.length > 0) {
|
|
492
|
-
const { missingTables, missingColumns } = await detectModelDiffs(db, allModels);
|
|
493
|
-
if (missingTables.length > 0 || missingColumns.length > 0) {
|
|
494
|
-
console.log(colors.yellow(`[WARN] Detected ${missingTables.length} missing table(s) and ${missingColumns.length} missing column(s) in app/models/.`));
|
|
495
|
-
const shouldGenerate = autoYes || (await promptConfirm("? Detected unmigrated changes in app/models/. Generate and run migration SQL now? (Y/n): ", true));
|
|
496
|
-
if (shouldGenerate) {
|
|
497
|
-
await db.close();
|
|
498
|
-
await makeMigration(null, null, true, true);
|
|
499
|
-
if (exitOnFinish) process.exit(0);
|
|
500
|
-
return;
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
|
|
505
507
|
const files = fs
|
|
506
508
|
.readdirSync(migrationsDir)
|
|
507
509
|
.filter((f) => f.endsWith(".sql") || f.endsWith(".js") || f.endsWith(".ts"))
|
|
508
510
|
.sort();
|
|
509
511
|
|
|
510
|
-
if (files.length === 0) {
|
|
511
|
-
console.log(colors.yellow("[INFO] No migration files found in 'database/migrations'."));
|
|
512
|
-
await db.close();
|
|
513
|
-
if (exitOnFinish) process.exit(0);
|
|
514
|
-
return;
|
|
515
|
-
}
|
|
516
|
-
|
|
517
512
|
const appliedRows = (await db.query("SELECT name, batch FROM _bluebird_migrations ORDER BY id ASC")) || [];
|
|
518
513
|
const appliedSet = new Set(appliedRows.map((r) => r.name));
|
|
519
514
|
|
|
@@ -522,6 +517,30 @@ async function runMigrations(exitOnFinish = true, autoYes = false) {
|
|
|
522
517
|
|
|
523
518
|
const pending = files.filter((f) => !appliedSet.has(f));
|
|
524
519
|
|
|
520
|
+
if (pending.length === 0 && !options.skipModelDiff) {
|
|
521
|
+
const allModels = await loadAllModels();
|
|
522
|
+
if (allModels.length > 0) {
|
|
523
|
+
const { missingTables, missingColumns } = await detectModelDiffs(db, allModels);
|
|
524
|
+
if (missingTables.length > 0 || missingColumns.length > 0) {
|
|
525
|
+
console.log(colors.yellow(`[WARN] Detected ${missingTables.length} missing table(s) and ${missingColumns.length} missing column(s) in app/models/.`));
|
|
526
|
+
const shouldGenerate = autoYes || (await promptConfirm("? Detected unmigrated changes in app/models/. Generate and run migration SQL now? (Y/n): ", true));
|
|
527
|
+
if (shouldGenerate) {
|
|
528
|
+
await db.close();
|
|
529
|
+
await makeMigration(null, null, true, true);
|
|
530
|
+
if (exitOnFinish) process.exit(0);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (files.length === 0) {
|
|
538
|
+
console.log(colors.yellow("[INFO] No migration files found in 'database/migrations'."));
|
|
539
|
+
await db.close();
|
|
540
|
+
if (exitOnFinish) process.exit(0);
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
|
|
525
544
|
if (pending.length === 0) {
|
|
526
545
|
console.log(colors.green("[INFO] Database is up to date. No pending migrations."));
|
|
527
546
|
await db.close();
|
|
@@ -764,9 +783,16 @@ async function runSeeds() {
|
|
|
764
783
|
process.exit(0);
|
|
765
784
|
}
|
|
766
785
|
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
786
|
+
/**
|
|
787
|
+
* Commands handled by this module when dispatched from `npx bluebird-js <command>` (process.argv[1] is init.js then).
|
|
788
|
+
*/
|
|
789
|
+
const MIGRATE_COMMANDS = new Set(["migrate", "migrate:status", "migrate:rollback", "seed", "make:migration", "make:seed"]);
|
|
790
|
+
|
|
791
|
+
const isMain = Boolean(
|
|
792
|
+
process.argv[1] &&
|
|
793
|
+
(process.argv[1].endsWith("migrate.js") ||
|
|
794
|
+
process.argv[1].endsWith("migrate") ||
|
|
795
|
+
MIGRATE_COMMANDS.has(process.argv[2]))
|
|
770
796
|
);
|
|
771
797
|
|
|
772
798
|
if (isMain) {
|
package/core/cli/route.js
CHANGED
|
@@ -36,7 +36,7 @@ class RouteCLI {
|
|
|
36
36
|
const singularName = routeName.endsWith("s") ? routeName.slice(0, -1) : routeName;
|
|
37
37
|
const pascalName = routeName.charAt(0).toUpperCase() + routeName.slice(1);
|
|
38
38
|
const routerVarName = `router${pascalName}`;
|
|
39
|
-
const basePath =
|
|
39
|
+
const basePath = `/api/${routeName}`;
|
|
40
40
|
|
|
41
41
|
const routesFolder = path.resolve(process.cwd(), "app/routes");
|
|
42
42
|
if (!fs.existsSync(routesFolder)) {
|
|
@@ -59,7 +59,10 @@ class RouteCLI {
|
|
|
59
59
|
const content = `import Router from "@seip/bluebird-js/core/router.js";
|
|
60
60
|
import Validator from "@seip/bluebird-js/core/validate.js";
|
|
61
61
|
import Cache from "@seip/bluebird-js/core/cache.js";
|
|
62
|
-
|
|
62
|
+
import Csrf from "@seip/bluebird-js/core/csrf.js";
|
|
63
|
+
${authImport}
|
|
64
|
+
const ${routerVarName} = new Router("${basePath}");
|
|
65
|
+
${routerVarName}.use(Csrf.middleware());
|
|
63
66
|
|
|
64
67
|
const ${singularName}Schema = {
|
|
65
68
|
name: { required: true, min: 2, max: 255 },
|
|
@@ -81,7 +84,7 @@ ${routerVarName}.get("/:id", Cache.middleware(60), (req, res) => {
|
|
|
81
84
|
${routerVarName}.post("/", ${authProtect}validate${pascalName}.middleware(), async (req, res) => {
|
|
82
85
|
const data = req.body;
|
|
83
86
|
|
|
84
|
-
await Cache.
|
|
87
|
+
await Cache.invalidateRoute("${basePath}");
|
|
85
88
|
|
|
86
89
|
res.created({ ${singularName}: data }, "${pascalName} created successfully");
|
|
87
90
|
});
|
|
@@ -90,8 +93,7 @@ ${routerVarName}.put("/:id", ${authProtect}validate${pascalName}.middleware(), a
|
|
|
90
93
|
const { id } = req.params;
|
|
91
94
|
const data = req.body;
|
|
92
95
|
|
|
93
|
-
await Cache.
|
|
94
|
-
await Cache.delete(\`${basePath}/\${id}\`);
|
|
96
|
+
await Cache.invalidateRoute("${basePath}");
|
|
95
97
|
|
|
96
98
|
res.ok({ ${singularName}: { id, ...data } }, "${pascalName} updated successfully");
|
|
97
99
|
});
|
|
@@ -99,8 +101,7 @@ ${routerVarName}.put("/:id", ${authProtect}validate${pascalName}.middleware(), a
|
|
|
99
101
|
${routerVarName}.delete("/:id", ${authProtect}async (req, res) => {
|
|
100
102
|
const { id } = req.params;
|
|
101
103
|
|
|
102
|
-
await Cache.
|
|
103
|
-
await Cache.delete(\`${basePath}/\${id}\`);
|
|
104
|
+
await Cache.invalidateRoute("${basePath}");
|
|
104
105
|
|
|
105
106
|
res.ok({ id }, "${pascalName} deleted successfully");
|
|
106
107
|
});
|