pocketbase-zod-schema 0.1.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/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/README.md +167 -0
- package/dist/cli/index.cjs +3383 -0
- package/dist/cli/index.cjs.map +1 -0
- package/dist/cli/index.d.cts +30 -0
- package/dist/cli/index.d.ts +30 -0
- package/dist/cli/index.js +3331 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/migrate.cjs +3380 -0
- package/dist/cli/migrate.cjs.map +1 -0
- package/dist/cli/migrate.d.cts +1 -0
- package/dist/cli/migrate.d.ts +1 -0
- package/dist/cli/migrate.js +3353 -0
- package/dist/cli/migrate.js.map +1 -0
- package/dist/cli/utils/index.cjs +540 -0
- package/dist/cli/utils/index.cjs.map +1 -0
- package/dist/cli/utils/index.d.cts +232 -0
- package/dist/cli/utils/index.d.ts +232 -0
- package/dist/cli/utils/index.js +487 -0
- package/dist/cli/utils/index.js.map +1 -0
- package/dist/enums.cjs +19 -0
- package/dist/enums.cjs.map +1 -0
- package/dist/enums.d.cts +6 -0
- package/dist/enums.d.ts +6 -0
- package/dist/enums.js +17 -0
- package/dist/enums.js.map +1 -0
- package/dist/index.cjs +4900 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +18 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +4726 -0
- package/dist/index.js.map +1 -0
- package/dist/migration/analyzer.cjs +1267 -0
- package/dist/migration/analyzer.cjs.map +1 -0
- package/dist/migration/analyzer.d.cts +186 -0
- package/dist/migration/analyzer.d.ts +186 -0
- package/dist/migration/analyzer.js +1232 -0
- package/dist/migration/analyzer.js.map +1 -0
- package/dist/migration/diff.cjs +557 -0
- package/dist/migration/diff.cjs.map +1 -0
- package/dist/migration/diff.d.cts +291 -0
- package/dist/migration/diff.d.ts +291 -0
- package/dist/migration/diff.js +534 -0
- package/dist/migration/diff.js.map +1 -0
- package/dist/migration/generator.cjs +778 -0
- package/dist/migration/generator.cjs.map +1 -0
- package/dist/migration/generator.d.cts +225 -0
- package/dist/migration/generator.d.ts +225 -0
- package/dist/migration/generator.js +737 -0
- package/dist/migration/generator.js.map +1 -0
- package/dist/migration/index.cjs +3390 -0
- package/dist/migration/index.cjs.map +1 -0
- package/dist/migration/index.d.cts +103 -0
- package/dist/migration/index.d.ts +103 -0
- package/dist/migration/index.js +3265 -0
- package/dist/migration/index.js.map +1 -0
- package/dist/migration/snapshot.cjs +609 -0
- package/dist/migration/snapshot.cjs.map +1 -0
- package/dist/migration/snapshot.d.cts +167 -0
- package/dist/migration/snapshot.d.ts +167 -0
- package/dist/migration/snapshot.js +575 -0
- package/dist/migration/snapshot.js.map +1 -0
- package/dist/migration/utils/index.cjs +672 -0
- package/dist/migration/utils/index.cjs.map +1 -0
- package/dist/migration/utils/index.d.cts +207 -0
- package/dist/migration/utils/index.d.ts +207 -0
- package/dist/migration/utils/index.js +641 -0
- package/dist/migration/utils/index.js.map +1 -0
- package/dist/mutator.cjs +427 -0
- package/dist/mutator.cjs.map +1 -0
- package/dist/mutator.d.cts +190 -0
- package/dist/mutator.d.ts +190 -0
- package/dist/mutator.js +425 -0
- package/dist/mutator.js.map +1 -0
- package/dist/permissions-ZHafVSIx.d.cts +71 -0
- package/dist/permissions-ZHafVSIx.d.ts +71 -0
- package/dist/schema.cjs +430 -0
- package/dist/schema.cjs.map +1 -0
- package/dist/schema.d.cts +316 -0
- package/dist/schema.d.ts +316 -0
- package/dist/schema.js +396 -0
- package/dist/schema.js.map +1 -0
- package/dist/types-BbTgmg6H.d.cts +91 -0
- package/dist/types-z1Dkjg8m.d.ts +91 -0
- package/dist/types.cjs +4 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +14 -0
- package/dist/types.d.ts +14 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/user-jS1aYoeD.d.cts +123 -0
- package/dist/user-jS1aYoeD.d.ts +123 -0
- package/package.json +165 -0
|
@@ -0,0 +1,3383 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var path4 = require('path');
|
|
4
|
+
var fs4 = require('fs');
|
|
5
|
+
var zod = require('zod');
|
|
6
|
+
var chalk = require('chalk');
|
|
7
|
+
var ora = require('ora');
|
|
8
|
+
|
|
9
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
10
|
+
|
|
11
|
+
function _interopNamespace(e) {
|
|
12
|
+
if (e && e.__esModule) return e;
|
|
13
|
+
var n = Object.create(null);
|
|
14
|
+
if (e) {
|
|
15
|
+
Object.keys(e).forEach(function (k) {
|
|
16
|
+
if (k !== 'default') {
|
|
17
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
18
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
19
|
+
enumerable: true,
|
|
20
|
+
get: function () { return e[k]; }
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
n.default = e;
|
|
26
|
+
return Object.freeze(n);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
var path4__namespace = /*#__PURE__*/_interopNamespace(path4);
|
|
30
|
+
var fs4__namespace = /*#__PURE__*/_interopNamespace(fs4);
|
|
31
|
+
var chalk__default = /*#__PURE__*/_interopDefault(chalk);
|
|
32
|
+
var ora__default = /*#__PURE__*/_interopDefault(ora);
|
|
33
|
+
|
|
34
|
+
// src/cli/commands/generate.ts
|
|
35
|
+
|
|
36
|
+
// src/migration/errors.ts
|
|
37
|
+
var MigrationError = class _MigrationError extends Error {
|
|
38
|
+
constructor(message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = "MigrationError";
|
|
41
|
+
Object.setPrototypeOf(this, _MigrationError.prototype);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var SchemaParsingError = class _SchemaParsingError extends MigrationError {
|
|
45
|
+
filePath;
|
|
46
|
+
originalError;
|
|
47
|
+
constructor(message, filePath, originalError) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "SchemaParsingError";
|
|
50
|
+
this.filePath = filePath;
|
|
51
|
+
this.originalError = originalError;
|
|
52
|
+
Object.setPrototypeOf(this, _SchemaParsingError.prototype);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Creates a formatted error message with file path and original error details
|
|
56
|
+
*/
|
|
57
|
+
getDetailedMessage() {
|
|
58
|
+
const parts = [this.message];
|
|
59
|
+
if (this.filePath) {
|
|
60
|
+
parts.push(`
|
|
61
|
+
File: ${this.filePath}`);
|
|
62
|
+
}
|
|
63
|
+
if (this.originalError) {
|
|
64
|
+
parts.push(`
|
|
65
|
+
Cause: ${this.originalError.message}`);
|
|
66
|
+
}
|
|
67
|
+
return parts.join("");
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
var SnapshotError = class _SnapshotError extends MigrationError {
|
|
71
|
+
snapshotPath;
|
|
72
|
+
operation;
|
|
73
|
+
originalError;
|
|
74
|
+
constructor(message, snapshotPath, operation, originalError) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.name = "SnapshotError";
|
|
77
|
+
this.snapshotPath = snapshotPath;
|
|
78
|
+
this.operation = operation;
|
|
79
|
+
this.originalError = originalError;
|
|
80
|
+
Object.setPrototypeOf(this, _SnapshotError.prototype);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Creates a formatted error message with snapshot path and operation details
|
|
84
|
+
*/
|
|
85
|
+
getDetailedMessage() {
|
|
86
|
+
const parts = [this.message];
|
|
87
|
+
if (this.operation) {
|
|
88
|
+
parts.push(`
|
|
89
|
+
Operation: ${this.operation}`);
|
|
90
|
+
}
|
|
91
|
+
if (this.snapshotPath) {
|
|
92
|
+
parts.push(`
|
|
93
|
+
Snapshot: ${this.snapshotPath}`);
|
|
94
|
+
}
|
|
95
|
+
if (this.originalError) {
|
|
96
|
+
parts.push(`
|
|
97
|
+
Cause: ${this.originalError.message}`);
|
|
98
|
+
}
|
|
99
|
+
return parts.join("");
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
var MigrationGenerationError = class _MigrationGenerationError extends MigrationError {
|
|
103
|
+
migrationPath;
|
|
104
|
+
originalError;
|
|
105
|
+
constructor(message, migrationPath, originalError) {
|
|
106
|
+
super(message);
|
|
107
|
+
this.name = "MigrationGenerationError";
|
|
108
|
+
this.migrationPath = migrationPath;
|
|
109
|
+
this.originalError = originalError;
|
|
110
|
+
Object.setPrototypeOf(this, _MigrationGenerationError.prototype);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Creates a formatted error message with migration path and original error details
|
|
114
|
+
*/
|
|
115
|
+
getDetailedMessage() {
|
|
116
|
+
const parts = [this.message];
|
|
117
|
+
if (this.migrationPath) {
|
|
118
|
+
parts.push(`
|
|
119
|
+
Migration: ${this.migrationPath}`);
|
|
120
|
+
}
|
|
121
|
+
if (this.originalError) {
|
|
122
|
+
parts.push(`
|
|
123
|
+
Cause: ${this.originalError.message}`);
|
|
124
|
+
}
|
|
125
|
+
return parts.join("");
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
var FileSystemError = class _FileSystemError extends MigrationError {
|
|
129
|
+
path;
|
|
130
|
+
operation;
|
|
131
|
+
code;
|
|
132
|
+
originalError;
|
|
133
|
+
constructor(message, path6, operation, code, originalError) {
|
|
134
|
+
super(message);
|
|
135
|
+
this.name = "FileSystemError";
|
|
136
|
+
this.path = path6;
|
|
137
|
+
this.operation = operation;
|
|
138
|
+
this.code = code;
|
|
139
|
+
this.originalError = originalError;
|
|
140
|
+
Object.setPrototypeOf(this, _FileSystemError.prototype);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Creates a formatted error message with path, operation, and error code details
|
|
144
|
+
*/
|
|
145
|
+
getDetailedMessage() {
|
|
146
|
+
const parts = [this.message];
|
|
147
|
+
if (this.operation) {
|
|
148
|
+
parts.push(`
|
|
149
|
+
Operation: ${this.operation}`);
|
|
150
|
+
}
|
|
151
|
+
if (this.path) {
|
|
152
|
+
parts.push(`
|
|
153
|
+
Path: ${this.path}`);
|
|
154
|
+
}
|
|
155
|
+
if (this.code) {
|
|
156
|
+
parts.push(`
|
|
157
|
+
Error Code: ${this.code}`);
|
|
158
|
+
}
|
|
159
|
+
if (this.originalError) {
|
|
160
|
+
parts.push(`
|
|
161
|
+
Cause: ${this.originalError.message}`);
|
|
162
|
+
}
|
|
163
|
+
return parts.join("");
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
var ConfigurationError = class _ConfigurationError extends MigrationError {
|
|
167
|
+
configPath;
|
|
168
|
+
invalidFields;
|
|
169
|
+
originalError;
|
|
170
|
+
constructor(message, configPath, invalidFields, originalError) {
|
|
171
|
+
super(message);
|
|
172
|
+
this.name = "ConfigurationError";
|
|
173
|
+
this.configPath = configPath;
|
|
174
|
+
this.invalidFields = invalidFields;
|
|
175
|
+
this.originalError = originalError;
|
|
176
|
+
Object.setPrototypeOf(this, _ConfigurationError.prototype);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Creates a formatted error message with configuration details
|
|
180
|
+
*/
|
|
181
|
+
getDetailedMessage() {
|
|
182
|
+
const parts = [this.message];
|
|
183
|
+
if (this.configPath) {
|
|
184
|
+
parts.push(`
|
|
185
|
+
Configuration File: ${this.configPath}`);
|
|
186
|
+
}
|
|
187
|
+
if (this.invalidFields && this.invalidFields.length > 0) {
|
|
188
|
+
parts.push(`
|
|
189
|
+
Invalid Fields: ${this.invalidFields.join(", ")}`);
|
|
190
|
+
}
|
|
191
|
+
if (this.originalError) {
|
|
192
|
+
parts.push(`
|
|
193
|
+
Cause: ${this.originalError.message}`);
|
|
194
|
+
}
|
|
195
|
+
return parts.join("");
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// src/schema/permission-templates.ts
|
|
200
|
+
var PermissionTemplates = {
|
|
201
|
+
/**
|
|
202
|
+
* Public access - anyone can perform all operations
|
|
203
|
+
*/
|
|
204
|
+
public: () => ({
|
|
205
|
+
listRule: "",
|
|
206
|
+
viewRule: "",
|
|
207
|
+
createRule: "",
|
|
208
|
+
updateRule: "",
|
|
209
|
+
deleteRule: ""
|
|
210
|
+
}),
|
|
211
|
+
/**
|
|
212
|
+
* Authenticated users only - requires valid authentication for all operations
|
|
213
|
+
*/
|
|
214
|
+
authenticated: () => ({
|
|
215
|
+
listRule: '@request.auth.id != ""',
|
|
216
|
+
viewRule: '@request.auth.id != ""',
|
|
217
|
+
createRule: '@request.auth.id != ""',
|
|
218
|
+
updateRule: '@request.auth.id != ""',
|
|
219
|
+
deleteRule: '@request.auth.id != ""'
|
|
220
|
+
}),
|
|
221
|
+
/**
|
|
222
|
+
* Owner-only access - users can only manage their own records
|
|
223
|
+
* @param ownerField - Name of the relation field pointing to user (default: 'User')
|
|
224
|
+
*/
|
|
225
|
+
ownerOnly: (ownerField = "User") => ({
|
|
226
|
+
listRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
|
|
227
|
+
viewRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
|
|
228
|
+
createRule: '@request.auth.id != ""',
|
|
229
|
+
updateRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
|
|
230
|
+
deleteRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`
|
|
231
|
+
}),
|
|
232
|
+
/**
|
|
233
|
+
* Admin/superuser only access
|
|
234
|
+
* Assumes a 'role' field exists with 'admin' value
|
|
235
|
+
* @param roleField - Name of the role field (default: 'role')
|
|
236
|
+
*/
|
|
237
|
+
adminOnly: (roleField = "role") => ({
|
|
238
|
+
listRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
|
|
239
|
+
viewRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
|
|
240
|
+
createRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
|
|
241
|
+
updateRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
|
|
242
|
+
deleteRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`
|
|
243
|
+
}),
|
|
244
|
+
/**
|
|
245
|
+
* Public read, authenticated write
|
|
246
|
+
* Anyone can list/view, but only authenticated users can create/update/delete
|
|
247
|
+
*/
|
|
248
|
+
readPublic: () => ({
|
|
249
|
+
listRule: "",
|
|
250
|
+
viewRule: "",
|
|
251
|
+
createRule: '@request.auth.id != ""',
|
|
252
|
+
updateRule: '@request.auth.id != ""',
|
|
253
|
+
deleteRule: '@request.auth.id != ""'
|
|
254
|
+
}),
|
|
255
|
+
/**
|
|
256
|
+
* Locked access - only superusers can perform operations
|
|
257
|
+
* All rules are set to null (locked)
|
|
258
|
+
*/
|
|
259
|
+
locked: () => ({
|
|
260
|
+
listRule: null,
|
|
261
|
+
viewRule: null,
|
|
262
|
+
createRule: null,
|
|
263
|
+
updateRule: null,
|
|
264
|
+
deleteRule: null
|
|
265
|
+
}),
|
|
266
|
+
/**
|
|
267
|
+
* Read-only authenticated - authenticated users can read, no write access
|
|
268
|
+
*/
|
|
269
|
+
readOnlyAuthenticated: () => ({
|
|
270
|
+
listRule: '@request.auth.id != ""',
|
|
271
|
+
viewRule: '@request.auth.id != ""',
|
|
272
|
+
createRule: null,
|
|
273
|
+
updateRule: null,
|
|
274
|
+
deleteRule: null
|
|
275
|
+
})
|
|
276
|
+
};
|
|
277
|
+
function resolveTemplate(config) {
|
|
278
|
+
let baseRules;
|
|
279
|
+
switch (config.template) {
|
|
280
|
+
case "public":
|
|
281
|
+
baseRules = PermissionTemplates.public();
|
|
282
|
+
break;
|
|
283
|
+
case "authenticated":
|
|
284
|
+
baseRules = PermissionTemplates.authenticated();
|
|
285
|
+
break;
|
|
286
|
+
case "owner-only":
|
|
287
|
+
baseRules = PermissionTemplates.ownerOnly(config.ownerField);
|
|
288
|
+
break;
|
|
289
|
+
case "admin-only":
|
|
290
|
+
baseRules = PermissionTemplates.adminOnly(config.roleField);
|
|
291
|
+
break;
|
|
292
|
+
case "read-public":
|
|
293
|
+
baseRules = PermissionTemplates.readPublic();
|
|
294
|
+
break;
|
|
295
|
+
case "custom":
|
|
296
|
+
baseRules = {};
|
|
297
|
+
break;
|
|
298
|
+
default: {
|
|
299
|
+
const _exhaustive = config.template;
|
|
300
|
+
throw new Error(`Unknown template type: ${_exhaustive}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
...baseRules,
|
|
305
|
+
...config.customRules
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/migration/rule-validator.ts
|
|
310
|
+
var RuleValidator = class {
|
|
311
|
+
fields;
|
|
312
|
+
collectionName;
|
|
313
|
+
isAuthCollection;
|
|
314
|
+
constructor(collectionName, fields, isAuthCollection2 = false) {
|
|
315
|
+
this.collectionName = collectionName;
|
|
316
|
+
this.fields = new Map(fields.map((f) => [f.name, f]));
|
|
317
|
+
this.isAuthCollection = isAuthCollection2;
|
|
318
|
+
this.addSystemFields();
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Add system fields that are always available in PocketBase collections
|
|
322
|
+
* These fields are automatically added by PocketBase and can be referenced in rules
|
|
323
|
+
*/
|
|
324
|
+
addSystemFields() {
|
|
325
|
+
const systemFields = [
|
|
326
|
+
{ name: "id", type: "text", required: true, options: {} },
|
|
327
|
+
{ name: "created", type: "date", required: true, options: {} },
|
|
328
|
+
{ name: "updated", type: "date", required: true, options: {} },
|
|
329
|
+
{ name: "collectionId", type: "text", required: true, options: {} },
|
|
330
|
+
{ name: "collectionName", type: "text", required: true, options: {} }
|
|
331
|
+
];
|
|
332
|
+
if (this.isAuthCollection) {
|
|
333
|
+
systemFields.push(
|
|
334
|
+
{ name: "email", type: "email", required: true, options: {} },
|
|
335
|
+
{ name: "emailVisibility", type: "bool", required: false, options: {} },
|
|
336
|
+
{ name: "verified", type: "bool", required: false, options: {} },
|
|
337
|
+
{ name: "tokenKey", type: "text", required: true, options: {} },
|
|
338
|
+
{ name: "password", type: "text", required: true, options: {} }
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
for (const field of systemFields) {
|
|
342
|
+
if (!this.fields.has(field.name)) {
|
|
343
|
+
this.fields.set(field.name, field);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Validate a rule expression
|
|
349
|
+
*
|
|
350
|
+
* @param ruleType - The type of rule being validated
|
|
351
|
+
* @param expression - The rule expression to validate
|
|
352
|
+
* @returns Validation result with errors, warnings, and field references
|
|
353
|
+
*/
|
|
354
|
+
validate(ruleType, expression) {
|
|
355
|
+
const result = {
|
|
356
|
+
valid: true,
|
|
357
|
+
errors: [],
|
|
358
|
+
warnings: [],
|
|
359
|
+
fieldReferences: []
|
|
360
|
+
};
|
|
361
|
+
if (expression === null) {
|
|
362
|
+
return result;
|
|
363
|
+
}
|
|
364
|
+
if (expression === "") {
|
|
365
|
+
result.warnings.push(`${ruleType} is public - anyone can perform this operation`);
|
|
366
|
+
return result;
|
|
367
|
+
}
|
|
368
|
+
if (ruleType === "manageRule" && !this.isAuthCollection) {
|
|
369
|
+
result.valid = false;
|
|
370
|
+
result.errors.push("manageRule is only valid for auth collections");
|
|
371
|
+
return result;
|
|
372
|
+
}
|
|
373
|
+
const fieldRefs = this.extractFieldReferences(expression);
|
|
374
|
+
result.fieldReferences = fieldRefs;
|
|
375
|
+
for (const fieldRef of fieldRefs) {
|
|
376
|
+
this.validateFieldReference(fieldRef, result);
|
|
377
|
+
}
|
|
378
|
+
this.validateRequestReferences(expression, result);
|
|
379
|
+
this.validateSyntax(expression, result);
|
|
380
|
+
return result;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Extract field references from expression
|
|
384
|
+
*
|
|
385
|
+
* Matches field names that are not @request references.
|
|
386
|
+
* Handles dot notation for relations: user.email, post.author.name
|
|
387
|
+
*
|
|
388
|
+
* @param expression - The rule expression
|
|
389
|
+
* @returns Array of unique field references
|
|
390
|
+
*/
|
|
391
|
+
extractFieldReferences(expression) {
|
|
392
|
+
const refs = [];
|
|
393
|
+
let cleaned = expression.replace(/"[^"]*"/g, '""').replace(/'[^']*'/g, "''");
|
|
394
|
+
cleaned = cleaned.replace(/@request\.[a-zA-Z_][a-zA-Z0-9_.]*/g, "");
|
|
395
|
+
const fieldPattern = /(?:^|[^@\w])([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)(?=[^a-zA-Z0-9_.]|$)/g;
|
|
396
|
+
let match;
|
|
397
|
+
while ((match = fieldPattern.exec(cleaned)) !== null) {
|
|
398
|
+
const ref = match[1];
|
|
399
|
+
if (!this.isKeyword(ref)) {
|
|
400
|
+
refs.push(ref);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return [...new Set(refs)];
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Check if a word is a PocketBase keyword
|
|
407
|
+
*
|
|
408
|
+
* @param word - The word to check
|
|
409
|
+
* @returns True if the word is a keyword
|
|
410
|
+
*/
|
|
411
|
+
isKeyword(word) {
|
|
412
|
+
const keywords = ["true", "false", "null", "AND", "OR", "NOT", "LIKE", "IN"];
|
|
413
|
+
return keywords.includes(word.toUpperCase());
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Validate a field reference exists in schema
|
|
417
|
+
*
|
|
418
|
+
* Checks if the root field exists and validates relation chains.
|
|
419
|
+
* For nested references, warns about potential issues since we can't
|
|
420
|
+
* validate across collections without loading related schemas.
|
|
421
|
+
*
|
|
422
|
+
* @param fieldRef - The field reference to validate (e.g., "user" or "user.email")
|
|
423
|
+
* @param result - The validation result to update
|
|
424
|
+
*/
|
|
425
|
+
validateFieldReference(fieldRef, result) {
|
|
426
|
+
const parts = fieldRef.split(".");
|
|
427
|
+
const rootField = parts[0];
|
|
428
|
+
if (!this.fields.has(rootField)) {
|
|
429
|
+
result.errors.push(`Field '${rootField}' does not exist in collection '${this.collectionName}'`);
|
|
430
|
+
result.valid = false;
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (parts.length > 1) {
|
|
434
|
+
const field = this.fields.get(rootField);
|
|
435
|
+
if (field.type !== "relation") {
|
|
436
|
+
result.errors.push(`Field '${rootField}' is not a relation field, cannot access nested property '${parts[1]}'`);
|
|
437
|
+
result.valid = false;
|
|
438
|
+
} else {
|
|
439
|
+
result.warnings.push(
|
|
440
|
+
`Nested field reference '${fieldRef}' - ensure target collection has field '${parts.slice(1).join(".")}'`
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Validate @request references
|
|
447
|
+
*
|
|
448
|
+
* Checks that @request references follow valid PocketBase patterns:
|
|
449
|
+
* - @request.auth.* - authenticated user data
|
|
450
|
+
* - @request.body.* - request body fields
|
|
451
|
+
* - @request.query.* - query parameters
|
|
452
|
+
* - @request.headers.* - request headers
|
|
453
|
+
* - @request.method - HTTP method
|
|
454
|
+
* - @request.context - execution context
|
|
455
|
+
*
|
|
456
|
+
* @param expression - The rule expression
|
|
457
|
+
* @param result - The validation result to update
|
|
458
|
+
*/
|
|
459
|
+
validateRequestReferences(expression, result) {
|
|
460
|
+
const requestRefs = expression.match(/@request\.[a-zA-Z_][a-zA-Z0-9_.]*/g) || [];
|
|
461
|
+
for (const ref of requestRefs) {
|
|
462
|
+
const isValid = ref.startsWith("@request.auth.") || ref === "@request.method" || ref === "@request.context" || ref.startsWith("@request.body.") || ref.startsWith("@request.query.") || ref.startsWith("@request.headers.");
|
|
463
|
+
if (!isValid) {
|
|
464
|
+
result.errors.push(`Invalid @request reference: '${ref}'`);
|
|
465
|
+
result.valid = false;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Validate basic syntax patterns
|
|
471
|
+
*
|
|
472
|
+
* Checks for:
|
|
473
|
+
* - Balanced parentheses
|
|
474
|
+
* - Common operator mistakes (== instead of =)
|
|
475
|
+
*
|
|
476
|
+
* @param expression - The rule expression
|
|
477
|
+
* @param result - The validation result to update
|
|
478
|
+
*/
|
|
479
|
+
validateSyntax(expression, result) {
|
|
480
|
+
let parenCount = 0;
|
|
481
|
+
for (const char of expression) {
|
|
482
|
+
if (char === "(") parenCount++;
|
|
483
|
+
if (char === ")") parenCount--;
|
|
484
|
+
if (parenCount < 0) {
|
|
485
|
+
result.errors.push("Unbalanced parentheses in expression");
|
|
486
|
+
result.valid = false;
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (parenCount !== 0) {
|
|
491
|
+
result.errors.push("Unbalanced parentheses in expression");
|
|
492
|
+
result.valid = false;
|
|
493
|
+
}
|
|
494
|
+
if (expression.includes("==")) {
|
|
495
|
+
result.warnings.push("Use '=' instead of '==' for equality comparison in PocketBase rules");
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
// src/migration/permission-analyzer.ts
|
|
501
|
+
var PermissionAnalyzer = class {
|
|
502
|
+
/**
|
|
503
|
+
* Extract permission metadata from Zod schema description
|
|
504
|
+
*
|
|
505
|
+
* Zod schemas can have permission metadata attached via the describe() method.
|
|
506
|
+
* This method parses the description and extracts the permission configuration.
|
|
507
|
+
*
|
|
508
|
+
* @param schemaDescription - The Zod schema description string
|
|
509
|
+
* @returns Permission schema if found, null otherwise
|
|
510
|
+
*
|
|
511
|
+
* @example
|
|
512
|
+
* ```typescript
|
|
513
|
+
* const analyzer = new PermissionAnalyzer();
|
|
514
|
+
* const permissions = analyzer.extractPermissions(schema.description);
|
|
515
|
+
* ```
|
|
516
|
+
*/
|
|
517
|
+
extractPermissions(schemaDescription) {
|
|
518
|
+
if (!schemaDescription) {
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
try {
|
|
522
|
+
const metadata = JSON.parse(schemaDescription);
|
|
523
|
+
if (metadata.permissions) {
|
|
524
|
+
return metadata.permissions;
|
|
525
|
+
}
|
|
526
|
+
} catch {
|
|
527
|
+
return null;
|
|
528
|
+
}
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Resolve template configuration to concrete rules
|
|
533
|
+
*
|
|
534
|
+
* Takes either a template configuration or a direct permission schema
|
|
535
|
+
* and returns a fully resolved permission schema with all rules defined.
|
|
536
|
+
*
|
|
537
|
+
* If the input is already a permission schema (has rule properties),
|
|
538
|
+
* it's returned as-is. Otherwise, the template is resolved using the
|
|
539
|
+
* template resolver.
|
|
540
|
+
*
|
|
541
|
+
* @param config - Template configuration or direct permission schema
|
|
542
|
+
* @returns Resolved permission schema
|
|
543
|
+
*
|
|
544
|
+
* @example
|
|
545
|
+
* ```typescript
|
|
546
|
+
* const analyzer = new PermissionAnalyzer();
|
|
547
|
+
*
|
|
548
|
+
* // Resolve from template
|
|
549
|
+
* const permissions = analyzer.resolvePermissions({
|
|
550
|
+
* template: 'owner-only',
|
|
551
|
+
* ownerField: 'User'
|
|
552
|
+
* });
|
|
553
|
+
*
|
|
554
|
+
* // Or pass direct schema
|
|
555
|
+
* const permissions = analyzer.resolvePermissions({
|
|
556
|
+
* listRule: '@request.auth.id != ""',
|
|
557
|
+
* viewRule: '@request.auth.id != ""'
|
|
558
|
+
* });
|
|
559
|
+
* ```
|
|
560
|
+
*/
|
|
561
|
+
resolvePermissions(config) {
|
|
562
|
+
if ("listRule" in config || "viewRule" in config || "createRule" in config || "updateRule" in config || "deleteRule" in config || "manageRule" in config) {
|
|
563
|
+
return config;
|
|
564
|
+
}
|
|
565
|
+
return resolveTemplate(config);
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Validate all rules in a permission schema
|
|
569
|
+
*
|
|
570
|
+
* Validates each rule in the permission schema against the collection's
|
|
571
|
+
* field definitions. Returns a map of validation results keyed by rule type.
|
|
572
|
+
*
|
|
573
|
+
* Only validates rules that are defined (not undefined). Undefined rules
|
|
574
|
+
* are treated as null (locked) by default.
|
|
575
|
+
*
|
|
576
|
+
* @param collectionName - Name of the collection being validated
|
|
577
|
+
* @param permissions - Permission schema to validate
|
|
578
|
+
* @param fields - Collection field definitions
|
|
579
|
+
* @param isAuthCollection - Whether this is an auth collection (allows manageRule)
|
|
580
|
+
* @returns Map of validation results by rule type
|
|
581
|
+
*
|
|
582
|
+
* @example
|
|
583
|
+
* ```typescript
|
|
584
|
+
* const analyzer = new PermissionAnalyzer();
|
|
585
|
+
* const results = analyzer.validatePermissions(
|
|
586
|
+
* 'posts',
|
|
587
|
+
* { listRule: '@request.auth.id != ""', viewRule: 'author = @request.auth.id' },
|
|
588
|
+
* fields,
|
|
589
|
+
* false
|
|
590
|
+
* );
|
|
591
|
+
*
|
|
592
|
+
* for (const [ruleType, result] of results) {
|
|
593
|
+
* if (!result.valid) {
|
|
594
|
+
* console.error(`${ruleType} validation failed:`, result.errors);
|
|
595
|
+
* }
|
|
596
|
+
* }
|
|
597
|
+
* ```
|
|
598
|
+
*/
|
|
599
|
+
validatePermissions(collectionName, permissions, fields, isAuthCollection2 = false) {
|
|
600
|
+
const validator = new RuleValidator(collectionName, fields, isAuthCollection2);
|
|
601
|
+
const results = /* @__PURE__ */ new Map();
|
|
602
|
+
const ruleTypes = ["listRule", "viewRule", "createRule", "updateRule", "deleteRule"];
|
|
603
|
+
if (isAuthCollection2) {
|
|
604
|
+
ruleTypes.push("manageRule");
|
|
605
|
+
}
|
|
606
|
+
for (const ruleType of ruleTypes) {
|
|
607
|
+
const expression = permissions[ruleType];
|
|
608
|
+
if (expression !== void 0) {
|
|
609
|
+
results.set(ruleType, validator.validate(ruleType, expression));
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
return results;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Merge permissions with defaults
|
|
616
|
+
*
|
|
617
|
+
* Ensures all rule types have a defined value. Undefined rules are set
|
|
618
|
+
* to null (locked to superusers only), which is the PocketBase default.
|
|
619
|
+
*
|
|
620
|
+
* This is useful when generating migrations to ensure all rules are
|
|
621
|
+
* explicitly set in the collection configuration.
|
|
622
|
+
*
|
|
623
|
+
* @param permissions - Permission schema (may have undefined rules)
|
|
624
|
+
* @returns Permission schema with all rules defined (null if not specified)
|
|
625
|
+
*
|
|
626
|
+
* @example
|
|
627
|
+
* ```typescript
|
|
628
|
+
* const analyzer = new PermissionAnalyzer();
|
|
629
|
+
* const merged = analyzer.mergeWithDefaults({
|
|
630
|
+
* listRule: '@request.auth.id != ""'
|
|
631
|
+
* // other rules undefined
|
|
632
|
+
* });
|
|
633
|
+
*
|
|
634
|
+
* // Result:
|
|
635
|
+
* // {
|
|
636
|
+
* // listRule: '@request.auth.id != ""',
|
|
637
|
+
* // viewRule: null,
|
|
638
|
+
* // createRule: null,
|
|
639
|
+
* // updateRule: null,
|
|
640
|
+
* // deleteRule: null,
|
|
641
|
+
* // manageRule: null
|
|
642
|
+
* // }
|
|
643
|
+
* ```
|
|
644
|
+
*/
|
|
645
|
+
mergeWithDefaults(permissions) {
|
|
646
|
+
return {
|
|
647
|
+
listRule: permissions.listRule ?? null,
|
|
648
|
+
viewRule: permissions.viewRule ?? null,
|
|
649
|
+
createRule: permissions.createRule ?? null,
|
|
650
|
+
updateRule: permissions.updateRule ?? null,
|
|
651
|
+
deleteRule: permissions.deleteRule ?? null,
|
|
652
|
+
manageRule: permissions.manageRule ?? null
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
|
|
657
|
+
// src/migration/utils/pluralize.ts
|
|
658
|
+
var SPECIAL_CASES = {
|
|
659
|
+
// Common irregular plurals
|
|
660
|
+
person: "people",
|
|
661
|
+
Person: "People",
|
|
662
|
+
child: "children",
|
|
663
|
+
Child: "Children",
|
|
664
|
+
man: "men",
|
|
665
|
+
Man: "Men",
|
|
666
|
+
woman: "women",
|
|
667
|
+
Woman: "Women",
|
|
668
|
+
tooth: "teeth",
|
|
669
|
+
Tooth: "Teeth",
|
|
670
|
+
foot: "feet",
|
|
671
|
+
Foot: "Feet",
|
|
672
|
+
mouse: "mice",
|
|
673
|
+
Mouse: "Mice",
|
|
674
|
+
goose: "geese",
|
|
675
|
+
Goose: "Geese",
|
|
676
|
+
// Words ending in -y
|
|
677
|
+
category: "categories",
|
|
678
|
+
Category: "Categories",
|
|
679
|
+
company: "companies",
|
|
680
|
+
Company: "Companies",
|
|
681
|
+
city: "cities",
|
|
682
|
+
City: "Cities",
|
|
683
|
+
country: "countries",
|
|
684
|
+
Country: "Countries",
|
|
685
|
+
story: "stories",
|
|
686
|
+
Story: "Stories",
|
|
687
|
+
party: "parties",
|
|
688
|
+
Party: "Parties",
|
|
689
|
+
family: "families",
|
|
690
|
+
Family: "Families",
|
|
691
|
+
activity: "activities",
|
|
692
|
+
Activity: "Activities",
|
|
693
|
+
priority: "priorities",
|
|
694
|
+
Priority: "Priorities",
|
|
695
|
+
// Words ending in -f or -fe
|
|
696
|
+
life: "lives",
|
|
697
|
+
Life: "Lives",
|
|
698
|
+
wife: "wives",
|
|
699
|
+
Wife: "Wives",
|
|
700
|
+
knife: "knives",
|
|
701
|
+
Knife: "Knives",
|
|
702
|
+
leaf: "leaves",
|
|
703
|
+
Leaf: "Leaves",
|
|
704
|
+
shelf: "shelves",
|
|
705
|
+
Shelf: "Shelves",
|
|
706
|
+
half: "halves",
|
|
707
|
+
Half: "Halves",
|
|
708
|
+
// Words ending in -is
|
|
709
|
+
analysis: "analyses",
|
|
710
|
+
Analysis: "Analyses",
|
|
711
|
+
basis: "bases",
|
|
712
|
+
Basis: "Bases",
|
|
713
|
+
crisis: "crises",
|
|
714
|
+
Crisis: "Crises",
|
|
715
|
+
thesis: "theses",
|
|
716
|
+
Thesis: "Theses",
|
|
717
|
+
// Words ending in -us
|
|
718
|
+
cactus: "cacti",
|
|
719
|
+
Cactus: "Cacti",
|
|
720
|
+
focus: "foci",
|
|
721
|
+
Focus: "Foci",
|
|
722
|
+
fungus: "fungi",
|
|
723
|
+
Fungus: "Fungi",
|
|
724
|
+
nucleus: "nuclei",
|
|
725
|
+
Nucleus: "Nuclei",
|
|
726
|
+
radius: "radii",
|
|
727
|
+
Radius: "Radii",
|
|
728
|
+
// Words ending in -on
|
|
729
|
+
phenomenon: "phenomena",
|
|
730
|
+
Phenomenon: "Phenomena",
|
|
731
|
+
criterion: "criteria",
|
|
732
|
+
Criterion: "Criteria",
|
|
733
|
+
// Words ending in -um
|
|
734
|
+
datum: "data",
|
|
735
|
+
Datum: "Data",
|
|
736
|
+
medium: "media",
|
|
737
|
+
Medium: "Media",
|
|
738
|
+
curriculum: "curricula",
|
|
739
|
+
Curriculum: "Curricula",
|
|
740
|
+
// Unchanged plurals
|
|
741
|
+
sheep: "sheep",
|
|
742
|
+
Sheep: "Sheep",
|
|
743
|
+
deer: "deer",
|
|
744
|
+
Deer: "Deer",
|
|
745
|
+
fish: "fish",
|
|
746
|
+
Fish: "Fish",
|
|
747
|
+
species: "species",
|
|
748
|
+
Species: "Species",
|
|
749
|
+
series: "series",
|
|
750
|
+
Series: "Series"
|
|
751
|
+
};
|
|
752
|
+
function pluralize(singular) {
|
|
753
|
+
if (SPECIAL_CASES[singular]) {
|
|
754
|
+
return SPECIAL_CASES[singular];
|
|
755
|
+
}
|
|
756
|
+
if (singular.length > 3 && singular.endsWith("s") && !singular.endsWith("ss")) {
|
|
757
|
+
return singular;
|
|
758
|
+
}
|
|
759
|
+
const lowerSingular = singular.toLowerCase();
|
|
760
|
+
let plural;
|
|
761
|
+
if (/(?:s|ss|sh|ch|x|z)$/.test(lowerSingular)) {
|
|
762
|
+
plural = singular + "es";
|
|
763
|
+
} else if (/[^aeiou]y$/.test(lowerSingular)) {
|
|
764
|
+
plural = singular.slice(0, -1) + "ies";
|
|
765
|
+
} else if (/[^aeiou]o$/.test(lowerSingular)) {
|
|
766
|
+
plural = singular + "es";
|
|
767
|
+
} else if (/fe?$/.test(lowerSingular)) {
|
|
768
|
+
if (lowerSingular.endsWith("fe")) {
|
|
769
|
+
plural = singular.slice(0, -2) + "ves";
|
|
770
|
+
} else {
|
|
771
|
+
plural = singular.slice(0, -1) + "ves";
|
|
772
|
+
}
|
|
773
|
+
} else {
|
|
774
|
+
plural = singular + "s";
|
|
775
|
+
}
|
|
776
|
+
return plural;
|
|
777
|
+
}
|
|
778
|
+
function toCollectionName(entityName) {
|
|
779
|
+
return pluralize(entityName);
|
|
780
|
+
}
|
|
781
|
+
function isSingleRelationField(fieldName, zodType) {
|
|
782
|
+
let unwrappedType = zodType;
|
|
783
|
+
if (zodType instanceof zod.z.ZodOptional) {
|
|
784
|
+
unwrappedType = zodType._def.innerType;
|
|
785
|
+
}
|
|
786
|
+
if (unwrappedType instanceof zod.z.ZodNullable) {
|
|
787
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
788
|
+
}
|
|
789
|
+
if (unwrappedType instanceof zod.z.ZodDefault) {
|
|
790
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
791
|
+
}
|
|
792
|
+
if (!(unwrappedType instanceof zod.z.ZodString)) {
|
|
793
|
+
return false;
|
|
794
|
+
}
|
|
795
|
+
const startsWithUppercase = /^[A-Z]/.test(fieldName);
|
|
796
|
+
const commonStringFields = ["Title", "Name", "Description", "Content", "Summary", "Status", "Type"];
|
|
797
|
+
const isCommonField = commonStringFields.includes(fieldName);
|
|
798
|
+
return startsWithUppercase && !isCommonField;
|
|
799
|
+
}
|
|
800
|
+
function isMultipleRelationField(fieldName, zodType) {
|
|
801
|
+
let unwrappedType = zodType;
|
|
802
|
+
if (zodType instanceof zod.z.ZodOptional) {
|
|
803
|
+
unwrappedType = zodType._def.innerType;
|
|
804
|
+
}
|
|
805
|
+
if (unwrappedType instanceof zod.z.ZodNullable) {
|
|
806
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
807
|
+
}
|
|
808
|
+
if (unwrappedType instanceof zod.z.ZodDefault) {
|
|
809
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
810
|
+
}
|
|
811
|
+
if (!(unwrappedType instanceof zod.z.ZodArray)) {
|
|
812
|
+
return false;
|
|
813
|
+
}
|
|
814
|
+
const elementType = unwrappedType._def.type;
|
|
815
|
+
if (!(elementType instanceof zod.z.ZodString)) {
|
|
816
|
+
return false;
|
|
817
|
+
}
|
|
818
|
+
const hasUppercase = /[A-Z]/.test(fieldName);
|
|
819
|
+
return hasUppercase;
|
|
820
|
+
}
|
|
821
|
+
function resolveTargetCollection(fieldName) {
|
|
822
|
+
const matches = fieldName.match(/[A-Z][a-z]+/g);
|
|
823
|
+
if (!matches || matches.length === 0) {
|
|
824
|
+
return pluralize(fieldName);
|
|
825
|
+
}
|
|
826
|
+
const entityName = matches[matches.length - 1];
|
|
827
|
+
return pluralize(entityName);
|
|
828
|
+
}
|
|
829
|
+
function isRelationField(fieldName, zodType) {
|
|
830
|
+
return isSingleRelationField(fieldName, zodType) || isMultipleRelationField(fieldName, zodType);
|
|
831
|
+
}
|
|
832
|
+
function getMaxSelect(fieldName, zodType) {
|
|
833
|
+
if (isSingleRelationField(fieldName, zodType)) {
|
|
834
|
+
return 1;
|
|
835
|
+
}
|
|
836
|
+
if (isMultipleRelationField(fieldName, zodType)) {
|
|
837
|
+
let unwrappedType = zodType;
|
|
838
|
+
if (zodType instanceof zod.z.ZodOptional) {
|
|
839
|
+
unwrappedType = zodType._def.innerType;
|
|
840
|
+
}
|
|
841
|
+
if (unwrappedType instanceof zod.z.ZodNullable) {
|
|
842
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
843
|
+
}
|
|
844
|
+
if (unwrappedType instanceof zod.z.ZodDefault) {
|
|
845
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
846
|
+
}
|
|
847
|
+
if (unwrappedType instanceof zod.z.ZodArray) {
|
|
848
|
+
const arrayDef = unwrappedType._def;
|
|
849
|
+
if (arrayDef.maxLength) {
|
|
850
|
+
return arrayDef.maxLength.value;
|
|
851
|
+
}
|
|
852
|
+
return 999;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return 1;
|
|
856
|
+
}
|
|
857
|
+
function getMinSelect(fieldName, zodType) {
|
|
858
|
+
if (!isMultipleRelationField(fieldName, zodType)) {
|
|
859
|
+
return void 0;
|
|
860
|
+
}
|
|
861
|
+
let unwrappedType = zodType;
|
|
862
|
+
if (zodType instanceof zod.z.ZodOptional) {
|
|
863
|
+
unwrappedType = zodType._def.innerType;
|
|
864
|
+
}
|
|
865
|
+
if (unwrappedType instanceof zod.z.ZodNullable) {
|
|
866
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
867
|
+
}
|
|
868
|
+
if (unwrappedType instanceof zod.z.ZodDefault) {
|
|
869
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
870
|
+
}
|
|
871
|
+
if (unwrappedType instanceof zod.z.ZodArray) {
|
|
872
|
+
const arrayDef = unwrappedType._def;
|
|
873
|
+
if (arrayDef.minLength) {
|
|
874
|
+
return arrayDef.minLength.value;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
return void 0;
|
|
878
|
+
}
|
|
879
|
+
function mapZodStringType(zodType) {
|
|
880
|
+
const checks = zodType._def.checks || [];
|
|
881
|
+
const hasEmail = checks.some((check) => check.kind === "email");
|
|
882
|
+
if (hasEmail) {
|
|
883
|
+
return "email";
|
|
884
|
+
}
|
|
885
|
+
const hasUrl = checks.some((check) => check.kind === "url");
|
|
886
|
+
if (hasUrl) {
|
|
887
|
+
return "url";
|
|
888
|
+
}
|
|
889
|
+
const hasDatetime = checks.some((check) => check.kind === "datetime");
|
|
890
|
+
if (hasDatetime) {
|
|
891
|
+
return "date";
|
|
892
|
+
}
|
|
893
|
+
return "text";
|
|
894
|
+
}
|
|
895
|
+
function mapZodNumberType(_zodType) {
|
|
896
|
+
return "number";
|
|
897
|
+
}
|
|
898
|
+
function mapZodBooleanType(_zodType) {
|
|
899
|
+
return "bool";
|
|
900
|
+
}
|
|
901
|
+
function mapZodEnumType(_zodType) {
|
|
902
|
+
return "select";
|
|
903
|
+
}
|
|
904
|
+
function mapZodArrayType(zodType, _fieldName) {
|
|
905
|
+
const elementType = zodType._def.type;
|
|
906
|
+
if (elementType instanceof zod.z.ZodType) {
|
|
907
|
+
const typeName = elementType._def.typeName;
|
|
908
|
+
if (typeName === "ZodType" && elementType._def?.innerType?.name === "File") {
|
|
909
|
+
return "file";
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
if (elementType._def?.typeName === "ZodType") {
|
|
913
|
+
const checks = elementType._def?.checks || [];
|
|
914
|
+
const isFileInstance = checks.some(
|
|
915
|
+
(check) => check.kind === "instanceof" || elementType._def?.innerType?.name === "File"
|
|
916
|
+
);
|
|
917
|
+
if (isFileInstance) {
|
|
918
|
+
return "file";
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (elementType instanceof zod.z.ZodString) {
|
|
922
|
+
return "relation";
|
|
923
|
+
}
|
|
924
|
+
return "json";
|
|
925
|
+
}
|
|
926
|
+
function mapZodDateType(_zodType) {
|
|
927
|
+
return "date";
|
|
928
|
+
}
|
|
929
|
+
function mapZodRecordType(_zodType) {
|
|
930
|
+
return "json";
|
|
931
|
+
}
|
|
932
|
+
function mapZodTypeToPocketBase(zodType, fieldName) {
|
|
933
|
+
let unwrappedType = zodType;
|
|
934
|
+
if (zodType instanceof zod.z.ZodOptional) {
|
|
935
|
+
unwrappedType = zodType._def.innerType;
|
|
936
|
+
}
|
|
937
|
+
if (unwrappedType instanceof zod.z.ZodNullable) {
|
|
938
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
939
|
+
}
|
|
940
|
+
if (unwrappedType instanceof zod.z.ZodDefault) {
|
|
941
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
942
|
+
}
|
|
943
|
+
if (unwrappedType._def?.typeName === "ZodEffects") {
|
|
944
|
+
const effect = unwrappedType._def?.effect;
|
|
945
|
+
if (effect?.type === "refinement") {
|
|
946
|
+
const fileFieldNames = ["avatar", "image", "file", "attachment", "photo", "picture", "document", "upload"];
|
|
947
|
+
if (fileFieldNames.some((name) => fieldName.toLowerCase().includes(name))) {
|
|
948
|
+
return "file";
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
if (unwrappedType._def?.typeName === "ZodType") {
|
|
953
|
+
const checks = unwrappedType._def?.checks || [];
|
|
954
|
+
const innerType = unwrappedType._def?.innerType;
|
|
955
|
+
if (innerType?.name === "File" || checks.some((check) => check.kind === "instanceof")) {
|
|
956
|
+
return "file";
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
if (unwrappedType instanceof zod.z.ZodString) {
|
|
960
|
+
return mapZodStringType(unwrappedType);
|
|
961
|
+
}
|
|
962
|
+
if (unwrappedType instanceof zod.z.ZodNumber) {
|
|
963
|
+
return mapZodNumberType();
|
|
964
|
+
}
|
|
965
|
+
if (unwrappedType instanceof zod.z.ZodBoolean) {
|
|
966
|
+
return mapZodBooleanType();
|
|
967
|
+
}
|
|
968
|
+
if (unwrappedType instanceof zod.z.ZodEnum) {
|
|
969
|
+
return mapZodEnumType();
|
|
970
|
+
}
|
|
971
|
+
if (unwrappedType instanceof zod.z.ZodArray) {
|
|
972
|
+
return mapZodArrayType(unwrappedType);
|
|
973
|
+
}
|
|
974
|
+
if (unwrappedType instanceof zod.z.ZodDate) {
|
|
975
|
+
return mapZodDateType();
|
|
976
|
+
}
|
|
977
|
+
if (unwrappedType instanceof zod.z.ZodRecord || unwrappedType instanceof zod.z.ZodObject) {
|
|
978
|
+
return mapZodRecordType();
|
|
979
|
+
}
|
|
980
|
+
return "text";
|
|
981
|
+
}
|
|
982
|
+
function extractFieldOptions(zodType) {
|
|
983
|
+
const options = {};
|
|
984
|
+
let unwrappedType = zodType;
|
|
985
|
+
if (zodType instanceof zod.z.ZodOptional) {
|
|
986
|
+
unwrappedType = zodType._def.innerType;
|
|
987
|
+
}
|
|
988
|
+
if (unwrappedType instanceof zod.z.ZodNullable) {
|
|
989
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
990
|
+
}
|
|
991
|
+
if (unwrappedType instanceof zod.z.ZodDefault) {
|
|
992
|
+
unwrappedType = unwrappedType._def.innerType;
|
|
993
|
+
}
|
|
994
|
+
const checks = unwrappedType._def?.checks || [];
|
|
995
|
+
if (unwrappedType instanceof zod.z.ZodString) {
|
|
996
|
+
for (const check of checks) {
|
|
997
|
+
if (check.kind === "min") {
|
|
998
|
+
options.min = check.value;
|
|
999
|
+
}
|
|
1000
|
+
if (check.kind === "max") {
|
|
1001
|
+
options.max = check.value;
|
|
1002
|
+
}
|
|
1003
|
+
if (check.kind === "regex") {
|
|
1004
|
+
options.pattern = check.regex.source;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
if (unwrappedType instanceof zod.z.ZodNumber) {
|
|
1009
|
+
for (const check of checks) {
|
|
1010
|
+
if (check.kind === "min") {
|
|
1011
|
+
options.min = check.value;
|
|
1012
|
+
}
|
|
1013
|
+
if (check.kind === "max") {
|
|
1014
|
+
options.max = check.value;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
if (unwrappedType instanceof zod.z.ZodEnum) {
|
|
1019
|
+
options.values = unwrappedType._def.values;
|
|
1020
|
+
}
|
|
1021
|
+
if (unwrappedType instanceof zod.z.ZodArray) {
|
|
1022
|
+
const arrayChecks = unwrappedType._def?.checks || [];
|
|
1023
|
+
for (const check of arrayChecks) {
|
|
1024
|
+
if (check.kind === "min") {
|
|
1025
|
+
options.minSelect = check.value;
|
|
1026
|
+
}
|
|
1027
|
+
if (check.kind === "max") {
|
|
1028
|
+
options.maxSelect = check.value;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
return options;
|
|
1033
|
+
}
|
|
1034
|
+
function isFieldRequired(zodType) {
|
|
1035
|
+
if (zodType instanceof zod.z.ZodOptional) {
|
|
1036
|
+
return false;
|
|
1037
|
+
}
|
|
1038
|
+
if (zodType instanceof zod.z.ZodDefault) {
|
|
1039
|
+
return false;
|
|
1040
|
+
}
|
|
1041
|
+
if (zodType instanceof zod.z.ZodNullable) {
|
|
1042
|
+
return false;
|
|
1043
|
+
}
|
|
1044
|
+
return true;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// src/migration/analyzer.ts
|
|
1048
|
+
var DEFAULT_CONFIG = {
|
|
1049
|
+
workspaceRoot: process.cwd(),
|
|
1050
|
+
excludePatterns: [
|
|
1051
|
+
"base.ts",
|
|
1052
|
+
"index.ts",
|
|
1053
|
+
"permissions.ts",
|
|
1054
|
+
"permission-templates.ts",
|
|
1055
|
+
"base.js",
|
|
1056
|
+
"index.js",
|
|
1057
|
+
"permissions.js",
|
|
1058
|
+
"permission-templates.js"
|
|
1059
|
+
],
|
|
1060
|
+
includeExtensions: [".ts", ".js"],
|
|
1061
|
+
schemaPatterns: ["Schema", "InputSchema"],
|
|
1062
|
+
useCompiledFiles: true
|
|
1063
|
+
};
|
|
1064
|
+
function mergeConfig(config) {
|
|
1065
|
+
return {
|
|
1066
|
+
...DEFAULT_CONFIG,
|
|
1067
|
+
...config,
|
|
1068
|
+
excludePatterns: config.excludePatterns || DEFAULT_CONFIG.excludePatterns,
|
|
1069
|
+
includeExtensions: config.includeExtensions || DEFAULT_CONFIG.includeExtensions,
|
|
1070
|
+
schemaPatterns: config.schemaPatterns || DEFAULT_CONFIG.schemaPatterns
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
function resolveSchemaDir(config) {
|
|
1074
|
+
const workspaceRoot = config.workspaceRoot || process.cwd();
|
|
1075
|
+
if (path4__namespace.isAbsolute(config.schemaDir)) {
|
|
1076
|
+
return config.schemaDir;
|
|
1077
|
+
}
|
|
1078
|
+
return path4__namespace.join(workspaceRoot, config.schemaDir);
|
|
1079
|
+
}
|
|
1080
|
+
function discoverSchemaFiles(config) {
|
|
1081
|
+
const normalizedConfig = typeof config === "string" ? { schemaDir: config } : config;
|
|
1082
|
+
const mergedConfig = mergeConfig(normalizedConfig);
|
|
1083
|
+
const schemaDir = resolveSchemaDir(normalizedConfig);
|
|
1084
|
+
try {
|
|
1085
|
+
if (!fs4__namespace.existsSync(schemaDir)) {
|
|
1086
|
+
throw new FileSystemError(`Schema directory not found: ${schemaDir}`, schemaDir, "access", "ENOENT");
|
|
1087
|
+
}
|
|
1088
|
+
const files = fs4__namespace.readdirSync(schemaDir);
|
|
1089
|
+
const schemaFiles = files.filter((file) => {
|
|
1090
|
+
const hasValidExtension = mergedConfig.includeExtensions.some((ext) => file.endsWith(ext));
|
|
1091
|
+
if (!hasValidExtension) return false;
|
|
1092
|
+
const isExcluded = mergedConfig.excludePatterns.some((pattern) => {
|
|
1093
|
+
if (pattern.includes("*")) {
|
|
1094
|
+
const regex = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
|
|
1095
|
+
return regex.test(file);
|
|
1096
|
+
}
|
|
1097
|
+
return file === pattern;
|
|
1098
|
+
});
|
|
1099
|
+
if (isExcluded) return false;
|
|
1100
|
+
return true;
|
|
1101
|
+
});
|
|
1102
|
+
return schemaFiles.map((file) => {
|
|
1103
|
+
const ext = mergedConfig.includeExtensions.find((ext2) => file.endsWith(ext2)) || ".ts";
|
|
1104
|
+
return path4__namespace.join(schemaDir, file.replace(new RegExp(`\\${ext}$`), ""));
|
|
1105
|
+
});
|
|
1106
|
+
} catch (error) {
|
|
1107
|
+
if (error instanceof FileSystemError) {
|
|
1108
|
+
throw error;
|
|
1109
|
+
}
|
|
1110
|
+
const fsError = error;
|
|
1111
|
+
if (fsError.code === "EACCES" || fsError.code === "EPERM") {
|
|
1112
|
+
throw new FileSystemError(
|
|
1113
|
+
`Permission denied reading schema directory: ${schemaDir}`,
|
|
1114
|
+
schemaDir,
|
|
1115
|
+
"read",
|
|
1116
|
+
fsError.code,
|
|
1117
|
+
error
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
throw new FileSystemError(
|
|
1121
|
+
`Failed to read schema directory: ${schemaDir}`,
|
|
1122
|
+
schemaDir,
|
|
1123
|
+
"read",
|
|
1124
|
+
fsError.code,
|
|
1125
|
+
error
|
|
1126
|
+
);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
async function importSchemaModule(filePath, config) {
|
|
1130
|
+
try {
|
|
1131
|
+
let importPath = filePath;
|
|
1132
|
+
if (config?.pathTransformer) {
|
|
1133
|
+
importPath = config.pathTransformer(filePath);
|
|
1134
|
+
}
|
|
1135
|
+
if (!importPath.endsWith(".js")) {
|
|
1136
|
+
importPath = `${importPath}.js`;
|
|
1137
|
+
}
|
|
1138
|
+
const fileUrl = new URL(`file://${path4__namespace.resolve(importPath)}`);
|
|
1139
|
+
const module = await import(fileUrl.href);
|
|
1140
|
+
return module;
|
|
1141
|
+
} catch (error) {
|
|
1142
|
+
throw new SchemaParsingError(
|
|
1143
|
+
`Failed to import schema module. Make sure the schema files are compiled to JavaScript.`,
|
|
1144
|
+
filePath,
|
|
1145
|
+
error
|
|
1146
|
+
);
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
function getCollectionNameFromFile(filePath) {
|
|
1150
|
+
const filename = path4__namespace.basename(filePath).replace(/\.(ts|js)$/, "");
|
|
1151
|
+
return toCollectionName(filename);
|
|
1152
|
+
}
|
|
1153
|
+
function extractSchemaDefinitions(module, patterns = ["Schema", "InputSchema"]) {
|
|
1154
|
+
const result = {};
|
|
1155
|
+
for (const [key, value] of Object.entries(module)) {
|
|
1156
|
+
if (value instanceof zod.z.ZodObject) {
|
|
1157
|
+
if (patterns.includes("InputSchema") && key.endsWith("InputSchema")) {
|
|
1158
|
+
result.inputSchema = value;
|
|
1159
|
+
} else if (patterns.includes("Schema") && key.endsWith("Schema") && !key.endsWith("InputSchema")) {
|
|
1160
|
+
result.schema = value;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
return result;
|
|
1165
|
+
}
|
|
1166
|
+
function selectSchemaForCollection(schemas) {
|
|
1167
|
+
if (schemas.schema) {
|
|
1168
|
+
return schemas.schema;
|
|
1169
|
+
}
|
|
1170
|
+
if (schemas.inputSchema) {
|
|
1171
|
+
return schemas.inputSchema;
|
|
1172
|
+
}
|
|
1173
|
+
return null;
|
|
1174
|
+
}
|
|
1175
|
+
function extractFieldDefinitions(zodSchema, excludeFields) {
|
|
1176
|
+
const shape = zodSchema.shape;
|
|
1177
|
+
const fields = [];
|
|
1178
|
+
const baseFields = ["id", "collectionId", "collectionName", "created", "updated", "expand"];
|
|
1179
|
+
const defaultExcludeFields = ["thumbnailURL", "imageFiles"];
|
|
1180
|
+
const allExclusions = /* @__PURE__ */ new Set([...baseFields, ...defaultExcludeFields, ...[]]);
|
|
1181
|
+
for (const [fieldName, zodType] of Object.entries(shape)) {
|
|
1182
|
+
if (!allExclusions.has(fieldName)) {
|
|
1183
|
+
fields.push({ name: fieldName, zodType });
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
return fields;
|
|
1187
|
+
}
|
|
1188
|
+
function isAuthCollection(fields) {
|
|
1189
|
+
const fieldNames = fields.map((f) => f.name.toLowerCase());
|
|
1190
|
+
const hasEmail = fieldNames.includes("email");
|
|
1191
|
+
const hasPassword = fieldNames.includes("password");
|
|
1192
|
+
return hasEmail && hasPassword;
|
|
1193
|
+
}
|
|
1194
|
+
function buildFieldDefinition(fieldName, zodType) {
|
|
1195
|
+
const fieldType = mapZodTypeToPocketBase(zodType, fieldName);
|
|
1196
|
+
const required = isFieldRequired(zodType);
|
|
1197
|
+
const options = extractFieldOptions(zodType);
|
|
1198
|
+
const fieldDef = {
|
|
1199
|
+
name: fieldName,
|
|
1200
|
+
type: fieldType,
|
|
1201
|
+
required,
|
|
1202
|
+
options
|
|
1203
|
+
};
|
|
1204
|
+
if (isRelationField(fieldName, zodType)) {
|
|
1205
|
+
fieldDef.type = "relation";
|
|
1206
|
+
const targetCollection = resolveTargetCollection(fieldName);
|
|
1207
|
+
const maxSelect = getMaxSelect(fieldName, zodType);
|
|
1208
|
+
const minSelect = getMinSelect(fieldName, zodType);
|
|
1209
|
+
fieldDef.relation = {
|
|
1210
|
+
collection: targetCollection,
|
|
1211
|
+
maxSelect,
|
|
1212
|
+
minSelect,
|
|
1213
|
+
cascadeDelete: false
|
|
1214
|
+
// Default to false, can be configured later
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
return fieldDef;
|
|
1218
|
+
}
|
|
1219
|
+
function extractIndexes(schema) {
|
|
1220
|
+
const schemaDescription = schema.description;
|
|
1221
|
+
if (!schemaDescription) {
|
|
1222
|
+
return void 0;
|
|
1223
|
+
}
|
|
1224
|
+
try {
|
|
1225
|
+
const metadata = JSON.parse(schemaDescription);
|
|
1226
|
+
if (metadata.indexes && Array.isArray(metadata.indexes)) {
|
|
1227
|
+
return metadata.indexes;
|
|
1228
|
+
}
|
|
1229
|
+
} catch {
|
|
1230
|
+
}
|
|
1231
|
+
return void 0;
|
|
1232
|
+
}
|
|
1233
|
+
function convertZodSchemaToCollectionSchema(collectionName, zodSchema) {
|
|
1234
|
+
const rawFields = extractFieldDefinitions(zodSchema);
|
|
1235
|
+
const collectionType = isAuthCollection(rawFields) ? "auth" : "base";
|
|
1236
|
+
const fields = rawFields.map(({ name, zodType }) => buildFieldDefinition(name, zodType));
|
|
1237
|
+
const indexes = extractIndexes(zodSchema) || [];
|
|
1238
|
+
const permissionAnalyzer = new PermissionAnalyzer();
|
|
1239
|
+
let permissions = void 0;
|
|
1240
|
+
const schemaDescription = zodSchema.description;
|
|
1241
|
+
const extractedPermissions = permissionAnalyzer.extractPermissions(schemaDescription);
|
|
1242
|
+
if (extractedPermissions) {
|
|
1243
|
+
const resolvedPermissions = permissionAnalyzer.resolvePermissions(extractedPermissions);
|
|
1244
|
+
const validationResults = permissionAnalyzer.validatePermissions(
|
|
1245
|
+
collectionName,
|
|
1246
|
+
resolvedPermissions,
|
|
1247
|
+
fields,
|
|
1248
|
+
collectionType === "auth"
|
|
1249
|
+
);
|
|
1250
|
+
for (const [ruleType, result] of validationResults) {
|
|
1251
|
+
if (!result.valid) {
|
|
1252
|
+
console.error(`[${collectionName}] Permission validation failed for ${ruleType}:`);
|
|
1253
|
+
result.errors.forEach((error) => console.error(` - ${error}`));
|
|
1254
|
+
}
|
|
1255
|
+
if (result.warnings.length > 0) {
|
|
1256
|
+
console.warn(`[${collectionName}] Permission warnings for ${ruleType}:`);
|
|
1257
|
+
result.warnings.forEach((warning) => console.warn(` - ${warning}`));
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
permissions = permissionAnalyzer.mergeWithDefaults(resolvedPermissions);
|
|
1261
|
+
}
|
|
1262
|
+
const collectionSchema = {
|
|
1263
|
+
name: collectionName,
|
|
1264
|
+
type: collectionType,
|
|
1265
|
+
fields,
|
|
1266
|
+
indexes,
|
|
1267
|
+
rules: {
|
|
1268
|
+
listRule: null,
|
|
1269
|
+
viewRule: null,
|
|
1270
|
+
createRule: null,
|
|
1271
|
+
updateRule: null,
|
|
1272
|
+
deleteRule: null
|
|
1273
|
+
},
|
|
1274
|
+
permissions
|
|
1275
|
+
};
|
|
1276
|
+
return collectionSchema;
|
|
1277
|
+
}
|
|
1278
|
+
async function buildSchemaDefinition(config) {
|
|
1279
|
+
const normalizedConfig = typeof config === "string" ? { schemaDir: config } : config;
|
|
1280
|
+
const mergedConfig = mergeConfig(normalizedConfig);
|
|
1281
|
+
const collections = /* @__PURE__ */ new Map();
|
|
1282
|
+
const schemaFiles = discoverSchemaFiles(normalizedConfig);
|
|
1283
|
+
if (schemaFiles.length === 0) {
|
|
1284
|
+
const schemaDir = resolveSchemaDir(normalizedConfig);
|
|
1285
|
+
throw new SchemaParsingError(
|
|
1286
|
+
`No schema files found in ${schemaDir}. Make sure you have schema files in the directory.`,
|
|
1287
|
+
schemaDir
|
|
1288
|
+
);
|
|
1289
|
+
}
|
|
1290
|
+
for (const filePath of schemaFiles) {
|
|
1291
|
+
try {
|
|
1292
|
+
let importPath = filePath;
|
|
1293
|
+
if (normalizedConfig.pathTransformer) {
|
|
1294
|
+
importPath = normalizedConfig.pathTransformer(filePath);
|
|
1295
|
+
} else if (mergedConfig.useCompiledFiles) {
|
|
1296
|
+
importPath = filePath.replace(/\/src\//, "/dist/");
|
|
1297
|
+
}
|
|
1298
|
+
const module = await importSchemaModule(importPath, normalizedConfig);
|
|
1299
|
+
const schemas = extractSchemaDefinitions(module, mergedConfig.schemaPatterns);
|
|
1300
|
+
const zodSchema = selectSchemaForCollection(schemas);
|
|
1301
|
+
if (!zodSchema) {
|
|
1302
|
+
console.warn(`No valid schema found in ${filePath}, skipping...`);
|
|
1303
|
+
continue;
|
|
1304
|
+
}
|
|
1305
|
+
const collectionName = getCollectionNameFromFile(filePath);
|
|
1306
|
+
const collectionSchema = convertZodSchemaToCollectionSchema(collectionName, zodSchema);
|
|
1307
|
+
collections.set(collectionName, collectionSchema);
|
|
1308
|
+
} catch (error) {
|
|
1309
|
+
if (error instanceof SchemaParsingError) {
|
|
1310
|
+
throw error;
|
|
1311
|
+
}
|
|
1312
|
+
throw new SchemaParsingError(
|
|
1313
|
+
`Error processing schema file: ${error instanceof Error ? error.message : String(error)}`,
|
|
1314
|
+
filePath,
|
|
1315
|
+
error
|
|
1316
|
+
);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
return { collections };
|
|
1320
|
+
}
|
|
1321
|
+
async function parseSchemaFiles(config) {
|
|
1322
|
+
return buildSchemaDefinition(config);
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
// src/migration/diff.ts
|
|
1326
|
+
var DEFAULT_CONFIG2 = {
|
|
1327
|
+
warnOnDelete: true,
|
|
1328
|
+
requireForceForDestructive: true,
|
|
1329
|
+
severityThreshold: "high",
|
|
1330
|
+
systemCollections: ["_mfas", "_otps", "_externalAuths", "_authOrigins", "_superusers"],
|
|
1331
|
+
usersSystemFields: ["id", "password", "tokenKey", "email", "emailVisibility", "verified", "created", "updated"]
|
|
1332
|
+
};
|
|
1333
|
+
function mergeConfig2(config) {
|
|
1334
|
+
return {
|
|
1335
|
+
...DEFAULT_CONFIG2,
|
|
1336
|
+
...config
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
function isSystemCollection(collectionName, config) {
|
|
1340
|
+
const mergedConfig = mergeConfig2(config);
|
|
1341
|
+
return mergedConfig.systemCollections.includes(collectionName);
|
|
1342
|
+
}
|
|
1343
|
+
function getUsersSystemFields(config) {
|
|
1344
|
+
const mergedConfig = mergeConfig2(config);
|
|
1345
|
+
return new Set(mergedConfig.usersSystemFields);
|
|
1346
|
+
}
|
|
1347
|
+
function findNewCollections(currentSchema, previousSnapshot) {
|
|
1348
|
+
const newCollections = [];
|
|
1349
|
+
if (!previousSnapshot) {
|
|
1350
|
+
return Array.from(currentSchema.collections.values());
|
|
1351
|
+
}
|
|
1352
|
+
for (const [collectionName, collectionSchema] of currentSchema.collections) {
|
|
1353
|
+
if (!previousSnapshot.collections.has(collectionName)) {
|
|
1354
|
+
newCollections.push(collectionSchema);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
return newCollections;
|
|
1358
|
+
}
|
|
1359
|
+
function findRemovedCollections(currentSchema, previousSnapshot) {
|
|
1360
|
+
const removedCollections = [];
|
|
1361
|
+
if (!previousSnapshot) {
|
|
1362
|
+
return removedCollections;
|
|
1363
|
+
}
|
|
1364
|
+
for (const [collectionName, collectionSchema] of previousSnapshot.collections) {
|
|
1365
|
+
if (!currentSchema.collections.has(collectionName)) {
|
|
1366
|
+
removedCollections.push(collectionSchema);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
return removedCollections;
|
|
1370
|
+
}
|
|
1371
|
+
function matchCollectionsByName(currentSchema, previousSnapshot) {
|
|
1372
|
+
const matches = [];
|
|
1373
|
+
if (!previousSnapshot) {
|
|
1374
|
+
return matches;
|
|
1375
|
+
}
|
|
1376
|
+
for (const [collectionName, currentCollection] of currentSchema.collections) {
|
|
1377
|
+
const previousCollection = previousSnapshot.collections.get(collectionName);
|
|
1378
|
+
if (previousCollection) {
|
|
1379
|
+
matches.push([currentCollection, previousCollection]);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
return matches;
|
|
1383
|
+
}
|
|
1384
|
+
function findNewFields(currentFields, previousFields) {
|
|
1385
|
+
const newFields = [];
|
|
1386
|
+
const previousFieldNames = new Set(previousFields.map((f) => f.name));
|
|
1387
|
+
for (const currentField of currentFields) {
|
|
1388
|
+
if (!previousFieldNames.has(currentField.name)) {
|
|
1389
|
+
newFields.push(currentField);
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
return newFields;
|
|
1393
|
+
}
|
|
1394
|
+
function findRemovedFields(currentFields, previousFields) {
|
|
1395
|
+
const removedFields = [];
|
|
1396
|
+
const currentFieldNames = new Set(currentFields.map((f) => f.name));
|
|
1397
|
+
for (const previousField of previousFields) {
|
|
1398
|
+
if (!currentFieldNames.has(previousField.name)) {
|
|
1399
|
+
removedFields.push(previousField);
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
return removedFields;
|
|
1403
|
+
}
|
|
1404
|
+
function matchFieldsByName(currentFields, previousFields) {
|
|
1405
|
+
const matches = [];
|
|
1406
|
+
const previousFieldMap = /* @__PURE__ */ new Map();
|
|
1407
|
+
for (const previousField of previousFields) {
|
|
1408
|
+
previousFieldMap.set(previousField.name, previousField);
|
|
1409
|
+
}
|
|
1410
|
+
for (const currentField of currentFields) {
|
|
1411
|
+
const previousField = previousFieldMap.get(currentField.name);
|
|
1412
|
+
if (previousField) {
|
|
1413
|
+
matches.push([currentField, previousField]);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
return matches;
|
|
1417
|
+
}
|
|
1418
|
+
function areValuesEqual(a, b) {
|
|
1419
|
+
if (a === b) return true;
|
|
1420
|
+
if (a == null || b == null) return false;
|
|
1421
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
1422
|
+
if (a.length !== b.length) return false;
|
|
1423
|
+
return a.every((val, idx) => areValuesEqual(val, b[idx]));
|
|
1424
|
+
}
|
|
1425
|
+
if (typeof a === "object" && typeof b === "object") {
|
|
1426
|
+
const keysA = Object.keys(a);
|
|
1427
|
+
const keysB = Object.keys(b);
|
|
1428
|
+
if (keysA.length !== keysB.length) return false;
|
|
1429
|
+
return keysA.every((key) => areValuesEqual(a[key], b[key]));
|
|
1430
|
+
}
|
|
1431
|
+
return a === b;
|
|
1432
|
+
}
|
|
1433
|
+
function compareFieldTypes(currentField, previousField) {
|
|
1434
|
+
if (currentField.type !== previousField.type) {
|
|
1435
|
+
return {
|
|
1436
|
+
property: "type",
|
|
1437
|
+
oldValue: previousField.type,
|
|
1438
|
+
newValue: currentField.type
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
return null;
|
|
1442
|
+
}
|
|
1443
|
+
function compareFieldConstraints(currentField, previousField) {
|
|
1444
|
+
const changes = [];
|
|
1445
|
+
if (currentField.required !== previousField.required) {
|
|
1446
|
+
changes.push({
|
|
1447
|
+
property: "required",
|
|
1448
|
+
oldValue: previousField.required,
|
|
1449
|
+
newValue: currentField.required
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
if (currentField.unique !== previousField.unique) {
|
|
1453
|
+
changes.push({
|
|
1454
|
+
property: "unique",
|
|
1455
|
+
oldValue: previousField.unique,
|
|
1456
|
+
newValue: currentField.unique
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
return changes;
|
|
1460
|
+
}
|
|
1461
|
+
function compareFieldOptions(currentField, previousField) {
|
|
1462
|
+
const changes = [];
|
|
1463
|
+
const currentOptions = currentField.options || {};
|
|
1464
|
+
const previousOptions = previousField.options || {};
|
|
1465
|
+
const allKeys = /* @__PURE__ */ new Set([...Object.keys(currentOptions), ...Object.keys(previousOptions)]);
|
|
1466
|
+
for (const key of allKeys) {
|
|
1467
|
+
const currentValue = currentOptions[key];
|
|
1468
|
+
const previousValue = previousOptions[key];
|
|
1469
|
+
if (!areValuesEqual(currentValue, previousValue)) {
|
|
1470
|
+
changes.push({
|
|
1471
|
+
property: `options.${key}`,
|
|
1472
|
+
oldValue: previousValue,
|
|
1473
|
+
newValue: currentValue
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
return changes;
|
|
1478
|
+
}
|
|
1479
|
+
function compareRelationConfigurations(currentField, previousField) {
|
|
1480
|
+
const changes = [];
|
|
1481
|
+
const currentRelation = currentField.relation;
|
|
1482
|
+
const previousRelation = previousField.relation;
|
|
1483
|
+
if (!currentRelation && !previousRelation) {
|
|
1484
|
+
return changes;
|
|
1485
|
+
}
|
|
1486
|
+
if (!currentRelation || !previousRelation) {
|
|
1487
|
+
return changes;
|
|
1488
|
+
}
|
|
1489
|
+
if (currentRelation.collection !== previousRelation.collection) {
|
|
1490
|
+
changes.push({
|
|
1491
|
+
property: "relation.collection",
|
|
1492
|
+
oldValue: previousRelation.collection,
|
|
1493
|
+
newValue: currentRelation.collection
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
if (currentRelation.cascadeDelete !== previousRelation.cascadeDelete) {
|
|
1497
|
+
changes.push({
|
|
1498
|
+
property: "relation.cascadeDelete",
|
|
1499
|
+
oldValue: previousRelation.cascadeDelete,
|
|
1500
|
+
newValue: currentRelation.cascadeDelete
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
if (currentRelation.maxSelect !== previousRelation.maxSelect) {
|
|
1504
|
+
changes.push({
|
|
1505
|
+
property: "relation.maxSelect",
|
|
1506
|
+
oldValue: previousRelation.maxSelect,
|
|
1507
|
+
newValue: currentRelation.maxSelect
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
if (currentRelation.minSelect !== previousRelation.minSelect) {
|
|
1511
|
+
changes.push({
|
|
1512
|
+
property: "relation.minSelect",
|
|
1513
|
+
oldValue: previousRelation.minSelect,
|
|
1514
|
+
newValue: currentRelation.minSelect
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
return changes;
|
|
1518
|
+
}
|
|
1519
|
+
function detectFieldChanges(currentField, previousField) {
|
|
1520
|
+
const changes = [];
|
|
1521
|
+
const typeChange = compareFieldTypes(currentField, previousField);
|
|
1522
|
+
if (typeChange) {
|
|
1523
|
+
changes.push(typeChange);
|
|
1524
|
+
}
|
|
1525
|
+
changes.push(...compareFieldConstraints(currentField, previousField));
|
|
1526
|
+
changes.push(...compareFieldOptions(currentField, previousField));
|
|
1527
|
+
if (currentField.type === "relation" && previousField.type === "relation") {
|
|
1528
|
+
changes.push(...compareRelationConfigurations(currentField, previousField));
|
|
1529
|
+
}
|
|
1530
|
+
return changes;
|
|
1531
|
+
}
|
|
1532
|
+
function compareIndexes(currentIndexes = [], previousIndexes = []) {
|
|
1533
|
+
const currentSet = new Set(currentIndexes);
|
|
1534
|
+
const previousSet = new Set(previousIndexes);
|
|
1535
|
+
const indexesToAdd = currentIndexes.filter((idx) => !previousSet.has(idx));
|
|
1536
|
+
const indexesToRemove = previousIndexes.filter((idx) => !currentSet.has(idx));
|
|
1537
|
+
return { indexesToAdd, indexesToRemove };
|
|
1538
|
+
}
|
|
1539
|
+
function compareRules(currentRules, previousRules) {
|
|
1540
|
+
const updates = [];
|
|
1541
|
+
const ruleTypes = [
|
|
1542
|
+
"listRule",
|
|
1543
|
+
"viewRule",
|
|
1544
|
+
"createRule",
|
|
1545
|
+
"updateRule",
|
|
1546
|
+
"deleteRule",
|
|
1547
|
+
"manageRule"
|
|
1548
|
+
];
|
|
1549
|
+
for (const ruleType of ruleTypes) {
|
|
1550
|
+
const currentValue = currentRules?.[ruleType] ?? null;
|
|
1551
|
+
const previousValue = previousRules?.[ruleType] ?? null;
|
|
1552
|
+
if (currentValue !== previousValue) {
|
|
1553
|
+
updates.push({
|
|
1554
|
+
ruleType,
|
|
1555
|
+
oldValue: previousValue,
|
|
1556
|
+
newValue: currentValue
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
return updates;
|
|
1561
|
+
}
|
|
1562
|
+
function comparePermissions(currentPermissions, previousPermissions) {
|
|
1563
|
+
const changes = [];
|
|
1564
|
+
const ruleTypes = ["listRule", "viewRule", "createRule", "updateRule", "deleteRule", "manageRule"];
|
|
1565
|
+
for (const ruleType of ruleTypes) {
|
|
1566
|
+
const currentValue = currentPermissions?.[ruleType] ?? null;
|
|
1567
|
+
const previousValue = previousPermissions?.[ruleType] ?? null;
|
|
1568
|
+
if (currentValue !== previousValue) {
|
|
1569
|
+
changes.push({
|
|
1570
|
+
ruleType,
|
|
1571
|
+
oldValue: previousValue,
|
|
1572
|
+
newValue: currentValue
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
return changes;
|
|
1577
|
+
}
|
|
1578
|
+
function compareCollectionFields(currentCollection, previousCollection, config) {
|
|
1579
|
+
let fieldsToAdd = findNewFields(currentCollection.fields, previousCollection.fields);
|
|
1580
|
+
const fieldsToRemove = findRemovedFields(currentCollection.fields, previousCollection.fields);
|
|
1581
|
+
const fieldsToModify = [];
|
|
1582
|
+
if (currentCollection.name === "users") {
|
|
1583
|
+
const systemFields = getUsersSystemFields(config);
|
|
1584
|
+
fieldsToAdd = fieldsToAdd.filter((field) => !systemFields.has(field.name));
|
|
1585
|
+
}
|
|
1586
|
+
const matchedFields = matchFieldsByName(currentCollection.fields, previousCollection.fields);
|
|
1587
|
+
for (const [currentField, previousField] of matchedFields) {
|
|
1588
|
+
const changes = detectFieldChanges(currentField, previousField);
|
|
1589
|
+
if (changes.length > 0) {
|
|
1590
|
+
fieldsToModify.push({
|
|
1591
|
+
fieldName: currentField.name,
|
|
1592
|
+
currentDefinition: previousField,
|
|
1593
|
+
newDefinition: currentField,
|
|
1594
|
+
changes
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
return { fieldsToAdd, fieldsToRemove, fieldsToModify };
|
|
1599
|
+
}
|
|
1600
|
+
function buildCollectionModification(currentCollection, previousCollection, config) {
|
|
1601
|
+
const { fieldsToAdd, fieldsToRemove, fieldsToModify } = compareCollectionFields(
|
|
1602
|
+
currentCollection,
|
|
1603
|
+
previousCollection,
|
|
1604
|
+
config
|
|
1605
|
+
);
|
|
1606
|
+
const { indexesToAdd, indexesToRemove } = compareIndexes(currentCollection.indexes, previousCollection.indexes);
|
|
1607
|
+
const rulesToUpdate = compareRules(currentCollection.rules, previousCollection.rules);
|
|
1608
|
+
const permissionsToUpdate = comparePermissions(currentCollection.permissions, previousCollection.permissions);
|
|
1609
|
+
return {
|
|
1610
|
+
collection: currentCollection.name,
|
|
1611
|
+
fieldsToAdd,
|
|
1612
|
+
fieldsToRemove,
|
|
1613
|
+
fieldsToModify,
|
|
1614
|
+
indexesToAdd,
|
|
1615
|
+
indexesToRemove,
|
|
1616
|
+
rulesToUpdate,
|
|
1617
|
+
permissionsToUpdate
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
function hasChanges(modification) {
|
|
1621
|
+
return modification.fieldsToAdd.length > 0 || modification.fieldsToRemove.length > 0 || modification.fieldsToModify.length > 0 || modification.indexesToAdd.length > 0 || modification.indexesToRemove.length > 0 || modification.rulesToUpdate.length > 0 || modification.permissionsToUpdate.length > 0;
|
|
1622
|
+
}
|
|
1623
|
+
function aggregateChanges(currentSchema, previousSnapshot, config) {
|
|
1624
|
+
const collectionsToCreate = findNewCollections(currentSchema, previousSnapshot);
|
|
1625
|
+
const collectionsToDelete = findRemovedCollections(currentSchema, previousSnapshot);
|
|
1626
|
+
const filteredCollectionsToCreate = collectionsToCreate.filter(
|
|
1627
|
+
(collection) => !isSystemCollection(collection.name, config)
|
|
1628
|
+
);
|
|
1629
|
+
const filteredCollectionsToDelete = collectionsToDelete.filter(
|
|
1630
|
+
(collection) => !isSystemCollection(collection.name, config)
|
|
1631
|
+
);
|
|
1632
|
+
const collectionsToModify = [];
|
|
1633
|
+
const matchedCollections = matchCollectionsByName(currentSchema, previousSnapshot);
|
|
1634
|
+
for (const [currentCollection, previousCollection] of matchedCollections) {
|
|
1635
|
+
const modification = buildCollectionModification(currentCollection, previousCollection, config);
|
|
1636
|
+
if (hasChanges(modification)) {
|
|
1637
|
+
collectionsToModify.push(modification);
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
return {
|
|
1641
|
+
collectionsToCreate: filteredCollectionsToCreate,
|
|
1642
|
+
collectionsToDelete: filteredCollectionsToDelete,
|
|
1643
|
+
collectionsToModify
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
function categorizeChangesBySeverity(diff, _config) {
|
|
1647
|
+
const destructive = [];
|
|
1648
|
+
const nonDestructive = [];
|
|
1649
|
+
for (const collection of diff.collectionsToDelete) {
|
|
1650
|
+
destructive.push(`Delete collection: ${collection.name}`);
|
|
1651
|
+
}
|
|
1652
|
+
for (const collection of diff.collectionsToCreate) {
|
|
1653
|
+
nonDestructive.push(`Create collection: ${collection.name}`);
|
|
1654
|
+
}
|
|
1655
|
+
for (const modification of diff.collectionsToModify) {
|
|
1656
|
+
const collectionName = modification.collection;
|
|
1657
|
+
for (const field of modification.fieldsToRemove) {
|
|
1658
|
+
destructive.push(`Delete field: ${collectionName}.${field.name}`);
|
|
1659
|
+
}
|
|
1660
|
+
for (const field of modification.fieldsToAdd) {
|
|
1661
|
+
nonDestructive.push(`Add field: ${collectionName}.${field.name}`);
|
|
1662
|
+
}
|
|
1663
|
+
for (const fieldMod of modification.fieldsToModify) {
|
|
1664
|
+
const hasTypeChange = fieldMod.changes.some((c) => c.property === "type");
|
|
1665
|
+
const hasRequiredChange = fieldMod.changes.some((c) => c.property === "required" && c.newValue === true);
|
|
1666
|
+
if (hasTypeChange) {
|
|
1667
|
+
destructive.push(
|
|
1668
|
+
`Change field type: ${collectionName}.${fieldMod.fieldName} (${fieldMod.changes.find((c) => c.property === "type")?.oldValue} \u2192 ${fieldMod.changes.find((c) => c.property === "type")?.newValue})`
|
|
1669
|
+
);
|
|
1670
|
+
} else if (hasRequiredChange) {
|
|
1671
|
+
destructive.push(`Make field required: ${collectionName}.${fieldMod.fieldName}`);
|
|
1672
|
+
} else {
|
|
1673
|
+
nonDestructive.push(`Modify field: ${collectionName}.${fieldMod.fieldName}`);
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
for (const _index of modification.indexesToAdd) {
|
|
1677
|
+
nonDestructive.push(`Add index: ${collectionName}`);
|
|
1678
|
+
}
|
|
1679
|
+
for (const _index of modification.indexesToRemove) {
|
|
1680
|
+
nonDestructive.push(`Remove index: ${collectionName}`);
|
|
1681
|
+
}
|
|
1682
|
+
for (const rule of modification.rulesToUpdate) {
|
|
1683
|
+
nonDestructive.push(`Update rule: ${collectionName}.${rule.ruleType}`);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
return { destructive, nonDestructive };
|
|
1687
|
+
}
|
|
1688
|
+
function compare(currentSchema, previousSnapshot, config) {
|
|
1689
|
+
return aggregateChanges(currentSchema, previousSnapshot, config);
|
|
1690
|
+
}
|
|
1691
|
+
var DEFAULT_TEMPLATE = `/// <reference path="{{TYPES_PATH}}" />
|
|
1692
|
+
migrate((app) => {
|
|
1693
|
+
{{UP_CODE}}
|
|
1694
|
+
return true;
|
|
1695
|
+
}, (app) => {
|
|
1696
|
+
{{DOWN_CODE}}
|
|
1697
|
+
return true;
|
|
1698
|
+
});
|
|
1699
|
+
`;
|
|
1700
|
+
var DEFAULT_CONFIG3 = {
|
|
1701
|
+
workspaceRoot: process.cwd(),
|
|
1702
|
+
timestampGenerator: () => Math.floor(Date.now() / 1e3).toString(),
|
|
1703
|
+
template: DEFAULT_TEMPLATE,
|
|
1704
|
+
includeTypeReference: true,
|
|
1705
|
+
typesPath: "../pb_data/types.d.ts"
|
|
1706
|
+
};
|
|
1707
|
+
function mergeConfig3(config) {
|
|
1708
|
+
return {
|
|
1709
|
+
...DEFAULT_CONFIG3,
|
|
1710
|
+
...config
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
function resolveMigrationDir(config) {
|
|
1714
|
+
const workspaceRoot = config.workspaceRoot || process.cwd();
|
|
1715
|
+
if (path4__namespace.isAbsolute(config.migrationDir)) {
|
|
1716
|
+
return config.migrationDir;
|
|
1717
|
+
}
|
|
1718
|
+
return path4__namespace.join(workspaceRoot, config.migrationDir);
|
|
1719
|
+
}
|
|
1720
|
+
function generateTimestamp(config) {
|
|
1721
|
+
if (config?.timestampGenerator) {
|
|
1722
|
+
return config.timestampGenerator();
|
|
1723
|
+
}
|
|
1724
|
+
return Math.floor(Date.now() / 1e3).toString();
|
|
1725
|
+
}
|
|
1726
|
+
function generateMigrationDescription(diff) {
|
|
1727
|
+
const parts = [];
|
|
1728
|
+
if (diff.collectionsToCreate.length > 0) {
|
|
1729
|
+
if (diff.collectionsToCreate.length === 1) {
|
|
1730
|
+
parts.push(`created_${diff.collectionsToCreate[0].name}`);
|
|
1731
|
+
} else {
|
|
1732
|
+
parts.push(`created_${diff.collectionsToCreate.length}_collections`);
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
if (diff.collectionsToDelete.length > 0) {
|
|
1736
|
+
if (diff.collectionsToDelete.length === 1) {
|
|
1737
|
+
parts.push(`deleted_${diff.collectionsToDelete[0].name}`);
|
|
1738
|
+
} else {
|
|
1739
|
+
parts.push(`deleted_${diff.collectionsToDelete.length}_collections`);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
if (diff.collectionsToModify.length > 0) {
|
|
1743
|
+
if (diff.collectionsToModify.length === 1) {
|
|
1744
|
+
parts.push(`updated_${diff.collectionsToModify[0].collection}`);
|
|
1745
|
+
} else {
|
|
1746
|
+
parts.push(`updated_${diff.collectionsToModify.length}_collections`);
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
if (parts.length === 0) {
|
|
1750
|
+
return "no_changes";
|
|
1751
|
+
}
|
|
1752
|
+
let description = parts.join("_");
|
|
1753
|
+
if (description.length > 80) {
|
|
1754
|
+
description = description.substring(0, 77) + "...";
|
|
1755
|
+
}
|
|
1756
|
+
return description;
|
|
1757
|
+
}
|
|
1758
|
+
function generateMigrationFilename(diff, config) {
|
|
1759
|
+
const timestamp = generateTimestamp(config);
|
|
1760
|
+
const description = generateMigrationDescription(diff);
|
|
1761
|
+
return `${timestamp}_${description}.js`;
|
|
1762
|
+
}
|
|
1763
|
+
function createMigrationFileStructure(upCode, downCode, config) {
|
|
1764
|
+
const mergedConfig = config ? mergeConfig3(config) : DEFAULT_CONFIG3;
|
|
1765
|
+
let template = mergedConfig.template;
|
|
1766
|
+
template = template.replace("{{TYPES_PATH}}", mergedConfig.typesPath);
|
|
1767
|
+
template = template.replace("{{UP_CODE}}", upCode);
|
|
1768
|
+
template = template.replace("{{DOWN_CODE}}", downCode);
|
|
1769
|
+
if (!mergedConfig.includeTypeReference) {
|
|
1770
|
+
template = template.replace(/\/\/\/ <reference path="[^"]*" \/>\n?/, "");
|
|
1771
|
+
}
|
|
1772
|
+
return template;
|
|
1773
|
+
}
|
|
1774
|
+
function writeMigrationFile(migrationDir, filename, content) {
|
|
1775
|
+
try {
|
|
1776
|
+
if (!fs4__namespace.existsSync(migrationDir)) {
|
|
1777
|
+
try {
|
|
1778
|
+
fs4__namespace.mkdirSync(migrationDir, { recursive: true });
|
|
1779
|
+
} catch (error) {
|
|
1780
|
+
const fsError = error;
|
|
1781
|
+
if (fsError.code === "EACCES" || fsError.code === "EPERM") {
|
|
1782
|
+
throw new FileSystemError(
|
|
1783
|
+
`Permission denied creating migration directory. Check directory permissions.`,
|
|
1784
|
+
migrationDir,
|
|
1785
|
+
"create",
|
|
1786
|
+
fsError.code,
|
|
1787
|
+
error
|
|
1788
|
+
);
|
|
1789
|
+
}
|
|
1790
|
+
throw new FileSystemError(
|
|
1791
|
+
`Failed to create migration directory: ${fsError.message}`,
|
|
1792
|
+
migrationDir,
|
|
1793
|
+
"create",
|
|
1794
|
+
fsError.code,
|
|
1795
|
+
error
|
|
1796
|
+
);
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
const filePath = path4__namespace.join(migrationDir, filename);
|
|
1800
|
+
fs4__namespace.writeFileSync(filePath, content, "utf-8");
|
|
1801
|
+
return filePath;
|
|
1802
|
+
} catch (error) {
|
|
1803
|
+
if (error instanceof FileSystemError) {
|
|
1804
|
+
throw error;
|
|
1805
|
+
}
|
|
1806
|
+
const fsError = error;
|
|
1807
|
+
const filePath = path4__namespace.join(migrationDir, filename);
|
|
1808
|
+
if (fsError.code === "EACCES" || fsError.code === "EPERM") {
|
|
1809
|
+
throw new FileSystemError(
|
|
1810
|
+
`Permission denied writing migration file. Check file and directory permissions.`,
|
|
1811
|
+
filePath,
|
|
1812
|
+
"write",
|
|
1813
|
+
fsError.code,
|
|
1814
|
+
error
|
|
1815
|
+
);
|
|
1816
|
+
} else if (fsError.code === "ENOSPC") {
|
|
1817
|
+
throw new FileSystemError(
|
|
1818
|
+
`No space left on device when writing migration file.`,
|
|
1819
|
+
filePath,
|
|
1820
|
+
"write",
|
|
1821
|
+
fsError.code,
|
|
1822
|
+
error
|
|
1823
|
+
);
|
|
1824
|
+
}
|
|
1825
|
+
throw new MigrationGenerationError(`Failed to write migration file: ${fsError.message}`, filePath, error);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
function formatValue(value) {
|
|
1829
|
+
if (value === null || value === void 0) {
|
|
1830
|
+
return "null";
|
|
1831
|
+
}
|
|
1832
|
+
if (typeof value === "string") {
|
|
1833
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
|
|
1834
|
+
}
|
|
1835
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
1836
|
+
return String(value);
|
|
1837
|
+
}
|
|
1838
|
+
if (Array.isArray(value)) {
|
|
1839
|
+
const items = value.map((v) => formatValue(v)).join(", ");
|
|
1840
|
+
return `[${items}]`;
|
|
1841
|
+
}
|
|
1842
|
+
if (typeof value === "object") {
|
|
1843
|
+
const entries = Object.entries(value).map(([k, v]) => `${k}: ${formatValue(v)}`).join(", ");
|
|
1844
|
+
return `{ ${entries} }`;
|
|
1845
|
+
}
|
|
1846
|
+
return String(value);
|
|
1847
|
+
}
|
|
1848
|
+
function generateFieldDefinitionObject(field) {
|
|
1849
|
+
const parts = [];
|
|
1850
|
+
parts.push(` name: "${field.name}"`);
|
|
1851
|
+
parts.push(` type: "${field.type}"`);
|
|
1852
|
+
parts.push(` required: ${field.required}`);
|
|
1853
|
+
if (field.unique !== void 0) {
|
|
1854
|
+
parts.push(` unique: ${field.unique}`);
|
|
1855
|
+
}
|
|
1856
|
+
if (field.options && Object.keys(field.options).length > 0) {
|
|
1857
|
+
for (const [key, value] of Object.entries(field.options)) {
|
|
1858
|
+
parts.push(` ${key}: ${formatValue(value)}`);
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
if (field.relation) {
|
|
1862
|
+
const collectionIdPlaceholder = field.relation.collection === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
|
|
1863
|
+
parts.push(` collectionId: ${collectionIdPlaceholder}`);
|
|
1864
|
+
if (field.relation.maxSelect !== void 0) {
|
|
1865
|
+
parts.push(` maxSelect: ${field.relation.maxSelect}`);
|
|
1866
|
+
}
|
|
1867
|
+
if (field.relation.minSelect !== void 0) {
|
|
1868
|
+
parts.push(` minSelect: ${field.relation.minSelect}`);
|
|
1869
|
+
}
|
|
1870
|
+
if (field.relation.cascadeDelete !== void 0) {
|
|
1871
|
+
parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
return ` {
|
|
1875
|
+
${parts.join(",\n")},
|
|
1876
|
+
}`;
|
|
1877
|
+
}
|
|
1878
|
+
function generateFieldsArray(fields) {
|
|
1879
|
+
if (fields.length === 0) {
|
|
1880
|
+
return "[]";
|
|
1881
|
+
}
|
|
1882
|
+
const fieldObjects = fields.map((field) => generateFieldDefinitionObject(field));
|
|
1883
|
+
return `[
|
|
1884
|
+
${fieldObjects.join(",\n")},
|
|
1885
|
+
]`;
|
|
1886
|
+
}
|
|
1887
|
+
function generateCollectionRules(rules) {
|
|
1888
|
+
if (!rules) {
|
|
1889
|
+
return "";
|
|
1890
|
+
}
|
|
1891
|
+
const parts = [];
|
|
1892
|
+
if (rules.listRule !== void 0) {
|
|
1893
|
+
parts.push(`listRule: ${formatValue(rules.listRule)}`);
|
|
1894
|
+
}
|
|
1895
|
+
if (rules.viewRule !== void 0) {
|
|
1896
|
+
parts.push(`viewRule: ${formatValue(rules.viewRule)}`);
|
|
1897
|
+
}
|
|
1898
|
+
if (rules.createRule !== void 0) {
|
|
1899
|
+
parts.push(`createRule: ${formatValue(rules.createRule)}`);
|
|
1900
|
+
}
|
|
1901
|
+
if (rules.updateRule !== void 0) {
|
|
1902
|
+
parts.push(`updateRule: ${formatValue(rules.updateRule)}`);
|
|
1903
|
+
}
|
|
1904
|
+
if (rules.deleteRule !== void 0) {
|
|
1905
|
+
parts.push(`deleteRule: ${formatValue(rules.deleteRule)}`);
|
|
1906
|
+
}
|
|
1907
|
+
if (rules.manageRule !== void 0) {
|
|
1908
|
+
parts.push(`manageRule: ${formatValue(rules.manageRule)}`);
|
|
1909
|
+
}
|
|
1910
|
+
return parts.join(",\n ");
|
|
1911
|
+
}
|
|
1912
|
+
function generateCollectionPermissions(permissions) {
|
|
1913
|
+
if (!permissions) {
|
|
1914
|
+
return "";
|
|
1915
|
+
}
|
|
1916
|
+
const parts = [];
|
|
1917
|
+
if (permissions.listRule !== void 0) {
|
|
1918
|
+
parts.push(`listRule: ${formatValue(permissions.listRule)}`);
|
|
1919
|
+
}
|
|
1920
|
+
if (permissions.viewRule !== void 0) {
|
|
1921
|
+
parts.push(`viewRule: ${formatValue(permissions.viewRule)}`);
|
|
1922
|
+
}
|
|
1923
|
+
if (permissions.createRule !== void 0) {
|
|
1924
|
+
parts.push(`createRule: ${formatValue(permissions.createRule)}`);
|
|
1925
|
+
}
|
|
1926
|
+
if (permissions.updateRule !== void 0) {
|
|
1927
|
+
parts.push(`updateRule: ${formatValue(permissions.updateRule)}`);
|
|
1928
|
+
}
|
|
1929
|
+
if (permissions.deleteRule !== void 0) {
|
|
1930
|
+
parts.push(`deleteRule: ${formatValue(permissions.deleteRule)}`);
|
|
1931
|
+
}
|
|
1932
|
+
if (permissions.manageRule !== void 0) {
|
|
1933
|
+
parts.push(`manageRule: ${formatValue(permissions.manageRule)}`);
|
|
1934
|
+
}
|
|
1935
|
+
return parts.join(",\n ");
|
|
1936
|
+
}
|
|
1937
|
+
function generateIndexesArray(indexes) {
|
|
1938
|
+
if (!indexes || indexes.length === 0) {
|
|
1939
|
+
return "[]";
|
|
1940
|
+
}
|
|
1941
|
+
const indexStrings = indexes.map((idx) => `"${idx}"`);
|
|
1942
|
+
return `[
|
|
1943
|
+
${indexStrings.join(",\n ")},
|
|
1944
|
+
]`;
|
|
1945
|
+
}
|
|
1946
|
+
function generateCollectionCreation(collection, varName = "collection") {
|
|
1947
|
+
const lines = [];
|
|
1948
|
+
lines.push(` const ${varName} = new Collection({`);
|
|
1949
|
+
lines.push(` name: "${collection.name}",`);
|
|
1950
|
+
lines.push(` type: "${collection.type}",`);
|
|
1951
|
+
const permissionsCode = generateCollectionPermissions(collection.permissions);
|
|
1952
|
+
const rulesCode = generateCollectionRules(collection.rules);
|
|
1953
|
+
if (permissionsCode) {
|
|
1954
|
+
lines.push(` ${permissionsCode},`);
|
|
1955
|
+
} else if (rulesCode) {
|
|
1956
|
+
lines.push(` ${rulesCode},`);
|
|
1957
|
+
}
|
|
1958
|
+
lines.push(` fields: ${generateFieldsArray(collection.fields)},`);
|
|
1959
|
+
lines.push(` indexes: ${generateIndexesArray(collection.indexes)},`);
|
|
1960
|
+
lines.push(` });`);
|
|
1961
|
+
lines.push(``);
|
|
1962
|
+
lines.push(` app.save(${varName});`);
|
|
1963
|
+
return lines.join("\n");
|
|
1964
|
+
}
|
|
1965
|
+
function getFieldConstructorName(fieldType) {
|
|
1966
|
+
const constructorMap = {
|
|
1967
|
+
text: "TextField",
|
|
1968
|
+
email: "EmailField",
|
|
1969
|
+
url: "URLField",
|
|
1970
|
+
number: "NumberField",
|
|
1971
|
+
bool: "BoolField",
|
|
1972
|
+
date: "DateField",
|
|
1973
|
+
select: "SelectField",
|
|
1974
|
+
relation: "RelationField",
|
|
1975
|
+
file: "FileField",
|
|
1976
|
+
json: "JSONField"
|
|
1977
|
+
};
|
|
1978
|
+
return constructorMap[fieldType] || "TextField";
|
|
1979
|
+
}
|
|
1980
|
+
function generateFieldConstructorOptions(field) {
|
|
1981
|
+
const parts = [];
|
|
1982
|
+
parts.push(` name: "${field.name}"`);
|
|
1983
|
+
parts.push(` required: ${field.required}`);
|
|
1984
|
+
if (field.unique !== void 0) {
|
|
1985
|
+
parts.push(` unique: ${field.unique}`);
|
|
1986
|
+
}
|
|
1987
|
+
if (field.options && Object.keys(field.options).length > 0) {
|
|
1988
|
+
for (const [key, value] of Object.entries(field.options)) {
|
|
1989
|
+
parts.push(` ${key}: ${formatValue(value)}`);
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
if (field.relation && field.type === "relation") {
|
|
1993
|
+
const collectionIdPlaceholder = field.relation.collection === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
|
|
1994
|
+
parts.push(` collectionId: ${collectionIdPlaceholder}`);
|
|
1995
|
+
if (field.relation.maxSelect !== void 0) {
|
|
1996
|
+
parts.push(` maxSelect: ${field.relation.maxSelect}`);
|
|
1997
|
+
}
|
|
1998
|
+
if (field.relation.minSelect !== void 0) {
|
|
1999
|
+
parts.push(` minSelect: ${field.relation.minSelect}`);
|
|
2000
|
+
}
|
|
2001
|
+
if (field.relation.cascadeDelete !== void 0) {
|
|
2002
|
+
parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
return parts.join(",\n");
|
|
2006
|
+
}
|
|
2007
|
+
function generateFieldAddition(collectionName, field, varName) {
|
|
2008
|
+
const lines = [];
|
|
2009
|
+
const constructorName = getFieldConstructorName(field.type);
|
|
2010
|
+
const collectionVar = varName || `collection_${collectionName}_${field.name}`;
|
|
2011
|
+
lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2012
|
+
lines.push(``);
|
|
2013
|
+
lines.push(` ${collectionVar}.fields.add(new ${constructorName}({`);
|
|
2014
|
+
lines.push(generateFieldConstructorOptions(field));
|
|
2015
|
+
lines.push(` }));`);
|
|
2016
|
+
lines.push(``);
|
|
2017
|
+
lines.push(` app.save(${collectionVar});`);
|
|
2018
|
+
return lines.join("\n");
|
|
2019
|
+
}
|
|
2020
|
+
function generateFieldModification(collectionName, modification, varName) {
|
|
2021
|
+
const lines = [];
|
|
2022
|
+
const collectionVar = varName || `collection_${collectionName}_${modification.fieldName}`;
|
|
2023
|
+
const fieldVar = `${collectionVar}_field`;
|
|
2024
|
+
lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2025
|
+
lines.push(` const ${fieldVar} = ${collectionVar}.fields.getByName("${modification.fieldName}");`);
|
|
2026
|
+
lines.push(``);
|
|
2027
|
+
for (const change of modification.changes) {
|
|
2028
|
+
if (change.property.startsWith("options.")) {
|
|
2029
|
+
const optionKey = change.property.replace("options.", "");
|
|
2030
|
+
lines.push(` ${fieldVar}.${optionKey} = ${formatValue(change.newValue)};`);
|
|
2031
|
+
} else if (change.property.startsWith("relation.")) {
|
|
2032
|
+
const relationKey = change.property.replace("relation.", "");
|
|
2033
|
+
if (relationKey === "collection") {
|
|
2034
|
+
const collectionIdValue = change.newValue === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${change.newValue}").id`;
|
|
2035
|
+
lines.push(` ${fieldVar}.collectionId = ${collectionIdValue};`);
|
|
2036
|
+
} else {
|
|
2037
|
+
lines.push(` ${fieldVar}.${relationKey} = ${formatValue(change.newValue)};`);
|
|
2038
|
+
}
|
|
2039
|
+
} else {
|
|
2040
|
+
lines.push(` ${fieldVar}.${change.property} = ${formatValue(change.newValue)};`);
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
lines.push(``);
|
|
2044
|
+
lines.push(` app.save(${collectionVar});`);
|
|
2045
|
+
return lines.join("\n");
|
|
2046
|
+
}
|
|
2047
|
+
function generateFieldDeletion(collectionName, fieldName, varName) {
|
|
2048
|
+
const lines = [];
|
|
2049
|
+
const collectionVar = varName || `collection_${collectionName}_${fieldName}`;
|
|
2050
|
+
const fieldVar = `${collectionVar}_field`;
|
|
2051
|
+
lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2052
|
+
lines.push(` const ${fieldVar} = ${collectionVar}.fields.getByName("${fieldName}");`);
|
|
2053
|
+
lines.push(``);
|
|
2054
|
+
lines.push(` ${collectionVar}.fields.remove(${fieldVar}.id);`);
|
|
2055
|
+
lines.push(``);
|
|
2056
|
+
lines.push(` app.save(${collectionVar});`);
|
|
2057
|
+
return lines.join("\n");
|
|
2058
|
+
}
|
|
2059
|
+
function generateIndexAddition(collectionName, index, varName) {
|
|
2060
|
+
const lines = [];
|
|
2061
|
+
const collectionVar = varName || `collection_${collectionName}_idx`;
|
|
2062
|
+
lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2063
|
+
lines.push(` ${collectionVar}.indexes.push("${index}");`);
|
|
2064
|
+
lines.push(` app.save(${collectionVar});`);
|
|
2065
|
+
return lines.join("\n");
|
|
2066
|
+
}
|
|
2067
|
+
function generateIndexRemoval(collectionName, index, varName) {
|
|
2068
|
+
const lines = [];
|
|
2069
|
+
const collectionVar = varName || `collection_${collectionName}_idx`;
|
|
2070
|
+
const indexVar = `${collectionVar}_indexToRemove`;
|
|
2071
|
+
lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2072
|
+
lines.push(` const ${indexVar} = ${collectionVar}.indexes.findIndex(idx => idx === "${index}");`);
|
|
2073
|
+
lines.push(` if (${indexVar} !== -1) {`);
|
|
2074
|
+
lines.push(` ${collectionVar}.indexes.splice(${indexVar}, 1);`);
|
|
2075
|
+
lines.push(` }`);
|
|
2076
|
+
lines.push(` app.save(${collectionVar});`);
|
|
2077
|
+
return lines.join("\n");
|
|
2078
|
+
}
|
|
2079
|
+
function generateRuleUpdate(collectionName, ruleType, newValue, varName) {
|
|
2080
|
+
const lines = [];
|
|
2081
|
+
const collectionVar = varName || `collection_${collectionName}_${ruleType}`;
|
|
2082
|
+
lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2083
|
+
lines.push(` ${collectionVar}.${ruleType} = ${formatValue(newValue)};`);
|
|
2084
|
+
lines.push(` app.save(${collectionVar});`);
|
|
2085
|
+
return lines.join("\n");
|
|
2086
|
+
}
|
|
2087
|
+
function generatePermissionUpdate(collectionName, ruleType, newValue, varName) {
|
|
2088
|
+
const lines = [];
|
|
2089
|
+
const collectionVar = varName || `collection_${collectionName}_${ruleType}`;
|
|
2090
|
+
lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2091
|
+
lines.push(` ${collectionVar}.${ruleType} = ${formatValue(newValue)};`);
|
|
2092
|
+
lines.push(` app.save(${collectionVar});`);
|
|
2093
|
+
return lines.join("\n");
|
|
2094
|
+
}
|
|
2095
|
+
function generateCollectionDeletion(collectionName, varName = "collection") {
|
|
2096
|
+
const lines = [];
|
|
2097
|
+
lines.push(` const ${varName} = app.findCollectionByNameOrId("${collectionName}");`);
|
|
2098
|
+
lines.push(` app.delete(${varName});`);
|
|
2099
|
+
return lines.join("\n");
|
|
2100
|
+
}
|
|
2101
|
+
function generateUpMigration(diff) {
|
|
2102
|
+
const lines = [];
|
|
2103
|
+
lines.push(` // UP MIGRATION`);
|
|
2104
|
+
lines.push(``);
|
|
2105
|
+
if (diff.collectionsToCreate.length > 0) {
|
|
2106
|
+
lines.push(` // Create new collections`);
|
|
2107
|
+
for (let i = 0; i < diff.collectionsToCreate.length; i++) {
|
|
2108
|
+
const collection = diff.collectionsToCreate[i];
|
|
2109
|
+
const varName = `collection_${collection.name}_create`;
|
|
2110
|
+
lines.push(generateCollectionCreation(collection, varName));
|
|
2111
|
+
lines.push(``);
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
if (diff.collectionsToModify.length > 0) {
|
|
2115
|
+
lines.push(` // Modify existing collections`);
|
|
2116
|
+
for (const modification of diff.collectionsToModify) {
|
|
2117
|
+
const collectionName = modification.collection;
|
|
2118
|
+
if (modification.fieldsToAdd.length > 0) {
|
|
2119
|
+
lines.push(` // Add fields to ${collectionName}`);
|
|
2120
|
+
for (const field of modification.fieldsToAdd) {
|
|
2121
|
+
const varName = `collection_${collectionName}_add_${field.name}`;
|
|
2122
|
+
lines.push(generateFieldAddition(collectionName, field, varName));
|
|
2123
|
+
lines.push(``);
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
if (modification.fieldsToModify.length > 0) {
|
|
2127
|
+
lines.push(` // Modify fields in ${collectionName}`);
|
|
2128
|
+
for (const fieldMod of modification.fieldsToModify) {
|
|
2129
|
+
const varName = `collection_${collectionName}_modify_${fieldMod.fieldName}`;
|
|
2130
|
+
lines.push(generateFieldModification(collectionName, fieldMod, varName));
|
|
2131
|
+
lines.push(``);
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
if (modification.fieldsToRemove.length > 0) {
|
|
2135
|
+
lines.push(` // Remove fields from ${collectionName}`);
|
|
2136
|
+
for (const field of modification.fieldsToRemove) {
|
|
2137
|
+
const varName = `collection_${collectionName}_remove_${field.name}`;
|
|
2138
|
+
lines.push(generateFieldDeletion(collectionName, field.name, varName));
|
|
2139
|
+
lines.push(``);
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
if (modification.indexesToAdd.length > 0) {
|
|
2143
|
+
lines.push(` // Add indexes to ${collectionName}`);
|
|
2144
|
+
for (let i = 0; i < modification.indexesToAdd.length; i++) {
|
|
2145
|
+
const index = modification.indexesToAdd[i];
|
|
2146
|
+
const varName = `collection_${collectionName}_addidx_${i}`;
|
|
2147
|
+
lines.push(generateIndexAddition(collectionName, index, varName));
|
|
2148
|
+
lines.push(``);
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
if (modification.indexesToRemove.length > 0) {
|
|
2152
|
+
lines.push(` // Remove indexes from ${collectionName}`);
|
|
2153
|
+
for (let i = 0; i < modification.indexesToRemove.length; i++) {
|
|
2154
|
+
const index = modification.indexesToRemove[i];
|
|
2155
|
+
const varName = `collection_${collectionName}_rmidx_${i}`;
|
|
2156
|
+
lines.push(generateIndexRemoval(collectionName, index, varName));
|
|
2157
|
+
lines.push(``);
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
|
|
2161
|
+
lines.push(` // Update permissions for ${collectionName}`);
|
|
2162
|
+
for (const permission of modification.permissionsToUpdate) {
|
|
2163
|
+
const varName = `collection_${collectionName}_perm_${permission.ruleType}`;
|
|
2164
|
+
lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.newValue, varName));
|
|
2165
|
+
lines.push(``);
|
|
2166
|
+
}
|
|
2167
|
+
} else if (modification.rulesToUpdate.length > 0) {
|
|
2168
|
+
lines.push(` // Update rules for ${collectionName}`);
|
|
2169
|
+
for (const rule of modification.rulesToUpdate) {
|
|
2170
|
+
const varName = `collection_${collectionName}_rule_${rule.ruleType}`;
|
|
2171
|
+
lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.newValue, varName));
|
|
2172
|
+
lines.push(``);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
if (diff.collectionsToDelete.length > 0) {
|
|
2178
|
+
lines.push(` // Delete collections`);
|
|
2179
|
+
for (let i = 0; i < diff.collectionsToDelete.length; i++) {
|
|
2180
|
+
const collection = diff.collectionsToDelete[i];
|
|
2181
|
+
const varName = `collection_${collection.name}_delete`;
|
|
2182
|
+
lines.push(generateCollectionDeletion(collection.name, varName));
|
|
2183
|
+
lines.push(``);
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
if (lines.length === 2) {
|
|
2187
|
+
lines.push(` // No changes detected`);
|
|
2188
|
+
lines.push(``);
|
|
2189
|
+
}
|
|
2190
|
+
return lines.join("\n");
|
|
2191
|
+
}
|
|
2192
|
+
function generateDownMigration(diff) {
|
|
2193
|
+
const lines = [];
|
|
2194
|
+
lines.push(` // DOWN MIGRATION (ROLLBACK)`);
|
|
2195
|
+
lines.push(``);
|
|
2196
|
+
if (diff.collectionsToDelete.length > 0) {
|
|
2197
|
+
lines.push(` // Recreate deleted collections`);
|
|
2198
|
+
for (let i = 0; i < diff.collectionsToDelete.length; i++) {
|
|
2199
|
+
const collection = diff.collectionsToDelete[i];
|
|
2200
|
+
const varName = `collection_${collection.name}_recreate`;
|
|
2201
|
+
lines.push(generateCollectionCreation(collection, varName));
|
|
2202
|
+
lines.push(``);
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
if (diff.collectionsToModify.length > 0) {
|
|
2206
|
+
lines.push(` // Revert modifications`);
|
|
2207
|
+
for (const modification of diff.collectionsToModify) {
|
|
2208
|
+
const collectionName = modification.collection;
|
|
2209
|
+
if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
|
|
2210
|
+
lines.push(` // Revert permissions for ${collectionName}`);
|
|
2211
|
+
for (const permission of modification.permissionsToUpdate) {
|
|
2212
|
+
const varName = `collection_${collectionName}_revert_perm_${permission.ruleType}`;
|
|
2213
|
+
lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.oldValue, varName));
|
|
2214
|
+
lines.push(``);
|
|
2215
|
+
}
|
|
2216
|
+
} else if (modification.rulesToUpdate.length > 0) {
|
|
2217
|
+
lines.push(` // Revert rules for ${collectionName}`);
|
|
2218
|
+
for (const rule of modification.rulesToUpdate) {
|
|
2219
|
+
const varName = `collection_${collectionName}_revert_rule_${rule.ruleType}`;
|
|
2220
|
+
lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.oldValue, varName));
|
|
2221
|
+
lines.push(``);
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
if (modification.indexesToRemove.length > 0) {
|
|
2225
|
+
lines.push(` // Restore indexes to ${collectionName}`);
|
|
2226
|
+
for (let i = 0; i < modification.indexesToRemove.length; i++) {
|
|
2227
|
+
const index = modification.indexesToRemove[i];
|
|
2228
|
+
const varName = `collection_${collectionName}_restore_idx_${i}`;
|
|
2229
|
+
lines.push(generateIndexAddition(collectionName, index, varName));
|
|
2230
|
+
lines.push(``);
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
if (modification.indexesToAdd.length > 0) {
|
|
2234
|
+
lines.push(` // Remove indexes from ${collectionName}`);
|
|
2235
|
+
for (let i = 0; i < modification.indexesToAdd.length; i++) {
|
|
2236
|
+
const index = modification.indexesToAdd[i];
|
|
2237
|
+
const varName = `collection_${collectionName}_revert_idx_${i}`;
|
|
2238
|
+
lines.push(generateIndexRemoval(collectionName, index, varName));
|
|
2239
|
+
lines.push(``);
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
if (modification.fieldsToRemove.length > 0) {
|
|
2243
|
+
lines.push(` // Restore fields to ${collectionName}`);
|
|
2244
|
+
for (const field of modification.fieldsToRemove) {
|
|
2245
|
+
const varName = `collection_${collectionName}_restore_${field.name}`;
|
|
2246
|
+
lines.push(generateFieldAddition(collectionName, field, varName));
|
|
2247
|
+
lines.push(``);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
if (modification.fieldsToModify.length > 0) {
|
|
2251
|
+
lines.push(` // Revert field modifications in ${collectionName}`);
|
|
2252
|
+
for (const fieldMod of modification.fieldsToModify) {
|
|
2253
|
+
const reverseChanges = fieldMod.changes.map((change) => ({
|
|
2254
|
+
property: change.property,
|
|
2255
|
+
oldValue: change.newValue,
|
|
2256
|
+
newValue: change.oldValue
|
|
2257
|
+
}));
|
|
2258
|
+
const reverseMod = {
|
|
2259
|
+
fieldName: fieldMod.fieldName,
|
|
2260
|
+
currentDefinition: fieldMod.newDefinition,
|
|
2261
|
+
newDefinition: fieldMod.currentDefinition,
|
|
2262
|
+
changes: reverseChanges
|
|
2263
|
+
};
|
|
2264
|
+
const varName = `collection_${collectionName}_revert_${fieldMod.fieldName}`;
|
|
2265
|
+
lines.push(generateFieldModification(collectionName, reverseMod, varName));
|
|
2266
|
+
lines.push(``);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
if (modification.fieldsToAdd.length > 0) {
|
|
2270
|
+
lines.push(` // Remove added fields from ${collectionName}`);
|
|
2271
|
+
for (const field of modification.fieldsToAdd) {
|
|
2272
|
+
const varName = `collection_${collectionName}_revert_add_${field.name}`;
|
|
2273
|
+
lines.push(generateFieldDeletion(collectionName, field.name, varName));
|
|
2274
|
+
lines.push(``);
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
if (diff.collectionsToCreate.length > 0) {
|
|
2280
|
+
lines.push(` // Delete created collections`);
|
|
2281
|
+
for (let i = 0; i < diff.collectionsToCreate.length; i++) {
|
|
2282
|
+
const collection = diff.collectionsToCreate[i];
|
|
2283
|
+
const varName = `collection_${collection.name}_rollback`;
|
|
2284
|
+
lines.push(generateCollectionDeletion(collection.name, varName));
|
|
2285
|
+
lines.push(``);
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
if (lines.length === 2) {
|
|
2289
|
+
lines.push(` // No changes to revert`);
|
|
2290
|
+
lines.push(``);
|
|
2291
|
+
}
|
|
2292
|
+
return lines.join("\n");
|
|
2293
|
+
}
|
|
2294
|
+
function generate(diff, config) {
|
|
2295
|
+
const normalizedConfig = typeof config === "string" ? { migrationDir: config } : config;
|
|
2296
|
+
try {
|
|
2297
|
+
const migrationDir = resolveMigrationDir(normalizedConfig);
|
|
2298
|
+
const upCode = generateUpMigration(diff);
|
|
2299
|
+
const downCode = generateDownMigration(diff);
|
|
2300
|
+
const content = createMigrationFileStructure(upCode, downCode, normalizedConfig);
|
|
2301
|
+
const filename = generateMigrationFilename(diff, normalizedConfig);
|
|
2302
|
+
const filePath = writeMigrationFile(migrationDir, filename, content);
|
|
2303
|
+
return filePath;
|
|
2304
|
+
} catch (error) {
|
|
2305
|
+
if (error instanceof MigrationGenerationError || error instanceof FileSystemError) {
|
|
2306
|
+
throw error;
|
|
2307
|
+
}
|
|
2308
|
+
throw new MigrationGenerationError(
|
|
2309
|
+
`Failed to generate migration: ${error instanceof Error ? error.message : String(error)}`,
|
|
2310
|
+
normalizedConfig.migrationDir,
|
|
2311
|
+
error
|
|
2312
|
+
);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
var SNAPSHOT_VERSION = "1.0.0";
|
|
2316
|
+
({
|
|
2317
|
+
workspaceRoot: process.cwd()});
|
|
2318
|
+
function findLatestSnapshot(migrationsPath) {
|
|
2319
|
+
try {
|
|
2320
|
+
if (!fs4__namespace.existsSync(migrationsPath)) {
|
|
2321
|
+
return null;
|
|
2322
|
+
}
|
|
2323
|
+
const files = fs4__namespace.readdirSync(migrationsPath);
|
|
2324
|
+
const snapshotFiles = files.filter(
|
|
2325
|
+
(file) => file.endsWith("_collections_snapshot.js") || file.endsWith("_snapshot.js")
|
|
2326
|
+
);
|
|
2327
|
+
if (snapshotFiles.length === 0) {
|
|
2328
|
+
return null;
|
|
2329
|
+
}
|
|
2330
|
+
snapshotFiles.sort().reverse();
|
|
2331
|
+
const latestSnapshot = snapshotFiles[0];
|
|
2332
|
+
if (!latestSnapshot) {
|
|
2333
|
+
return null;
|
|
2334
|
+
}
|
|
2335
|
+
return path4__namespace.join(migrationsPath, latestSnapshot);
|
|
2336
|
+
} catch (error) {
|
|
2337
|
+
console.warn(`Error finding latest snapshot: ${error}`);
|
|
2338
|
+
return null;
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
function loadSnapshotIfExists(config = {}) {
|
|
2342
|
+
const migrationsPath = config.migrationsPath;
|
|
2343
|
+
if (!migrationsPath) {
|
|
2344
|
+
return null;
|
|
2345
|
+
}
|
|
2346
|
+
if (fs4__namespace.existsSync(migrationsPath) && fs4__namespace.statSync(migrationsPath).isFile()) {
|
|
2347
|
+
try {
|
|
2348
|
+
const migrationContent = fs4__namespace.readFileSync(migrationsPath, "utf-8");
|
|
2349
|
+
return convertPocketBaseMigration(migrationContent);
|
|
2350
|
+
} catch (error) {
|
|
2351
|
+
console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);
|
|
2352
|
+
return null;
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
const latestSnapshotPath = findLatestSnapshot(migrationsPath);
|
|
2356
|
+
if (latestSnapshotPath) {
|
|
2357
|
+
try {
|
|
2358
|
+
const migrationContent = fs4__namespace.readFileSync(latestSnapshotPath, "utf-8");
|
|
2359
|
+
return convertPocketBaseMigration(migrationContent);
|
|
2360
|
+
} catch (error) {
|
|
2361
|
+
console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);
|
|
2362
|
+
return null;
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
return null;
|
|
2366
|
+
}
|
|
2367
|
+
function convertPocketBaseCollection(pbCollection) {
|
|
2368
|
+
const fields = [];
|
|
2369
|
+
const systemFieldNames = ["id", "created", "updated", "collectionId", "collectionName", "expand"];
|
|
2370
|
+
const authSystemFieldNames = ["email", "emailVisibility", "verified", "password", "tokenKey"];
|
|
2371
|
+
if (pbCollection.fields && Array.isArray(pbCollection.fields)) {
|
|
2372
|
+
for (const pbField of pbCollection.fields) {
|
|
2373
|
+
if (pbField.system || systemFieldNames.includes(pbField.name)) {
|
|
2374
|
+
continue;
|
|
2375
|
+
}
|
|
2376
|
+
if (pbCollection.type === "auth" && authSystemFieldNames.includes(pbField.name)) {
|
|
2377
|
+
continue;
|
|
2378
|
+
}
|
|
2379
|
+
const field = {
|
|
2380
|
+
name: pbField.name,
|
|
2381
|
+
type: pbField.type,
|
|
2382
|
+
required: pbField.required || false
|
|
2383
|
+
};
|
|
2384
|
+
if (pbField.options) {
|
|
2385
|
+
field.options = pbField.options;
|
|
2386
|
+
}
|
|
2387
|
+
if (pbField.type === "relation") {
|
|
2388
|
+
field.relation = {
|
|
2389
|
+
collection: pbField.options?.collectionId || "",
|
|
2390
|
+
cascadeDelete: pbField.options?.cascadeDelete || false,
|
|
2391
|
+
maxSelect: pbField.options?.maxSelect,
|
|
2392
|
+
minSelect: pbField.options?.minSelect
|
|
2393
|
+
};
|
|
2394
|
+
}
|
|
2395
|
+
fields.push(field);
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
const schema = {
|
|
2399
|
+
name: pbCollection.name,
|
|
2400
|
+
type: pbCollection.type || "base",
|
|
2401
|
+
fields
|
|
2402
|
+
};
|
|
2403
|
+
if (pbCollection.indexes && Array.isArray(pbCollection.indexes)) {
|
|
2404
|
+
schema.indexes = pbCollection.indexes;
|
|
2405
|
+
}
|
|
2406
|
+
const rules = {};
|
|
2407
|
+
if (pbCollection.listRule !== void 0) rules.listRule = pbCollection.listRule;
|
|
2408
|
+
if (pbCollection.viewRule !== void 0) rules.viewRule = pbCollection.viewRule;
|
|
2409
|
+
if (pbCollection.createRule !== void 0) rules.createRule = pbCollection.createRule;
|
|
2410
|
+
if (pbCollection.updateRule !== void 0) rules.updateRule = pbCollection.updateRule;
|
|
2411
|
+
if (pbCollection.deleteRule !== void 0) rules.deleteRule = pbCollection.deleteRule;
|
|
2412
|
+
if (pbCollection.manageRule !== void 0) rules.manageRule = pbCollection.manageRule;
|
|
2413
|
+
if (Object.keys(rules).length > 0) {
|
|
2414
|
+
schema.rules = rules;
|
|
2415
|
+
}
|
|
2416
|
+
return schema;
|
|
2417
|
+
}
|
|
2418
|
+
function convertPocketBaseMigration(migrationContent) {
|
|
2419
|
+
try {
|
|
2420
|
+
const snapshotMatch = migrationContent.match(/const\s+snapshot\s*=\s*(\[[\s\S]*?\]);/);
|
|
2421
|
+
if (!snapshotMatch) {
|
|
2422
|
+
throw new Error("Could not find snapshot array in migration file");
|
|
2423
|
+
}
|
|
2424
|
+
const snapshotArrayStr = snapshotMatch[1];
|
|
2425
|
+
let snapshotArray;
|
|
2426
|
+
try {
|
|
2427
|
+
snapshotArray = new Function(`return ${snapshotArrayStr}`)();
|
|
2428
|
+
} catch (parseError) {
|
|
2429
|
+
throw new Error(`Failed to parse snapshot array: ${parseError}`);
|
|
2430
|
+
}
|
|
2431
|
+
if (!Array.isArray(snapshotArray)) {
|
|
2432
|
+
throw new Error("Snapshot is not an array");
|
|
2433
|
+
}
|
|
2434
|
+
const collections = /* @__PURE__ */ new Map();
|
|
2435
|
+
for (const pbCollection of snapshotArray) {
|
|
2436
|
+
if (!pbCollection.name) {
|
|
2437
|
+
console.warn("Skipping collection without name");
|
|
2438
|
+
continue;
|
|
2439
|
+
}
|
|
2440
|
+
const schema = convertPocketBaseCollection(pbCollection);
|
|
2441
|
+
collections.set(pbCollection.name, schema);
|
|
2442
|
+
}
|
|
2443
|
+
return {
|
|
2444
|
+
version: SNAPSHOT_VERSION,
|
|
2445
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2446
|
+
collections
|
|
2447
|
+
};
|
|
2448
|
+
} catch (error) {
|
|
2449
|
+
throw new SnapshotError(
|
|
2450
|
+
`Failed to convert PocketBase migration: ${error instanceof Error ? error.message : String(error)}`,
|
|
2451
|
+
void 0,
|
|
2452
|
+
"parse",
|
|
2453
|
+
error instanceof Error ? error : void 0
|
|
2454
|
+
);
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
// src/migration/validation.ts
|
|
2459
|
+
function detectCollectionDeletions(diff) {
|
|
2460
|
+
const changes = [];
|
|
2461
|
+
for (const collection of diff.collectionsToDelete) {
|
|
2462
|
+
changes.push({
|
|
2463
|
+
type: "collection_deletion" /* COLLECTION_DELETION */,
|
|
2464
|
+
description: `Delete collection: ${collection.name}`,
|
|
2465
|
+
collection: collection.name,
|
|
2466
|
+
severity: "high",
|
|
2467
|
+
warning: `All data in the "${collection.name}" collection will be permanently deleted.`
|
|
2468
|
+
});
|
|
2469
|
+
}
|
|
2470
|
+
return changes;
|
|
2471
|
+
}
|
|
2472
|
+
function detectFieldDeletions(diff) {
|
|
2473
|
+
const changes = [];
|
|
2474
|
+
for (const modification of diff.collectionsToModify) {
|
|
2475
|
+
for (const field of modification.fieldsToRemove) {
|
|
2476
|
+
changes.push({
|
|
2477
|
+
type: "field_deletion" /* FIELD_DELETION */,
|
|
2478
|
+
description: `Delete field: ${modification.collection}.${field.name}`,
|
|
2479
|
+
collection: modification.collection,
|
|
2480
|
+
field: field.name,
|
|
2481
|
+
severity: "high",
|
|
2482
|
+
warning: `All data in the "${field.name}" field of "${modification.collection}" will be permanently deleted.`
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
return changes;
|
|
2487
|
+
}
|
|
2488
|
+
function detectFieldTypeChanges(diff) {
|
|
2489
|
+
const changes = [];
|
|
2490
|
+
for (const modification of diff.collectionsToModify) {
|
|
2491
|
+
for (const fieldMod of modification.fieldsToModify) {
|
|
2492
|
+
const typeChange = fieldMod.changes.find((c) => c.property === "type");
|
|
2493
|
+
if (typeChange) {
|
|
2494
|
+
changes.push({
|
|
2495
|
+
type: "field_type_change" /* FIELD_TYPE_CHANGE */,
|
|
2496
|
+
description: `Change field type: ${modification.collection}.${fieldMod.fieldName}`,
|
|
2497
|
+
collection: modification.collection,
|
|
2498
|
+
field: fieldMod.fieldName,
|
|
2499
|
+
details: {
|
|
2500
|
+
oldValue: typeChange.oldValue,
|
|
2501
|
+
newValue: typeChange.newValue
|
|
2502
|
+
},
|
|
2503
|
+
severity: "high",
|
|
2504
|
+
warning: `Changing field type from "${typeChange.oldValue}" to "${typeChange.newValue}" may cause data loss or conversion errors.`
|
|
2505
|
+
});
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
return changes;
|
|
2510
|
+
}
|
|
2511
|
+
function detectFieldRequiredChanges(diff) {
|
|
2512
|
+
const changes = [];
|
|
2513
|
+
for (const modification of diff.collectionsToModify) {
|
|
2514
|
+
for (const fieldMod of modification.fieldsToModify) {
|
|
2515
|
+
const requiredChange = fieldMod.changes.find(
|
|
2516
|
+
(c) => c.property === "required" && c.newValue === true && c.oldValue === false
|
|
2517
|
+
);
|
|
2518
|
+
if (requiredChange) {
|
|
2519
|
+
changes.push({
|
|
2520
|
+
type: "field_required_change" /* FIELD_REQUIRED_CHANGE */,
|
|
2521
|
+
description: `Make field required: ${modification.collection}.${fieldMod.fieldName}`,
|
|
2522
|
+
collection: modification.collection,
|
|
2523
|
+
field: fieldMod.fieldName,
|
|
2524
|
+
details: {
|
|
2525
|
+
oldValue: false,
|
|
2526
|
+
newValue: true
|
|
2527
|
+
},
|
|
2528
|
+
severity: "medium",
|
|
2529
|
+
warning: `Making "${fieldMod.fieldName}" required may cause issues with existing records that have null/empty values.`
|
|
2530
|
+
});
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
return changes;
|
|
2535
|
+
}
|
|
2536
|
+
function detectDestructiveChanges(diff) {
|
|
2537
|
+
const changes = [];
|
|
2538
|
+
changes.push(...detectCollectionDeletions(diff));
|
|
2539
|
+
changes.push(...detectFieldDeletions(diff));
|
|
2540
|
+
changes.push(...detectFieldTypeChanges(diff));
|
|
2541
|
+
changes.push(...detectFieldRequiredChanges(diff));
|
|
2542
|
+
return changes;
|
|
2543
|
+
}
|
|
2544
|
+
function formatDestructiveChanges(changes) {
|
|
2545
|
+
if (changes.length === 0) {
|
|
2546
|
+
return "No destructive changes detected.";
|
|
2547
|
+
}
|
|
2548
|
+
const lines = [];
|
|
2549
|
+
const highSeverity = changes.filter((c) => c.severity === "high");
|
|
2550
|
+
const mediumSeverity = changes.filter((c) => c.severity === "medium");
|
|
2551
|
+
const lowSeverity = changes.filter((c) => c.severity === "low");
|
|
2552
|
+
if (highSeverity.length > 0) {
|
|
2553
|
+
lines.push("\u{1F534} HIGH SEVERITY CHANGES (Data Loss Risk):");
|
|
2554
|
+
lines.push("");
|
|
2555
|
+
for (const change of highSeverity) {
|
|
2556
|
+
lines.push(` \u2022 ${change.description}`);
|
|
2557
|
+
lines.push(` \u26A0\uFE0F ${change.warning}`);
|
|
2558
|
+
if (change.details) {
|
|
2559
|
+
if (change.details.oldValue !== void 0 && change.details.newValue !== void 0) {
|
|
2560
|
+
lines.push(` Old: ${change.details.oldValue} \u2192 New: ${change.details.newValue}`);
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
lines.push("");
|
|
2564
|
+
}
|
|
2565
|
+
}
|
|
2566
|
+
if (mediumSeverity.length > 0) {
|
|
2567
|
+
lines.push("\u{1F7E1} MEDIUM SEVERITY CHANGES (Potential Issues):");
|
|
2568
|
+
lines.push("");
|
|
2569
|
+
for (const change of mediumSeverity) {
|
|
2570
|
+
lines.push(` \u2022 ${change.description}`);
|
|
2571
|
+
lines.push(` \u26A0\uFE0F ${change.warning}`);
|
|
2572
|
+
if (change.details) {
|
|
2573
|
+
if (change.details.oldValue !== void 0 && change.details.newValue !== void 0) {
|
|
2574
|
+
lines.push(` Old: ${change.details.oldValue} \u2192 New: ${change.details.newValue}`);
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
lines.push("");
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
if (lowSeverity.length > 0) {
|
|
2581
|
+
lines.push("\u{1F7E2} LOW SEVERITY CHANGES:");
|
|
2582
|
+
lines.push("");
|
|
2583
|
+
for (const change of lowSeverity) {
|
|
2584
|
+
lines.push(` \u2022 ${change.description}`);
|
|
2585
|
+
lines.push(` \u2139\uFE0F ${change.warning}`);
|
|
2586
|
+
lines.push("");
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
return lines.join("\n");
|
|
2590
|
+
}
|
|
2591
|
+
function summarizeDestructiveChanges(changes) {
|
|
2592
|
+
return {
|
|
2593
|
+
total: changes.length,
|
|
2594
|
+
high: changes.filter((c) => c.severity === "high").length,
|
|
2595
|
+
medium: changes.filter((c) => c.severity === "medium").length,
|
|
2596
|
+
low: changes.filter((c) => c.severity === "low").length
|
|
2597
|
+
};
|
|
2598
|
+
}
|
|
2599
|
+
function requiresForceFlag(changes) {
|
|
2600
|
+
return changes.some((c) => c.severity === "high" || c.severity === "medium");
|
|
2601
|
+
}
|
|
2602
|
+
var CONFIG_FILE_NAMES = [
|
|
2603
|
+
"pocketbase-migrate.config.js",
|
|
2604
|
+
"pocketbase-migrate.config.mjs",
|
|
2605
|
+
"pocketbase-migrate.config.json",
|
|
2606
|
+
"migrate.config.js",
|
|
2607
|
+
"migrate.config.mjs",
|
|
2608
|
+
"migrate.config.json"
|
|
2609
|
+
];
|
|
2610
|
+
var DEFAULT_CONFIG5 = {
|
|
2611
|
+
schema: {
|
|
2612
|
+
directory: "src/schema",
|
|
2613
|
+
exclude: ["base.ts", "index.ts", "permissions.ts", "permission-templates.ts"]
|
|
2614
|
+
},
|
|
2615
|
+
migrations: {
|
|
2616
|
+
directory: "pocketbase/pb_migrations",
|
|
2617
|
+
format: "timestamp_description"
|
|
2618
|
+
},
|
|
2619
|
+
diff: {
|
|
2620
|
+
warnOnDelete: true,
|
|
2621
|
+
requireForceForDestructive: true
|
|
2622
|
+
}
|
|
2623
|
+
};
|
|
2624
|
+
function findConfigFile(directory) {
|
|
2625
|
+
for (const fileName of CONFIG_FILE_NAMES) {
|
|
2626
|
+
const filePath = path4__namespace.join(directory, fileName);
|
|
2627
|
+
if (fs4__namespace.existsSync(filePath)) {
|
|
2628
|
+
return filePath;
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
return null;
|
|
2632
|
+
}
|
|
2633
|
+
function loadJsonConfig(configPath) {
|
|
2634
|
+
try {
|
|
2635
|
+
const content = fs4__namespace.readFileSync(configPath, "utf-8");
|
|
2636
|
+
return JSON.parse(content);
|
|
2637
|
+
} catch (error) {
|
|
2638
|
+
if (error instanceof SyntaxError) {
|
|
2639
|
+
throw new ConfigurationError("Invalid JSON syntax in configuration file", configPath, void 0, error);
|
|
2640
|
+
}
|
|
2641
|
+
throw new ConfigurationError(
|
|
2642
|
+
"Failed to read configuration file",
|
|
2643
|
+
configPath,
|
|
2644
|
+
void 0,
|
|
2645
|
+
error instanceof Error ? error : void 0
|
|
2646
|
+
);
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
async function loadJsConfig(configPath) {
|
|
2650
|
+
try {
|
|
2651
|
+
const fileUrl = `file://${configPath}`;
|
|
2652
|
+
const module = await import(fileUrl);
|
|
2653
|
+
return module.default || module;
|
|
2654
|
+
} catch (error) {
|
|
2655
|
+
throw new ConfigurationError(
|
|
2656
|
+
"Failed to load JavaScript configuration file",
|
|
2657
|
+
configPath,
|
|
2658
|
+
void 0,
|
|
2659
|
+
error instanceof Error ? error : void 0
|
|
2660
|
+
);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
async function loadConfigFile(configPath) {
|
|
2664
|
+
if (!fs4__namespace.existsSync(configPath)) {
|
|
2665
|
+
return null;
|
|
2666
|
+
}
|
|
2667
|
+
const ext = path4__namespace.extname(configPath).toLowerCase();
|
|
2668
|
+
if (ext === ".json") {
|
|
2669
|
+
return loadJsonConfig(configPath);
|
|
2670
|
+
} else if (ext === ".js" || ext === ".mjs") {
|
|
2671
|
+
return loadJsConfig(configPath);
|
|
2672
|
+
} else {
|
|
2673
|
+
throw new ConfigurationError(`Unsupported configuration file format: ${ext}`, configPath, void 0);
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
function mergeConfig4(base, override) {
|
|
2677
|
+
return {
|
|
2678
|
+
schema: { ...base.schema, ...override.schema },
|
|
2679
|
+
migrations: { ...base.migrations, ...override.migrations },
|
|
2680
|
+
diff: { ...base.diff, ...override.diff }
|
|
2681
|
+
};
|
|
2682
|
+
}
|
|
2683
|
+
function loadConfigFromEnv() {
|
|
2684
|
+
const config = {};
|
|
2685
|
+
if (process.env.MIGRATION_SCHEMA_DIR) {
|
|
2686
|
+
config.schema = { directory: process.env.MIGRATION_SCHEMA_DIR };
|
|
2687
|
+
}
|
|
2688
|
+
if (process.env.MIGRATION_SCHEMA_EXCLUDE) {
|
|
2689
|
+
config.schema = {
|
|
2690
|
+
...config.schema,
|
|
2691
|
+
exclude: process.env.MIGRATION_SCHEMA_EXCLUDE.split(",").map((s) => s.trim())
|
|
2692
|
+
};
|
|
2693
|
+
}
|
|
2694
|
+
if (process.env.MIGRATION_OUTPUT_DIR) {
|
|
2695
|
+
config.migrations = { directory: process.env.MIGRATION_OUTPUT_DIR };
|
|
2696
|
+
}
|
|
2697
|
+
if (process.env.MIGRATION_REQUIRE_FORCE !== void 0) {
|
|
2698
|
+
config.diff = { requireForceForDestructive: process.env.MIGRATION_REQUIRE_FORCE === "true" };
|
|
2699
|
+
}
|
|
2700
|
+
return config;
|
|
2701
|
+
}
|
|
2702
|
+
function loadConfigFromArgs(options) {
|
|
2703
|
+
const config = {};
|
|
2704
|
+
if (options.output) {
|
|
2705
|
+
config.migrations = { directory: options.output };
|
|
2706
|
+
}
|
|
2707
|
+
if (options.schemaDir) {
|
|
2708
|
+
config.schema = { directory: options.schemaDir };
|
|
2709
|
+
}
|
|
2710
|
+
return config;
|
|
2711
|
+
}
|
|
2712
|
+
function validateConfig(config, configPath) {
|
|
2713
|
+
const invalidFields = [];
|
|
2714
|
+
if (typeof config.schema.directory !== "string" || config.schema.directory.trim() === "") {
|
|
2715
|
+
invalidFields.push("schema.directory (must be a non-empty string)");
|
|
2716
|
+
}
|
|
2717
|
+
if (!Array.isArray(config.schema.exclude)) {
|
|
2718
|
+
invalidFields.push("schema.exclude (must be an array of strings)");
|
|
2719
|
+
}
|
|
2720
|
+
if (typeof config.migrations.directory !== "string" || config.migrations.directory.trim() === "") {
|
|
2721
|
+
invalidFields.push("migrations.directory (must be a non-empty string)");
|
|
2722
|
+
}
|
|
2723
|
+
if (typeof config.diff.warnOnDelete !== "boolean") {
|
|
2724
|
+
invalidFields.push("diff.warnOnDelete (must be a boolean)");
|
|
2725
|
+
}
|
|
2726
|
+
if (typeof config.diff.requireForceForDestructive !== "boolean") {
|
|
2727
|
+
invalidFields.push("diff.requireForceForDestructive (must be a boolean)");
|
|
2728
|
+
}
|
|
2729
|
+
if (invalidFields.length > 0) {
|
|
2730
|
+
throw new ConfigurationError("Invalid configuration values", configPath, invalidFields);
|
|
2731
|
+
}
|
|
2732
|
+
const cwd = process.cwd();
|
|
2733
|
+
const possiblePaths = [
|
|
2734
|
+
path4__namespace.resolve(cwd, config.schema.directory),
|
|
2735
|
+
path4__namespace.resolve(cwd, "shared", config.schema.directory)
|
|
2736
|
+
];
|
|
2737
|
+
const schemaDir = possiblePaths.find((p) => fs4__namespace.existsSync(p));
|
|
2738
|
+
if (!schemaDir) {
|
|
2739
|
+
throw new ConfigurationError(`Schema directory not found. Tried: ${possiblePaths.join(", ")}`, configPath, [
|
|
2740
|
+
"schema.directory"
|
|
2741
|
+
]);
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
async function loadConfig(options = {}) {
|
|
2745
|
+
let config = { ...DEFAULT_CONFIG5 };
|
|
2746
|
+
let configFilePath;
|
|
2747
|
+
const cwd = process.cwd();
|
|
2748
|
+
if (options.config) {
|
|
2749
|
+
const explicitPath = path4__namespace.resolve(cwd, options.config);
|
|
2750
|
+
if (!fs4__namespace.existsSync(explicitPath)) {
|
|
2751
|
+
throw new ConfigurationError(`Configuration file not found: ${explicitPath}`, explicitPath);
|
|
2752
|
+
}
|
|
2753
|
+
configFilePath = explicitPath;
|
|
2754
|
+
} else {
|
|
2755
|
+
const searchDirs = [cwd, path4__namespace.join(cwd, "shared")];
|
|
2756
|
+
for (const dir of searchDirs) {
|
|
2757
|
+
if (fs4__namespace.existsSync(dir)) {
|
|
2758
|
+
const found = findConfigFile(dir);
|
|
2759
|
+
if (found) {
|
|
2760
|
+
configFilePath = found;
|
|
2761
|
+
break;
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
if (configFilePath) {
|
|
2767
|
+
const fileConfig = await loadConfigFile(configFilePath);
|
|
2768
|
+
if (fileConfig) {
|
|
2769
|
+
config = mergeConfig4(config, fileConfig);
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
const envConfig = loadConfigFromEnv();
|
|
2773
|
+
if (Object.keys(envConfig).length > 0) {
|
|
2774
|
+
config = mergeConfig4(config, envConfig);
|
|
2775
|
+
}
|
|
2776
|
+
const argsConfig = loadConfigFromArgs(options);
|
|
2777
|
+
if (Object.keys(argsConfig).length > 0) {
|
|
2778
|
+
config = mergeConfig4(config, argsConfig);
|
|
2779
|
+
}
|
|
2780
|
+
validateConfig(config, configFilePath);
|
|
2781
|
+
return config;
|
|
2782
|
+
}
|
|
2783
|
+
function getSchemaDirectory(config) {
|
|
2784
|
+
const cwd = process.cwd();
|
|
2785
|
+
const possiblePaths = [
|
|
2786
|
+
path4__namespace.resolve(cwd, config.schema.directory),
|
|
2787
|
+
path4__namespace.resolve(cwd, "shared", config.schema.directory)
|
|
2788
|
+
];
|
|
2789
|
+
return possiblePaths.find((p) => fs4__namespace.existsSync(p)) || possiblePaths[0];
|
|
2790
|
+
}
|
|
2791
|
+
function getMigrationsDirectory(config) {
|
|
2792
|
+
const cwd = process.cwd();
|
|
2793
|
+
const possiblePaths = [
|
|
2794
|
+
path4__namespace.resolve(cwd, config.migrations.directory),
|
|
2795
|
+
path4__namespace.resolve(cwd, "shared", config.migrations.directory)
|
|
2796
|
+
];
|
|
2797
|
+
return possiblePaths.find((p) => fs4__namespace.existsSync(p)) || possiblePaths[0];
|
|
2798
|
+
}
|
|
2799
|
+
var currentVerbosity = "normal";
|
|
2800
|
+
function setVerbosity(level) {
|
|
2801
|
+
currentVerbosity = level;
|
|
2802
|
+
}
|
|
2803
|
+
function getVerbosity() {
|
|
2804
|
+
return currentVerbosity;
|
|
2805
|
+
}
|
|
2806
|
+
function shouldLog(requiredLevel) {
|
|
2807
|
+
const levels = ["quiet", "normal", "verbose"];
|
|
2808
|
+
const currentIndex = levels.indexOf(currentVerbosity);
|
|
2809
|
+
const requiredIndex = levels.indexOf(requiredLevel);
|
|
2810
|
+
return currentIndex >= requiredIndex;
|
|
2811
|
+
}
|
|
2812
|
+
function createSpinner(text) {
|
|
2813
|
+
if (currentVerbosity === "quiet") {
|
|
2814
|
+
return ora__default.default({ text, isSilent: true });
|
|
2815
|
+
}
|
|
2816
|
+
return ora__default.default(text);
|
|
2817
|
+
}
|
|
2818
|
+
function logSuccess(message) {
|
|
2819
|
+
if (shouldLog("normal")) {
|
|
2820
|
+
console.log(chalk__default.default.green("\u2713"), message);
|
|
2821
|
+
}
|
|
2822
|
+
}
|
|
2823
|
+
function logError(message) {
|
|
2824
|
+
console.error(chalk__default.default.red("\u2717"), message);
|
|
2825
|
+
}
|
|
2826
|
+
function logWarning(message) {
|
|
2827
|
+
if (shouldLog("normal")) {
|
|
2828
|
+
console.warn(chalk__default.default.yellow("\u26A0"), message);
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
function logInfo(message) {
|
|
2832
|
+
if (shouldLog("normal")) {
|
|
2833
|
+
console.log(chalk__default.default.blue("\u2139"), message);
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
function logDebug(message) {
|
|
2837
|
+
if (shouldLog("verbose")) {
|
|
2838
|
+
console.log(chalk__default.default.gray("\u2699"), chalk__default.default.gray(message));
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
function logSection(title) {
|
|
2842
|
+
if (shouldLog("normal")) {
|
|
2843
|
+
console.log();
|
|
2844
|
+
console.log(chalk__default.default.bold.cyan(title));
|
|
2845
|
+
console.log(chalk__default.default.cyan("\u2500".repeat(title.length)));
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
function formatFieldChange(change) {
|
|
2849
|
+
const oldValue = change.oldValue === null ? "null" : JSON.stringify(change.oldValue);
|
|
2850
|
+
const newValue = change.newValue === null ? "null" : JSON.stringify(change.newValue);
|
|
2851
|
+
return `${change.property}: ${chalk__default.default.red(oldValue)} \u2192 ${chalk__default.default.green(newValue)}`;
|
|
2852
|
+
}
|
|
2853
|
+
function formatChangeSummary(diff) {
|
|
2854
|
+
const lines = [];
|
|
2855
|
+
const totalCollectionsToCreate = diff.collectionsToCreate.length;
|
|
2856
|
+
const totalCollectionsToDelete = diff.collectionsToDelete.length;
|
|
2857
|
+
const totalCollectionsToModify = diff.collectionsToModify.length;
|
|
2858
|
+
const totalChanges = totalCollectionsToCreate + totalCollectionsToDelete + totalCollectionsToModify;
|
|
2859
|
+
if (totalChanges === 0) {
|
|
2860
|
+
return chalk__default.default.gray("No changes detected");
|
|
2861
|
+
}
|
|
2862
|
+
lines.push(chalk__default.default.bold(`Found ${totalChanges} collection change(s):`));
|
|
2863
|
+
lines.push("");
|
|
2864
|
+
if (totalCollectionsToCreate > 0) {
|
|
2865
|
+
lines.push(chalk__default.default.green.bold(`\u2713 ${totalCollectionsToCreate} collection(s) to create:`));
|
|
2866
|
+
for (const collection of diff.collectionsToCreate) {
|
|
2867
|
+
lines.push(chalk__default.default.green(` + ${collection.name} (${collection.type})`));
|
|
2868
|
+
lines.push(chalk__default.default.gray(` ${collection.fields.length} field(s)`));
|
|
2869
|
+
}
|
|
2870
|
+
lines.push("");
|
|
2871
|
+
}
|
|
2872
|
+
if (totalCollectionsToDelete > 0) {
|
|
2873
|
+
lines.push(chalk__default.default.red.bold(`\u2717 ${totalCollectionsToDelete} collection(s) to delete:`));
|
|
2874
|
+
for (const collection of diff.collectionsToDelete) {
|
|
2875
|
+
lines.push(chalk__default.default.red(` - ${collection.name}`));
|
|
2876
|
+
}
|
|
2877
|
+
lines.push("");
|
|
2878
|
+
}
|
|
2879
|
+
if (totalCollectionsToModify > 0) {
|
|
2880
|
+
lines.push(chalk__default.default.yellow.bold(`\u26A1 ${totalCollectionsToModify} collection(s) to modify:`));
|
|
2881
|
+
for (const modification of diff.collectionsToModify) {
|
|
2882
|
+
lines.push(chalk__default.default.yellow(` ~ ${modification.collection}`));
|
|
2883
|
+
if (modification.fieldsToAdd.length > 0) {
|
|
2884
|
+
lines.push(chalk__default.default.green(` + ${modification.fieldsToAdd.length} field(s) to add:`));
|
|
2885
|
+
for (const field of modification.fieldsToAdd) {
|
|
2886
|
+
lines.push(chalk__default.default.green(` + ${field.name} (${field.type})`));
|
|
2887
|
+
}
|
|
2888
|
+
}
|
|
2889
|
+
if (modification.fieldsToRemove.length > 0) {
|
|
2890
|
+
lines.push(chalk__default.default.red(` - ${modification.fieldsToRemove.length} field(s) to remove:`));
|
|
2891
|
+
for (const field of modification.fieldsToRemove) {
|
|
2892
|
+
lines.push(chalk__default.default.red(` - ${field.name}`));
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
if (modification.fieldsToModify.length > 0) {
|
|
2896
|
+
lines.push(chalk__default.default.yellow(` ~ ${modification.fieldsToModify.length} field(s) to modify:`));
|
|
2897
|
+
for (const fieldMod of modification.fieldsToModify) {
|
|
2898
|
+
lines.push(chalk__default.default.yellow(` ~ ${fieldMod.fieldName}`));
|
|
2899
|
+
for (const change of fieldMod.changes) {
|
|
2900
|
+
lines.push(chalk__default.default.gray(` ${formatFieldChange(change)}`));
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
if (modification.indexesToAdd.length > 0) {
|
|
2905
|
+
lines.push(chalk__default.default.green(` + ${modification.indexesToAdd.length} index(es) to add`));
|
|
2906
|
+
}
|
|
2907
|
+
if (modification.indexesToRemove.length > 0) {
|
|
2908
|
+
lines.push(chalk__default.default.red(` - ${modification.indexesToRemove.length} index(es) to remove`));
|
|
2909
|
+
}
|
|
2910
|
+
if (modification.rulesToUpdate.length > 0) {
|
|
2911
|
+
lines.push(chalk__default.default.yellow(` ~ ${modification.rulesToUpdate.length} rule(s) to update`));
|
|
2912
|
+
}
|
|
2913
|
+
lines.push("");
|
|
2914
|
+
}
|
|
2915
|
+
}
|
|
2916
|
+
return lines.join("\n");
|
|
2917
|
+
}
|
|
2918
|
+
async function withProgress(message, operation) {
|
|
2919
|
+
const spinner = createSpinner(message).start();
|
|
2920
|
+
try {
|
|
2921
|
+
const result = await operation();
|
|
2922
|
+
spinner.succeed();
|
|
2923
|
+
return result;
|
|
2924
|
+
} catch (error) {
|
|
2925
|
+
spinner.fail();
|
|
2926
|
+
throw error;
|
|
2927
|
+
}
|
|
2928
|
+
}
|
|
2929
|
+
function logStep(step, total, message) {
|
|
2930
|
+
if (shouldLog("normal")) {
|
|
2931
|
+
const progress = chalk__default.default.gray(`[${step}/${total}]`);
|
|
2932
|
+
console.log(progress, message);
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
function logList(items, indent = 2) {
|
|
2936
|
+
if (shouldLog("normal")) {
|
|
2937
|
+
const padding = " ".repeat(indent);
|
|
2938
|
+
for (const item of items) {
|
|
2939
|
+
console.log(`${padding}\u2022 ${item}`);
|
|
2940
|
+
}
|
|
2941
|
+
}
|
|
2942
|
+
}
|
|
2943
|
+
function logKeyValue(key, value, indent = 2) {
|
|
2944
|
+
if (shouldLog("normal")) {
|
|
2945
|
+
const padding = " ".repeat(indent);
|
|
2946
|
+
console.log(`${padding}${chalk__default.default.gray(key + ":")} ${value}`);
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
function logTable(headers, rows) {
|
|
2950
|
+
if (!shouldLog("normal")) return;
|
|
2951
|
+
const widths = headers.map((h, i) => {
|
|
2952
|
+
const maxRowWidth = Math.max(...rows.map((r) => (r[i] || "").length));
|
|
2953
|
+
return Math.max(h.length, maxRowWidth);
|
|
2954
|
+
});
|
|
2955
|
+
const headerLine = headers.map((h, i) => h.padEnd(widths[i])).join(" ");
|
|
2956
|
+
console.log(chalk__default.default.bold(headerLine));
|
|
2957
|
+
console.log(chalk__default.default.gray("\u2500".repeat(headerLine.length)));
|
|
2958
|
+
for (const row of rows) {
|
|
2959
|
+
const rowLine = row.map((cell, i) => (cell || "").padEnd(widths[i])).join(" ");
|
|
2960
|
+
console.log(rowLine);
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
function logBox(title, content) {
|
|
2964
|
+
if (!shouldLog("normal")) return;
|
|
2965
|
+
const maxWidth = Math.max(title.length, ...content.map((c) => c.length));
|
|
2966
|
+
const border = "\u2500".repeat(maxWidth + 2);
|
|
2967
|
+
console.log();
|
|
2968
|
+
console.log(chalk__default.default.cyan(`\u250C${border}\u2510`));
|
|
2969
|
+
console.log(chalk__default.default.cyan("\u2502 ") + chalk__default.default.bold(title.padEnd(maxWidth)) + chalk__default.default.cyan(" \u2502"));
|
|
2970
|
+
console.log(chalk__default.default.cyan(`\u251C${border}\u2524`));
|
|
2971
|
+
for (const line of content) {
|
|
2972
|
+
console.log(chalk__default.default.cyan("\u2502 ") + line.padEnd(maxWidth) + chalk__default.default.cyan(" \u2502"));
|
|
2973
|
+
}
|
|
2974
|
+
console.log(chalk__default.default.cyan(`\u2514${border}\u2518`));
|
|
2975
|
+
}
|
|
2976
|
+
function createProgressBar(current, total, width = 20) {
|
|
2977
|
+
const percentage = Math.min(100, Math.round(current / total * 100));
|
|
2978
|
+
const filled = Math.round(percentage / 100 * width);
|
|
2979
|
+
const empty = width - filled;
|
|
2980
|
+
const bar = chalk__default.default.green("\u2588".repeat(filled)) + chalk__default.default.gray("\u2591".repeat(empty));
|
|
2981
|
+
return `${bar} ${percentage}%`;
|
|
2982
|
+
}
|
|
2983
|
+
function logTimestamp(message) {
|
|
2984
|
+
if (shouldLog("verbose")) {
|
|
2985
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
2986
|
+
console.log(chalk__default.default.gray(`[${timestamp}]`), message);
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
function formatDuration(ms) {
|
|
2990
|
+
if (ms < 1e3) {
|
|
2991
|
+
return `${ms}ms`;
|
|
2992
|
+
} else if (ms < 6e4) {
|
|
2993
|
+
return `${(ms / 1e3).toFixed(1)}s`;
|
|
2994
|
+
} else {
|
|
2995
|
+
const minutes = Math.floor(ms / 6e4);
|
|
2996
|
+
const seconds = Math.round(ms % 6e4 / 1e3);
|
|
2997
|
+
return `${minutes}m ${seconds}s`;
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
function logTimed(message, startTime) {
|
|
3001
|
+
if (shouldLog("normal")) {
|
|
3002
|
+
const duration = Date.now() - startTime;
|
|
3003
|
+
console.log(chalk__default.default.green("\u2713"), message, chalk__default.default.gray(`(${formatDuration(duration)})`));
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
function formatStatusJson(output) {
|
|
3007
|
+
return JSON.stringify(output, null, 2);
|
|
3008
|
+
}
|
|
3009
|
+
|
|
3010
|
+
// src/cli/commands/generate.ts
|
|
3011
|
+
function hasChanges2(diff) {
|
|
3012
|
+
return diff.collectionsToCreate.length > 0 || diff.collectionsToDelete.length > 0 || diff.collectionsToModify.length > 0;
|
|
3013
|
+
}
|
|
3014
|
+
function handleDestructiveChanges(diff, config, force) {
|
|
3015
|
+
const destructiveChanges = detectDestructiveChanges(diff);
|
|
3016
|
+
if (destructiveChanges.length === 0) {
|
|
3017
|
+
return true;
|
|
3018
|
+
}
|
|
3019
|
+
logSection("\u26A0\uFE0F Destructive Changes Detected");
|
|
3020
|
+
console.log();
|
|
3021
|
+
console.log(formatDestructiveChanges(destructiveChanges));
|
|
3022
|
+
const summary = summarizeDestructiveChanges(destructiveChanges);
|
|
3023
|
+
console.log("Summary:");
|
|
3024
|
+
console.log(` Total: ${summary.total} destructive change(s)`);
|
|
3025
|
+
if (summary.high > 0) {
|
|
3026
|
+
console.log(` High Severity: ${summary.high}`);
|
|
3027
|
+
}
|
|
3028
|
+
if (summary.medium > 0) {
|
|
3029
|
+
console.log(` Medium Severity: ${summary.medium}`);
|
|
3030
|
+
}
|
|
3031
|
+
if (summary.low > 0) {
|
|
3032
|
+
console.log(` Low Severity: ${summary.low}`);
|
|
3033
|
+
}
|
|
3034
|
+
console.log();
|
|
3035
|
+
const forceRequired = config.diff.requireForceForDestructive && requiresForceFlag(destructiveChanges);
|
|
3036
|
+
if (forceRequired && !force) {
|
|
3037
|
+
logError("Destructive changes require the --force flag to proceed.");
|
|
3038
|
+
console.log();
|
|
3039
|
+
logInfo("To proceed with these changes, run the command again with --force:");
|
|
3040
|
+
console.log(" yarn migrate:generate --force");
|
|
3041
|
+
console.log();
|
|
3042
|
+
logWarning("\u26A0\uFE0F WARNING: Using --force will apply these changes and may result in data loss!");
|
|
3043
|
+
return false;
|
|
3044
|
+
}
|
|
3045
|
+
if (force) {
|
|
3046
|
+
logWarning("Proceeding with destructive changes (--force flag provided)");
|
|
3047
|
+
console.log();
|
|
3048
|
+
}
|
|
3049
|
+
return true;
|
|
3050
|
+
}
|
|
3051
|
+
async function executeGenerate(options) {
|
|
3052
|
+
try {
|
|
3053
|
+
const parentOpts = options.parent?.opts?.() || {};
|
|
3054
|
+
if (parentOpts.verbose) {
|
|
3055
|
+
setVerbosity("verbose");
|
|
3056
|
+
} else if (parentOpts.quiet) {
|
|
3057
|
+
setVerbosity("quiet");
|
|
3058
|
+
}
|
|
3059
|
+
logDebug("Starting migration generation...");
|
|
3060
|
+
logDebug(`Options: ${JSON.stringify(options, null, 2)}`);
|
|
3061
|
+
const config = await loadConfig(options);
|
|
3062
|
+
const schemaDir = getSchemaDirectory(config);
|
|
3063
|
+
const migrationsDir = getMigrationsDirectory(config);
|
|
3064
|
+
logSection("\u{1F50D} Analyzing Schema");
|
|
3065
|
+
const currentSchema = await withProgress("Parsing Zod schemas...", () => parseSchemaFiles(schemaDir));
|
|
3066
|
+
logSuccess(`Found ${currentSchema.collections.size} collection(s)`);
|
|
3067
|
+
logInfo("Loading previous snapshot...");
|
|
3068
|
+
const previousSnapshot = loadSnapshotIfExists({
|
|
3069
|
+
migrationsPath: migrationsDir,
|
|
3070
|
+
workspaceRoot: process.cwd()
|
|
3071
|
+
});
|
|
3072
|
+
if (!previousSnapshot) {
|
|
3073
|
+
logInfo("No previous snapshot found - treating as empty database (first-time generation)");
|
|
3074
|
+
} else {
|
|
3075
|
+
logSuccess("Loaded previous snapshot as base reference");
|
|
3076
|
+
}
|
|
3077
|
+
logSection("\u{1F4CA} Comparing Schemas");
|
|
3078
|
+
const diff = compare(currentSchema, previousSnapshot);
|
|
3079
|
+
if (!hasChanges2(diff)) {
|
|
3080
|
+
logInfo("No changes detected");
|
|
3081
|
+
console.log();
|
|
3082
|
+
logSuccess("Schema is up to date!");
|
|
3083
|
+
return;
|
|
3084
|
+
}
|
|
3085
|
+
console.log();
|
|
3086
|
+
console.log(formatChangeSummary(diff));
|
|
3087
|
+
if (!handleDestructiveChanges(diff, config, options.force)) {
|
|
3088
|
+
process.exit(1);
|
|
3089
|
+
}
|
|
3090
|
+
logSection("\u{1F4DD} Generating Migration");
|
|
3091
|
+
const migrationPath = await withProgress(
|
|
3092
|
+
"Creating migration file...",
|
|
3093
|
+
() => Promise.resolve(generate(diff, migrationsDir))
|
|
3094
|
+
);
|
|
3095
|
+
logSuccess(`Migration file created: ${path4__namespace.basename(migrationPath)}`);
|
|
3096
|
+
logSection("\u2705 Next Steps");
|
|
3097
|
+
console.log();
|
|
3098
|
+
console.log(" 1. Review the generated migration file:");
|
|
3099
|
+
console.log(` ${migrationPath}`);
|
|
3100
|
+
console.log();
|
|
3101
|
+
console.log(" 2. Apply the migration by running PocketBase:");
|
|
3102
|
+
console.log(" yarn pb");
|
|
3103
|
+
console.log();
|
|
3104
|
+
console.log(" Or apply migrations manually:");
|
|
3105
|
+
console.log(" cd pb && ./pocketbase migrate up");
|
|
3106
|
+
console.log();
|
|
3107
|
+
} catch (error) {
|
|
3108
|
+
if (error instanceof SchemaParsingError) {
|
|
3109
|
+
logError("Schema Parsing Error");
|
|
3110
|
+
console.error();
|
|
3111
|
+
console.error(error.getDetailedMessage());
|
|
3112
|
+
console.error();
|
|
3113
|
+
logInfo("Suggestions:");
|
|
3114
|
+
console.log(" \u2022 Make sure your schema files are valid Zod schemas");
|
|
3115
|
+
console.log(' \u2022 Run "yarn build" in the shared workspace to compile TypeScript files');
|
|
3116
|
+
console.log(' \u2022 Check that schema files export schemas ending with "Schema" or "InputSchema"');
|
|
3117
|
+
} else if (error instanceof SnapshotError) {
|
|
3118
|
+
logError("Snapshot Error");
|
|
3119
|
+
console.error();
|
|
3120
|
+
console.error(error.getDetailedMessage());
|
|
3121
|
+
console.error();
|
|
3122
|
+
logInfo("Suggestions:");
|
|
3123
|
+
console.log(" \u2022 Check that the snapshot file is not corrupted");
|
|
3124
|
+
console.log(" \u2022 Verify file permissions for the snapshot file");
|
|
3125
|
+
console.log(" \u2022 If this is the first run, this error should not occur");
|
|
3126
|
+
} else if (error instanceof MigrationGenerationError) {
|
|
3127
|
+
logError("Migration Generation Error");
|
|
3128
|
+
console.error();
|
|
3129
|
+
console.error(error.getDetailedMessage());
|
|
3130
|
+
console.error();
|
|
3131
|
+
logInfo("Suggestions:");
|
|
3132
|
+
console.log(" \u2022 Check that the migration directory exists and is writable");
|
|
3133
|
+
console.log(" \u2022 Verify you have sufficient disk space");
|
|
3134
|
+
console.log(" \u2022 Check file permissions for the migration directory");
|
|
3135
|
+
} else if (error instanceof FileSystemError) {
|
|
3136
|
+
logError("File System Error");
|
|
3137
|
+
console.error();
|
|
3138
|
+
console.error(error.getDetailedMessage());
|
|
3139
|
+
console.error();
|
|
3140
|
+
logInfo("Suggestions:");
|
|
3141
|
+
console.log(" \u2022 Check file and directory permissions");
|
|
3142
|
+
console.log(" \u2022 Verify you have sufficient disk space");
|
|
3143
|
+
console.log(" \u2022 Ensure the paths are correct and accessible");
|
|
3144
|
+
} else if (error instanceof ConfigurationError) {
|
|
3145
|
+
logError("Configuration Error");
|
|
3146
|
+
console.error();
|
|
3147
|
+
console.error(error.getDetailedMessage());
|
|
3148
|
+
console.error();
|
|
3149
|
+
logInfo("Suggestions:");
|
|
3150
|
+
console.log(" \u2022 Check your configuration file syntax");
|
|
3151
|
+
console.log(" \u2022 Verify all paths are correct and accessible");
|
|
3152
|
+
console.log(" \u2022 Run with --verbose flag for more details");
|
|
3153
|
+
} else {
|
|
3154
|
+
logError(`Failed to generate migration: ${error}`);
|
|
3155
|
+
if (error instanceof Error && error.stack) {
|
|
3156
|
+
console.error();
|
|
3157
|
+
console.error(error.stack);
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
console.error();
|
|
3161
|
+
process.exit(1);
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
function hasChanges3(diff) {
|
|
3165
|
+
return diff.collectionsToCreate.length > 0 || diff.collectionsToDelete.length > 0 || diff.collectionsToModify.length > 0;
|
|
3166
|
+
}
|
|
3167
|
+
function hasDestructiveChanges(diff) {
|
|
3168
|
+
const { destructive } = categorizeChangesBySeverity(diff);
|
|
3169
|
+
return destructive.length > 0;
|
|
3170
|
+
}
|
|
3171
|
+
function createStatusOutput(status, currentCount, snapshotCount, diff) {
|
|
3172
|
+
return {
|
|
3173
|
+
status,
|
|
3174
|
+
collections: {
|
|
3175
|
+
current: currentCount,
|
|
3176
|
+
snapshot: snapshotCount
|
|
3177
|
+
},
|
|
3178
|
+
changes: {
|
|
3179
|
+
create: diff?.collectionsToCreate.length ?? 0,
|
|
3180
|
+
delete: diff?.collectionsToDelete.length ?? 0,
|
|
3181
|
+
modify: diff?.collectionsToModify.length ?? 0
|
|
3182
|
+
},
|
|
3183
|
+
destructive: diff ? hasDestructiveChanges(diff) : false
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
function displayDestructiveChangesSummary(diff) {
|
|
3187
|
+
const { destructive, nonDestructive } = categorizeChangesBySeverity(diff);
|
|
3188
|
+
if (destructive.length > 0) {
|
|
3189
|
+
logSection("\u26A0\uFE0F Destructive Changes");
|
|
3190
|
+
console.log();
|
|
3191
|
+
for (const change of destructive) {
|
|
3192
|
+
console.log(chalk__default.default.red(` ${change}`));
|
|
3193
|
+
}
|
|
3194
|
+
console.log();
|
|
3195
|
+
}
|
|
3196
|
+
if (nonDestructive.length > 0) {
|
|
3197
|
+
logSection("\u2713 Non-Destructive Changes");
|
|
3198
|
+
console.log();
|
|
3199
|
+
for (const change of nonDestructive) {
|
|
3200
|
+
console.log(chalk__default.default.green(` ${change}`));
|
|
3201
|
+
}
|
|
3202
|
+
console.log();
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
function displayChangeTable(diff) {
|
|
3206
|
+
const rows = [];
|
|
3207
|
+
for (const collection of diff.collectionsToCreate) {
|
|
3208
|
+
rows.push([
|
|
3209
|
+
chalk__default.default.green("+"),
|
|
3210
|
+
collection.name,
|
|
3211
|
+
collection.type,
|
|
3212
|
+
`${collection.fields.length} fields`,
|
|
3213
|
+
chalk__default.default.green("Create")
|
|
3214
|
+
]);
|
|
3215
|
+
}
|
|
3216
|
+
for (const collection of diff.collectionsToDelete) {
|
|
3217
|
+
rows.push([chalk__default.default.red("-"), collection.name, collection.type || "base", "-", chalk__default.default.red("Delete")]);
|
|
3218
|
+
}
|
|
3219
|
+
for (const mod of diff.collectionsToModify) {
|
|
3220
|
+
const changes = [];
|
|
3221
|
+
if (mod.fieldsToAdd.length > 0) changes.push(`+${mod.fieldsToAdd.length} fields`);
|
|
3222
|
+
if (mod.fieldsToRemove.length > 0) changes.push(`-${mod.fieldsToRemove.length} fields`);
|
|
3223
|
+
if (mod.fieldsToModify.length > 0) changes.push(`~${mod.fieldsToModify.length} fields`);
|
|
3224
|
+
if (mod.indexesToAdd.length > 0) changes.push(`+${mod.indexesToAdd.length} indexes`);
|
|
3225
|
+
if (mod.indexesToRemove.length > 0) changes.push(`-${mod.indexesToRemove.length} indexes`);
|
|
3226
|
+
if (mod.rulesToUpdate.length > 0) changes.push(`~${mod.rulesToUpdate.length} rules`);
|
|
3227
|
+
rows.push([chalk__default.default.yellow("~"), mod.collection, "-", changes.join(", ") || "No changes", chalk__default.default.yellow("Modify")]);
|
|
3228
|
+
}
|
|
3229
|
+
if (rows.length > 0) {
|
|
3230
|
+
logTable(["", "Collection", "Type", "Changes", "Action"], rows);
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
async function executeStatus(options) {
|
|
3234
|
+
const isJsonMode = options.json === true;
|
|
3235
|
+
try {
|
|
3236
|
+
if (isJsonMode) {
|
|
3237
|
+
setVerbosity("quiet");
|
|
3238
|
+
} else {
|
|
3239
|
+
const parentOpts = options.parent?.opts?.() || {};
|
|
3240
|
+
if (parentOpts.verbose) {
|
|
3241
|
+
setVerbosity("verbose");
|
|
3242
|
+
} else if (parentOpts.quiet) {
|
|
3243
|
+
setVerbosity("quiet");
|
|
3244
|
+
}
|
|
3245
|
+
}
|
|
3246
|
+
logDebug("Checking migration status...");
|
|
3247
|
+
logDebug(`Options: ${JSON.stringify(options, null, 2)}`);
|
|
3248
|
+
const config = await loadConfig(options);
|
|
3249
|
+
const schemaDir = getSchemaDirectory(config);
|
|
3250
|
+
const migrationsDir = getMigrationsDirectory(config);
|
|
3251
|
+
logSection("\u{1F50D} Checking Migration Status");
|
|
3252
|
+
const currentSchema = await withProgress("Parsing Zod schemas...", () => parseSchemaFiles(schemaDir));
|
|
3253
|
+
logSuccess(`Found ${currentSchema.collections.size} collection(s) in schema`);
|
|
3254
|
+
logInfo("Loading previous snapshot...");
|
|
3255
|
+
const previousSnapshot = loadSnapshotIfExists({
|
|
3256
|
+
migrationsPath: migrationsDir,
|
|
3257
|
+
workspaceRoot: process.cwd()
|
|
3258
|
+
});
|
|
3259
|
+
if (!previousSnapshot) {
|
|
3260
|
+
if (isJsonMode) {
|
|
3261
|
+
const output = createStatusOutput("first-time-setup", currentSchema.collections.size, 0);
|
|
3262
|
+
console.log(formatStatusJson(output));
|
|
3263
|
+
return;
|
|
3264
|
+
}
|
|
3265
|
+
logSection("\u{1F195} First-Time Setup Detected");
|
|
3266
|
+
console.log();
|
|
3267
|
+
logInfo("No previous snapshot found. This appears to be a first-time setup.");
|
|
3268
|
+
console.log();
|
|
3269
|
+
logKeyValue("Collections in schema", String(currentSchema.collections.size));
|
|
3270
|
+
console.log();
|
|
3271
|
+
logInfo('Run "pocketbase-migrate generate" to create the initial migration.');
|
|
3272
|
+
return;
|
|
3273
|
+
}
|
|
3274
|
+
logSuccess(`Loaded snapshot with ${previousSnapshot.collections.size} collection(s)`);
|
|
3275
|
+
logSection("\u{1F4CA} Schema Comparison");
|
|
3276
|
+
const diff = compare(currentSchema, previousSnapshot);
|
|
3277
|
+
if (!hasChanges3(diff)) {
|
|
3278
|
+
if (isJsonMode) {
|
|
3279
|
+
const output = createStatusOutput(
|
|
3280
|
+
"up-to-date",
|
|
3281
|
+
currentSchema.collections.size,
|
|
3282
|
+
previousSnapshot.collections.size,
|
|
3283
|
+
diff
|
|
3284
|
+
);
|
|
3285
|
+
console.log(formatStatusJson(output));
|
|
3286
|
+
return;
|
|
3287
|
+
}
|
|
3288
|
+
console.log();
|
|
3289
|
+
logSuccess("\u2713 Schema is in sync with snapshot");
|
|
3290
|
+
logInfo("No pending changes detected");
|
|
3291
|
+
console.log();
|
|
3292
|
+
logKeyValue("Collections", String(currentSchema.collections.size));
|
|
3293
|
+
return;
|
|
3294
|
+
}
|
|
3295
|
+
if (isJsonMode) {
|
|
3296
|
+
const output = createStatusOutput(
|
|
3297
|
+
"changes-pending",
|
|
3298
|
+
currentSchema.collections.size,
|
|
3299
|
+
previousSnapshot.collections.size,
|
|
3300
|
+
diff
|
|
3301
|
+
);
|
|
3302
|
+
console.log(formatStatusJson(output));
|
|
3303
|
+
return;
|
|
3304
|
+
}
|
|
3305
|
+
console.log();
|
|
3306
|
+
console.log(formatChangeSummary(diff));
|
|
3307
|
+
logDebug("Detailed change table:");
|
|
3308
|
+
displayChangeTable(diff);
|
|
3309
|
+
displayDestructiveChangesSummary(diff);
|
|
3310
|
+
logSection("\u{1F4DD} Next Steps");
|
|
3311
|
+
console.log();
|
|
3312
|
+
console.log(" To generate a migration for these changes, run:");
|
|
3313
|
+
console.log(chalk__default.default.cyan(" pocketbase-migrate generate"));
|
|
3314
|
+
console.log();
|
|
3315
|
+
const { destructive } = categorizeChangesBySeverity(diff);
|
|
3316
|
+
if (destructive.length > 0) {
|
|
3317
|
+
console.log(chalk__default.default.yellow(" \u26A0\uFE0F Destructive changes detected. Use --force flag when generating:"));
|
|
3318
|
+
console.log(chalk__default.default.cyan(" pocketbase-migrate generate --force"));
|
|
3319
|
+
console.log();
|
|
3320
|
+
}
|
|
3321
|
+
} catch (error) {
|
|
3322
|
+
if (error instanceof SchemaParsingError) {
|
|
3323
|
+
logError("Schema Parsing Error");
|
|
3324
|
+
console.error();
|
|
3325
|
+
console.error(error.getDetailedMessage());
|
|
3326
|
+
console.error();
|
|
3327
|
+
logInfo("Suggestions:");
|
|
3328
|
+
console.log(" \u2022 Make sure your schema files are valid Zod schemas");
|
|
3329
|
+
console.log(' \u2022 Check that schema files export schemas ending with "Schema" or "InputSchema"');
|
|
3330
|
+
} else if (error instanceof SnapshotError) {
|
|
3331
|
+
logError("Snapshot Error");
|
|
3332
|
+
console.error();
|
|
3333
|
+
console.error(error.getDetailedMessage());
|
|
3334
|
+
console.error();
|
|
3335
|
+
logInfo("Suggestions:");
|
|
3336
|
+
console.log(" \u2022 Check that the snapshot file is not corrupted");
|
|
3337
|
+
console.log(" \u2022 Verify file permissions for the snapshot file");
|
|
3338
|
+
} else if (error instanceof ConfigurationError) {
|
|
3339
|
+
logError("Configuration Error");
|
|
3340
|
+
console.error();
|
|
3341
|
+
console.error(error.getDetailedMessage());
|
|
3342
|
+
console.error();
|
|
3343
|
+
logInfo("Suggestions:");
|
|
3344
|
+
console.log(" \u2022 Check your configuration file syntax");
|
|
3345
|
+
console.log(" \u2022 Verify all paths are correct and accessible");
|
|
3346
|
+
} else {
|
|
3347
|
+
logError(`Failed to check status: ${error}`);
|
|
3348
|
+
if (error instanceof Error && error.stack) {
|
|
3349
|
+
console.error(error.stack);
|
|
3350
|
+
}
|
|
3351
|
+
}
|
|
3352
|
+
process.exit(1);
|
|
3353
|
+
}
|
|
3354
|
+
}
|
|
3355
|
+
|
|
3356
|
+
exports.createProgressBar = createProgressBar;
|
|
3357
|
+
exports.createSpinner = createSpinner;
|
|
3358
|
+
exports.formatChangeSummary = formatChangeSummary;
|
|
3359
|
+
exports.formatDuration = formatDuration;
|
|
3360
|
+
exports.formatStatusJson = formatStatusJson;
|
|
3361
|
+
exports.generateMigration = executeGenerate;
|
|
3362
|
+
exports.getMigrationStatus = executeStatus;
|
|
3363
|
+
exports.getMigrationsDirectory = getMigrationsDirectory;
|
|
3364
|
+
exports.getSchemaDirectory = getSchemaDirectory;
|
|
3365
|
+
exports.getVerbosity = getVerbosity;
|
|
3366
|
+
exports.loadConfig = loadConfig;
|
|
3367
|
+
exports.logBox = logBox;
|
|
3368
|
+
exports.logDebug = logDebug;
|
|
3369
|
+
exports.logError = logError;
|
|
3370
|
+
exports.logInfo = logInfo;
|
|
3371
|
+
exports.logKeyValue = logKeyValue;
|
|
3372
|
+
exports.logList = logList;
|
|
3373
|
+
exports.logSection = logSection;
|
|
3374
|
+
exports.logStep = logStep;
|
|
3375
|
+
exports.logSuccess = logSuccess;
|
|
3376
|
+
exports.logTable = logTable;
|
|
3377
|
+
exports.logTimed = logTimed;
|
|
3378
|
+
exports.logTimestamp = logTimestamp;
|
|
3379
|
+
exports.logWarning = logWarning;
|
|
3380
|
+
exports.setVerbosity = setVerbosity;
|
|
3381
|
+
exports.withProgress = withProgress;
|
|
3382
|
+
//# sourceMappingURL=index.cjs.map
|
|
3383
|
+
//# sourceMappingURL=index.cjs.map
|