@seip/bluebird-js 0.2.0 → 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 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:
@@ -636,11 +639,12 @@ npx bluebird-js export --router browser --base / --out dist/web # static host w
636
639
  | `createRouter`, `isExported`, `getExportConfig`, `getAuthToken`, `setAuthToken`, `getAuthMode` | Router factory and static export helpers |
637
640
  | `AuthProvider`, `useAuth`, `RequireAuth`, `GuestOnly` | Session sync with `/api/auth/me` and optional role guards (`roles={["admin"]}`) |
638
641
  | `Link`, `Button`, `buttonVariants`, `Form`, `SubmitButton`, `Input`, `Textarea`, `Select`, `Card`, `Badge`, `Carousel`, `Modal`, `Drawer`, `Skeleton`, `PageSkeleton`, `ProgressBar`, `Spinner`, `Toaster`, `toast`, `ThemeToggle`, `useTheme`, `cn` | React UI kit built on the design system below (light + dark) |
642
+ | `DataTable`, `normalizeTableResponse` | Responsive table: search, sort, pagination with page sizes, view/edit/delete (confirmed) and custom actions, cards with details on narrow containers; local `rows` or server `url` (`?page&limit&search&sort&order`, reads `res.paginate()` / `Model.paginate()`), `ref.reload()` |
639
643
  | `useLocale`, `t`, `setLocale`, `getLocale`, `addMessages`, `MESSAGES` | Component UI strings in the page language (`<html lang>`): `en`, `es`, `pt`, `fr`, `de`, `it`, with base-language and English fallback |
640
644
 
641
645
  ### Vanilla Browser Helpers (`public/js/bluebird.js`)
642
646
 
643
- Includes event-delegated `[data-carousel]`, `[data-toast]`, `[data-modal]` / `[data-modal-open]`, `[data-dropdown]`, `[data-tabs]`, `[data-theme-toggle]`, `[data-copy]`, `[data-confirm]`, `[data-password-toggle]`, and `form[data-form]` (CSRF-aware fetch with inline field errors). Exposed globally as `window.Bluebird` (including `Bluebird.i18n.t / addMessages / setLocale`). Including the script twice is harmless: the second copy is ignored.
647
+ Includes `[data-datatable]` (same DataTable for HTML views: config in a child `<script type="application/json">` built with `safeJson()`, `data-url`, `format` for badge/number/currency/date cells, `{ action: "delete", url }` with a native confirm dialog and CSRF, `bluebird:datatable` events, and `Bluebird.dataTable(el, options)`), event-delegated `[data-carousel]`, `[data-toast]`, `[data-modal]` / `[data-modal-open]`, `[data-dropdown]`, `[data-tabs]`, `[data-theme-toggle]`, `[data-copy]`, `[data-confirm]`, `[data-password-toggle]`, and `form[data-form]` (CSRF-aware fetch with inline field errors). Exposed globally as `window.Bluebird` (including `Bluebird.i18n.t / addMessages / setLocale`). Including the script twice is harmless: the second copy is ignored.
644
648
 
645
649
  Built-in component strings (toast badges such as `Correcto` / `Cuidado` in Spanish, close buttons, carousel controls, error fallbacks) follow `<html lang>` in both the React kit and `public/js/bluebird.js`. Never hardcode those labels in components; add new keys to `core/react/client/i18n.js` and the identical `MESSAGES` object in `public/js/bluebird.js` (the regression suite checks they match).
646
650
 
package/README.md CHANGED
@@ -362,6 +362,61 @@ Customize it by overriding the variables in `app/resources/styles.css` (your val
362
362
  .dark { --primary: oklch(0.7 0.16 264); --primary-foreground: oklch(0.15 0 0); }
363
363
  ```
364
364
 
365
+ #### DataTable (React and HTML views)
366
+
367
+ A responsive table with search, sortable columns, pagination with page sizes, row actions (view, edit, delete with a confirmation dialog, and custom ones), loading skeletons, and an empty state. Wide containers show a table; narrow ones (phones, sidebars) switch to cards with the `primary` column as the title and `mobile: "details"` columns behind "Show details". Labels follow the page language.
368
+
369
+ ```jsx
370
+ import { Badge, DataTable, api } from "@seip/bluebird-js/react";
371
+
372
+ <DataTable
373
+ url="/api/users"
374
+ columns={[
375
+ { key: "name", label: "Name", sortable: true, primary: true },
376
+ { key: "email", label: "Email", sortable: true },
377
+ { key: "role", label: "Role", render: (u) => <Badge>{u.role}</Badge> },
378
+ { key: "sales", label: "Sales", numeric: true, sortable: true },
379
+ { key: "created_at", label: "Joined", mobile: "details" },
380
+ ]}
381
+ onView="/users/:id"
382
+ onEdit={(user) => openEditor(user)}
383
+ onDelete={(user) => api.delete(`/api/users/${user.id}`)}
384
+ actions={[{ label: "Resend invite", hidden: (u) => u.status !== "invited", onClick: resend }]}
385
+ toolbar={<Button size="sm">New user</Button>}
386
+ />
387
+ ```
388
+
389
+ - **Local data**: pass `rows={items}` for client-side search, sort, and pagination.
390
+ - **Server data**: pass `url`. It calls `?page&limit&search&sort&order` and accepts `res.paginate(items, { page, limit, total })`, `res.ok(await Model.paginate(...))`, or a plain array. Server tables reload after a delete; `ref.current.reload()` reloads on demand. Allowlist the `sort` column on the server.
391
+ - `api.get(url, { raw: true })` returns the whole JSON body (`{ data, pagination }`) when you need pagination metadata yourself.
392
+
393
+ In HTML `{{ }}` views, `public/js/bluebird.js` renders the same table from a declarative element. Pass the config with `safeJson()`; cell values are always inserted as text, and `format` covers `badge` (with `tones`), `number`, `currency`, `date`, `datetime`, and `boolean`:
394
+
395
+ ```html
396
+ <div data-datatable data-url="/api/users" data-page-size="10">
397
+ <script type="application/json">{{{ tableConfig }}}</script>
398
+ </div>
399
+ ```
400
+
401
+ ```javascript
402
+ import { SafeHtml, safeJson } from "@seip/bluebird-js/core/html.js";
403
+
404
+ const tableConfig = new SafeHtml(safeJson({
405
+ columns: [
406
+ { key: "name", label: "Name", sortable: true, primary: true },
407
+ { key: "status", label: "Status", format: "badge", tones: { active: "success", invited: "info" } },
408
+ { key: "created_at", label: "Joined", format: "date", mobile: "details" },
409
+ ],
410
+ actions: [
411
+ { action: "view", href: "/users/:id" },
412
+ { action: "delete", url: "/api/users/:id" },
413
+ { action: "invite", label: "Resend invite", when: { key: "status", value: "invited" } },
414
+ ],
415
+ }));
416
+ ```
417
+
418
+ `{ action: "delete", url }` asks in a native dialog and sends a CSRF-protected `DELETE`; every action also dispatches a bubbling `bluebird:datatable` event with `{ action, row }`. From JavaScript use `Bluebird.dataTable(el, { rows | url, columns, onView, onEdit, onDelete, actions })`, which returns `{ reload, setRows, destroy }`.
419
+
365
420
  #### Component Languages (i18n)
366
421
 
367
422
  Built-in UI strings (toast badges, close buttons, carousel controls, loading and error fallbacks, theme toggle labels) follow the page language from `<html lang>`: `{{ lang }}` in HTML views and `lang` in `app/resources/spa.js` for the React SPA. English, Spanish, Portuguese, French, German, and Italian are included; regional tags fall back to their base language (`es-AR` uses `es`) and unknown languages fall back to English. In Spanish, `toast.success()` shows **Correcto**, `toast.warning()` **Cuidado**, and `toast.error()` **Error**.
@@ -476,8 +531,17 @@ await Cache.set("metrics", { activeUsers: 450 }, 60, { driver: "memory" });
476
531
  const metrics = await Cache.get("metrics", { driver: "memory" });
477
532
 
478
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
+ });
479
541
  ```
480
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
+
481
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.
482
546
 
483
547
  #### Security Defaults (CORS & CSP)
@@ -22,11 +22,12 @@
22
22
  <span class="inline-flex size-8 items-center justify-center rounded-lg border border-border bg-card shadow-2xs" aria-hidden="true">
23
23
  <svg class="size-4 text-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 7h.01M3.4 18H12a8 8 0 0 0 8-8V7a4 4 0 0 0-7.28-2.3L2 20"/><path d="m20 7 2 .5-2 .5M10 18v3M14 17.75V21M7 18a6 6 0 0 0 3.84-10.61"/></svg>
24
24
  </span>
25
- <span class="brand text-base">Blue Bird</span>
25
+ <span class="brand whitespace-nowrap text-base">Blue Bird</span>
26
26
  <span class="badge hidden sm:inline-flex">HTML SSR</span>
27
27
  </a>
28
28
  <div class="flex items-center gap-1.5">
29
29
  <a href="/" class="nav-link">Home</a>
30
+ <a href="/table" class="nav-link">Table</a>
30
31
  <a href="/terms" class="nav-link">Terms</a>
31
32
  <a href="/app" class="btn btn-primary btn-sm ml-1">Open React App</a>
32
33
  <button
@@ -0,0 +1,15 @@
1
+ <section class="py-6 md:py-10">
2
+ <span class="badge">
3
+ <span class="badge-dot bg-info" aria-hidden="true"></span>
4
+ public/js/bluebird.js
5
+ </span>
6
+ <h1 class="mt-4 text-3xl font-semibold tracking-tight text-foreground md:text-4xl">DataTable in HTML views</h1>
7
+ <p class="mt-3 max-w-2xl text-muted-foreground">
8
+ A declarative <code>[data-datatable]</code> element: server-side search, sorting, and pagination from
9
+ <code>res.paginate()</code>, view and delete actions with a native confirmation dialog, and cards on small screens.
10
+ </p>
11
+ </section>
12
+
13
+ <div data-datatable data-url="/api/demo/people" data-page-size="10">
14
+ <script type="application/json">{{{ tableConfig }}}</script>
15
+ </div>
@@ -34,7 +34,7 @@ export default function AppLayout() {
34
34
  <div className="flex items-center gap-3">
35
35
  <Link to="/" exact className="flex items-center gap-2.5 text-sm font-semibold tracking-tight text-foreground">
36
36
  <BrandMark />
37
- <span className="brand text-base">Blue Bird</span>
37
+ <span className="brand whitespace-nowrap text-base">Blue Bird</span>
38
38
  <span className="badge hidden sm:inline-flex">React SPA</span>
39
39
  </Link>
40
40
  {isExported() ? null : (
@@ -51,6 +51,9 @@ export default function AppLayout() {
51
51
  <Link to="/" exact className="nav-link">
52
52
  Explore
53
53
  </Link>
54
+ <Link to="/table" className="nav-link">
55
+ Table
56
+ </Link>
54
57
  {user ? (
55
58
  <>
56
59
  <Link to="/dashboard" className="nav-link">
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useEffect, useState } from "react";
2
- import { Badge, Button, Card, Form, Input, Skeleton, SubmitButton, api, toast, useAuth } from "@seip/bluebird-js/react";
2
+ import { api, Badge, Card, DataTable, Form, Input, SubmitButton, toast, useAuth } from "@seip/bluebird-js/react";
3
3
 
4
4
  /**
5
5
  * Authenticated dashboard view consuming `/api/tasks`.
@@ -26,13 +26,9 @@ export default function Dashboard() {
26
26
  }, [loadTasks]);
27
27
 
28
28
  const handleDelete = async (id) => {
29
- try {
30
- await api.delete(`/api/tasks/${id}`);
31
- toast.success("Task removed");
32
- loadTasks();
33
- } catch (err) {
34
- toast.error("Failed to delete", err.message);
35
- }
29
+ await api.delete(`/api/tasks/${id}`);
30
+ toast.success("Task removed");
31
+ await loadTasks();
36
32
  };
37
33
 
38
34
  return (
@@ -53,30 +49,29 @@ export default function Dashboard() {
53
49
  </div>
54
50
 
55
51
  <div className="grid gap-6 lg:grid-cols-3">
56
- <Card title="Tasks" description="Fetched from /api/tasks with CSRF-protected mutations." className="lg:col-span-2">
57
- {loading ? (
58
- <div className="space-y-3">
59
- <Skeleton className="h-11 w-full" />
60
- <Skeleton className="h-11 w-full" />
61
- <Skeleton className="h-11 w-full" />
62
- </div>
63
- ) : tasks.length === 0 ? (
64
- <div className="rounded-xl border border-dashed border-border p-8 text-center">
65
- <p className="text-sm text-muted-foreground">No tasks yet. Add one using the form.</p>
66
- </div>
67
- ) : (
68
- <ul className="divide-y divide-border/80">
69
- {tasks.map((task) => (
70
- <li key={task.id} className="flex items-center justify-between gap-3 py-3">
71
- <span className="text-sm font-medium text-foreground">{task.title}</span>
72
- <Button size="sm" variant="ghost" onClick={() => handleDelete(task.id)}>
73
- Delete
74
- </Button>
75
- </li>
76
- ))}
77
- </ul>
78
- )}
79
- </Card>
52
+ <div className="space-y-2 lg:col-span-2">
53
+ <div>
54
+ <h2 className="card-title">Tasks</h2>
55
+ <p className="card-description">Fetched from /api/tasks with CSRF-protected mutations (local DataTable).</p>
56
+ </div>
57
+ <DataTable
58
+ rows={tasks}
59
+ loading={loading}
60
+ pageSize={5}
61
+ pageSizes={[5, 10]}
62
+ empty="No tasks yet. Add one using the form."
63
+ columns={[
64
+ { key: "title", label: "Title", sortable: true, primary: true },
65
+ {
66
+ key: "status",
67
+ label: "Status",
68
+ sortable: true,
69
+ render: (task) => <Badge tone={task.status === "done" ? "success" : "info"}>{task.status}</Badge>,
70
+ },
71
+ ]}
72
+ onDelete={(task) => handleDelete(task.id)}
73
+ />
74
+ </div>
80
75
 
81
76
  <Card variant="glass" title="New task" description="Create a task via POST /api/tasks.">
82
77
  <Form
@@ -0,0 +1,85 @@
1
+ import { useRef, useState } from "react";
2
+ import { Badge, Button, DataTable, Modal, api, toast } from "@seip/bluebird-js/react";
3
+
4
+ const STATUS_TONES = { active: "success", invited: "info", suspended: "warning" };
5
+
6
+ /**
7
+ * DataTable showcase: server-side pagination (`/api/demo/people` answered with `res.paginate()`), search, sorting,
8
+ * view/edit/delete actions with confirmation, a custom action, and cards on narrow screens.
9
+ */
10
+ export default function TableDemo() {
11
+ const tableRef = useRef(null);
12
+ const [selected, setSelected] = useState(null);
13
+
14
+ const columns = [
15
+ { key: "name", label: "Name", sortable: true, primary: true },
16
+ { key: "email", label: "Email", sortable: true },
17
+ { key: "role", label: "Role", sortable: true, render: (p) => <Badge>{p.role}</Badge> },
18
+ {
19
+ key: "status",
20
+ label: "Status",
21
+ sortable: true,
22
+ render: (p) => <Badge tone={STATUS_TONES[p.status]}>{p.status}</Badge>,
23
+ },
24
+ {
25
+ key: "sales",
26
+ label: "Sales",
27
+ sortable: true,
28
+ numeric: true,
29
+ render: (p) => p.sales.toLocaleString(undefined, { style: "currency", currency: "USD" }),
30
+ },
31
+ { key: "joined", label: "Joined", sortable: true, mobile: "details" },
32
+ ];
33
+
34
+ return (
35
+ <div className="space-y-6">
36
+ <div className="border-b border-border/75 pb-5">
37
+ <h1 className="text-3xl font-semibold tracking-tight text-foreground">DataTable</h1>
38
+ <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
39
+ Server-side search, sorting, and pagination from <code>res.paginate()</code>, row actions with a confirmation
40
+ dialog, and cards with expandable details on narrow screens.
41
+ </p>
42
+ </div>
43
+
44
+ <DataTable
45
+ ref={tableRef}
46
+ url="/api/demo/people"
47
+ columns={columns}
48
+ defaultSort={{ key: "name" }}
49
+ caption="People"
50
+ onView={(person) => setSelected(person)}
51
+ onEdit={(person) => toast.info(`Edit ${person.name}`, "Open your form or navigate to an edit page here.")}
52
+ onDelete={async (person) => {
53
+ await api.delete(`/api/demo/people/${person.id}`);
54
+ toast.success(`${person.name} deleted`);
55
+ }}
56
+ actions={[
57
+ {
58
+ key: "invite",
59
+ label: "Resend invite",
60
+ hidden: (person) => person.status !== "invited",
61
+ onClick: (person) => toast.success("Invite sent", person.email),
62
+ },
63
+ ]}
64
+ toolbar={
65
+ <Button size="sm" variant="outline" onClick={() => tableRef.current?.reload()}>
66
+ Refresh
67
+ </Button>
68
+ }
69
+ />
70
+
71
+ <Modal open={Boolean(selected)} onClose={() => setSelected(null)} title={selected?.name} description={selected?.email}>
72
+ {selected ? (
73
+ <dl className="grid grid-cols-2 gap-3 text-sm">
74
+ {columns.slice(2).map((c) => (
75
+ <div key={c.key}>
76
+ <dt className="text-xs text-muted-foreground">{c.label}</dt>
77
+ <dd className="mt-0.5">{c.render ? c.render(selected) : selected[c.key]}</dd>
78
+ </div>
79
+ ))}
80
+ </dl>
81
+ ) : null}
82
+ </Modal>
83
+ </div>
84
+ );
85
+ }
@@ -6,6 +6,7 @@ const Home = lazy(() => import("./pages/Home.jsx"));
6
6
  const Login = lazy(() => import("./pages/Login.jsx"));
7
7
  const Register = lazy(() => import("./pages/Register.jsx"));
8
8
  const Dashboard = lazy(() => import("./pages/Dashboard.jsx"));
9
+ const TableDemo = lazy(() => import("./pages/TableDemo.jsx"));
9
10
  const NotFound = lazy(() => import("./pages/NotFound.jsx"));
10
11
 
11
12
  /**
@@ -30,6 +31,10 @@ export const router = createRouter(
30
31
  index: true,
31
32
  element: withSuspense(<Home />),
32
33
  },
34
+ {
35
+ path: "table",
36
+ element: withSuspense(<TableDemo />),
37
+ },
33
38
  {
34
39
  element: <GuestOnly redirectTo="/dashboard" />,
35
40
  children: [
@@ -55,6 +55,12 @@ const spa = {
55
55
  robots: "index, follow",
56
56
  skeleton: "auth",
57
57
  },
58
+ table: {
59
+ title: "DataTable",
60
+ description: "Responsive DataTable with search, sorting, pagination, and row actions.",
61
+ robots: "index, follow",
62
+ skeleton: "app",
63
+ },
58
64
  dashboard: {
59
65
  title: "Dashboard",
60
66
  description: "Authenticated user dashboard.",
package/app/routes/api.js CHANGED
@@ -62,6 +62,50 @@ routerApi.delete("/tasks/:id", Auth.protect(), (req, res) => {
62
62
  return res.ok({ id }, "Task processed");
63
63
  });
64
64
 
65
+ const FIRST_NAMES = ["Ana", "Bruno", "Carla", "Diego", "Elena", "Facundo", "Gabriela", "Hugo", "Inés", "Julián", "Karen", "Lucas"];
66
+ const LAST_NAMES = ["García", "Martínez", "López", "Silva", "Pereira", "Fernández", "Gómez", "Rossi", "Díaz", "Torres"];
67
+ const demoPeople = Array.from({ length: 57 }, (_, i) => {
68
+ const first = FIRST_NAMES[i % FIRST_NAMES.length];
69
+ const last = LAST_NAMES[(i * 7) % LAST_NAMES.length];
70
+ return {
71
+ id: i + 1,
72
+ name: `${first} ${last}`,
73
+ email: `${first}.${last}${i + 1}@example.com`.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""),
74
+ role: ["admin", "editor", "user", "user"][i % 4],
75
+ status: i % 5 === 0 ? "invited" : i % 7 === 0 ? "suspended" : "active",
76
+ sales: Math.round(((i * 7919) % 100000) / 10) / 10,
77
+ joined: new Date(Date.UTC(2026, i % 12, (i % 27) + 1)).toISOString().slice(0, 10),
78
+ };
79
+ });
80
+ const PEOPLE_SORTABLE = new Set(["name", "email", "role", "status", "sales", "joined"]);
81
+
82
+ /**
83
+ * Server-side DataTable demo: `?page&limit&search&sort&order` answered with `res.paginate()`.
84
+ */
85
+ routerApi.get("/demo/people", (req, res) => {
86
+ const page = Math.max(1, Number(req.query.page) || 1);
87
+ const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 10));
88
+ const search = String(req.query.search || "").trim().toLowerCase();
89
+ const sort = PEOPLE_SORTABLE.has(req.query.sort) ? req.query.sort : null;
90
+ const order = req.query.order === "desc" ? -1 : 1;
91
+ let list = search
92
+ ? demoPeople.filter((p) => [p.name, p.email, p.role, p.status].some((v) => v.toLowerCase().includes(search)))
93
+ : demoPeople;
94
+ if (sort) {
95
+ list = [...list].sort((a, b) =>
96
+ (typeof a[sort] === "number" ? a[sort] - b[sort] : String(a[sort]).localeCompare(String(b[sort]))) * order
97
+ );
98
+ }
99
+ res.paginate(list.slice((page - 1) * limit, page * limit), { page, limit, total: list.length });
100
+ });
101
+
102
+ routerApi.delete("/demo/people/:id", (req, res) => {
103
+ const idx = demoPeople.findIndex((p) => p.id === Number(req.params.id));
104
+ if (idx === -1) return res.notFound("Person not found");
105
+ const [removed] = demoPeople.splice(idx, 1);
106
+ return res.ok(removed, `${removed.name} deleted`);
107
+ });
108
+
65
109
  routerApi.get("/stream", (req, res) => {
66
110
  const stream = res.sse({ keepAliveMs: 15000, retry: 3000 });
67
111
  let tick = 1;
package/app/routes/web.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import Router from "@seip/bluebird-js/core/router.js";
2
2
  import Render from "@seip/bluebird-js/core/render.js";
3
- import { escapeHtml } from "@seip/bluebird-js/core/html.js";
3
+ import { SafeHtml, escapeHtml, safeJson } from "@seip/bluebird-js/core/html.js";
4
4
  import spa from "../resources/spa.js";
5
5
 
6
6
  const routerWeb = new Router("/", { seo: true });
@@ -54,6 +54,36 @@ routerWeb.get("/", (req, res) => {
54
54
 
55
55
  routerWeb.get("/terms", Render.view("terms", { title: "Terms of Service" }, { cache: 86400, ttl: 86400 }));
56
56
 
57
+ routerWeb.get("/table", (req, res) =>
58
+ Render.html(
59
+ res,
60
+ "table",
61
+ {
62
+ title: "DataTable — Bluebird.js",
63
+ tableConfig: new SafeHtml(
64
+ safeJson({
65
+ caption: "People",
66
+ defaultSort: { key: "name" },
67
+ columns: [
68
+ { key: "name", label: "Name", sortable: true, primary: true },
69
+ { key: "email", label: "Email", sortable: true },
70
+ { key: "role", label: "Role", sortable: true, format: "badge" },
71
+ { key: "status", label: "Status", sortable: true, format: "badge", tones: { active: "success", invited: "info", suspended: "warning" } },
72
+ { key: "sales", label: "Sales", sortable: true, format: "currency", numeric: true },
73
+ { key: "joined", label: "Joined", sortable: true, format: "date", mobile: "details" },
74
+ ],
75
+ actions: [
76
+ { action: "view", href: "/app/table" },
77
+ { action: "invite", label: "Resend invite", when: { key: "status", value: "invited" } },
78
+ { action: "delete", url: "/api/demo/people/:id" },
79
+ ],
80
+ })
81
+ ),
82
+ },
83
+ { layout: "main" }
84
+ )
85
+ );
86
+
57
87
  routerWeb.spa(spa.mount, spa);
58
88
 
59
89
  export default routerWeb;
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
@@ -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 = `${getTimestamp()}_${migrationTitle}.sql`;
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 = `${getTimestamp()}_${cleanName}.sql`;
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 migrations.
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
- const isMain = process.argv[1] && (
768
- process.argv[1].endsWith("migrate.js") ||
769
- process.argv[1].endsWith("migrate")
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) {