@seip/bluebird-js 0.0.0-stage → 0.0.1
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/.env_example +54 -0
- package/AGENTS.md +403 -0
- package/LICENSE +21 -0
- package/README.md +284 -2
- package/app/routes/api.js +50 -0
- package/app/routes/web.js +53 -0
- package/app/views/about.html +161 -0
- package/app/views/dashboard.html +140 -0
- package/app/views/index.html +150 -0
- package/app/views/login.html +144 -0
- package/core/app.d.ts +18 -0
- package/core/app.js +644 -0
- package/core/auth.d.ts +13 -0
- package/core/auth.js +326 -0
- package/core/cache.d.ts +17 -0
- package/core/cache.js +475 -0
- package/core/cli/doctor.js +287 -0
- package/core/cli/ecosystem.js +162 -0
- package/core/cli/init.js +779 -0
- package/core/cli/migrate.js +541 -0
- package/core/cli/model.js +66 -0
- package/core/cli/nginx.js +199 -0
- package/core/cli/route.js +121 -0
- package/core/cli/swagger.js +45 -0
- package/core/cli/view.js +77 -0
- package/core/config.d.ts +3 -0
- package/core/config.js +111 -0
- package/core/csrf.d.ts +3 -0
- package/core/csrf.js +114 -0
- package/core/database.d.ts +15 -0
- package/core/database.js +636 -0
- package/core/debug.d.ts +3 -0
- package/core/debug.js +250 -0
- package/core/hash.d.ts +3 -0
- package/core/hash.js +194 -0
- package/core/index.d.ts +1071 -0
- package/core/logger.d.ts +3 -0
- package/core/logger.js +124 -0
- package/core/middleware.d.ts +3 -0
- package/core/middleware.js +28 -0
- package/core/model.d.ts +19 -0
- package/core/model.js +600 -0
- package/core/queue.d.ts +13 -0
- package/core/queue.js +172 -0
- package/core/ratelimit.d.ts +3 -0
- package/core/ratelimit.js +145 -0
- package/core/redis.d.ts +21 -0
- package/core/redis.js +230 -0
- package/core/render.d.ts +3 -0
- package/core/render.js +676 -0
- package/core/router.d.ts +3 -0
- package/core/router.js +171 -0
- package/core/seo.d.ts +3 -0
- package/core/seo.js +106 -0
- package/core/swagger.d.ts +3 -0
- package/core/swagger.js +60 -0
- package/core/upload.d.ts +13 -0
- package/core/upload.js +102 -0
- package/core/util/colors.js +82 -0
- package/core/validate.d.ts +15 -0
- package/core/validate.js +364 -0
- package/core/vite.d.ts +3 -0
- package/core/vite.js +145 -0
- package/core/ws.d.ts +13 -0
- package/core/ws.js +245 -0
- package/index.js +18 -0
- package/jsconfig.json +15 -0
- package/package.json +84 -3
- package/production.md +273 -0
- package/public/css/bluebird.min.css +2 -0
- package/public/images/favicon.ico +0 -0
- package/public/js/bluebird-client.js +1663 -0
- package/public/js/bluebird.min.js +1073 -0
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import colors from "../util/colors.js";
|
|
6
|
+
import { Database, DB_TYPE } from "../database.js";
|
|
7
|
+
|
|
8
|
+
try {
|
|
9
|
+
process.loadEnvFile?.();
|
|
10
|
+
} catch {}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Generates current timestamp string in YYYYMMDD_HHMMSS format.
|
|
14
|
+
* @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
function getTimestamp() {
|
|
17
|
+
const now = new Date();
|
|
18
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
19
|
+
const year = now.getFullYear();
|
|
20
|
+
const month = pad(now.getMonth() + 1);
|
|
21
|
+
const day = pad(now.getDate());
|
|
22
|
+
const hours = pad(now.getHours());
|
|
23
|
+
const mins = pad(now.getMinutes());
|
|
24
|
+
const secs = pad(now.getSeconds());
|
|
25
|
+
return `${year}${month}${day}_${hours}${mins}${secs}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Splits raw SQL content into discrete executable statements,
|
|
30
|
+
* stripping line comments and trimming whitespace.
|
|
31
|
+
* @param {string} sqlText
|
|
32
|
+
* @returns {string[]}
|
|
33
|
+
*/
|
|
34
|
+
function splitSqlStatements(sqlText) {
|
|
35
|
+
return sqlText
|
|
36
|
+
.split(";")
|
|
37
|
+
.map((chunk) =>
|
|
38
|
+
chunk
|
|
39
|
+
.split("\n")
|
|
40
|
+
.map((line) => line.trim())
|
|
41
|
+
.filter((line) => !line.startsWith("--"))
|
|
42
|
+
.join("\n")
|
|
43
|
+
.trim()
|
|
44
|
+
)
|
|
45
|
+
.filter((chunk) => chunk.length > 0);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Creates a new migration file in database/migrations/.
|
|
50
|
+
* Optionally inspects a Model class to generate automatic DDL,
|
|
51
|
+
* or batch generates migrations for all models in app/models/.
|
|
52
|
+
* @param {string} [name]
|
|
53
|
+
* @param {string} [modelName]
|
|
54
|
+
* @param {boolean} [isAll=false]
|
|
55
|
+
*/
|
|
56
|
+
async function makeMigration(name, modelName = null, isAll = false) {
|
|
57
|
+
const migrationsDir = path.resolve(process.cwd(), "database/migrations");
|
|
58
|
+
const modelsDir = path.resolve(process.cwd(), "app/models");
|
|
59
|
+
|
|
60
|
+
if (!fs.existsSync(migrationsDir)) {
|
|
61
|
+
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (isAll) {
|
|
65
|
+
if (!fs.existsSync(modelsDir)) {
|
|
66
|
+
console.log(colors.yellow("[WARN] Directory app/models/ does not exist."));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const modelFiles = fs.readdirSync(modelsDir).filter(
|
|
71
|
+
(f) => (f.endsWith(".js") || f.endsWith(".ts")) && !f.endsWith(".d.ts")
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
if (modelFiles.length === 0) {
|
|
75
|
+
console.log(colors.yellow("[WARN] No model files found in app/models/."));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let count = 0;
|
|
80
|
+
for (const file of modelFiles) {
|
|
81
|
+
const baseName = path.basename(file, path.extname(file));
|
|
82
|
+
const modelPath = path.join(modelsDir, file);
|
|
83
|
+
try {
|
|
84
|
+
const mod = await import(`file://${modelPath}`);
|
|
85
|
+
const ModelClass = mod.default || mod[Object.keys(mod)[0]];
|
|
86
|
+
if (ModelClass && typeof ModelClass.toDDL === "function") {
|
|
87
|
+
const tableName = ModelClass.table || `${baseName.toLowerCase()}s`;
|
|
88
|
+
const migrationName = `create_${tableName}_table`;
|
|
89
|
+
const filename = `${getTimestamp()}_${migrationName}.sql`;
|
|
90
|
+
const filePath = path.join(migrationsDir, filename);
|
|
91
|
+
|
|
92
|
+
const ddl = ModelClass.toDDL(DB_TYPE);
|
|
93
|
+
const template = `-- =============================================================\n-- Migration: ${migrationName}\n-- Created At: ${new Date().toISOString()}\n-- Driver Compatibility: ${DB_TYPE}\n-- =============================================================\n\n-- Up\n${ddl}\n\n-- Down\nDROP TABLE IF EXISTS ${tableName};\n`;
|
|
94
|
+
|
|
95
|
+
fs.writeFileSync(filePath, template, "utf-8");
|
|
96
|
+
console.log(colors.green(`[OK] Migration created for model '${ModelClass.name || baseName}': database/migrations/${filename}`));
|
|
97
|
+
count++;
|
|
98
|
+
await new Promise((r) => setTimeout(r, 1050));
|
|
99
|
+
}
|
|
100
|
+
} catch (err) {
|
|
101
|
+
console.warn(colors.yellow(`[WARN] Could not process model '${file}': ${err.message}`));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
console.log(colors.bold.green(`\n[OK] Generated ${count} migrations from app/models/.`));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let cleanName = name ? name.toLowerCase().replace(/[^a-z0-9_]/g, "_") : "";
|
|
110
|
+
let tableName = cleanName;
|
|
111
|
+
let ddl = "";
|
|
112
|
+
|
|
113
|
+
if (modelName) {
|
|
114
|
+
const modelPathJs = path.resolve(process.cwd(), `app/models/${modelName.toLowerCase()}.js`);
|
|
115
|
+
const modelPathTs = path.resolve(process.cwd(), `app/models/${modelName.toLowerCase()}.ts`);
|
|
116
|
+
const targetPath = fs.existsSync(modelPathJs) ? modelPathJs : (fs.existsSync(modelPathTs) ? modelPathTs : null);
|
|
117
|
+
|
|
118
|
+
if (targetPath) {
|
|
119
|
+
try {
|
|
120
|
+
const mod = await import(`file://${targetPath}`);
|
|
121
|
+
const ModelClass = mod.default || mod[modelName];
|
|
122
|
+
if (ModelClass && typeof ModelClass.toDDL === "function") {
|
|
123
|
+
ddl = ModelClass.toDDL(DB_TYPE);
|
|
124
|
+
tableName = ModelClass.table || modelName.toLowerCase();
|
|
125
|
+
if (!cleanName) {
|
|
126
|
+
cleanName = `create_${tableName}_table`;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} catch (err) {
|
|
130
|
+
console.warn(colors.yellow(`[WARN] Could not load model '${modelName}': ${err.message}`));
|
|
131
|
+
}
|
|
132
|
+
} else {
|
|
133
|
+
console.warn(colors.yellow(`[WARN] Model file for '${modelName}' not found in app/models/.`));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (!cleanName) {
|
|
138
|
+
console.log(colors.red("[ERROR] Missing migration name or target model."));
|
|
139
|
+
console.log("");
|
|
140
|
+
console.log("Usage:");
|
|
141
|
+
console.log(" npx blue-bird make:migration <name> Create blank migration");
|
|
142
|
+
console.log(" npx blue-bird make:migration --model <ModelName> Generate migration from Model schema");
|
|
143
|
+
console.log(" npx blue-bird make:migration <name> --model <Model> Custom migration name for Model");
|
|
144
|
+
console.log(" npx blue-bird make:migration --all Generate migrations for all models");
|
|
145
|
+
|
|
146
|
+
if (fs.existsSync(modelsDir)) {
|
|
147
|
+
const availableModels = fs.readdirSync(modelsDir)
|
|
148
|
+
.filter((f) => (f.endsWith(".js") || f.endsWith(".ts")) && !f.endsWith(".d.ts"))
|
|
149
|
+
.map((f) => path.basename(f, path.extname(f)));
|
|
150
|
+
if (availableModels.length > 0) {
|
|
151
|
+
console.log(colors.cyan(`\nModels available in app/models/: ${availableModels.join(", ")}`));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
process.exit(1);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (!tableName) {
|
|
158
|
+
tableName = cleanName;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const filename = `${getTimestamp()}_${cleanName}.sql`;
|
|
162
|
+
const filePath = path.join(migrationsDir, filename);
|
|
163
|
+
|
|
164
|
+
if (!ddl) {
|
|
165
|
+
let idCol = "id INTEGER PRIMARY KEY AUTOINCREMENT";
|
|
166
|
+
if (DB_TYPE === "postgres") idCol = "id SERIAL PRIMARY KEY";
|
|
167
|
+
if (DB_TYPE === "mysql") idCol = "id INT AUTO_INCREMENT PRIMARY KEY";
|
|
168
|
+
|
|
169
|
+
ddl = `CREATE TABLE IF NOT EXISTS ${tableName} (\n ${idCol},\n name VARCHAR(255) NOT NULL,\n description TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const template = `-- =============================================================\n-- Migration: ${cleanName}\n-- Created At: ${new Date().toISOString()}\n-- Driver Compatibility: ${DB_TYPE}\n-- =============================================================\n\n-- Up\n${ddl}\n\n-- Down\nDROP TABLE IF EXISTS ${tableName};\n`;
|
|
173
|
+
|
|
174
|
+
fs.writeFileSync(filePath, template, "utf-8");
|
|
175
|
+
console.log(colors.green(`[OK] Migration created: database/migrations/${filename}`));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Creates a new seed file in database/seeds/.
|
|
180
|
+
* @param {string} name
|
|
181
|
+
*/
|
|
182
|
+
function makeSeed(name) {
|
|
183
|
+
if (!name) {
|
|
184
|
+
console.log(colors.red("[ERROR] Missing seed name."));
|
|
185
|
+
console.log("Usage: npx blue-bird make:seed <name>");
|
|
186
|
+
process.exit(1);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const cleanName = name.toLowerCase().replace(/[^a-z0-9_]/g, "_");
|
|
190
|
+
const filename = `${cleanName}.sql`;
|
|
191
|
+
const seedsDir = path.resolve(process.cwd(), "database/seeds");
|
|
192
|
+
|
|
193
|
+
if (!fs.existsSync(seedsDir)) {
|
|
194
|
+
fs.mkdirSync(seedsDir, { recursive: true });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const filePath = path.join(seedsDir, filename);
|
|
198
|
+
|
|
199
|
+
const template = `-- =============================================================
|
|
200
|
+
-- Seed: ${cleanName}
|
|
201
|
+
-- Created At: ${new Date().toISOString()}
|
|
202
|
+
-- =============================================================
|
|
203
|
+
|
|
204
|
+
-- INSERT INTO ${cleanName} (name) VALUES ('Sample Item 1');
|
|
205
|
+
`;
|
|
206
|
+
|
|
207
|
+
fs.writeFileSync(filePath, template, "utf-8");
|
|
208
|
+
console.log(colors.green(`[OK] Seed file created: database/seeds/${filename}`));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Ensures migrations tracking table exists.
|
|
213
|
+
* @param {Database} db
|
|
214
|
+
*/
|
|
215
|
+
async function ensureMigrationsTable(db) {
|
|
216
|
+
let ddl = "";
|
|
217
|
+
if (DB_TYPE === "postgres") {
|
|
218
|
+
ddl = `CREATE TABLE IF NOT EXISTS _bluebird_migrations (
|
|
219
|
+
id SERIAL PRIMARY KEY,
|
|
220
|
+
name VARCHAR(255) NOT NULL UNIQUE,
|
|
221
|
+
batch INT NOT NULL,
|
|
222
|
+
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
223
|
+
);`;
|
|
224
|
+
} else if (DB_TYPE === "mysql") {
|
|
225
|
+
ddl = `CREATE TABLE IF NOT EXISTS _bluebird_migrations (
|
|
226
|
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
227
|
+
name VARCHAR(255) NOT NULL UNIQUE,
|
|
228
|
+
batch INT NOT NULL,
|
|
229
|
+
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
230
|
+
);`;
|
|
231
|
+
} else {
|
|
232
|
+
ddl = `CREATE TABLE IF NOT EXISTS _bluebird_migrations (
|
|
233
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
234
|
+
name TEXT NOT NULL UNIQUE,
|
|
235
|
+
batch INTEGER NOT NULL,
|
|
236
|
+
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
237
|
+
);`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
await db.query(ddl);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Executes pending database migrations.
|
|
245
|
+
*/
|
|
246
|
+
async function runMigrations() {
|
|
247
|
+
const migrationsDir = path.resolve(process.cwd(), "database/migrations");
|
|
248
|
+
if (!fs.existsSync(migrationsDir)) {
|
|
249
|
+
console.log(colors.yellow("[INFO] No 'database/migrations' directory found. Nothing to migrate."));
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const files = fs
|
|
254
|
+
.readdirSync(migrationsDir)
|
|
255
|
+
.filter((f) => f.endsWith(".sql") || f.endsWith(".js") || f.endsWith(".ts"))
|
|
256
|
+
.sort();
|
|
257
|
+
|
|
258
|
+
if (files.length === 0) {
|
|
259
|
+
console.log(colors.yellow("[INFO] No migration files found in 'database/migrations'."));
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
let db;
|
|
264
|
+
try {
|
|
265
|
+
db = new Database(5);
|
|
266
|
+
await ensureMigrationsTable(db);
|
|
267
|
+
} catch (err) {
|
|
268
|
+
console.error(colors.red("[ERROR] Could not connect to database to run migrations:"), err.message);
|
|
269
|
+
process.exit(1);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const appliedRows = (await db.query("SELECT name, batch FROM _bluebird_migrations ORDER BY id ASC")) || [];
|
|
273
|
+
const appliedSet = new Set(appliedRows.map((r) => r.name));
|
|
274
|
+
|
|
275
|
+
const maxBatchRow = await db.query("SELECT MAX(batch) as max_batch FROM _bluebird_migrations", [], "return_row");
|
|
276
|
+
const currentBatch = ((maxBatchRow && maxBatchRow.max_batch) || 0) + 1;
|
|
277
|
+
|
|
278
|
+
const pending = files.filter((f) => !appliedSet.has(f));
|
|
279
|
+
|
|
280
|
+
if (pending.length === 0) {
|
|
281
|
+
console.log(colors.green("[INFO] Database is up to date. No pending migrations."));
|
|
282
|
+
process.exit(0);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
console.log(colors.cyan(`[INFO] Running ${pending.length} pending migration(s) (Batch #${currentBatch})...\n`));
|
|
286
|
+
|
|
287
|
+
for (const file of pending) {
|
|
288
|
+
const filePath = path.join(migrationsDir, file);
|
|
289
|
+
try {
|
|
290
|
+
if (file.endsWith(".sql")) {
|
|
291
|
+
const fullContent = fs.readFileSync(filePath, "utf-8");
|
|
292
|
+
const upSection = fullContent.split(/--\s*Down/i)[0] || fullContent;
|
|
293
|
+
const statements = splitSqlStatements(upSection);
|
|
294
|
+
|
|
295
|
+
await db.transaction(async (tx) => {
|
|
296
|
+
for (const stmt of statements) {
|
|
297
|
+
await tx.query(stmt);
|
|
298
|
+
}
|
|
299
|
+
await tx.query(
|
|
300
|
+
"INSERT INTO _bluebird_migrations (name, batch) VALUES (?, ?)",
|
|
301
|
+
[file, currentBatch]
|
|
302
|
+
);
|
|
303
|
+
});
|
|
304
|
+
} else {
|
|
305
|
+
const modulePath = `file://${filePath}`;
|
|
306
|
+
const migrationModule = await import(modulePath);
|
|
307
|
+
if (typeof migrationModule.up === "function") {
|
|
308
|
+
await db.transaction(async (tx) => {
|
|
309
|
+
await migrationModule.up(tx);
|
|
310
|
+
await tx.query(
|
|
311
|
+
"INSERT INTO _bluebird_migrations (name, batch) VALUES (?, ?)",
|
|
312
|
+
[file, currentBatch]
|
|
313
|
+
);
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
console.log(colors.green(` [MIGRATED] ${file}`));
|
|
319
|
+
} catch (err) {
|
|
320
|
+
console.error(colors.red(` [FAILED] ${file}: ${err.message}`));
|
|
321
|
+
process.exit(1);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
console.log(colors.bold.green("\n[OK] All pending migrations executed successfully."));
|
|
326
|
+
process.exit(0);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Rolls back the latest batch of database migrations.
|
|
331
|
+
*/
|
|
332
|
+
async function rollbackMigrations() {
|
|
333
|
+
const migrationsDir = path.resolve(process.cwd(), "database/migrations");
|
|
334
|
+
if (!fs.existsSync(migrationsDir)) {
|
|
335
|
+
console.log(colors.yellow("[INFO] No 'database/migrations' directory found."));
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
let db;
|
|
340
|
+
try {
|
|
341
|
+
db = new Database(5);
|
|
342
|
+
await ensureMigrationsTable(db);
|
|
343
|
+
} catch (err) {
|
|
344
|
+
console.error(colors.red("[ERROR] Could not connect to database:"), err.message);
|
|
345
|
+
process.exit(1);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const maxBatchRow = await db.query("SELECT MAX(batch) as max_batch FROM _bluebird_migrations", [], "return_row");
|
|
349
|
+
const lastBatch = maxBatchRow?.max_batch;
|
|
350
|
+
|
|
351
|
+
if (!lastBatch) {
|
|
352
|
+
console.log(colors.yellow("[INFO] No migrations found to rollback."));
|
|
353
|
+
process.exit(0);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const batchRows = (await db.query("SELECT name FROM _bluebird_migrations WHERE batch = ? ORDER BY id DESC", [lastBatch])) || [];
|
|
357
|
+
console.log(colors.cyan(`[INFO] Rolling back Batch #${lastBatch} (${batchRows.length} migration(s))...\n`));
|
|
358
|
+
|
|
359
|
+
for (const row of batchRows) {
|
|
360
|
+
const file = row.name;
|
|
361
|
+
const filePath = path.join(migrationsDir, file);
|
|
362
|
+
|
|
363
|
+
try {
|
|
364
|
+
if (fs.existsSync(filePath)) {
|
|
365
|
+
if (file.endsWith(".sql")) {
|
|
366
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
367
|
+
const downParts = content.split(/--\s*Down/i);
|
|
368
|
+
if (downParts.length > 1) {
|
|
369
|
+
const downStatements = splitSqlStatements(downParts[1]);
|
|
370
|
+
|
|
371
|
+
await db.transaction(async (tx) => {
|
|
372
|
+
for (const stmt of downStatements) {
|
|
373
|
+
await tx.query(stmt);
|
|
374
|
+
}
|
|
375
|
+
await tx.query("DELETE FROM _bluebird_migrations WHERE name = ?", [file]);
|
|
376
|
+
});
|
|
377
|
+
} else {
|
|
378
|
+
await db.query("DELETE FROM _bluebird_migrations WHERE name = ?", [file]);
|
|
379
|
+
}
|
|
380
|
+
} else {
|
|
381
|
+
const mod = await import(`file://${filePath}`);
|
|
382
|
+
if (typeof mod.down === "function") {
|
|
383
|
+
await db.transaction(async (tx) => {
|
|
384
|
+
await mod.down(tx);
|
|
385
|
+
await tx.query("DELETE FROM _bluebird_migrations WHERE name = ?", [file]);
|
|
386
|
+
});
|
|
387
|
+
} else {
|
|
388
|
+
await db.query("DELETE FROM _bluebird_migrations WHERE name = ?", [file]);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
} else {
|
|
392
|
+
await db.query("DELETE FROM _bluebird_migrations WHERE name = ?", [file]);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
console.log(colors.green(` [ROLLED BACK] ${file}`));
|
|
396
|
+
} catch (err) {
|
|
397
|
+
console.error(colors.red(` [FAILED] ${file}: ${err.message}`));
|
|
398
|
+
process.exit(1);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
console.log(colors.bold.green("\n[OK] Rollback completed successfully."));
|
|
403
|
+
process.exit(0);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Shows migration status list.
|
|
408
|
+
*/
|
|
409
|
+
async function showMigrationStatus() {
|
|
410
|
+
const migrationsDir = path.resolve(process.cwd(), "database/migrations");
|
|
411
|
+
if (!fs.existsSync(migrationsDir)) {
|
|
412
|
+
console.log(colors.yellow("[INFO] No 'database/migrations' directory found."));
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const files = fs
|
|
417
|
+
.readdirSync(migrationsDir)
|
|
418
|
+
.filter((f) => f.endsWith(".sql") || f.endsWith(".js") || f.endsWith(".ts"))
|
|
419
|
+
.sort();
|
|
420
|
+
|
|
421
|
+
let db;
|
|
422
|
+
try {
|
|
423
|
+
db = new Database(5);
|
|
424
|
+
await ensureMigrationsTable(db);
|
|
425
|
+
} catch (err) {
|
|
426
|
+
console.error(colors.red("[ERROR] Could not connect to database:"), err.message);
|
|
427
|
+
process.exit(1);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const appliedRows = (await db.query("SELECT name, batch, executed_at FROM _bluebird_migrations ORDER BY id ASC")) || [];
|
|
431
|
+
const appliedMap = new Map(appliedRows.map((r) => [r.name, r]));
|
|
432
|
+
|
|
433
|
+
console.log(colors.bold.cyan("\n============================================================="));
|
|
434
|
+
console.log(colors.bold.cyan(" Database Migrations Status"));
|
|
435
|
+
console.log(colors.bold.cyan("=============================================================\n"));
|
|
436
|
+
|
|
437
|
+
for (const file of files) {
|
|
438
|
+
if (appliedMap.has(file)) {
|
|
439
|
+
const record = appliedMap.get(file);
|
|
440
|
+
console.log(` ${colors.green("[APPLIED]")} ${file.padEnd(40)} (Batch: ${record.batch}, At: ${record.executed_at})`);
|
|
441
|
+
} else {
|
|
442
|
+
console.log(` ${colors.yellow("[PENDING]")} ${file}`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
console.log("");
|
|
447
|
+
process.exit(0);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Runs seed scripts from database/seeds/.
|
|
452
|
+
*/
|
|
453
|
+
async function runSeeds() {
|
|
454
|
+
const seedsDir = path.resolve(process.cwd(), "database/seeds");
|
|
455
|
+
if (!fs.existsSync(seedsDir)) {
|
|
456
|
+
console.log(colors.yellow("[INFO] No 'database/seeds' directory found. Nothing to seed."));
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const files = fs
|
|
461
|
+
.readdirSync(seedsDir)
|
|
462
|
+
.filter((f) => f.endsWith(".sql") || f.endsWith(".js") || f.endsWith(".ts"))
|
|
463
|
+
.sort();
|
|
464
|
+
|
|
465
|
+
if (files.length === 0) {
|
|
466
|
+
console.log(colors.yellow("[INFO] No seed files found in 'database/seeds'."));
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
let db;
|
|
471
|
+
try {
|
|
472
|
+
db = new Database(5);
|
|
473
|
+
} catch (err) {
|
|
474
|
+
console.error(colors.red("[ERROR] Could not connect to database to run seeds:"), err.message);
|
|
475
|
+
process.exit(1);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
console.log(colors.cyan(`[INFO] Running ${files.length} seed file(s)...\n`));
|
|
479
|
+
|
|
480
|
+
for (const file of files) {
|
|
481
|
+
const filePath = path.join(seedsDir, file);
|
|
482
|
+
try {
|
|
483
|
+
if (file.endsWith(".sql")) {
|
|
484
|
+
const sql = fs.readFileSync(filePath, "utf-8");
|
|
485
|
+
const statements = splitSqlStatements(sql);
|
|
486
|
+
|
|
487
|
+
await db.transaction(async (tx) => {
|
|
488
|
+
for (const stmt of statements) {
|
|
489
|
+
await tx.query(stmt);
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
} else {
|
|
493
|
+
const modulePath = `file://${filePath}`;
|
|
494
|
+
const seedModule = await import(modulePath);
|
|
495
|
+
if (typeof seedModule.seed === "function") {
|
|
496
|
+
await db.transaction(async (tx) => {
|
|
497
|
+
await seedModule.seed(tx);
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
console.log(colors.green(` [SEEDED] ${file}`));
|
|
503
|
+
} catch (err) {
|
|
504
|
+
console.error(colors.red(` [FAILED] ${file}: ${err.message}`));
|
|
505
|
+
process.exit(1);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
console.log(colors.bold.green("\n[OK] Database seeding completed."));
|
|
510
|
+
process.exit(0);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const rawArgs = process.argv.slice(2);
|
|
514
|
+
const cmd = rawArgs[0];
|
|
515
|
+
|
|
516
|
+
if (cmd === "make:migration") {
|
|
517
|
+
const modelIdx = rawArgs.indexOf("--model");
|
|
518
|
+
const modelName = modelIdx !== -1 ? rawArgs[modelIdx + 1] : null;
|
|
519
|
+
const isAll = rawArgs.includes("--all") || rawArgs.includes("-a");
|
|
520
|
+
|
|
521
|
+
const positionalArgs = rawArgs.slice(1).filter((arg, i, arr) => {
|
|
522
|
+
if (arg.startsWith("-")) return false;
|
|
523
|
+
const prev = arr[i - 1];
|
|
524
|
+
if (prev === "--model" || prev === "-m") return false;
|
|
525
|
+
return true;
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
const name = positionalArgs[0] || null;
|
|
529
|
+
makeMigration(name, modelName, isAll);
|
|
530
|
+
|
|
531
|
+
} else if (cmd === "make:seed") {
|
|
532
|
+
makeSeed(rawArgs[1]);
|
|
533
|
+
} else if (cmd === "migrate:status") {
|
|
534
|
+
showMigrationStatus();
|
|
535
|
+
} else if (cmd === "migrate:rollback") {
|
|
536
|
+
rollbackMigrations();
|
|
537
|
+
} else if (cmd === "seed") {
|
|
538
|
+
runSeeds();
|
|
539
|
+
} else {
|
|
540
|
+
runMigrations();
|
|
541
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import colors from "../util/colors.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Creates a new Model file in app/models/.
|
|
9
|
+
* @param {string} name - Model class name (e.g. User, Product).
|
|
10
|
+
*/
|
|
11
|
+
export function makeModel(name) {
|
|
12
|
+
if (!name) {
|
|
13
|
+
console.log(colors.red("[ERROR] Missing model name."));
|
|
14
|
+
console.log("Usage: npx bluebird-js make:model <Name>");
|
|
15
|
+
process.exit(1);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const cleanName = name.charAt(0).toUpperCase() + name.slice(1).replace(/[^a-zA-Z0-9_]/g, "");
|
|
19
|
+
const tableName = cleanName.toLowerCase().endsWith("s")
|
|
20
|
+
? cleanName.toLowerCase()
|
|
21
|
+
: `${cleanName.toLowerCase()}s`;
|
|
22
|
+
|
|
23
|
+
const modelsDir = path.resolve(process.cwd(), "app/models");
|
|
24
|
+
if (!fs.existsSync(modelsDir)) {
|
|
25
|
+
fs.mkdirSync(modelsDir, { recursive: true });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const filename = `${cleanName.toLowerCase()}.js`;
|
|
29
|
+
const filePath = path.join(modelsDir, filename);
|
|
30
|
+
|
|
31
|
+
if (fs.existsSync(filePath)) {
|
|
32
|
+
console.log(colors.yellow(`[WARN] Model file already exists at app/models/${filename}`));
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const template = `import Model from "@seip/bluebird-js/core/model.js";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* ${cleanName} Model representation.
|
|
40
|
+
* Provides transparent schema definitions, validation bridge, and query shortcuts.
|
|
41
|
+
* Note: For complex multi-tier enterprise ORMs, Prisma is recommended.
|
|
42
|
+
*/
|
|
43
|
+
export default class ${cleanName} extends Model {
|
|
44
|
+
static table = "${tableName}";
|
|
45
|
+
static primaryKey = "id";
|
|
46
|
+
static timestamps = true;
|
|
47
|
+
static softDelete = false;
|
|
48
|
+
|
|
49
|
+
static schema = {
|
|
50
|
+
id: { type: "int", primary: true, auto: true },
|
|
51
|
+
name: { type: "string", length: 150, required: true },
|
|
52
|
+
created_at: { type: "date" },
|
|
53
|
+
updated_at: { type: "date" },
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
`;
|
|
57
|
+
|
|
58
|
+
fs.writeFileSync(filePath, template, "utf-8");
|
|
59
|
+
console.log(colors.green(`[OK] Model created: app/models/${filename}`));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const args = process.argv.slice(2);
|
|
63
|
+
if (args[0] === "make:model" || args[0] === "model") {
|
|
64
|
+
const modelName = args.find((a, i) => i > 0 && !a.startsWith("-"));
|
|
65
|
+
makeModel(modelName);
|
|
66
|
+
}
|