@zero-server/sdk 0.9.1 → 0.9.3

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.
Files changed (128) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/body.d.ts +14 -0
  113. package/types/cli.d.ts +2 -0
  114. package/types/cluster.d.ts +75 -75
  115. package/types/env.d.ts +80 -80
  116. package/types/errors.d.ts +316 -316
  117. package/types/fetch.d.ts +43 -43
  118. package/types/grpc.d.ts +432 -432
  119. package/types/index.d.ts +384 -384
  120. package/types/lifecycle.d.ts +60 -60
  121. package/types/middleware.d.ts +320 -320
  122. package/types/observe.d.ts +304 -304
  123. package/types/orm.d.ts +1887 -1887
  124. package/types/request.d.ts +109 -109
  125. package/types/response.d.ts +157 -157
  126. package/types/router.d.ts +78 -78
  127. package/types/sse.d.ts +78 -78
  128. package/types/websocket.d.ts +126 -126
@@ -1,432 +1,432 @@
1
- /**
2
- * @module orm/migrate
3
- * @description Versioned migration framework for the zero-server ORM.
4
- * Supports up/down migrations, batch tracking, rollback,
5
- * status reporting, and full reset/fresh operations.
6
- *
7
- * @example
8
- * const { Database, Migrator } = require('@zero-server/sdk');
9
- *
10
- * const db = Database.connect('sqlite', { filename: './app.db' });
11
- *
12
- * const migrator = new Migrator(db);
13
- *
14
- * // Define migrations
15
- * migrator.add({
16
- * name: '001_create_users',
17
- * async up(db) {
18
- * await db.adapter.execute({
19
- * action: 'raw',
20
- * sql: `CREATE TABLE users (
21
- * id INTEGER PRIMARY KEY AUTOINCREMENT,
22
- * name TEXT NOT NULL,
23
- * email TEXT UNIQUE
24
- * )`
25
- * });
26
- * },
27
- * async down(db) {
28
- * await db.adapter.dropTable('users');
29
- * }
30
- * });
31
- *
32
- * // Run pending migrations
33
- * const result = await migrator.migrate();
34
- *
35
- * // Rollback last batch
36
- * await migrator.rollback();
37
- *
38
- * // Check status
39
- * const status = await migrator.status();
40
- */
41
-
42
- const log = require('../debug')('zero:migrate');
43
-
44
- /**
45
- * Internal model for tracking migration state.
46
- * Stored in a `_migrations` table within the same database.
47
- */
48
- const MIGRATION_TABLE = '_migrations';
49
- const MIGRATION_SCHEMA = {
50
- id: { type: 'integer', primaryKey: true, autoIncrement: true },
51
- name: { type: 'string', required: true, unique: true },
52
- batch: { type: 'integer', required: true },
53
- executed: { type: 'datetime' },
54
- };
55
-
56
- class Migrator
57
- {
58
- /**
59
- * @constructor
60
- * @param {import('./index').Database} db - Database instance.
61
- * @param {object} [options] - Configuration options.
62
- * @param {string} [options.table='_migrations'] - Migration tracking table name.
63
- */
64
- constructor(db, options = {})
65
- {
66
- this._db = db;
67
- this._adapter = db.adapter;
68
- this._table = options.table || MIGRATION_TABLE;
69
- this._migrations = [];
70
- this._initialized = false;
71
- }
72
-
73
- /**
74
- * Add a migration definition.
75
- * @param {object} migration - Migration definition.
76
- * @param {string} migration.name - Unique migration name (e.g., '001_create_users').
77
- * @param {Function} migration.up - Forward migration: `async (db) => {}`.
78
- * @param {Function} migration.down - Reverse migration: `async (db) => {}`.
79
- * @returns {Migrator} this (for chaining)
80
- */
81
- add(migration)
82
- {
83
- if (!migration.name || typeof migration.name !== 'string')
84
- throw new Error('Migration must have a name');
85
- if (!/^[\w\-.]+$/.test(migration.name))
86
- throw new Error(`Migration name "${migration.name}" contains invalid characters (only letters, digits, underscore, hyphen, dot allowed)`);
87
- if (typeof migration.up !== 'function') throw new Error(`Migration "${migration.name}": up() must be a function`);
88
- if (typeof migration.down !== 'function') throw new Error(`Migration "${migration.name}": down() must be a function`);
89
-
90
- // Prevent duplicate names
91
- if (this._migrations.some(m => m.name === migration.name))
92
- {
93
- throw new Error(`Migration "${migration.name}" is already registered`);
94
- }
95
-
96
- this._migrations.push(migration);
97
- return this;
98
- }
99
-
100
- /**
101
- * Add multiple migrations at once.
102
- * @param {object[]} migrations - Array of migration definitions.
103
- * @returns {Migrator} this (for chaining)
104
- */
105
- addAll(migrations)
106
- {
107
- for (const m of migrations) this.add(m);
108
- return this;
109
- }
110
-
111
- /**
112
- * Ensure the migration tracking table exists.
113
- * @private
114
- */
115
- async _init()
116
- {
117
- if (this._initialized) return;
118
-
119
- await this._adapter.createTable(this._table, MIGRATION_SCHEMA);
120
- this._initialized = true;
121
- }
122
-
123
- /**
124
- * Get all previously executed migrations from the tracking table.
125
- * @private
126
- * @returns {Promise<object[]>} Executed migration records.
127
- */
128
- async _getExecuted()
129
- {
130
- await this._init();
131
- try
132
- {
133
- const rows = await this._adapter.execute({
134
- action: 'select',
135
- table: this._table,
136
- where: [],
137
- orderBy: [{ field: 'id', dir: 'ASC' }],
138
- });
139
- return Array.isArray(rows) ? rows : [];
140
- }
141
- catch (_)
142
- {
143
- return [];
144
- }
145
- }
146
-
147
- /**
148
- * Record a migration as executed.
149
- * @private
150
- */
151
- async _record(name, batch)
152
- {
153
- await this._adapter.insert(this._table, {
154
- name,
155
- batch,
156
- executed: new Date().toISOString(),
157
- });
158
- }
159
-
160
- /**
161
- * Remove a migration record.
162
- * @private
163
- */
164
- async _unrecord(name)
165
- {
166
- await this._adapter.deleteWhere(this._table, { name });
167
- }
168
-
169
- /**
170
- * Get the next batch number.
171
- * @private
172
- * @returns {Promise<number>} Next batch number.
173
- */
174
- async _nextBatch()
175
- {
176
- const executed = await this._getExecuted();
177
- if (executed.length === 0) return 1;
178
- return Math.max(...executed.map(m => m.batch)) + 1;
179
- }
180
-
181
- /**
182
- * Run all pending migrations.
183
- *
184
- * @returns {Promise<{ migrated: string[], batch: number }>}
185
- * List of migration names that were executed and the batch number.
186
- *
187
- * @example
188
- * const { migrated, batch } = await migrator.migrate();
189
- * console.log(`Ran ${migrated.length} migrations in batch ${batch}`);
190
- */
191
- async migrate()
192
- {
193
- await this._init();
194
-
195
- const executed = await this._getExecuted();
196
- const executedNames = new Set(executed.map(m => m.name));
197
- const pending = this._migrations.filter(m => !executedNames.has(m.name));
198
-
199
- if (pending.length === 0)
200
- {
201
- log('No pending migrations');
202
- return { migrated: [], batch: 0 };
203
- }
204
-
205
- const batch = await this._nextBatch();
206
- const migrated = [];
207
-
208
- for (const migration of pending)
209
- {
210
- log(`Migrating: ${migration.name}`);
211
- try
212
- {
213
- await migration.up(this._db);
214
- await this._record(migration.name, batch);
215
- migrated.push(migration.name);
216
- log(`Migrated: ${migration.name}`);
217
- }
218
- catch (err)
219
- {
220
- const error = new Error(
221
- `Migration "${migration.name}" failed: ${err.message}`
222
- );
223
- error.migration = migration.name;
224
- error.batch = batch;
225
- error.cause = err;
226
- throw error;
227
- }
228
- }
229
-
230
- return { migrated, batch };
231
- }
232
-
233
- /**
234
- * Rollback the last batch of migrations.
235
- *
236
- * @returns {Promise<{ rolledBack: string[], batch: number }>}
237
- *
238
- * @example
239
- * const { rolledBack } = await migrator.rollback();
240
- * console.log(`Rolled back: ${rolledBack.join(', ')}`);
241
- */
242
- async rollback()
243
- {
244
- await this._init();
245
-
246
- const executed = await this._getExecuted();
247
- if (executed.length === 0)
248
- {
249
- return { rolledBack: [], batch: 0 };
250
- }
251
-
252
- const lastBatch = Math.max(...executed.map(m => m.batch));
253
- const toRollback = executed
254
- .filter(m => m.batch === lastBatch)
255
- .reverse(); // Roll back in reverse order
256
-
257
- const rolledBack = [];
258
-
259
- for (const record of toRollback)
260
- {
261
- const migration = this._migrations.find(m => m.name === record.name);
262
- if (!migration)
263
- {
264
- throw new Error(
265
- `Cannot rollback "${record.name}": migration definition not found. ` +
266
- `Ensure all migrations are registered before rolling back.`
267
- );
268
- }
269
-
270
- log(`Rolling back: ${record.name}`);
271
- try
272
- {
273
- await migration.down(this._db);
274
- await this._unrecord(record.name);
275
- rolledBack.push(record.name);
276
- log(`Rolled back: ${record.name}`);
277
- }
278
- catch (err)
279
- {
280
- const error = new Error(
281
- `Rollback of "${record.name}" failed: ${err.message}`
282
- );
283
- error.migration = record.name;
284
- error.cause = err;
285
- throw error;
286
- }
287
- }
288
-
289
- return { rolledBack, batch: lastBatch };
290
- }
291
-
292
- /**
293
- * Rollback all migrations (in reverse order, batch by batch).
294
- *
295
- * @returns {Promise<{ rolledBack: string[] }>}
296
- */
297
- async rollbackAll()
298
- {
299
- const allRolledBack = [];
300
- let result;
301
- do
302
- {
303
- result = await this.rollback();
304
- allRolledBack.push(...result.rolledBack);
305
- }
306
- while (result.rolledBack.length > 0);
307
-
308
- return { rolledBack: allRolledBack };
309
- }
310
-
311
- /**
312
- * Reset the database: rollback all migrations, then re-run all.
313
- *
314
- * @returns {Promise<{ rolledBack: string[], migrated: string[], batch: number }>}
315
- */
316
- async reset()
317
- {
318
- const { rolledBack } = await this.rollbackAll();
319
- const { migrated, batch } = await this.migrate();
320
- return { rolledBack, migrated, batch };
321
- }
322
-
323
- /**
324
- * Fresh start: drop ALL tables (not just migrated ones) then re-migrate.
325
- * ⚠️ DESTRUCTIVE — use with caution.
326
- *
327
- * @returns {Promise<{ migrated: string[], batch: number }>}
328
- */
329
- async fresh()
330
- {
331
- // Drop all registered model tables via db.drop()
332
- try { await this._db.drop(); } catch (_) { /* ignore if no models registered */ }
333
-
334
- // Also drop the migration tracking table
335
- try { await this._adapter.dropTable(this._table); } catch (_) { /* ignore */ }
336
-
337
- this._initialized = false;
338
-
339
- // Re-run all migrations
340
- return this.migrate();
341
- }
342
-
343
- /**
344
- * Get the current migration status.
345
- *
346
- * @returns {Promise<{ executed: object[], pending: string[], lastBatch: number }>}
347
- *
348
- * @example
349
- * const { executed, pending, lastBatch } = await migrator.status();
350
- * console.log(`Executed: ${executed.length}, Pending: ${pending.length}`);
351
- */
352
- async status()
353
- {
354
- await this._init();
355
-
356
- const executed = await this._getExecuted();
357
- const executedNames = new Set(executed.map(m => m.name));
358
- const pending = this._migrations
359
- .filter(m => !executedNames.has(m.name))
360
- .map(m => m.name);
361
-
362
- const lastBatch = executed.length > 0
363
- ? Math.max(...executed.map(m => m.batch))
364
- : 0;
365
-
366
- return {
367
- executed: executed.map(m => ({
368
- name: m.name,
369
- batch: m.batch,
370
- executedAt: m.executed,
371
- })),
372
- pending,
373
- lastBatch,
374
- };
375
- }
376
-
377
- /**
378
- * Check if there are any pending migrations.
379
- * @returns {Promise<boolean>} True if there are pending migrations.
380
- */
381
- async hasPending()
382
- {
383
- const { pending } = await this.status();
384
- return pending.length > 0;
385
- }
386
-
387
- /**
388
- * Get the list of registered migration names.
389
- * @returns {string[]} Registered migration names in order.
390
- */
391
- list()
392
- {
393
- return this._migrations.map(m => m.name);
394
- }
395
- }
396
-
397
- /**
398
- * Helper to create a migration definition object.
399
- *
400
- * @param {string} name - Name identifier.
401
- * @param {Function} up - `async (db) => { ... }`
402
- * @param {Function} down - `async (db) => { ... }`
403
- * @returns {{ name: string, up: Function, down: Function }}
404
- *
405
- * @example
406
- * const { defineMigration } = require('@zero-server/sdk');
407
- *
408
- * module.exports = defineMigration('001_create_users',
409
- * async (db) => {
410
- * // up
411
- * await db.addColumn('users', 'avatar', { type: TYPES.STRING });
412
- * },
413
- * async (db) => {
414
- * // down
415
- * await db.dropColumn('users', 'avatar');
416
- * }
417
- * );
418
- */
419
- function defineMigration(name, up, down)
420
- {
421
- if (!name || typeof name !== 'string')
422
- throw new Error('defineMigration: name is required');
423
- if (!/^[\w\-.]+$/.test(name))
424
- throw new Error(`defineMigration: name "${name}" contains invalid characters`);
425
- if (typeof up !== 'function')
426
- throw new Error(`defineMigration "${name}": up must be a function`);
427
- if (typeof down !== 'function')
428
- throw new Error(`defineMigration "${name}": down must be a function`);
429
- return { name, up, down };
430
- }
431
-
432
- module.exports = { Migrator, defineMigration };
1
+ /**
2
+ * @module orm/migrate
3
+ * @description Versioned migration framework for the zero-server ORM.
4
+ * Supports up/down migrations, batch tracking, rollback,
5
+ * status reporting, and full reset/fresh operations.
6
+ *
7
+ * @example
8
+ * const { Database, Migrator } = require('@zero-server/sdk');
9
+ *
10
+ * const db = Database.connect('sqlite', { filename: './app.db' });
11
+ *
12
+ * const migrator = new Migrator(db);
13
+ *
14
+ * // Define migrations
15
+ * migrator.add({
16
+ * name: '001_create_users',
17
+ * async up(db) {
18
+ * await db.adapter.execute({
19
+ * action: 'raw',
20
+ * sql: `CREATE TABLE users (
21
+ * id INTEGER PRIMARY KEY AUTOINCREMENT,
22
+ * name TEXT NOT NULL,
23
+ * email TEXT UNIQUE
24
+ * )`
25
+ * });
26
+ * },
27
+ * async down(db) {
28
+ * await db.adapter.dropTable('users');
29
+ * }
30
+ * });
31
+ *
32
+ * // Run pending migrations
33
+ * const result = await migrator.migrate();
34
+ *
35
+ * // Rollback last batch
36
+ * await migrator.rollback();
37
+ *
38
+ * // Check status
39
+ * const status = await migrator.status();
40
+ */
41
+
42
+ const log = require('../debug')('zero:migrate');
43
+
44
+ /**
45
+ * Internal model for tracking migration state.
46
+ * Stored in a `_migrations` table within the same database.
47
+ */
48
+ const MIGRATION_TABLE = '_migrations';
49
+ const MIGRATION_SCHEMA = {
50
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
51
+ name: { type: 'string', required: true, unique: true },
52
+ batch: { type: 'integer', required: true },
53
+ executed: { type: 'datetime' },
54
+ };
55
+
56
+ class Migrator
57
+ {
58
+ /**
59
+ * @constructor
60
+ * @param {import('./index').Database} db - Database instance.
61
+ * @param {object} [options] - Configuration options.
62
+ * @param {string} [options.table='_migrations'] - Migration tracking table name.
63
+ */
64
+ constructor(db, options = {})
65
+ {
66
+ this._db = db;
67
+ this._adapter = db.adapter;
68
+ this._table = options.table || MIGRATION_TABLE;
69
+ this._migrations = [];
70
+ this._initialized = false;
71
+ }
72
+
73
+ /**
74
+ * Add a migration definition.
75
+ * @param {object} migration - Migration definition.
76
+ * @param {string} migration.name - Unique migration name (e.g., '001_create_users').
77
+ * @param {Function} migration.up - Forward migration: `async (db) => {}`.
78
+ * @param {Function} migration.down - Reverse migration: `async (db) => {}`.
79
+ * @returns {Migrator} this (for chaining)
80
+ */
81
+ add(migration)
82
+ {
83
+ if (!migration.name || typeof migration.name !== 'string')
84
+ throw new Error('Migration must have a name');
85
+ if (!/^[\w\-.]+$/.test(migration.name))
86
+ throw new Error(`Migration name "${migration.name}" contains invalid characters (only letters, digits, underscore, hyphen, dot allowed)`);
87
+ if (typeof migration.up !== 'function') throw new Error(`Migration "${migration.name}": up() must be a function`);
88
+ if (typeof migration.down !== 'function') throw new Error(`Migration "${migration.name}": down() must be a function`);
89
+
90
+ // Prevent duplicate names
91
+ if (this._migrations.some(m => m.name === migration.name))
92
+ {
93
+ throw new Error(`Migration "${migration.name}" is already registered`);
94
+ }
95
+
96
+ this._migrations.push(migration);
97
+ return this;
98
+ }
99
+
100
+ /**
101
+ * Add multiple migrations at once.
102
+ * @param {object[]} migrations - Array of migration definitions.
103
+ * @returns {Migrator} this (for chaining)
104
+ */
105
+ addAll(migrations)
106
+ {
107
+ for (const m of migrations) this.add(m);
108
+ return this;
109
+ }
110
+
111
+ /**
112
+ * Ensure the migration tracking table exists.
113
+ * @private
114
+ */
115
+ async _init()
116
+ {
117
+ if (this._initialized) return;
118
+
119
+ await this._adapter.createTable(this._table, MIGRATION_SCHEMA);
120
+ this._initialized = true;
121
+ }
122
+
123
+ /**
124
+ * Get all previously executed migrations from the tracking table.
125
+ * @private
126
+ * @returns {Promise<object[]>} Executed migration records.
127
+ */
128
+ async _getExecuted()
129
+ {
130
+ await this._init();
131
+ try
132
+ {
133
+ const rows = await this._adapter.execute({
134
+ action: 'select',
135
+ table: this._table,
136
+ where: [],
137
+ orderBy: [{ field: 'id', dir: 'ASC' }],
138
+ });
139
+ return Array.isArray(rows) ? rows : [];
140
+ }
141
+ catch (_)
142
+ {
143
+ return [];
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Record a migration as executed.
149
+ * @private
150
+ */
151
+ async _record(name, batch)
152
+ {
153
+ await this._adapter.insert(this._table, {
154
+ name,
155
+ batch,
156
+ executed: new Date().toISOString(),
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Remove a migration record.
162
+ * @private
163
+ */
164
+ async _unrecord(name)
165
+ {
166
+ await this._adapter.deleteWhere(this._table, { name });
167
+ }
168
+
169
+ /**
170
+ * Get the next batch number.
171
+ * @private
172
+ * @returns {Promise<number>} Next batch number.
173
+ */
174
+ async _nextBatch()
175
+ {
176
+ const executed = await this._getExecuted();
177
+ if (executed.length === 0) return 1;
178
+ return Math.max(...executed.map(m => m.batch)) + 1;
179
+ }
180
+
181
+ /**
182
+ * Run all pending migrations.
183
+ *
184
+ * @returns {Promise<{ migrated: string[], batch: number }>}
185
+ * List of migration names that were executed and the batch number.
186
+ *
187
+ * @example
188
+ * const { migrated, batch } = await migrator.migrate();
189
+ * console.log(`Ran ${migrated.length} migrations in batch ${batch}`);
190
+ */
191
+ async migrate()
192
+ {
193
+ await this._init();
194
+
195
+ const executed = await this._getExecuted();
196
+ const executedNames = new Set(executed.map(m => m.name));
197
+ const pending = this._migrations.filter(m => !executedNames.has(m.name));
198
+
199
+ if (pending.length === 0)
200
+ {
201
+ log('No pending migrations');
202
+ return { migrated: [], batch: 0 };
203
+ }
204
+
205
+ const batch = await this._nextBatch();
206
+ const migrated = [];
207
+
208
+ for (const migration of pending)
209
+ {
210
+ log(`Migrating: ${migration.name}`);
211
+ try
212
+ {
213
+ await migration.up(this._db);
214
+ await this._record(migration.name, batch);
215
+ migrated.push(migration.name);
216
+ log(`Migrated: ${migration.name}`);
217
+ }
218
+ catch (err)
219
+ {
220
+ const error = new Error(
221
+ `Migration "${migration.name}" failed: ${err.message}`
222
+ );
223
+ error.migration = migration.name;
224
+ error.batch = batch;
225
+ error.cause = err;
226
+ throw error;
227
+ }
228
+ }
229
+
230
+ return { migrated, batch };
231
+ }
232
+
233
+ /**
234
+ * Rollback the last batch of migrations.
235
+ *
236
+ * @returns {Promise<{ rolledBack: string[], batch: number }>}
237
+ *
238
+ * @example
239
+ * const { rolledBack } = await migrator.rollback();
240
+ * console.log(`Rolled back: ${rolledBack.join(', ')}`);
241
+ */
242
+ async rollback()
243
+ {
244
+ await this._init();
245
+
246
+ const executed = await this._getExecuted();
247
+ if (executed.length === 0)
248
+ {
249
+ return { rolledBack: [], batch: 0 };
250
+ }
251
+
252
+ const lastBatch = Math.max(...executed.map(m => m.batch));
253
+ const toRollback = executed
254
+ .filter(m => m.batch === lastBatch)
255
+ .reverse(); // Roll back in reverse order
256
+
257
+ const rolledBack = [];
258
+
259
+ for (const record of toRollback)
260
+ {
261
+ const migration = this._migrations.find(m => m.name === record.name);
262
+ if (!migration)
263
+ {
264
+ throw new Error(
265
+ `Cannot rollback "${record.name}": migration definition not found. ` +
266
+ `Ensure all migrations are registered before rolling back.`
267
+ );
268
+ }
269
+
270
+ log(`Rolling back: ${record.name}`);
271
+ try
272
+ {
273
+ await migration.down(this._db);
274
+ await this._unrecord(record.name);
275
+ rolledBack.push(record.name);
276
+ log(`Rolled back: ${record.name}`);
277
+ }
278
+ catch (err)
279
+ {
280
+ const error = new Error(
281
+ `Rollback of "${record.name}" failed: ${err.message}`
282
+ );
283
+ error.migration = record.name;
284
+ error.cause = err;
285
+ throw error;
286
+ }
287
+ }
288
+
289
+ return { rolledBack, batch: lastBatch };
290
+ }
291
+
292
+ /**
293
+ * Rollback all migrations (in reverse order, batch by batch).
294
+ *
295
+ * @returns {Promise<{ rolledBack: string[] }>}
296
+ */
297
+ async rollbackAll()
298
+ {
299
+ const allRolledBack = [];
300
+ let result;
301
+ do
302
+ {
303
+ result = await this.rollback();
304
+ allRolledBack.push(...result.rolledBack);
305
+ }
306
+ while (result.rolledBack.length > 0);
307
+
308
+ return { rolledBack: allRolledBack };
309
+ }
310
+
311
+ /**
312
+ * Reset the database: rollback all migrations, then re-run all.
313
+ *
314
+ * @returns {Promise<{ rolledBack: string[], migrated: string[], batch: number }>}
315
+ */
316
+ async reset()
317
+ {
318
+ const { rolledBack } = await this.rollbackAll();
319
+ const { migrated, batch } = await this.migrate();
320
+ return { rolledBack, migrated, batch };
321
+ }
322
+
323
+ /**
324
+ * Fresh start: drop ALL tables (not just migrated ones) then re-migrate.
325
+ * ⚠️ DESTRUCTIVE — use with caution.
326
+ *
327
+ * @returns {Promise<{ migrated: string[], batch: number }>}
328
+ */
329
+ async fresh()
330
+ {
331
+ // Drop all registered model tables via db.drop()
332
+ try { await this._db.drop(); } catch (_) { /* ignore if no models registered */ }
333
+
334
+ // Also drop the migration tracking table
335
+ try { await this._adapter.dropTable(this._table); } catch (_) { /* ignore */ }
336
+
337
+ this._initialized = false;
338
+
339
+ // Re-run all migrations
340
+ return this.migrate();
341
+ }
342
+
343
+ /**
344
+ * Get the current migration status.
345
+ *
346
+ * @returns {Promise<{ executed: object[], pending: string[], lastBatch: number }>}
347
+ *
348
+ * @example
349
+ * const { executed, pending, lastBatch } = await migrator.status();
350
+ * console.log(`Executed: ${executed.length}, Pending: ${pending.length}`);
351
+ */
352
+ async status()
353
+ {
354
+ await this._init();
355
+
356
+ const executed = await this._getExecuted();
357
+ const executedNames = new Set(executed.map(m => m.name));
358
+ const pending = this._migrations
359
+ .filter(m => !executedNames.has(m.name))
360
+ .map(m => m.name);
361
+
362
+ const lastBatch = executed.length > 0
363
+ ? Math.max(...executed.map(m => m.batch))
364
+ : 0;
365
+
366
+ return {
367
+ executed: executed.map(m => ({
368
+ name: m.name,
369
+ batch: m.batch,
370
+ executedAt: m.executed,
371
+ })),
372
+ pending,
373
+ lastBatch,
374
+ };
375
+ }
376
+
377
+ /**
378
+ * Check if there are any pending migrations.
379
+ * @returns {Promise<boolean>} True if there are pending migrations.
380
+ */
381
+ async hasPending()
382
+ {
383
+ const { pending } = await this.status();
384
+ return pending.length > 0;
385
+ }
386
+
387
+ /**
388
+ * Get the list of registered migration names.
389
+ * @returns {string[]} Registered migration names in order.
390
+ */
391
+ list()
392
+ {
393
+ return this._migrations.map(m => m.name);
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Helper to create a migration definition object.
399
+ *
400
+ * @param {string} name - Name identifier.
401
+ * @param {Function} up - `async (db) => { ... }`
402
+ * @param {Function} down - `async (db) => { ... }`
403
+ * @returns {{ name: string, up: Function, down: Function }}
404
+ *
405
+ * @example
406
+ * const { defineMigration } = require('@zero-server/sdk');
407
+ *
408
+ * module.exports = defineMigration('001_create_users',
409
+ * async (db) => {
410
+ * // up
411
+ * await db.addColumn('users', 'avatar', { type: TYPES.STRING });
412
+ * },
413
+ * async (db) => {
414
+ * // down
415
+ * await db.dropColumn('users', 'avatar');
416
+ * }
417
+ * );
418
+ */
419
+ function defineMigration(name, up, down)
420
+ {
421
+ if (!name || typeof name !== 'string')
422
+ throw new Error('defineMigration: name is required');
423
+ if (!/^[\w\-.]+$/.test(name))
424
+ throw new Error(`defineMigration: name "${name}" contains invalid characters`);
425
+ if (typeof up !== 'function')
426
+ throw new Error(`defineMigration "${name}": up must be a function`);
427
+ if (typeof down !== 'function')
428
+ throw new Error(`defineMigration "${name}": down must be a function`);
429
+ return { name, up, down };
430
+ }
431
+
432
+ module.exports = { Migrator, defineMigration };