@zero-server/sdk 0.9.0 → 0.9.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.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -437
  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 +460 -460
  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 +136 -136
  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 +254 -254
  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/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,366 +1,366 @@
1
- /**
2
- * @module orm/snapshot
3
- * @description Schema snapshot and diff engine for EF Core–style auto-generated
4
- * migrations. Compares the current Model schemas against a stored
5
- * snapshot and produces a structured change-set that the CLI can
6
- * render into migration code.
7
- *
8
- * The snapshot file (_schema_snapshot.json) is a plain JSON representation of
9
- * every tracked table's schema at the time the last migration was generated.
10
- *
11
- * @example
12
- * const { diffSnapshots, buildSnapshot } = require('./snapshot');
13
- *
14
- * const current = buildSnapshot(models); // from Model classes
15
- * const previous = loadSnapshot(dir); // from JSON file
16
- * const changes = diffSnapshots(previous, current);
17
- *
18
- * // changes = { tables: { created: [...], dropped: [...] },
19
- * // columns: { added: [...], dropped: [...], altered: [...] } }
20
- */
21
-
22
- 'use strict';
23
-
24
- const fs = require('fs');
25
- const path = require('path');
26
-
27
- const SNAPSHOT_FILE = '_schema_snapshot.json';
28
-
29
- // -- Building a snapshot ----------------------------------------
30
-
31
- /**
32
- * Build a normalised snapshot from an array of Model classes.
33
- * Each Model must have `static table` and `static schema`.
34
- *
35
- * @param {Function[]} models - Array of Model subclasses.
36
- * @returns {object} Snapshot keyed by table name.
37
- */
38
- function buildSnapshot(models)
39
- {
40
- const snap = {};
41
-
42
- for (const M of models)
43
- {
44
- const table = M.table;
45
- if (!table) continue;
46
-
47
- const schema = typeof M._fullSchema === 'function'
48
- ? M._fullSchema()
49
- : { ...M.schema };
50
-
51
- // Normalise each column to a serialisable form (strip functions)
52
- const cols = {};
53
- for (const [colName, def] of Object.entries(schema))
54
- {
55
- cols[colName] = _normaliseDef(def);
56
- }
57
-
58
- snap[table] = {
59
- schema: cols,
60
- timestamps: !!M.timestamps,
61
- softDelete: !!M.softDelete,
62
- };
63
- }
64
-
65
- return snap;
66
- }
67
-
68
- /**
69
- * Normalise a column definition to a JSON-serialisable object.
70
- * Strips function defaults to `null`.
71
- * @private
72
- */
73
- function _normaliseDef(def)
74
- {
75
- const out = {};
76
- for (const [k, v] of Object.entries(def))
77
- {
78
- if (typeof v === 'function') out[k] = null; // fn defaults not serialisable
79
- else if (v instanceof RegExp) out[k] = v.source; // match patterns
80
- else out[k] = v;
81
- }
82
- return out;
83
- }
84
-
85
- // -- Loading / saving snapshots ---------------------------------
86
-
87
- /**
88
- * Load a previously saved snapshot from disk.
89
- * Returns an empty object if no file exists.
90
- *
91
- * @param {string} dir - Directory containing the snapshot file.
92
- * @returns {object} Snapshot.
93
- */
94
- function loadSnapshot(dir)
95
- {
96
- const p = path.join(dir, SNAPSHOT_FILE);
97
- if (!fs.existsSync(p)) return {};
98
- return JSON.parse(fs.readFileSync(p, 'utf8'));
99
- }
100
-
101
- /**
102
- * Write a snapshot to disk.
103
- *
104
- * @param {string} dir - Directory to write to.
105
- * @param {object} snapshot - The snapshot object.
106
- */
107
- function saveSnapshot(dir, snapshot)
108
- {
109
- fs.mkdirSync(dir, { recursive: true });
110
- fs.writeFileSync(
111
- path.join(dir, SNAPSHOT_FILE),
112
- JSON.stringify(snapshot, null, 4) + '\n',
113
- 'utf8'
114
- );
115
- }
116
-
117
- // -- Diffing two snapshots --------------------------------------
118
-
119
- /**
120
- * Diff two snapshots and return a structured change-set.
121
- *
122
- * @param {object} prev - Previous snapshot (from file).
123
- * @param {object} current - Current snapshot (from live models).
124
- * @returns {object} `{ tables, columns }` change-set.
125
- */
126
- function diffSnapshots(prev, current)
127
- {
128
- const prevTables = Object.keys(prev);
129
- const currTables = Object.keys(current);
130
-
131
- const createdTables = currTables.filter(t => !prev[t]);
132
- const droppedTables = prevTables.filter(t => !current[t]);
133
- const commonTables = currTables.filter(t => !!prev[t]);
134
-
135
- const addedCols = [];
136
- const droppedCols = [];
137
- const alteredCols = [];
138
-
139
- for (const table of commonTables)
140
- {
141
- const prevCols = Object.keys(prev[table].schema);
142
- const currCols = Object.keys(current[table].schema);
143
-
144
- // New columns
145
- for (const col of currCols)
146
- {
147
- if (!prev[table].schema[col])
148
- {
149
- addedCols.push({ table, column: col, def: current[table].schema[col] });
150
- }
151
- }
152
-
153
- // Dropped columns
154
- for (const col of prevCols)
155
- {
156
- if (!current[table].schema[col])
157
- {
158
- droppedCols.push({ table, column: col, def: prev[table].schema[col] });
159
- }
160
- }
161
-
162
- // Altered columns (type or constraints changed)
163
- for (const col of currCols)
164
- {
165
- if (prev[table].schema[col] && current[table].schema[col])
166
- {
167
- if (!_defsEqual(prev[table].schema[col], current[table].schema[col]))
168
- {
169
- alteredCols.push({
170
- table,
171
- column: col,
172
- from: prev[table].schema[col],
173
- to: current[table].schema[col],
174
- });
175
- }
176
- }
177
- }
178
- }
179
-
180
- return {
181
- tables: { created: createdTables, dropped: droppedTables },
182
- columns: { added: addedCols, dropped: droppedCols, altered: alteredCols },
183
- };
184
- }
185
-
186
- /**
187
- * Deep-compare two column definitions (JSON-serialisable).
188
- * @private
189
- */
190
- function _defsEqual(a, b)
191
- {
192
- return JSON.stringify(a) === JSON.stringify(b);
193
- }
194
-
195
- /**
196
- * Returns true when the change-set has no changes.
197
- *
198
- * @param {object} changes - Output of `diffSnapshots`.
199
- * @returns {boolean}
200
- */
201
- function hasNoChanges(changes)
202
- {
203
- return changes.tables.created.length === 0
204
- && changes.tables.dropped.length === 0
205
- && changes.columns.added.length === 0
206
- && changes.columns.dropped.length === 0
207
- && changes.columns.altered.length === 0;
208
- }
209
-
210
- // -- Code generation -------------------------------------------
211
-
212
- /**
213
- * Generate the JavaScript source for a migration file from a change-set.
214
- *
215
- * @param {string} migrationName - Timestamped migration name.
216
- * @param {object} changes - Output of `diffSnapshots`.
217
- * @param {object} currentSnap - Current snapshot (for full table schemas on create).
218
- * @returns {string} Migration file source code.
219
- */
220
- function generateMigrationCode(migrationName, changes, currentSnap)
221
- {
222
- const upLines = [];
223
- const downLines = [];
224
-
225
- // -- Created tables --
226
- for (const table of changes.tables.created)
227
- {
228
- const schema = currentSnap[table].schema;
229
- upLines.push(` await db.adapter.createTable('${table}', ${_schemaLiteral(schema)});`);
230
- downLines.push(` await db.adapter.dropTable('${table}');`);
231
- }
232
-
233
- // -- Dropped tables (reverse of create) --
234
- for (const table of changes.tables.dropped)
235
- {
236
- upLines.push(` await db.adapter.dropTable('${table}');`);
237
- // down recreates — but we need the previous snapshot's schema for that
238
- // This is handled via the `prev` reference embedded in the dropped table
239
- }
240
-
241
- // -- Added columns --
242
- for (const { table, column, def } of changes.columns.added)
243
- {
244
- upLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(def)});`);
245
- downLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
246
- }
247
-
248
- // -- Dropped columns --
249
- for (const { table, column, def } of changes.columns.dropped)
250
- {
251
- upLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
252
- downLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(def)});`);
253
- }
254
-
255
- // -- Altered columns (drop + re-add with new def) --
256
- for (const { table, column, from, to } of changes.columns.altered)
257
- {
258
- upLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
259
- upLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(to)});`);
260
- downLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
261
- downLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(from)});`);
262
- }
263
-
264
- // Build the final source
265
- const upBody = upLines.length > 0 ? upLines.join('\n') : ' // No changes';
266
- const downBody = downLines.length > 0 ? downLines.join('\n') : ' // No changes';
267
-
268
- return `'use strict';
269
-
270
- /**
271
- * Auto-generated migration — ${migrationName}
272
- * Generated by: npx zh make:migration
273
- */
274
- module.exports = {
275
- name: '${migrationName}',
276
-
277
- async up(db) {
278
- ${upBody}
279
- },
280
-
281
- async down(db) {
282
- ${downBody}
283
- },
284
- };
285
- `;
286
- }
287
-
288
- /**
289
- * Serialise a full table schema into a code literal string.
290
- * @private
291
- */
292
- function _schemaLiteral(schema)
293
- {
294
- const entries = [];
295
- for (const [col, def] of Object.entries(schema))
296
- {
297
- entries.push(` ${col}: ${_defLiteral(def)}`);
298
- }
299
- return `{\n${entries.join(',\n')},\n }`;
300
- }
301
-
302
- /**
303
- * Serialise one column definition into a code literal string.
304
- * @private
305
- */
306
- function _defLiteral(def)
307
- {
308
- const parts = [];
309
- for (const [k, v] of Object.entries(def))
310
- {
311
- if (v === null || v === undefined) continue;
312
- if (typeof v === 'string') parts.push(`${k}: '${v}'`);
313
- else if (typeof v === 'boolean' || typeof v === 'number') parts.push(`${k}: ${v}`);
314
- else if (Array.isArray(v)) parts.push(`${k}: ${JSON.stringify(v)}`);
315
- else if (typeof v === 'object') parts.push(`${k}: ${JSON.stringify(v)}`);
316
- }
317
- return `{ ${parts.join(', ')} }`;
318
- }
319
-
320
- // -- Model discovery -------------------------------------------
321
-
322
- /**
323
- * Load all Model classes from a directory.
324
- *
325
- * @param {string} dir - Absolute path to the models directory.
326
- * @param {Function} ModelBase - The base Model class to check `instanceof`.
327
- * @returns {Function[]} Array of Model subclasses.
328
- */
329
- function discoverModels(dir, ModelBase)
330
- {
331
- if (!fs.existsSync(dir)) return [];
332
-
333
- const files = fs.readdirSync(dir).filter(f => f.endsWith('.js')).sort();
334
- const models = [];
335
-
336
- for (const file of files)
337
- {
338
- try
339
- {
340
- const exported = require(path.join(dir, file));
341
- const M = typeof exported === 'function' ? exported
342
- : (exported && exported.default && typeof exported.default === 'function')
343
- ? exported.default
344
- : null;
345
-
346
- if (M && M.table && M.schema && (M.prototype instanceof ModelBase || M === ModelBase))
347
- {
348
- models.push(M);
349
- }
350
- }
351
- catch (_) { /* skip files that fail to load */ }
352
- }
353
-
354
- return models;
355
- }
356
-
357
- module.exports = {
358
- buildSnapshot,
359
- loadSnapshot,
360
- saveSnapshot,
361
- diffSnapshots,
362
- hasNoChanges,
363
- generateMigrationCode,
364
- discoverModels,
365
- SNAPSHOT_FILE,
366
- };
1
+ /**
2
+ * @module orm/snapshot
3
+ * @description Schema snapshot and diff engine for EF Core–style auto-generated
4
+ * migrations. Compares the current Model schemas against a stored
5
+ * snapshot and produces a structured change-set that the CLI can
6
+ * render into migration code.
7
+ *
8
+ * The snapshot file (_schema_snapshot.json) is a plain JSON representation of
9
+ * every tracked table's schema at the time the last migration was generated.
10
+ *
11
+ * @example
12
+ * const { diffSnapshots, buildSnapshot } = require('./snapshot');
13
+ *
14
+ * const current = buildSnapshot(models); // from Model classes
15
+ * const previous = loadSnapshot(dir); // from JSON file
16
+ * const changes = diffSnapshots(previous, current);
17
+ *
18
+ * // changes = { tables: { created: [...], dropped: [...] },
19
+ * // columns: { added: [...], dropped: [...], altered: [...] } }
20
+ */
21
+
22
+ 'use strict';
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+
27
+ const SNAPSHOT_FILE = '_schema_snapshot.json';
28
+
29
+ // -- Building a snapshot ----------------------------------------
30
+
31
+ /**
32
+ * Build a normalised snapshot from an array of Model classes.
33
+ * Each Model must have `static table` and `static schema`.
34
+ *
35
+ * @param {Function[]} models - Array of Model subclasses.
36
+ * @returns {object} Snapshot keyed by table name.
37
+ */
38
+ function buildSnapshot(models)
39
+ {
40
+ const snap = {};
41
+
42
+ for (const M of models)
43
+ {
44
+ const table = M.table;
45
+ if (!table) continue;
46
+
47
+ const schema = typeof M._fullSchema === 'function'
48
+ ? M._fullSchema()
49
+ : { ...M.schema };
50
+
51
+ // Normalise each column to a serialisable form (strip functions)
52
+ const cols = {};
53
+ for (const [colName, def] of Object.entries(schema))
54
+ {
55
+ cols[colName] = _normaliseDef(def);
56
+ }
57
+
58
+ snap[table] = {
59
+ schema: cols,
60
+ timestamps: !!M.timestamps,
61
+ softDelete: !!M.softDelete,
62
+ };
63
+ }
64
+
65
+ return snap;
66
+ }
67
+
68
+ /**
69
+ * Normalise a column definition to a JSON-serialisable object.
70
+ * Strips function defaults to `null`.
71
+ * @private
72
+ */
73
+ function _normaliseDef(def)
74
+ {
75
+ const out = {};
76
+ for (const [k, v] of Object.entries(def))
77
+ {
78
+ if (typeof v === 'function') out[k] = null; // fn defaults not serialisable
79
+ else if (v instanceof RegExp) out[k] = v.source; // match patterns
80
+ else out[k] = v;
81
+ }
82
+ return out;
83
+ }
84
+
85
+ // -- Loading / saving snapshots ---------------------------------
86
+
87
+ /**
88
+ * Load a previously saved snapshot from disk.
89
+ * Returns an empty object if no file exists.
90
+ *
91
+ * @param {string} dir - Directory containing the snapshot file.
92
+ * @returns {object} Snapshot.
93
+ */
94
+ function loadSnapshot(dir)
95
+ {
96
+ const p = path.join(dir, SNAPSHOT_FILE);
97
+ if (!fs.existsSync(p)) return {};
98
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
99
+ }
100
+
101
+ /**
102
+ * Write a snapshot to disk.
103
+ *
104
+ * @param {string} dir - Directory to write to.
105
+ * @param {object} snapshot - The snapshot object.
106
+ */
107
+ function saveSnapshot(dir, snapshot)
108
+ {
109
+ fs.mkdirSync(dir, { recursive: true });
110
+ fs.writeFileSync(
111
+ path.join(dir, SNAPSHOT_FILE),
112
+ JSON.stringify(snapshot, null, 4) + '\n',
113
+ 'utf8'
114
+ );
115
+ }
116
+
117
+ // -- Diffing two snapshots --------------------------------------
118
+
119
+ /**
120
+ * Diff two snapshots and return a structured change-set.
121
+ *
122
+ * @param {object} prev - Previous snapshot (from file).
123
+ * @param {object} current - Current snapshot (from live models).
124
+ * @returns {object} `{ tables, columns }` change-set.
125
+ */
126
+ function diffSnapshots(prev, current)
127
+ {
128
+ const prevTables = Object.keys(prev);
129
+ const currTables = Object.keys(current);
130
+
131
+ const createdTables = currTables.filter(t => !prev[t]);
132
+ const droppedTables = prevTables.filter(t => !current[t]);
133
+ const commonTables = currTables.filter(t => !!prev[t]);
134
+
135
+ const addedCols = [];
136
+ const droppedCols = [];
137
+ const alteredCols = [];
138
+
139
+ for (const table of commonTables)
140
+ {
141
+ const prevCols = Object.keys(prev[table].schema);
142
+ const currCols = Object.keys(current[table].schema);
143
+
144
+ // New columns
145
+ for (const col of currCols)
146
+ {
147
+ if (!prev[table].schema[col])
148
+ {
149
+ addedCols.push({ table, column: col, def: current[table].schema[col] });
150
+ }
151
+ }
152
+
153
+ // Dropped columns
154
+ for (const col of prevCols)
155
+ {
156
+ if (!current[table].schema[col])
157
+ {
158
+ droppedCols.push({ table, column: col, def: prev[table].schema[col] });
159
+ }
160
+ }
161
+
162
+ // Altered columns (type or constraints changed)
163
+ for (const col of currCols)
164
+ {
165
+ if (prev[table].schema[col] && current[table].schema[col])
166
+ {
167
+ if (!_defsEqual(prev[table].schema[col], current[table].schema[col]))
168
+ {
169
+ alteredCols.push({
170
+ table,
171
+ column: col,
172
+ from: prev[table].schema[col],
173
+ to: current[table].schema[col],
174
+ });
175
+ }
176
+ }
177
+ }
178
+ }
179
+
180
+ return {
181
+ tables: { created: createdTables, dropped: droppedTables },
182
+ columns: { added: addedCols, dropped: droppedCols, altered: alteredCols },
183
+ };
184
+ }
185
+
186
+ /**
187
+ * Deep-compare two column definitions (JSON-serialisable).
188
+ * @private
189
+ */
190
+ function _defsEqual(a, b)
191
+ {
192
+ return JSON.stringify(a) === JSON.stringify(b);
193
+ }
194
+
195
+ /**
196
+ * Returns true when the change-set has no changes.
197
+ *
198
+ * @param {object} changes - Output of `diffSnapshots`.
199
+ * @returns {boolean}
200
+ */
201
+ function hasNoChanges(changes)
202
+ {
203
+ return changes.tables.created.length === 0
204
+ && changes.tables.dropped.length === 0
205
+ && changes.columns.added.length === 0
206
+ && changes.columns.dropped.length === 0
207
+ && changes.columns.altered.length === 0;
208
+ }
209
+
210
+ // -- Code generation -------------------------------------------
211
+
212
+ /**
213
+ * Generate the JavaScript source for a migration file from a change-set.
214
+ *
215
+ * @param {string} migrationName - Timestamped migration name.
216
+ * @param {object} changes - Output of `diffSnapshots`.
217
+ * @param {object} currentSnap - Current snapshot (for full table schemas on create).
218
+ * @returns {string} Migration file source code.
219
+ */
220
+ function generateMigrationCode(migrationName, changes, currentSnap)
221
+ {
222
+ const upLines = [];
223
+ const downLines = [];
224
+
225
+ // -- Created tables --
226
+ for (const table of changes.tables.created)
227
+ {
228
+ const schema = currentSnap[table].schema;
229
+ upLines.push(` await db.adapter.createTable('${table}', ${_schemaLiteral(schema)});`);
230
+ downLines.push(` await db.adapter.dropTable('${table}');`);
231
+ }
232
+
233
+ // -- Dropped tables (reverse of create) --
234
+ for (const table of changes.tables.dropped)
235
+ {
236
+ upLines.push(` await db.adapter.dropTable('${table}');`);
237
+ // down recreates — but we need the previous snapshot's schema for that
238
+ // This is handled via the `prev` reference embedded in the dropped table
239
+ }
240
+
241
+ // -- Added columns --
242
+ for (const { table, column, def } of changes.columns.added)
243
+ {
244
+ upLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(def)});`);
245
+ downLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
246
+ }
247
+
248
+ // -- Dropped columns --
249
+ for (const { table, column, def } of changes.columns.dropped)
250
+ {
251
+ upLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
252
+ downLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(def)});`);
253
+ }
254
+
255
+ // -- Altered columns (drop + re-add with new def) --
256
+ for (const { table, column, from, to } of changes.columns.altered)
257
+ {
258
+ upLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
259
+ upLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(to)});`);
260
+ downLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
261
+ downLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(from)});`);
262
+ }
263
+
264
+ // Build the final source
265
+ const upBody = upLines.length > 0 ? upLines.join('\n') : ' // No changes';
266
+ const downBody = downLines.length > 0 ? downLines.join('\n') : ' // No changes';
267
+
268
+ return `'use strict';
269
+
270
+ /**
271
+ * Auto-generated migration — ${migrationName}
272
+ * Generated by: npx zh make:migration
273
+ */
274
+ module.exports = {
275
+ name: '${migrationName}',
276
+
277
+ async up(db) {
278
+ ${upBody}
279
+ },
280
+
281
+ async down(db) {
282
+ ${downBody}
283
+ },
284
+ };
285
+ `;
286
+ }
287
+
288
+ /**
289
+ * Serialise a full table schema into a code literal string.
290
+ * @private
291
+ */
292
+ function _schemaLiteral(schema)
293
+ {
294
+ const entries = [];
295
+ for (const [col, def] of Object.entries(schema))
296
+ {
297
+ entries.push(` ${col}: ${_defLiteral(def)}`);
298
+ }
299
+ return `{\n${entries.join(',\n')},\n }`;
300
+ }
301
+
302
+ /**
303
+ * Serialise one column definition into a code literal string.
304
+ * @private
305
+ */
306
+ function _defLiteral(def)
307
+ {
308
+ const parts = [];
309
+ for (const [k, v] of Object.entries(def))
310
+ {
311
+ if (v === null || v === undefined) continue;
312
+ if (typeof v === 'string') parts.push(`${k}: '${v}'`);
313
+ else if (typeof v === 'boolean' || typeof v === 'number') parts.push(`${k}: ${v}`);
314
+ else if (Array.isArray(v)) parts.push(`${k}: ${JSON.stringify(v)}`);
315
+ else if (typeof v === 'object') parts.push(`${k}: ${JSON.stringify(v)}`);
316
+ }
317
+ return `{ ${parts.join(', ')} }`;
318
+ }
319
+
320
+ // -- Model discovery -------------------------------------------
321
+
322
+ /**
323
+ * Load all Model classes from a directory.
324
+ *
325
+ * @param {string} dir - Absolute path to the models directory.
326
+ * @param {Function} ModelBase - The base Model class to check `instanceof`.
327
+ * @returns {Function[]} Array of Model subclasses.
328
+ */
329
+ function discoverModels(dir, ModelBase)
330
+ {
331
+ if (!fs.existsSync(dir)) return [];
332
+
333
+ const files = fs.readdirSync(dir).filter(f => f.endsWith('.js')).sort();
334
+ const models = [];
335
+
336
+ for (const file of files)
337
+ {
338
+ try
339
+ {
340
+ const exported = require(path.join(dir, file));
341
+ const M = typeof exported === 'function' ? exported
342
+ : (exported && exported.default && typeof exported.default === 'function')
343
+ ? exported.default
344
+ : null;
345
+
346
+ if (M && M.table && M.schema && (M.prototype instanceof ModelBase || M === ModelBase))
347
+ {
348
+ models.push(M);
349
+ }
350
+ }
351
+ catch (_) { /* skip files that fail to load */ }
352
+ }
353
+
354
+ return models;
355
+ }
356
+
357
+ module.exports = {
358
+ buildSnapshot,
359
+ loadSnapshot,
360
+ saveSnapshot,
361
+ diffSnapshots,
362
+ hasNoChanges,
363
+ generateMigrationCode,
364
+ discoverModels,
365
+ SNAPSHOT_FILE,
366
+ };