@zero-server/sdk 0.9.1 → 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.
- package/LICENSE +21 -21
- package/README.md +460 -443
- package/index.js +414 -412
- package/lib/app.js +1172 -1172
- package/lib/auth/authorize.js +399 -399
- package/lib/auth/enrollment.js +367 -367
- package/lib/auth/index.js +57 -57
- package/lib/auth/jwt.js +731 -731
- package/lib/auth/oauth.js +362 -362
- package/lib/auth/session.js +588 -588
- package/lib/auth/trustedDevice.js +409 -409
- package/lib/auth/twoFactor.js +1150 -1150
- package/lib/auth/webauthn.js +946 -946
- package/lib/body/index.js +14 -14
- package/lib/body/json.js +109 -109
- package/lib/body/multipart.js +440 -440
- package/lib/body/raw.js +71 -71
- package/lib/body/rawBuffer.js +160 -160
- package/lib/body/sendError.js +25 -25
- package/lib/body/text.js +75 -75
- package/lib/body/typeMatch.js +41 -41
- package/lib/body/urlencoded.js +235 -235
- package/lib/cli.js +845 -845
- package/lib/cluster.js +666 -666
- package/lib/debug.js +372 -372
- package/lib/env/index.js +465 -465
- package/lib/errors.js +683 -683
- package/lib/fetch/index.js +256 -256
- package/lib/grpc/balancer.js +378 -378
- package/lib/grpc/call.js +708 -708
- package/lib/grpc/client.js +764 -764
- package/lib/grpc/codec.js +1221 -1221
- package/lib/grpc/credentials.js +398 -398
- package/lib/grpc/frame.js +262 -262
- package/lib/grpc/health.js +287 -287
- package/lib/grpc/index.js +121 -121
- package/lib/grpc/metadata.js +461 -461
- package/lib/grpc/proto.js +821 -821
- package/lib/grpc/reflection.js +590 -590
- package/lib/grpc/server.js +445 -445
- package/lib/grpc/status.js +118 -118
- package/lib/grpc/watch.js +173 -173
- package/lib/http/index.js +10 -10
- package/lib/http/request.js +727 -727
- package/lib/http/response.js +799 -799
- package/lib/lifecycle.js +557 -557
- package/lib/middleware/compress.js +230 -230
- package/lib/middleware/cookieParser.js +237 -237
- package/lib/middleware/cors.js +93 -93
- package/lib/middleware/csrf.js +137 -137
- package/lib/middleware/errorHandler.js +101 -101
- package/lib/middleware/helmet.js +175 -175
- package/lib/middleware/index.js +19 -17
- package/lib/middleware/logger.js +74 -74
- package/lib/middleware/rateLimit.js +88 -88
- package/lib/middleware/requestId.js +53 -53
- package/lib/middleware/static.js +326 -326
- package/lib/middleware/timeout.js +71 -71
- package/lib/middleware/validator.js +255 -255
- package/lib/observe/health.js +326 -326
- package/lib/observe/index.js +50 -50
- package/lib/observe/logger.js +359 -359
- package/lib/observe/metrics.js +805 -805
- package/lib/observe/tracing.js +592 -592
- package/lib/orm/adapters/json.js +290 -290
- package/lib/orm/adapters/memory.js +764 -764
- package/lib/orm/adapters/mongo.js +764 -764
- package/lib/orm/adapters/mysql.js +933 -933
- package/lib/orm/adapters/postgres.js +1144 -1144
- package/lib/orm/adapters/redis.js +1534 -1534
- package/lib/orm/adapters/sql-base.js +212 -212
- package/lib/orm/adapters/sqlite.js +858 -858
- package/lib/orm/audit.js +649 -649
- package/lib/orm/cache.js +394 -394
- package/lib/orm/geo.js +387 -387
- package/lib/orm/index.js +784 -784
- package/lib/orm/migrate.js +432 -432
- package/lib/orm/model.js +1706 -1706
- package/lib/orm/plugin.js +375 -375
- package/lib/orm/procedures.js +836 -836
- package/lib/orm/profiler.js +233 -233
- package/lib/orm/query.js +1772 -1772
- package/lib/orm/replicas.js +241 -241
- package/lib/orm/schema.js +307 -307
- package/lib/orm/search.js +380 -380
- package/lib/orm/seed/data/commerce.js +136 -136
- package/lib/orm/seed/data/internet.js +111 -111
- package/lib/orm/seed/data/locations.js +204 -204
- package/lib/orm/seed/data/names.js +338 -338
- package/lib/orm/seed/data/person.js +128 -128
- package/lib/orm/seed/data/phone.js +211 -211
- package/lib/orm/seed/data/words.js +134 -134
- package/lib/orm/seed/factory.js +178 -178
- package/lib/orm/seed/fake.js +1186 -1186
- package/lib/orm/seed/index.js +18 -18
- package/lib/orm/seed/rng.js +70 -70
- package/lib/orm/seed/seeder.js +124 -124
- package/lib/orm/seed/unique.js +68 -68
- package/lib/orm/snapshot.js +366 -366
- package/lib/orm/tenancy.js +605 -605
- package/lib/orm/views.js +350 -350
- package/lib/router/index.js +436 -436
- package/lib/sse/index.js +8 -8
- package/lib/sse/stream.js +349 -349
- package/lib/ws/connection.js +451 -451
- package/lib/ws/handshake.js +125 -125
- package/lib/ws/index.js +14 -14
- package/lib/ws/room.js +223 -223
- package/package.json +73 -73
- package/types/app.d.ts +223 -223
- package/types/auth.d.ts +520 -520
- package/types/cluster.d.ts +75 -75
- package/types/env.d.ts +80 -80
- package/types/errors.d.ts +316 -316
- package/types/fetch.d.ts +43 -43
- package/types/grpc.d.ts +432 -432
- package/types/index.d.ts +384 -384
- package/types/lifecycle.d.ts +60 -60
- package/types/middleware.d.ts +320 -320
- package/types/observe.d.ts +304 -304
- package/types/orm.d.ts +1887 -1887
- package/types/request.d.ts +109 -109
- package/types/response.d.ts +157 -157
- package/types/router.d.ts +78 -78
- package/types/sse.d.ts +78 -78
- package/types/websocket.d.ts +126 -126
package/lib/orm/snapshot.js
CHANGED
|
@@ -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
|
+
};
|