@seip/bluebird-js 0.2.2 → 0.2.4
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 -1
- package/core/cli/export.js +24 -2
- package/core/index.d.ts +2 -0
- package/core/model.js +42 -4
- package/core/ws.js +24 -5
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -134,6 +134,8 @@ const userId = await User.create({ name: "Alice", email: "alice@example.com", pa
|
|
|
134
134
|
const user = await User.find(1, { cache: 60 });
|
|
135
135
|
const userWithPosts = await User.find(1, { oneMany: Post });
|
|
136
136
|
const postWithAuthor = await Post.find(10, { belongsTo: User });
|
|
137
|
+
// oneMany adds `user.posts` (table name); belongsTo adds `post.user` (singular: categories -> category, addresses -> address).
|
|
138
|
+
// Foreign keys are `<singular>_id` or the column declared with `references: "users.id"`; override with `static singular = "person"`.
|
|
137
139
|
|
|
138
140
|
const page = await User.paginate({ where: { role: "user" }, page: 1, limit: 10 });
|
|
139
141
|
await User.update(userId, { name: "Alice Smith" });
|
|
@@ -222,7 +224,7 @@ router.post("/logout", async (req, res) => {
|
|
|
222
224
|
|
|
223
225
|
Project auth routes in `app/routes/auth.js` expose `/api/auth/me`, `/api/auth/login`, `/api/auth/logout`, and optional `/api/auth/register` via `createAuthRouter({ register: true })` (defaults to `register: false`). The auth and API routers apply `Csrf.middleware()`; bearer clients (`X-Auth-Mode: token`) receive `{ user, token }` instead of a cookie.
|
|
224
226
|
|
|
225
|
-
`Auth.configure({ resolveUser: async (payload, req) => user | null })` reloads the user on every `Auth.protect()` / `Auth.optional()` request after the token signature is checked: return the current user (fresh role) or `null` to reject the session; errors reject it too. The `auth`, `api`, and `blog` templates use it with a `session_version` column stored in the token as `sv`: password change/reset and `POST /api/auth/logout-all` increment it to revoke every existing session, `PUT /api/auth/password` returns a fresh session for the current device, and `PUT /api/auth/profile` requires `current_password` to change the email. Never trust roles from the token alone for sensitive actions.
|
|
227
|
+
`Auth.configure({ resolveUser: async (payload, req) => user | null })` reloads the user on every `Auth.protect()` / `Auth.optional()` request after the token signature is checked: return the current user (fresh role) or `null` to reject the session; errors reject it too. The `auth`, `api`, and `blog` templates use it with a `session_version` column stored in the token as `sv`: password change/reset and `POST /api/auth/logout-all` increment it to revoke every existing session, `PUT /api/auth/password` returns a fresh session for the current device, and `PUT /api/auth/profile` requires `current_password` to change the email. Never trust roles from the token alone for sensitive actions. WebSockets created with `app.websocket({ auth: true })` run the same session check on connect (cookie, `Authorization: Bearer`, or `?token=`), so revoked sessions cannot open sockets and `socket.user` is the current user.
|
|
226
228
|
|
|
227
229
|
## 8. HTTP Response Helpers & Health Check
|
|
228
230
|
|
package/core/cli/export.js
CHANGED
|
@@ -79,6 +79,26 @@ function rebaseLocalUrls(html, base) {
|
|
|
79
79
|
return html.replace(/(\s(?:src|href)=["'])\/(?!\/)/g, `$1${base}`);
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Validates a URL path option (`--base`, `--basename`). Git Bash on Windows rewrites a bare `/` argument into
|
|
84
|
+
* `C:/Program Files/Git/`, which would break every asset URL; that case falls back to `/` with a warning.
|
|
85
|
+
* @param {unknown} value
|
|
86
|
+
* @param {string} flag
|
|
87
|
+
* @returns {string|undefined}
|
|
88
|
+
*/
|
|
89
|
+
function urlPathOption(value, flag) {
|
|
90
|
+
if (typeof value !== "string") return undefined;
|
|
91
|
+
if (/^[A-Za-z]:[\\/]/.test(value)) {
|
|
92
|
+
const converted = /[\\/]Git[\\/]?$/i.test(value);
|
|
93
|
+
if (converted) {
|
|
94
|
+
console.log(colors.yellow(`[WARN] ${flag} '${value}' looks like a Git Bash path conversion of '/'; using '/'. Prefix the command with MSYS_NO_PATHCONV=1 or run it from PowerShell/cmd to avoid it.`));
|
|
95
|
+
return "/";
|
|
96
|
+
}
|
|
97
|
+
throw new Error(`${flag} must be a URL path such as / or /app/, not a filesystem path ('${value}').`);
|
|
98
|
+
}
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
|
|
82
102
|
/**
|
|
83
103
|
* `npx bluebird-js export`: static client build of the React SPA.
|
|
84
104
|
*/
|
|
@@ -99,7 +119,9 @@ async function exportSpa() {
|
|
|
99
119
|
delete process.env.DEBUG;
|
|
100
120
|
|
|
101
121
|
const router = ["hash", "browser", "memory"].includes(args.router) ? args.router : "hash";
|
|
102
|
-
const
|
|
122
|
+
const baseArg = urlPathOption(args.base, "--base");
|
|
123
|
+
const basenameArg = urlPathOption(args.basename, "--basename");
|
|
124
|
+
const base = typeof baseArg === "string" ? baseArg.replace(/\/?$/, "/") : router === "browser" ? "/" : "./";
|
|
103
125
|
const auth = args.auth === "cookie" ? "cookie" : "token";
|
|
104
126
|
const apiUrl = String(
|
|
105
127
|
(typeof args.api === "string" && args.api) || process.env.EXPORT_API_URL || process.env.APP_URL || ""
|
|
@@ -131,7 +153,7 @@ async function exportSpa() {
|
|
|
131
153
|
throw new Error(`Missing SPA entry files: ${missing.join(", ")}`);
|
|
132
154
|
}
|
|
133
155
|
|
|
134
|
-
const exportConfig = { apiUrl, router, auth, basename: typeof
|
|
156
|
+
const exportConfig = { apiUrl, router, auth, basename: typeof basenameArg === "string" ? basenameArg : "/" };
|
|
135
157
|
const bridge = new ViteBridge({ root, base });
|
|
136
158
|
const viteConfig = await bridge.inlineConfig();
|
|
137
159
|
const { build: viteBuild } = await import("vite");
|
package/core/index.d.ts
CHANGED
|
@@ -857,6 +857,8 @@ export interface ModelDeleteOptions {
|
|
|
857
857
|
|
|
858
858
|
export class Model {
|
|
859
859
|
static table: string;
|
|
860
|
+
/** Singular name for relation keys and `belongsTo` properties (default: singularized table name). */
|
|
861
|
+
static singular?: string;
|
|
860
862
|
static primaryKey: string;
|
|
861
863
|
static timestamps: boolean;
|
|
862
864
|
static softDelete: boolean;
|
package/core/model.js
CHANGED
|
@@ -72,6 +72,36 @@ function buildWhere(where) {
|
|
|
72
72
|
return { whereClauses, params, whereSql };
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Plurals that the suffix rules below would get wrong. Models can also set `static singular = "..."`.
|
|
77
|
+
* @type {Record<string, string>}
|
|
78
|
+
*/
|
|
79
|
+
const IRREGULAR_SINGULARS = {
|
|
80
|
+
movies: "movie",
|
|
81
|
+
cookies: "cookie",
|
|
82
|
+
series: "series",
|
|
83
|
+
species: "species",
|
|
84
|
+
news: "news",
|
|
85
|
+
people: "person",
|
|
86
|
+
children: "child",
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Singular form of a table name for relation keys and properties: `categories` -> `category`,
|
|
91
|
+
* `addresses` -> `address`, `boxes` -> `box`, `users` -> `user`.
|
|
92
|
+
* @param {string} table
|
|
93
|
+
* @returns {string}
|
|
94
|
+
*/
|
|
95
|
+
function singularize(table) {
|
|
96
|
+
const name = String(table);
|
|
97
|
+
const lower = name.toLowerCase();
|
|
98
|
+
if (IRREGULAR_SINGULARS[lower]) return IRREGULAR_SINGULARS[lower];
|
|
99
|
+
if (/[^aeiou]ies$/i.test(name)) return name.slice(0, -3) + "y";
|
|
100
|
+
if (/(ss|x|ch|sh)es$/i.test(name)) return name.slice(0, -2);
|
|
101
|
+
if (/s$/i.test(name) && !/ss$/i.test(name)) return name.slice(0, -1);
|
|
102
|
+
return name;
|
|
103
|
+
}
|
|
104
|
+
|
|
75
105
|
/**
|
|
76
106
|
* Validates and builds an ORDER BY clause from a string or array of expressions.
|
|
77
107
|
* Prevents SQL injection in dynamic sort parameters.
|
|
@@ -105,6 +135,13 @@ class Model {
|
|
|
105
135
|
/** @type {string} */
|
|
106
136
|
static table = "models";
|
|
107
137
|
|
|
138
|
+
/**
|
|
139
|
+
* Singular name used for relation keys (`<singular>_id`) and `belongsTo` properties.
|
|
140
|
+
* Defaults to the table name singularized (`categories` -> `category`).
|
|
141
|
+
* @type {string|undefined}
|
|
142
|
+
*/
|
|
143
|
+
static singular = undefined;
|
|
144
|
+
|
|
108
145
|
/** @type {string} */
|
|
109
146
|
static primaryKey = "id";
|
|
110
147
|
|
|
@@ -229,8 +266,9 @@ class Model {
|
|
|
229
266
|
}
|
|
230
267
|
}
|
|
231
268
|
|
|
232
|
-
const singular = this.
|
|
233
|
-
const
|
|
269
|
+
const singular = this.singular || singularize(this.table);
|
|
270
|
+
const legacy = this.table.endsWith("s") ? this.table.slice(0, -1) : this.table;
|
|
271
|
+
const candidates = [`${singular}_id`, `${legacy}_id`, `${this.table}_id`, `id_${singular}`, `id_${this.table}`];
|
|
234
272
|
|
|
235
273
|
for (const c of candidates) {
|
|
236
274
|
if (targetModel.schema[c]) {
|
|
@@ -303,7 +341,7 @@ class Model {
|
|
|
303
341
|
withDeleted: options.withDeleted,
|
|
304
342
|
withHidden: options.withHidden,
|
|
305
343
|
});
|
|
306
|
-
const singularParent = parent.
|
|
344
|
+
const singularParent = parent.singular || singularize(parent.table);
|
|
307
345
|
result[singularParent] = parentRow;
|
|
308
346
|
}
|
|
309
347
|
}
|
|
@@ -400,7 +438,7 @@ class Model {
|
|
|
400
438
|
parentMap.set(p[parent.primaryKey], p);
|
|
401
439
|
}
|
|
402
440
|
|
|
403
|
-
const singularParent = parent.
|
|
441
|
+
const singularParent = parent.singular || singularize(parent.table);
|
|
404
442
|
for (const item of results) {
|
|
405
443
|
item[singularParent] = parentMap.get(item[fk]) || null;
|
|
406
444
|
}
|
package/core/ws.js
CHANGED
|
@@ -21,7 +21,9 @@ class WebSocketManager {
|
|
|
21
21
|
* @param {import('http').Server} server - Express HTTP server instance.
|
|
22
22
|
* @param {Object} [options={}] - Configuration options.
|
|
23
23
|
* @param {string} [options.path="/ws"] - WebSocket endpoint route.
|
|
24
|
-
* @param {boolean} [options.auth=false] - Require valid
|
|
24
|
+
* @param {boolean} [options.auth=false] - Require a valid session on connection (auth cookie, `Authorization: Bearer`,
|
|
25
|
+
* or `?token=`), checked like `Auth.protect()`: revoked sessions and `Auth.configure({ resolveUser })` apply, and
|
|
26
|
+
* `socket.user` is the current user. Upgrades on other paths get a 404 when no other upgrade handler is attached.
|
|
25
27
|
* @param {number} [options.maxPayload=1048576] - Maximum payload size in bytes (default 1MB).
|
|
26
28
|
*/
|
|
27
29
|
constructor(server, options = {}) {
|
|
@@ -61,6 +63,10 @@ class WebSocketManager {
|
|
|
61
63
|
try {
|
|
62
64
|
const urlObj = new URL(request.url, `http://${request.headers.host || "localhost"}`);
|
|
63
65
|
if (urlObj.pathname !== this.path) {
|
|
66
|
+
if (this.server.listenerCount("upgrade") <= 1) {
|
|
67
|
+
socket.write("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
68
|
+
socket.destroy();
|
|
69
|
+
}
|
|
64
70
|
return;
|
|
65
71
|
}
|
|
66
72
|
|
|
@@ -68,12 +74,25 @@ class WebSocketManager {
|
|
|
68
74
|
const cookieHeader = request.headers.cookie || "";
|
|
69
75
|
const cookies = {};
|
|
70
76
|
cookieHeader.split(";").forEach((c) => {
|
|
71
|
-
const
|
|
72
|
-
|
|
77
|
+
const pair = c.trim();
|
|
78
|
+
const eq = pair.indexOf("=");
|
|
79
|
+
if (eq <= 0) return;
|
|
80
|
+
try {
|
|
81
|
+
cookies[pair.slice(0, eq)] = decodeURIComponent(pair.slice(eq + 1));
|
|
82
|
+
} catch {
|
|
83
|
+
cookies[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
84
|
+
}
|
|
73
85
|
});
|
|
74
86
|
|
|
75
|
-
const
|
|
76
|
-
const
|
|
87
|
+
const queryToken = urlObj.searchParams.get("token");
|
|
88
|
+
const authRequest = {
|
|
89
|
+
cookies,
|
|
90
|
+
headers: {
|
|
91
|
+
...request.headers,
|
|
92
|
+
authorization: request.headers.authorization || (queryToken ? `Bearer ${queryToken}` : undefined),
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
const user = await Auth._resolveUser(authRequest, { clearCookie() {} });
|
|
77
96
|
|
|
78
97
|
if (!user) {
|
|
79
98
|
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seip/bluebird-js",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"description": "Performance-first Node.js framework: Express + HTML {{ }} SSR templates + React Router SPA with Vite, Tailwind CSS, JWT auth, BaseModel, smart migrations, and multi-level caching",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "core/app.js",
|