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