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
package/dist/index.js ADDED
@@ -0,0 +1,4726 @@
1
+ import { z } from 'zod';
2
+ import * as fs2 from 'fs';
3
+ import * as path4 from 'path';
4
+ import chalk from 'chalk';
5
+ import ora from 'ora';
6
+
7
+ // src/enums.ts
8
+ var StatusEnum = z.enum([
9
+ "draft",
10
+ // Initial proposal stage (RequestDraft, ProjectDraft)
11
+ "active",
12
+ // Work in progress
13
+ "complete",
14
+ // Fully completed project
15
+ "fail"
16
+ // Failed project at any stage
17
+ ]);
18
+ var baseSchema = {
19
+ id: z.string().describe("unique id"),
20
+ collectionId: z.string().describe("collection id"),
21
+ collectionName: z.string().describe("collection name"),
22
+ expand: z.record(z.any()).describe("expandable fields")
23
+ };
24
+ var baseSchemaWithTimestamps = {
25
+ ...baseSchema,
26
+ created: z.string().describe("creation timestamp"),
27
+ updated: z.string().describe("last update timestamp")
28
+ };
29
+ var baseImageFileSchema = {
30
+ ...baseSchema,
31
+ thumbnailURL: z.string().optional(),
32
+ imageFiles: z.array(z.string())
33
+ };
34
+ var inputImageFileSchema = {
35
+ imageFiles: z.array(z.instanceof(File))
36
+ };
37
+ var omitImageFilesSchema = {
38
+ imageFiles: true
39
+ };
40
+ function textField(options) {
41
+ let schema = z.string();
42
+ if (options?.min !== void 0) schema = schema.min(options.min);
43
+ if (options?.max !== void 0) schema = schema.max(options.max);
44
+ if (options?.pattern !== void 0) schema = schema.regex(options.pattern);
45
+ return schema;
46
+ }
47
+ function emailField() {
48
+ return z.string().email();
49
+ }
50
+ function urlField() {
51
+ return z.string().url();
52
+ }
53
+ function numberField(options) {
54
+ let schema = z.number();
55
+ if (options?.min !== void 0) schema = schema.min(options.min);
56
+ if (options?.max !== void 0) schema = schema.max(options.max);
57
+ return schema;
58
+ }
59
+ function boolField() {
60
+ return z.boolean();
61
+ }
62
+ function dateField() {
63
+ return z.date();
64
+ }
65
+ function selectField(values) {
66
+ return z.enum(values);
67
+ }
68
+ function jsonField(schema) {
69
+ return schema ?? z.record(z.any());
70
+ }
71
+ function fileField() {
72
+ return z.instanceof(File);
73
+ }
74
+ function filesField(options) {
75
+ let schema = z.array(z.instanceof(File));
76
+ if (options?.min !== void 0) schema = schema.min(options.min);
77
+ if (options?.max !== void 0) schema = schema.max(options.max);
78
+ return schema;
79
+ }
80
+ function relationField() {
81
+ return z.string();
82
+ }
83
+ function relationsField(options) {
84
+ let schema = z.array(z.string());
85
+ if (options?.min !== void 0) schema = schema.min(options.min);
86
+ if (options?.max !== void 0) schema = schema.max(options.max);
87
+ return schema;
88
+ }
89
+ function editorField() {
90
+ return z.string();
91
+ }
92
+ function geoPointField() {
93
+ return z.object({
94
+ lon: z.number(),
95
+ lat: z.number()
96
+ });
97
+ }
98
+ function withPermissions(schema, config) {
99
+ const metadata = {
100
+ permissions: config
101
+ };
102
+ return schema.describe(JSON.stringify(metadata));
103
+ }
104
+ function withIndexes(schema, indexes) {
105
+ let existingMetadata = {};
106
+ if (schema.description) {
107
+ try {
108
+ existingMetadata = JSON.parse(schema.description);
109
+ } catch {
110
+ }
111
+ }
112
+ const metadata = {
113
+ ...existingMetadata,
114
+ indexes
115
+ };
116
+ return schema.describe(JSON.stringify(metadata));
117
+ }
118
+
119
+ // src/schema/permission-templates.ts
120
+ var PermissionTemplates = {
121
+ /**
122
+ * Public access - anyone can perform all operations
123
+ */
124
+ public: () => ({
125
+ listRule: "",
126
+ viewRule: "",
127
+ createRule: "",
128
+ updateRule: "",
129
+ deleteRule: ""
130
+ }),
131
+ /**
132
+ * Authenticated users only - requires valid authentication for all operations
133
+ */
134
+ authenticated: () => ({
135
+ listRule: '@request.auth.id != ""',
136
+ viewRule: '@request.auth.id != ""',
137
+ createRule: '@request.auth.id != ""',
138
+ updateRule: '@request.auth.id != ""',
139
+ deleteRule: '@request.auth.id != ""'
140
+ }),
141
+ /**
142
+ * Owner-only access - users can only manage their own records
143
+ * @param ownerField - Name of the relation field pointing to user (default: 'User')
144
+ */
145
+ ownerOnly: (ownerField = "User") => ({
146
+ listRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
147
+ viewRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
148
+ createRule: '@request.auth.id != ""',
149
+ updateRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`,
150
+ deleteRule: `@request.auth.id != "" && ${ownerField} = @request.auth.id`
151
+ }),
152
+ /**
153
+ * Admin/superuser only access
154
+ * Assumes a 'role' field exists with 'admin' value
155
+ * @param roleField - Name of the role field (default: 'role')
156
+ */
157
+ adminOnly: (roleField = "role") => ({
158
+ listRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
159
+ viewRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
160
+ createRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
161
+ updateRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`,
162
+ deleteRule: `@request.auth.id != "" && @request.auth.${roleField} = "admin"`
163
+ }),
164
+ /**
165
+ * Public read, authenticated write
166
+ * Anyone can list/view, but only authenticated users can create/update/delete
167
+ */
168
+ readPublic: () => ({
169
+ listRule: "",
170
+ viewRule: "",
171
+ createRule: '@request.auth.id != ""',
172
+ updateRule: '@request.auth.id != ""',
173
+ deleteRule: '@request.auth.id != ""'
174
+ }),
175
+ /**
176
+ * Locked access - only superusers can perform operations
177
+ * All rules are set to null (locked)
178
+ */
179
+ locked: () => ({
180
+ listRule: null,
181
+ viewRule: null,
182
+ createRule: null,
183
+ updateRule: null,
184
+ deleteRule: null
185
+ }),
186
+ /**
187
+ * Read-only authenticated - authenticated users can read, no write access
188
+ */
189
+ readOnlyAuthenticated: () => ({
190
+ listRule: '@request.auth.id != ""',
191
+ viewRule: '@request.auth.id != ""',
192
+ createRule: null,
193
+ updateRule: null,
194
+ deleteRule: null
195
+ })
196
+ };
197
+ function resolveTemplate(config) {
198
+ let baseRules;
199
+ switch (config.template) {
200
+ case "public":
201
+ baseRules = PermissionTemplates.public();
202
+ break;
203
+ case "authenticated":
204
+ baseRules = PermissionTemplates.authenticated();
205
+ break;
206
+ case "owner-only":
207
+ baseRules = PermissionTemplates.ownerOnly(config.ownerField);
208
+ break;
209
+ case "admin-only":
210
+ baseRules = PermissionTemplates.adminOnly(config.roleField);
211
+ break;
212
+ case "read-public":
213
+ baseRules = PermissionTemplates.readPublic();
214
+ break;
215
+ case "custom":
216
+ baseRules = {};
217
+ break;
218
+ default: {
219
+ const _exhaustive = config.template;
220
+ throw new Error(`Unknown template type: ${_exhaustive}`);
221
+ }
222
+ }
223
+ return {
224
+ ...baseRules,
225
+ ...config.customRules
226
+ };
227
+ }
228
+ function isTemplateConfig(config) {
229
+ return "template" in config;
230
+ }
231
+ function isPermissionSchema(config) {
232
+ return "listRule" in config || "viewRule" in config || "createRule" in config || "updateRule" in config || "deleteRule" in config || "manageRule" in config;
233
+ }
234
+ function validatePermissionConfig(config, isAuthCollection2 = false) {
235
+ const result = {
236
+ valid: true,
237
+ errors: [],
238
+ warnings: []
239
+ };
240
+ let permissions;
241
+ if (isTemplateConfig(config)) {
242
+ if (config.template === "owner-only" && !config.ownerField) {
243
+ result.warnings.push("owner-only template without ownerField specified - using default 'User'");
244
+ }
245
+ if (config.template === "admin-only" && !config.roleField) {
246
+ result.warnings.push("admin-only template without roleField specified - using default 'role'");
247
+ }
248
+ permissions = resolveTemplate(config);
249
+ } else {
250
+ permissions = config;
251
+ }
252
+ if (permissions.manageRule !== void 0 && !isAuthCollection2) {
253
+ result.errors.push("manageRule is only valid for auth collections");
254
+ result.valid = false;
255
+ }
256
+ const ruleTypes = ["listRule", "viewRule", "createRule", "updateRule", "deleteRule"];
257
+ if (isAuthCollection2) {
258
+ ruleTypes.push("manageRule");
259
+ }
260
+ for (const ruleType of ruleTypes) {
261
+ const rule = permissions[ruleType];
262
+ if (rule !== void 0 && rule !== null && rule !== "") {
263
+ const ruleValidation = validateRuleExpression(rule);
264
+ if (!ruleValidation.valid) {
265
+ result.errors.push(`${ruleType}: ${ruleValidation.errors.join(", ")}`);
266
+ result.valid = false;
267
+ }
268
+ result.warnings.push(...ruleValidation.warnings.map((w) => `${ruleType}: ${w}`));
269
+ }
270
+ }
271
+ return result;
272
+ }
273
+ function validateRuleExpression(expression) {
274
+ const result = {
275
+ valid: true,
276
+ errors: [],
277
+ warnings: []
278
+ };
279
+ if (expression === null || expression === "") {
280
+ return result;
281
+ }
282
+ let parenCount = 0;
283
+ for (const char of expression) {
284
+ if (char === "(") parenCount++;
285
+ if (char === ")") parenCount--;
286
+ if (parenCount < 0) {
287
+ result.errors.push("Unbalanced parentheses");
288
+ result.valid = false;
289
+ return result;
290
+ }
291
+ }
292
+ if (parenCount !== 0) {
293
+ result.errors.push("Unbalanced parentheses");
294
+ result.valid = false;
295
+ }
296
+ if (expression.includes("==")) {
297
+ result.warnings.push("Use '=' instead of '==' for equality comparison");
298
+ }
299
+ const requestRefs = expression.match(/@request\.[a-zA-Z_][a-zA-Z0-9_.]*/g) || [];
300
+ for (const ref of requestRefs) {
301
+ const isValid = ref.startsWith("@request.auth.") || ref === "@request.method" || ref === "@request.context" || ref.startsWith("@request.body.") || ref.startsWith("@request.query.") || ref.startsWith("@request.headers.");
302
+ if (!isValid) {
303
+ result.errors.push(`Invalid @request reference: '${ref}'`);
304
+ result.valid = false;
305
+ }
306
+ }
307
+ return result;
308
+ }
309
+ function createPermissions(permissions) {
310
+ return {
311
+ listRule: permissions.listRule ?? null,
312
+ viewRule: permissions.viewRule ?? null,
313
+ createRule: permissions.createRule ?? null,
314
+ updateRule: permissions.updateRule ?? null,
315
+ deleteRule: permissions.deleteRule ?? null,
316
+ manageRule: permissions.manageRule ?? null
317
+ };
318
+ }
319
+ function mergePermissions(...schemas) {
320
+ const merged = {
321
+ listRule: null,
322
+ viewRule: null,
323
+ createRule: null,
324
+ updateRule: null,
325
+ deleteRule: null,
326
+ manageRule: null
327
+ };
328
+ for (const schema of schemas) {
329
+ if (schema.listRule !== void 0) merged.listRule = schema.listRule;
330
+ if (schema.viewRule !== void 0) merged.viewRule = schema.viewRule;
331
+ if (schema.createRule !== void 0) merged.createRule = schema.createRule;
332
+ if (schema.updateRule !== void 0) merged.updateRule = schema.updateRule;
333
+ if (schema.deleteRule !== void 0) merged.deleteRule = schema.deleteRule;
334
+ if (schema.manageRule !== void 0) merged.manageRule = schema.manageRule;
335
+ }
336
+ return merged;
337
+ }
338
+ var ProjectInputSchema = z.object({
339
+ // Required fields
340
+ title: z.string(),
341
+ content: z.string(),
342
+ status: StatusEnum,
343
+ summary: z.string().optional(),
344
+ User: z.string().nonempty("User ID is missing"),
345
+ SubscriberUsers: z.array(z.string())
346
+ }).extend(inputImageFileSchema);
347
+ var ProjectSchema = withPermissions(
348
+ ProjectInputSchema.omit(omitImageFilesSchema).extend(baseImageFileSchema),
349
+ {
350
+ template: "owner-only",
351
+ ownerField: "User",
352
+ customRules: {
353
+ // Override list rule to allow authenticated users to see all projects
354
+ listRule: '@request.auth.id != ""',
355
+ // Allow viewing if user is owner OR a subscriber
356
+ viewRule: '@request.auth.id != "" && (User = @request.auth.id || SubscriberUsers ?= @request.auth.id)'
357
+ }
358
+ }
359
+ );
360
+ var UserInputSchema = z.object({
361
+ name: z.string().min(2, "Name must be longer").optional(),
362
+ email: z.string().email(),
363
+ password: z.string().min(8, "Password must be at least 8 characters"),
364
+ passwordConfirm: z.string(),
365
+ avatar: z.instanceof(File).optional()
366
+ });
367
+ var UserDatabaseSchema = z.object({
368
+ name: z.string().min(2, "Name must be longer").optional(),
369
+ email: z.string().email(),
370
+ password: z.string().min(8, "Password must be at least 8 characters"),
371
+ avatar: z.instanceof(File).optional()
372
+ });
373
+ var UserSchema = withIndexes(
374
+ withPermissions(UserDatabaseSchema.extend(baseSchema), {
375
+ // Users can list other users (for mentions, user search, etc.)
376
+ listRule: "id = @request.auth.id",
377
+ // Users can view their own profile
378
+ viewRule: "id = @request.auth.id",
379
+ // Anyone can create an account (sign up)
380
+ createRule: "",
381
+ // Users can only update their own profile
382
+ updateRule: "id = @request.auth.id",
383
+ // Users can only delete their own account
384
+ deleteRule: "id = @request.auth.id",
385
+ // Users can only manage their own account (change email, password, etc.)
386
+ manageRule: "id = @request.auth.id"
387
+ }),
388
+ [
389
+ // Email should be unique for authentication
390
+ "CREATE UNIQUE INDEX idx_users_email ON users (email)",
391
+ // Index on name for user search and sorting
392
+ "CREATE INDEX idx_users_name ON users (name)"
393
+ ]
394
+ );
395
+ var BaseMutator = class {
396
+ pb;
397
+ // Define a default property that subclasses will override
398
+ options = {
399
+ expand: [],
400
+ filter: [],
401
+ sort: []
402
+ };
403
+ constructor(pb, options) {
404
+ this.pb = pb;
405
+ this.initializeOptions();
406
+ if (options) {
407
+ this.overrideOptions(options);
408
+ }
409
+ }
410
+ initializeOptions() {
411
+ this.options = this.setDefaults();
412
+ }
413
+ /**
414
+ * Initialize options with class-specific defaults
415
+ * Subclasses should override this instead of directly setting options
416
+ */
417
+ setDefaults() {
418
+ return {
419
+ expand: [],
420
+ filter: [],
421
+ sort: []
422
+ };
423
+ }
424
+ /**
425
+ * Merge provided options with current options
426
+ */
427
+ overrideOptions(newOptions) {
428
+ if (newOptions.expand !== void 0) {
429
+ this.options.expand = newOptions.expand;
430
+ }
431
+ if (newOptions.filter !== void 0) {
432
+ this.options.filter = newOptions.filter;
433
+ }
434
+ if (newOptions.sort !== void 0) {
435
+ this.options.sort = newOptions.sort;
436
+ }
437
+ }
438
+ toSnakeCase(str) {
439
+ return str.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
440
+ }
441
+ /**
442
+ * Create a new entity
443
+ */
444
+ async create(input) {
445
+ try {
446
+ const data = await this.validateInput(input);
447
+ const record = await this.entityCreate(data);
448
+ return await this.processRecord(record);
449
+ } catch (error) {
450
+ return this.errorWrapper(error);
451
+ }
452
+ }
453
+ /**
454
+ * Update an existing entity
455
+ */
456
+ async update(id, input) {
457
+ try {
458
+ const record = await this.entityUpdate(id, input);
459
+ return await this.processRecord(record);
460
+ } catch (error) {
461
+ return this.errorWrapper(error);
462
+ }
463
+ }
464
+ /**
465
+ * Create or update entity (upsert)
466
+ */
467
+ async upsert(input) {
468
+ if (input?.id) {
469
+ return await this.update(input.id, input);
470
+ }
471
+ return await this.create(input);
472
+ }
473
+ /**
474
+ * Get entity by ID
475
+ */
476
+ async getById(id, expand) {
477
+ try {
478
+ const record = await this.entityGetById(id, expand);
479
+ return await this.processRecord(record);
480
+ } catch (error) {
481
+ return this.handleError(error, { allowNotFound: true });
482
+ }
483
+ }
484
+ /**
485
+ * Get first entity by filter
486
+ */
487
+ async getFirstByFilter(filter, expand, sort) {
488
+ try {
489
+ const record = await this.entityGetFirstByFilter(filter, expand, sort);
490
+ return await this.processRecord(record);
491
+ } catch (error) {
492
+ return this.handleError(error, { allowNotFound: true });
493
+ }
494
+ }
495
+ /**
496
+ * Get list of entities
497
+ */
498
+ async getList(page = 1, perPage = 100, filter, sort, expand) {
499
+ try {
500
+ const result = await this.entityGetList(page, perPage, filter, sort, expand);
501
+ return await this.processListResult(result);
502
+ } catch (error) {
503
+ return this.errorWrapper(error);
504
+ }
505
+ }
506
+ /**
507
+ * Delete entity by ID
508
+ */
509
+ async delete(id) {
510
+ try {
511
+ return await this.entityDelete(id);
512
+ } catch (error) {
513
+ return this.handleError(error, { returnValue: false });
514
+ }
515
+ }
516
+ /**
517
+ * Process a single record before returning it
518
+ * Can be overridden to handle special cases like mapped entities
519
+ */
520
+ async processRecord(record) {
521
+ return record;
522
+ }
523
+ /**
524
+ * Process a list result before returning it
525
+ * Can be overridden to handle special cases like mapped entities
526
+ */
527
+ async processListResult(result) {
528
+ const processedItems = await Promise.all(result.items.map((item) => this.processRecord(item)));
529
+ return {
530
+ ...result,
531
+ items: processedItems
532
+ };
533
+ }
534
+ /**
535
+ * Prepare expand parameter
536
+ * Combines default expands with provided expands
537
+ */
538
+ prepareExpand(expand) {
539
+ if (!this.options.expand.length && !expand) {
540
+ return void 0;
541
+ }
542
+ let expandArray = [...this.options.expand];
543
+ if (expand) {
544
+ if (typeof expand === "string") {
545
+ expandArray = expandArray.concat(expand.split(",").map((e) => e.trim()));
546
+ } else {
547
+ expandArray = expandArray.concat(expand);
548
+ }
549
+ }
550
+ const uniqueExpands = [...new Set(expandArray)].filter((e) => e !== "" && e !== void 0);
551
+ if (!uniqueExpands.length) {
552
+ return void 0;
553
+ }
554
+ return uniqueExpands.join(",");
555
+ }
556
+ /**
557
+ * Prepare filter parameter
558
+ * Combines default filters with provided filters
559
+ */
560
+ prepareFilter(filter) {
561
+ if (!this.options.filter.length && !filter) {
562
+ return void 0;
563
+ }
564
+ let filterArray = [...this.options.filter];
565
+ if (filter) {
566
+ if (typeof filter === "string") {
567
+ if (filter) filterArray.push(filter);
568
+ } else {
569
+ filterArray = filterArray.concat(filter);
570
+ }
571
+ }
572
+ const validFilters = filterArray.filter((f) => f !== "" && f !== void 0);
573
+ if (!validFilters.length) {
574
+ return void 0;
575
+ }
576
+ return validFilters.join("&&");
577
+ }
578
+ /**
579
+ * Prepare sort parameter
580
+ * Uses provided sort or falls back to default sort
581
+ */
582
+ prepareSort(sort) {
583
+ if (sort && sort !== "") {
584
+ return sort;
585
+ }
586
+ if (this.options.sort.length) {
587
+ const validSorts = this.options.sort.filter((s) => s !== "" && s !== void 0);
588
+ if (validSorts.length) {
589
+ return validSorts.join(",");
590
+ }
591
+ }
592
+ return void 0;
593
+ }
594
+ /**
595
+ * Perform the actual create operation
596
+ */
597
+ async entityCreate(data) {
598
+ return await this.getCollection().create(data);
599
+ }
600
+ /**
601
+ * Perform the actual update operation
602
+ */
603
+ async entityUpdate(id, data) {
604
+ return await this.getCollection().update(id, data);
605
+ }
606
+ /**
607
+ * Perform the actual getById operation
608
+ */
609
+ async entityGetById(id, expand) {
610
+ const finalExpand = this.prepareExpand(expand);
611
+ const options = finalExpand ? { expand: finalExpand } : {};
612
+ return await this.getCollection().getOne(id, options);
613
+ }
614
+ /**
615
+ * Perform the actual getFirstByFilter operation
616
+ */
617
+ async entityGetFirstByFilter(filter, expand, sort) {
618
+ const finalFilter = this.prepareFilter(filter);
619
+ const finalExpand = this.prepareExpand(expand);
620
+ const finalSort = this.prepareSort(sort);
621
+ const options = {};
622
+ if (finalExpand) options.expand = finalExpand;
623
+ if (finalSort) options.sort = finalSort;
624
+ return await this.getCollection().getFirstListItem(finalFilter || "", options);
625
+ }
626
+ /**
627
+ * Perform the actual getList operation
628
+ * Returns a list result with items of type T
629
+ */
630
+ async entityGetList(page, perPage, filter, sort, expand) {
631
+ const finalFilter = this.prepareFilter(filter);
632
+ const finalExpand = this.prepareExpand(expand);
633
+ const finalSort = this.prepareSort(sort);
634
+ const options = {};
635
+ if (finalFilter) options.filter = finalFilter;
636
+ if (finalExpand) options.expand = finalExpand;
637
+ if (finalSort) options.sort = finalSort;
638
+ return await this.getCollection().getList(page, perPage, options);
639
+ }
640
+ /**
641
+ * Perform the actual delete operation
642
+ */
643
+ async entityDelete(id) {
644
+ await this.getCollection().delete(id);
645
+ return true;
646
+ }
647
+ /**
648
+ * Error handler for common errors
649
+ * @param error The error to handle
650
+ * @param options Handler options
651
+ * @returns The value to return if the error is handled, or throws if not handled
652
+ */
653
+ handleError(error, options = { logError: true }) {
654
+ const { allowNotFound = false, returnValue, logError: logError2 = true } = options;
655
+ if (logError2) {
656
+ console.error(`Error in ${this.constructor.name}:`, error);
657
+ }
658
+ if (allowNotFound && this.isNotFoundError(error)) {
659
+ return null;
660
+ }
661
+ if (returnValue !== void 0) {
662
+ return returnValue;
663
+ }
664
+ throw error;
665
+ }
666
+ /**
667
+ * Check if an error is a "not found" error
668
+ */
669
+ isNotFoundError(error) {
670
+ return error instanceof Error && (error.message.includes("404") || error.message.toLowerCase().includes("not found"));
671
+ }
672
+ /**
673
+ * Standard error handling wrapper (legacy method, consider using handleError instead)
674
+ */
675
+ errorWrapper(error) {
676
+ console.error(`Error in ${this.constructor.name}:`, error);
677
+ throw error;
678
+ }
679
+ /**
680
+ * Subscribe to changes on a specific record
681
+ * @param id The ID of the record to subscribe to
682
+ * @param callback Function to call when changes occur
683
+ * @param expand Optional expand parameters
684
+ * @returns Promise that resolves to an unsubscribe function
685
+ */
686
+ async subscribeToRecord(id, callback, expand) {
687
+ const finalExpand = this.prepareExpand(expand);
688
+ const options = finalExpand ? { expand: finalExpand } : {};
689
+ return this.getCollection().subscribe(id, callback, options);
690
+ }
691
+ /**
692
+ * Subscribe to changes on the entire collection
693
+ * @param callback Function to call when changes occur
694
+ * @param expand Optional expand parameters
695
+ * @returns Promise that resolves to an unsubscribe function
696
+ */
697
+ async subscribeToCollection(callback, expand) {
698
+ const finalExpand = this.prepareExpand(expand);
699
+ const options = finalExpand ? { expand: finalExpand } : {};
700
+ return this.getCollection().subscribe("*", callback, options);
701
+ }
702
+ /**
703
+ * Unsubscribe from a specific record's changes
704
+ * @param id The ID of the record to unsubscribe from
705
+ */
706
+ unsubscribeFromRecord(id) {
707
+ this.getCollection().unsubscribe(id);
708
+ }
709
+ /**
710
+ * Unsubscribe from collection-wide changes
711
+ */
712
+ unsubscribeFromCollection() {
713
+ this.getCollection().unsubscribe("*");
714
+ }
715
+ /**
716
+ * Unsubscribe from all subscriptions in this collection
717
+ */
718
+ unsubscribeAll() {
719
+ this.getCollection().unsubscribe();
720
+ }
721
+ };
722
+
723
+ // src/mutator/userMutator.ts
724
+ var UserMutator = class extends BaseMutator {
725
+ setDefaults() {
726
+ return {
727
+ expand: [],
728
+ filter: [],
729
+ sort: ["-updated"]
730
+ };
731
+ }
732
+ getCollection() {
733
+ return this.pb.collection("Projects");
734
+ }
735
+ async validateInput(input) {
736
+ return UserInputSchema.parse(input);
737
+ }
738
+ };
739
+
740
+ // src/migration/errors.ts
741
+ var MigrationError = class _MigrationError extends Error {
742
+ constructor(message) {
743
+ super(message);
744
+ this.name = "MigrationError";
745
+ Object.setPrototypeOf(this, _MigrationError.prototype);
746
+ }
747
+ };
748
+ var SchemaParsingError = class _SchemaParsingError extends MigrationError {
749
+ filePath;
750
+ originalError;
751
+ constructor(message, filePath, originalError) {
752
+ super(message);
753
+ this.name = "SchemaParsingError";
754
+ this.filePath = filePath;
755
+ this.originalError = originalError;
756
+ Object.setPrototypeOf(this, _SchemaParsingError.prototype);
757
+ }
758
+ /**
759
+ * Creates a formatted error message with file path and original error details
760
+ */
761
+ getDetailedMessage() {
762
+ const parts = [this.message];
763
+ if (this.filePath) {
764
+ parts.push(`
765
+ File: ${this.filePath}`);
766
+ }
767
+ if (this.originalError) {
768
+ parts.push(`
769
+ Cause: ${this.originalError.message}`);
770
+ }
771
+ return parts.join("");
772
+ }
773
+ };
774
+ var SnapshotError = class _SnapshotError extends MigrationError {
775
+ snapshotPath;
776
+ operation;
777
+ originalError;
778
+ constructor(message, snapshotPath, operation, originalError) {
779
+ super(message);
780
+ this.name = "SnapshotError";
781
+ this.snapshotPath = snapshotPath;
782
+ this.operation = operation;
783
+ this.originalError = originalError;
784
+ Object.setPrototypeOf(this, _SnapshotError.prototype);
785
+ }
786
+ /**
787
+ * Creates a formatted error message with snapshot path and operation details
788
+ */
789
+ getDetailedMessage() {
790
+ const parts = [this.message];
791
+ if (this.operation) {
792
+ parts.push(`
793
+ Operation: ${this.operation}`);
794
+ }
795
+ if (this.snapshotPath) {
796
+ parts.push(`
797
+ Snapshot: ${this.snapshotPath}`);
798
+ }
799
+ if (this.originalError) {
800
+ parts.push(`
801
+ Cause: ${this.originalError.message}`);
802
+ }
803
+ return parts.join("");
804
+ }
805
+ };
806
+ var MigrationGenerationError = class _MigrationGenerationError extends MigrationError {
807
+ migrationPath;
808
+ originalError;
809
+ constructor(message, migrationPath, originalError) {
810
+ super(message);
811
+ this.name = "MigrationGenerationError";
812
+ this.migrationPath = migrationPath;
813
+ this.originalError = originalError;
814
+ Object.setPrototypeOf(this, _MigrationGenerationError.prototype);
815
+ }
816
+ /**
817
+ * Creates a formatted error message with migration path and original error details
818
+ */
819
+ getDetailedMessage() {
820
+ const parts = [this.message];
821
+ if (this.migrationPath) {
822
+ parts.push(`
823
+ Migration: ${this.migrationPath}`);
824
+ }
825
+ if (this.originalError) {
826
+ parts.push(`
827
+ Cause: ${this.originalError.message}`);
828
+ }
829
+ return parts.join("");
830
+ }
831
+ };
832
+ var FileSystemError = class _FileSystemError extends MigrationError {
833
+ path;
834
+ operation;
835
+ code;
836
+ originalError;
837
+ constructor(message, path6, operation, code, originalError) {
838
+ super(message);
839
+ this.name = "FileSystemError";
840
+ this.path = path6;
841
+ this.operation = operation;
842
+ this.code = code;
843
+ this.originalError = originalError;
844
+ Object.setPrototypeOf(this, _FileSystemError.prototype);
845
+ }
846
+ /**
847
+ * Creates a formatted error message with path, operation, and error code details
848
+ */
849
+ getDetailedMessage() {
850
+ const parts = [this.message];
851
+ if (this.operation) {
852
+ parts.push(`
853
+ Operation: ${this.operation}`);
854
+ }
855
+ if (this.path) {
856
+ parts.push(`
857
+ Path: ${this.path}`);
858
+ }
859
+ if (this.code) {
860
+ parts.push(`
861
+ Error Code: ${this.code}`);
862
+ }
863
+ if (this.originalError) {
864
+ parts.push(`
865
+ Cause: ${this.originalError.message}`);
866
+ }
867
+ return parts.join("");
868
+ }
869
+ };
870
+ var ConfigurationError = class _ConfigurationError extends MigrationError {
871
+ configPath;
872
+ invalidFields;
873
+ originalError;
874
+ constructor(message, configPath, invalidFields, originalError) {
875
+ super(message);
876
+ this.name = "ConfigurationError";
877
+ this.configPath = configPath;
878
+ this.invalidFields = invalidFields;
879
+ this.originalError = originalError;
880
+ Object.setPrototypeOf(this, _ConfigurationError.prototype);
881
+ }
882
+ /**
883
+ * Creates a formatted error message with configuration details
884
+ */
885
+ getDetailedMessage() {
886
+ const parts = [this.message];
887
+ if (this.configPath) {
888
+ parts.push(`
889
+ Configuration File: ${this.configPath}`);
890
+ }
891
+ if (this.invalidFields && this.invalidFields.length > 0) {
892
+ parts.push(`
893
+ Invalid Fields: ${this.invalidFields.join(", ")}`);
894
+ }
895
+ if (this.originalError) {
896
+ parts.push(`
897
+ Cause: ${this.originalError.message}`);
898
+ }
899
+ return parts.join("");
900
+ }
901
+ };
902
+ var CLIUsageError = class _CLIUsageError extends MigrationError {
903
+ command;
904
+ suggestion;
905
+ constructor(message, command, suggestion) {
906
+ super(message);
907
+ this.name = "CLIUsageError";
908
+ this.command = command;
909
+ this.suggestion = suggestion;
910
+ Object.setPrototypeOf(this, _CLIUsageError.prototype);
911
+ }
912
+ /**
913
+ * Creates a formatted error message with usage suggestions
914
+ */
915
+ getDetailedMessage() {
916
+ const parts = [this.message];
917
+ if (this.command) {
918
+ parts.push(`
919
+ Command: ${this.command}`);
920
+ }
921
+ if (this.suggestion) {
922
+ parts.push(`
923
+ Suggestion: ${this.suggestion}`);
924
+ }
925
+ return parts.join("");
926
+ }
927
+ };
928
+
929
+ // src/migration/rule-validator.ts
930
+ var RuleValidator = class {
931
+ fields;
932
+ collectionName;
933
+ isAuthCollection;
934
+ constructor(collectionName, fields, isAuthCollection2 = false) {
935
+ this.collectionName = collectionName;
936
+ this.fields = new Map(fields.map((f) => [f.name, f]));
937
+ this.isAuthCollection = isAuthCollection2;
938
+ this.addSystemFields();
939
+ }
940
+ /**
941
+ * Add system fields that are always available in PocketBase collections
942
+ * These fields are automatically added by PocketBase and can be referenced in rules
943
+ */
944
+ addSystemFields() {
945
+ const systemFields = [
946
+ { name: "id", type: "text", required: true, options: {} },
947
+ { name: "created", type: "date", required: true, options: {} },
948
+ { name: "updated", type: "date", required: true, options: {} },
949
+ { name: "collectionId", type: "text", required: true, options: {} },
950
+ { name: "collectionName", type: "text", required: true, options: {} }
951
+ ];
952
+ if (this.isAuthCollection) {
953
+ systemFields.push(
954
+ { name: "email", type: "email", required: true, options: {} },
955
+ { name: "emailVisibility", type: "bool", required: false, options: {} },
956
+ { name: "verified", type: "bool", required: false, options: {} },
957
+ { name: "tokenKey", type: "text", required: true, options: {} },
958
+ { name: "password", type: "text", required: true, options: {} }
959
+ );
960
+ }
961
+ for (const field of systemFields) {
962
+ if (!this.fields.has(field.name)) {
963
+ this.fields.set(field.name, field);
964
+ }
965
+ }
966
+ }
967
+ /**
968
+ * Validate a rule expression
969
+ *
970
+ * @param ruleType - The type of rule being validated
971
+ * @param expression - The rule expression to validate
972
+ * @returns Validation result with errors, warnings, and field references
973
+ */
974
+ validate(ruleType, expression) {
975
+ const result = {
976
+ valid: true,
977
+ errors: [],
978
+ warnings: [],
979
+ fieldReferences: []
980
+ };
981
+ if (expression === null) {
982
+ return result;
983
+ }
984
+ if (expression === "") {
985
+ result.warnings.push(`${ruleType} is public - anyone can perform this operation`);
986
+ return result;
987
+ }
988
+ if (ruleType === "manageRule" && !this.isAuthCollection) {
989
+ result.valid = false;
990
+ result.errors.push("manageRule is only valid for auth collections");
991
+ return result;
992
+ }
993
+ const fieldRefs = this.extractFieldReferences(expression);
994
+ result.fieldReferences = fieldRefs;
995
+ for (const fieldRef of fieldRefs) {
996
+ this.validateFieldReference(fieldRef, result);
997
+ }
998
+ this.validateRequestReferences(expression, result);
999
+ this.validateSyntax(expression, result);
1000
+ return result;
1001
+ }
1002
+ /**
1003
+ * Extract field references from expression
1004
+ *
1005
+ * Matches field names that are not @request references.
1006
+ * Handles dot notation for relations: user.email, post.author.name
1007
+ *
1008
+ * @param expression - The rule expression
1009
+ * @returns Array of unique field references
1010
+ */
1011
+ extractFieldReferences(expression) {
1012
+ const refs = [];
1013
+ let cleaned = expression.replace(/"[^"]*"/g, '""').replace(/'[^']*'/g, "''");
1014
+ cleaned = cleaned.replace(/@request\.[a-zA-Z_][a-zA-Z0-9_.]*/g, "");
1015
+ const fieldPattern = /(?:^|[^@\w])([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)(?=[^a-zA-Z0-9_.]|$)/g;
1016
+ let match;
1017
+ while ((match = fieldPattern.exec(cleaned)) !== null) {
1018
+ const ref = match[1];
1019
+ if (!this.isKeyword(ref)) {
1020
+ refs.push(ref);
1021
+ }
1022
+ }
1023
+ return [...new Set(refs)];
1024
+ }
1025
+ /**
1026
+ * Check if a word is a PocketBase keyword
1027
+ *
1028
+ * @param word - The word to check
1029
+ * @returns True if the word is a keyword
1030
+ */
1031
+ isKeyword(word) {
1032
+ const keywords = ["true", "false", "null", "AND", "OR", "NOT", "LIKE", "IN"];
1033
+ return keywords.includes(word.toUpperCase());
1034
+ }
1035
+ /**
1036
+ * Validate a field reference exists in schema
1037
+ *
1038
+ * Checks if the root field exists and validates relation chains.
1039
+ * For nested references, warns about potential issues since we can't
1040
+ * validate across collections without loading related schemas.
1041
+ *
1042
+ * @param fieldRef - The field reference to validate (e.g., "user" or "user.email")
1043
+ * @param result - The validation result to update
1044
+ */
1045
+ validateFieldReference(fieldRef, result) {
1046
+ const parts = fieldRef.split(".");
1047
+ const rootField = parts[0];
1048
+ if (!this.fields.has(rootField)) {
1049
+ result.errors.push(`Field '${rootField}' does not exist in collection '${this.collectionName}'`);
1050
+ result.valid = false;
1051
+ return;
1052
+ }
1053
+ if (parts.length > 1) {
1054
+ const field = this.fields.get(rootField);
1055
+ if (field.type !== "relation") {
1056
+ result.errors.push(`Field '${rootField}' is not a relation field, cannot access nested property '${parts[1]}'`);
1057
+ result.valid = false;
1058
+ } else {
1059
+ result.warnings.push(
1060
+ `Nested field reference '${fieldRef}' - ensure target collection has field '${parts.slice(1).join(".")}'`
1061
+ );
1062
+ }
1063
+ }
1064
+ }
1065
+ /**
1066
+ * Validate @request references
1067
+ *
1068
+ * Checks that @request references follow valid PocketBase patterns:
1069
+ * - @request.auth.* - authenticated user data
1070
+ * - @request.body.* - request body fields
1071
+ * - @request.query.* - query parameters
1072
+ * - @request.headers.* - request headers
1073
+ * - @request.method - HTTP method
1074
+ * - @request.context - execution context
1075
+ *
1076
+ * @param expression - The rule expression
1077
+ * @param result - The validation result to update
1078
+ */
1079
+ validateRequestReferences(expression, result) {
1080
+ const requestRefs = expression.match(/@request\.[a-zA-Z_][a-zA-Z0-9_.]*/g) || [];
1081
+ for (const ref of requestRefs) {
1082
+ const isValid = ref.startsWith("@request.auth.") || ref === "@request.method" || ref === "@request.context" || ref.startsWith("@request.body.") || ref.startsWith("@request.query.") || ref.startsWith("@request.headers.");
1083
+ if (!isValid) {
1084
+ result.errors.push(`Invalid @request reference: '${ref}'`);
1085
+ result.valid = false;
1086
+ }
1087
+ }
1088
+ }
1089
+ /**
1090
+ * Validate basic syntax patterns
1091
+ *
1092
+ * Checks for:
1093
+ * - Balanced parentheses
1094
+ * - Common operator mistakes (== instead of =)
1095
+ *
1096
+ * @param expression - The rule expression
1097
+ * @param result - The validation result to update
1098
+ */
1099
+ validateSyntax(expression, result) {
1100
+ let parenCount = 0;
1101
+ for (const char of expression) {
1102
+ if (char === "(") parenCount++;
1103
+ if (char === ")") parenCount--;
1104
+ if (parenCount < 0) {
1105
+ result.errors.push("Unbalanced parentheses in expression");
1106
+ result.valid = false;
1107
+ return;
1108
+ }
1109
+ }
1110
+ if (parenCount !== 0) {
1111
+ result.errors.push("Unbalanced parentheses in expression");
1112
+ result.valid = false;
1113
+ }
1114
+ if (expression.includes("==")) {
1115
+ result.warnings.push("Use '=' instead of '==' for equality comparison in PocketBase rules");
1116
+ }
1117
+ }
1118
+ };
1119
+
1120
+ // src/migration/permission-analyzer.ts
1121
+ var PermissionAnalyzer = class {
1122
+ /**
1123
+ * Extract permission metadata from Zod schema description
1124
+ *
1125
+ * Zod schemas can have permission metadata attached via the describe() method.
1126
+ * This method parses the description and extracts the permission configuration.
1127
+ *
1128
+ * @param schemaDescription - The Zod schema description string
1129
+ * @returns Permission schema if found, null otherwise
1130
+ *
1131
+ * @example
1132
+ * ```typescript
1133
+ * const analyzer = new PermissionAnalyzer();
1134
+ * const permissions = analyzer.extractPermissions(schema.description);
1135
+ * ```
1136
+ */
1137
+ extractPermissions(schemaDescription) {
1138
+ if (!schemaDescription) {
1139
+ return null;
1140
+ }
1141
+ try {
1142
+ const metadata = JSON.parse(schemaDescription);
1143
+ if (metadata.permissions) {
1144
+ return metadata.permissions;
1145
+ }
1146
+ } catch {
1147
+ return null;
1148
+ }
1149
+ return null;
1150
+ }
1151
+ /**
1152
+ * Resolve template configuration to concrete rules
1153
+ *
1154
+ * Takes either a template configuration or a direct permission schema
1155
+ * and returns a fully resolved permission schema with all rules defined.
1156
+ *
1157
+ * If the input is already a permission schema (has rule properties),
1158
+ * it's returned as-is. Otherwise, the template is resolved using the
1159
+ * template resolver.
1160
+ *
1161
+ * @param config - Template configuration or direct permission schema
1162
+ * @returns Resolved permission schema
1163
+ *
1164
+ * @example
1165
+ * ```typescript
1166
+ * const analyzer = new PermissionAnalyzer();
1167
+ *
1168
+ * // Resolve from template
1169
+ * const permissions = analyzer.resolvePermissions({
1170
+ * template: 'owner-only',
1171
+ * ownerField: 'User'
1172
+ * });
1173
+ *
1174
+ * // Or pass direct schema
1175
+ * const permissions = analyzer.resolvePermissions({
1176
+ * listRule: '@request.auth.id != ""',
1177
+ * viewRule: '@request.auth.id != ""'
1178
+ * });
1179
+ * ```
1180
+ */
1181
+ resolvePermissions(config) {
1182
+ if ("listRule" in config || "viewRule" in config || "createRule" in config || "updateRule" in config || "deleteRule" in config || "manageRule" in config) {
1183
+ return config;
1184
+ }
1185
+ return resolveTemplate(config);
1186
+ }
1187
+ /**
1188
+ * Validate all rules in a permission schema
1189
+ *
1190
+ * Validates each rule in the permission schema against the collection's
1191
+ * field definitions. Returns a map of validation results keyed by rule type.
1192
+ *
1193
+ * Only validates rules that are defined (not undefined). Undefined rules
1194
+ * are treated as null (locked) by default.
1195
+ *
1196
+ * @param collectionName - Name of the collection being validated
1197
+ * @param permissions - Permission schema to validate
1198
+ * @param fields - Collection field definitions
1199
+ * @param isAuthCollection - Whether this is an auth collection (allows manageRule)
1200
+ * @returns Map of validation results by rule type
1201
+ *
1202
+ * @example
1203
+ * ```typescript
1204
+ * const analyzer = new PermissionAnalyzer();
1205
+ * const results = analyzer.validatePermissions(
1206
+ * 'posts',
1207
+ * { listRule: '@request.auth.id != ""', viewRule: 'author = @request.auth.id' },
1208
+ * fields,
1209
+ * false
1210
+ * );
1211
+ *
1212
+ * for (const [ruleType, result] of results) {
1213
+ * if (!result.valid) {
1214
+ * console.error(`${ruleType} validation failed:`, result.errors);
1215
+ * }
1216
+ * }
1217
+ * ```
1218
+ */
1219
+ validatePermissions(collectionName, permissions, fields, isAuthCollection2 = false) {
1220
+ const validator = new RuleValidator(collectionName, fields, isAuthCollection2);
1221
+ const results = /* @__PURE__ */ new Map();
1222
+ const ruleTypes = ["listRule", "viewRule", "createRule", "updateRule", "deleteRule"];
1223
+ if (isAuthCollection2) {
1224
+ ruleTypes.push("manageRule");
1225
+ }
1226
+ for (const ruleType of ruleTypes) {
1227
+ const expression = permissions[ruleType];
1228
+ if (expression !== void 0) {
1229
+ results.set(ruleType, validator.validate(ruleType, expression));
1230
+ }
1231
+ }
1232
+ return results;
1233
+ }
1234
+ /**
1235
+ * Merge permissions with defaults
1236
+ *
1237
+ * Ensures all rule types have a defined value. Undefined rules are set
1238
+ * to null (locked to superusers only), which is the PocketBase default.
1239
+ *
1240
+ * This is useful when generating migrations to ensure all rules are
1241
+ * explicitly set in the collection configuration.
1242
+ *
1243
+ * @param permissions - Permission schema (may have undefined rules)
1244
+ * @returns Permission schema with all rules defined (null if not specified)
1245
+ *
1246
+ * @example
1247
+ * ```typescript
1248
+ * const analyzer = new PermissionAnalyzer();
1249
+ * const merged = analyzer.mergeWithDefaults({
1250
+ * listRule: '@request.auth.id != ""'
1251
+ * // other rules undefined
1252
+ * });
1253
+ *
1254
+ * // Result:
1255
+ * // {
1256
+ * // listRule: '@request.auth.id != ""',
1257
+ * // viewRule: null,
1258
+ * // createRule: null,
1259
+ * // updateRule: null,
1260
+ * // deleteRule: null,
1261
+ * // manageRule: null
1262
+ * // }
1263
+ * ```
1264
+ */
1265
+ mergeWithDefaults(permissions) {
1266
+ return {
1267
+ listRule: permissions.listRule ?? null,
1268
+ viewRule: permissions.viewRule ?? null,
1269
+ createRule: permissions.createRule ?? null,
1270
+ updateRule: permissions.updateRule ?? null,
1271
+ deleteRule: permissions.deleteRule ?? null,
1272
+ manageRule: permissions.manageRule ?? null
1273
+ };
1274
+ }
1275
+ };
1276
+
1277
+ // src/migration/utils/pluralize.ts
1278
+ var SPECIAL_CASES = {
1279
+ // Common irregular plurals
1280
+ person: "people",
1281
+ Person: "People",
1282
+ child: "children",
1283
+ Child: "Children",
1284
+ man: "men",
1285
+ Man: "Men",
1286
+ woman: "women",
1287
+ Woman: "Women",
1288
+ tooth: "teeth",
1289
+ Tooth: "Teeth",
1290
+ foot: "feet",
1291
+ Foot: "Feet",
1292
+ mouse: "mice",
1293
+ Mouse: "Mice",
1294
+ goose: "geese",
1295
+ Goose: "Geese",
1296
+ // Words ending in -y
1297
+ category: "categories",
1298
+ Category: "Categories",
1299
+ company: "companies",
1300
+ Company: "Companies",
1301
+ city: "cities",
1302
+ City: "Cities",
1303
+ country: "countries",
1304
+ Country: "Countries",
1305
+ story: "stories",
1306
+ Story: "Stories",
1307
+ party: "parties",
1308
+ Party: "Parties",
1309
+ family: "families",
1310
+ Family: "Families",
1311
+ activity: "activities",
1312
+ Activity: "Activities",
1313
+ priority: "priorities",
1314
+ Priority: "Priorities",
1315
+ // Words ending in -f or -fe
1316
+ life: "lives",
1317
+ Life: "Lives",
1318
+ wife: "wives",
1319
+ Wife: "Wives",
1320
+ knife: "knives",
1321
+ Knife: "Knives",
1322
+ leaf: "leaves",
1323
+ Leaf: "Leaves",
1324
+ shelf: "shelves",
1325
+ Shelf: "Shelves",
1326
+ half: "halves",
1327
+ Half: "Halves",
1328
+ // Words ending in -is
1329
+ analysis: "analyses",
1330
+ Analysis: "Analyses",
1331
+ basis: "bases",
1332
+ Basis: "Bases",
1333
+ crisis: "crises",
1334
+ Crisis: "Crises",
1335
+ thesis: "theses",
1336
+ Thesis: "Theses",
1337
+ // Words ending in -us
1338
+ cactus: "cacti",
1339
+ Cactus: "Cacti",
1340
+ focus: "foci",
1341
+ Focus: "Foci",
1342
+ fungus: "fungi",
1343
+ Fungus: "Fungi",
1344
+ nucleus: "nuclei",
1345
+ Nucleus: "Nuclei",
1346
+ radius: "radii",
1347
+ Radius: "Radii",
1348
+ // Words ending in -on
1349
+ phenomenon: "phenomena",
1350
+ Phenomenon: "Phenomena",
1351
+ criterion: "criteria",
1352
+ Criterion: "Criteria",
1353
+ // Words ending in -um
1354
+ datum: "data",
1355
+ Datum: "Data",
1356
+ medium: "media",
1357
+ Medium: "Media",
1358
+ curriculum: "curricula",
1359
+ Curriculum: "Curricula",
1360
+ // Unchanged plurals
1361
+ sheep: "sheep",
1362
+ Sheep: "Sheep",
1363
+ deer: "deer",
1364
+ Deer: "Deer",
1365
+ fish: "fish",
1366
+ Fish: "Fish",
1367
+ species: "species",
1368
+ Species: "Species",
1369
+ series: "series",
1370
+ Series: "Series"
1371
+ };
1372
+ function pluralize(singular) {
1373
+ if (SPECIAL_CASES[singular]) {
1374
+ return SPECIAL_CASES[singular];
1375
+ }
1376
+ if (singular.length > 3 && singular.endsWith("s") && !singular.endsWith("ss")) {
1377
+ return singular;
1378
+ }
1379
+ const lowerSingular = singular.toLowerCase();
1380
+ let plural;
1381
+ if (/(?:s|ss|sh|ch|x|z)$/.test(lowerSingular)) {
1382
+ plural = singular + "es";
1383
+ } else if (/[^aeiou]y$/.test(lowerSingular)) {
1384
+ plural = singular.slice(0, -1) + "ies";
1385
+ } else if (/[^aeiou]o$/.test(lowerSingular)) {
1386
+ plural = singular + "es";
1387
+ } else if (/fe?$/.test(lowerSingular)) {
1388
+ if (lowerSingular.endsWith("fe")) {
1389
+ plural = singular.slice(0, -2) + "ves";
1390
+ } else {
1391
+ plural = singular.slice(0, -1) + "ves";
1392
+ }
1393
+ } else {
1394
+ plural = singular + "s";
1395
+ }
1396
+ return plural;
1397
+ }
1398
+ function toCollectionName(entityName) {
1399
+ return pluralize(entityName);
1400
+ }
1401
+ function singularize(plural) {
1402
+ for (const [singular, pluralForm] of Object.entries(SPECIAL_CASES)) {
1403
+ if (pluralForm === plural) {
1404
+ return singular;
1405
+ }
1406
+ }
1407
+ const lower = plural.toLowerCase();
1408
+ if (lower.endsWith("ies") && plural.length > 3) {
1409
+ return plural.slice(0, -3) + "y";
1410
+ }
1411
+ if (lower.endsWith("ves")) {
1412
+ return plural.slice(0, -3) + "fe";
1413
+ }
1414
+ if (/(?:ses|shes|ches|xes|zes)$/.test(lower)) {
1415
+ return plural.slice(0, -2);
1416
+ }
1417
+ if (lower.endsWith("s") && plural.length > 1) {
1418
+ return plural.slice(0, -1);
1419
+ }
1420
+ return plural;
1421
+ }
1422
+ function isSingleRelationField(fieldName, zodType) {
1423
+ let unwrappedType = zodType;
1424
+ if (zodType instanceof z.ZodOptional) {
1425
+ unwrappedType = zodType._def.innerType;
1426
+ }
1427
+ if (unwrappedType instanceof z.ZodNullable) {
1428
+ unwrappedType = unwrappedType._def.innerType;
1429
+ }
1430
+ if (unwrappedType instanceof z.ZodDefault) {
1431
+ unwrappedType = unwrappedType._def.innerType;
1432
+ }
1433
+ if (!(unwrappedType instanceof z.ZodString)) {
1434
+ return false;
1435
+ }
1436
+ const startsWithUppercase = /^[A-Z]/.test(fieldName);
1437
+ const commonStringFields = ["Title", "Name", "Description", "Content", "Summary", "Status", "Type"];
1438
+ const isCommonField = commonStringFields.includes(fieldName);
1439
+ return startsWithUppercase && !isCommonField;
1440
+ }
1441
+ function isMultipleRelationField(fieldName, zodType) {
1442
+ let unwrappedType = zodType;
1443
+ if (zodType instanceof z.ZodOptional) {
1444
+ unwrappedType = zodType._def.innerType;
1445
+ }
1446
+ if (unwrappedType instanceof z.ZodNullable) {
1447
+ unwrappedType = unwrappedType._def.innerType;
1448
+ }
1449
+ if (unwrappedType instanceof z.ZodDefault) {
1450
+ unwrappedType = unwrappedType._def.innerType;
1451
+ }
1452
+ if (!(unwrappedType instanceof z.ZodArray)) {
1453
+ return false;
1454
+ }
1455
+ const elementType = unwrappedType._def.type;
1456
+ if (!(elementType instanceof z.ZodString)) {
1457
+ return false;
1458
+ }
1459
+ const hasUppercase = /[A-Z]/.test(fieldName);
1460
+ return hasUppercase;
1461
+ }
1462
+ function resolveTargetCollection(fieldName) {
1463
+ const matches = fieldName.match(/[A-Z][a-z]+/g);
1464
+ if (!matches || matches.length === 0) {
1465
+ return pluralize(fieldName);
1466
+ }
1467
+ const entityName = matches[matches.length - 1];
1468
+ return pluralize(entityName);
1469
+ }
1470
+ function isRelationField(fieldName, zodType) {
1471
+ return isSingleRelationField(fieldName, zodType) || isMultipleRelationField(fieldName, zodType);
1472
+ }
1473
+ function getMaxSelect(fieldName, zodType) {
1474
+ if (isSingleRelationField(fieldName, zodType)) {
1475
+ return 1;
1476
+ }
1477
+ if (isMultipleRelationField(fieldName, zodType)) {
1478
+ let unwrappedType = zodType;
1479
+ if (zodType instanceof z.ZodOptional) {
1480
+ unwrappedType = zodType._def.innerType;
1481
+ }
1482
+ if (unwrappedType instanceof z.ZodNullable) {
1483
+ unwrappedType = unwrappedType._def.innerType;
1484
+ }
1485
+ if (unwrappedType instanceof z.ZodDefault) {
1486
+ unwrappedType = unwrappedType._def.innerType;
1487
+ }
1488
+ if (unwrappedType instanceof z.ZodArray) {
1489
+ const arrayDef = unwrappedType._def;
1490
+ if (arrayDef.maxLength) {
1491
+ return arrayDef.maxLength.value;
1492
+ }
1493
+ return 999;
1494
+ }
1495
+ }
1496
+ return 1;
1497
+ }
1498
+ function getMinSelect(fieldName, zodType) {
1499
+ if (!isMultipleRelationField(fieldName, zodType)) {
1500
+ return void 0;
1501
+ }
1502
+ let unwrappedType = zodType;
1503
+ if (zodType instanceof z.ZodOptional) {
1504
+ unwrappedType = zodType._def.innerType;
1505
+ }
1506
+ if (unwrappedType instanceof z.ZodNullable) {
1507
+ unwrappedType = unwrappedType._def.innerType;
1508
+ }
1509
+ if (unwrappedType instanceof z.ZodDefault) {
1510
+ unwrappedType = unwrappedType._def.innerType;
1511
+ }
1512
+ if (unwrappedType instanceof z.ZodArray) {
1513
+ const arrayDef = unwrappedType._def;
1514
+ if (arrayDef.minLength) {
1515
+ return arrayDef.minLength.value;
1516
+ }
1517
+ }
1518
+ return void 0;
1519
+ }
1520
+ var POCKETBASE_FIELD_TYPES = [
1521
+ "text",
1522
+ "email",
1523
+ "url",
1524
+ "number",
1525
+ "bool",
1526
+ "date",
1527
+ "select",
1528
+ "relation",
1529
+ "file",
1530
+ "json",
1531
+ "editor",
1532
+ "geoPoint",
1533
+ "autodate"
1534
+ ];
1535
+ var FIELD_TYPE_INFO = {
1536
+ text: {
1537
+ type: "text",
1538
+ description: "Plain text field",
1539
+ zodTypes: ["ZodString"],
1540
+ supportsMultiple: false
1541
+ },
1542
+ email: {
1543
+ type: "email",
1544
+ description: "Email address field with validation",
1545
+ zodTypes: ["ZodString with email()"],
1546
+ supportsMultiple: false
1547
+ },
1548
+ url: {
1549
+ type: "url",
1550
+ description: "URL field with validation",
1551
+ zodTypes: ["ZodString with url()"],
1552
+ supportsMultiple: false
1553
+ },
1554
+ editor: {
1555
+ type: "editor",
1556
+ description: "Rich text editor field",
1557
+ zodTypes: ["ZodString"],
1558
+ supportsMultiple: false
1559
+ },
1560
+ number: {
1561
+ type: "number",
1562
+ description: "Numeric field (integer or float)",
1563
+ zodTypes: ["ZodNumber"],
1564
+ supportsMultiple: false
1565
+ },
1566
+ bool: {
1567
+ type: "bool",
1568
+ description: "Boolean field",
1569
+ zodTypes: ["ZodBoolean"],
1570
+ supportsMultiple: false
1571
+ },
1572
+ date: {
1573
+ type: "date",
1574
+ description: "Date/datetime field",
1575
+ zodTypes: ["ZodDate", "ZodString with datetime format"],
1576
+ supportsMultiple: false
1577
+ },
1578
+ autodate: {
1579
+ type: "autodate",
1580
+ description: "Auto-managed date field (created/updated)",
1581
+ zodTypes: ["ZodString"],
1582
+ supportsMultiple: false
1583
+ },
1584
+ select: {
1585
+ type: "select",
1586
+ description: "Single or multiple select from predefined values",
1587
+ zodTypes: ["ZodEnum", "ZodArray<ZodEnum>"],
1588
+ supportsMultiple: true
1589
+ },
1590
+ relation: {
1591
+ type: "relation",
1592
+ description: "Reference to another collection",
1593
+ zodTypes: ["ZodString", "ZodArray<ZodString>"],
1594
+ supportsMultiple: true
1595
+ },
1596
+ file: {
1597
+ type: "file",
1598
+ description: "File upload field",
1599
+ zodTypes: ["File", "ZodArray<File>"],
1600
+ supportsMultiple: true
1601
+ },
1602
+ json: {
1603
+ type: "json",
1604
+ description: "JSON data field",
1605
+ zodTypes: ["ZodRecord", "ZodObject", "ZodArray"],
1606
+ supportsMultiple: false
1607
+ },
1608
+ geoPoint: {
1609
+ type: "geoPoint",
1610
+ description: "Geographic coordinates (lon, lat)",
1611
+ zodTypes: ["ZodObject with lon/lat"],
1612
+ supportsMultiple: false
1613
+ }
1614
+ };
1615
+ function mapZodStringType(zodType) {
1616
+ const checks = zodType._def.checks || [];
1617
+ const hasEmail = checks.some((check) => check.kind === "email");
1618
+ if (hasEmail) {
1619
+ return "email";
1620
+ }
1621
+ const hasUrl = checks.some((check) => check.kind === "url");
1622
+ if (hasUrl) {
1623
+ return "url";
1624
+ }
1625
+ const hasDatetime = checks.some((check) => check.kind === "datetime");
1626
+ if (hasDatetime) {
1627
+ return "date";
1628
+ }
1629
+ return "text";
1630
+ }
1631
+ function mapZodNumberType(_zodType) {
1632
+ return "number";
1633
+ }
1634
+ function mapZodBooleanType(_zodType) {
1635
+ return "bool";
1636
+ }
1637
+ function mapZodEnumType(_zodType) {
1638
+ return "select";
1639
+ }
1640
+ function mapZodArrayType(zodType, _fieldName) {
1641
+ const elementType = zodType._def.type;
1642
+ if (elementType instanceof z.ZodType) {
1643
+ const typeName = elementType._def.typeName;
1644
+ if (typeName === "ZodType" && elementType._def?.innerType?.name === "File") {
1645
+ return "file";
1646
+ }
1647
+ }
1648
+ if (elementType._def?.typeName === "ZodType") {
1649
+ const checks = elementType._def?.checks || [];
1650
+ const isFileInstance = checks.some(
1651
+ (check) => check.kind === "instanceof" || elementType._def?.innerType?.name === "File"
1652
+ );
1653
+ if (isFileInstance) {
1654
+ return "file";
1655
+ }
1656
+ }
1657
+ if (elementType instanceof z.ZodString) {
1658
+ return "relation";
1659
+ }
1660
+ return "json";
1661
+ }
1662
+ function mapZodDateType(_zodType) {
1663
+ return "date";
1664
+ }
1665
+ function mapZodRecordType(_zodType) {
1666
+ return "json";
1667
+ }
1668
+ function mapZodTypeToPocketBase(zodType, fieldName) {
1669
+ let unwrappedType = zodType;
1670
+ if (zodType instanceof z.ZodOptional) {
1671
+ unwrappedType = zodType._def.innerType;
1672
+ }
1673
+ if (unwrappedType instanceof z.ZodNullable) {
1674
+ unwrappedType = unwrappedType._def.innerType;
1675
+ }
1676
+ if (unwrappedType instanceof z.ZodDefault) {
1677
+ unwrappedType = unwrappedType._def.innerType;
1678
+ }
1679
+ if (unwrappedType._def?.typeName === "ZodEffects") {
1680
+ const effect = unwrappedType._def?.effect;
1681
+ if (effect?.type === "refinement") {
1682
+ const fileFieldNames = ["avatar", "image", "file", "attachment", "photo", "picture", "document", "upload"];
1683
+ if (fileFieldNames.some((name) => fieldName.toLowerCase().includes(name))) {
1684
+ return "file";
1685
+ }
1686
+ }
1687
+ }
1688
+ if (unwrappedType._def?.typeName === "ZodType") {
1689
+ const checks = unwrappedType._def?.checks || [];
1690
+ const innerType = unwrappedType._def?.innerType;
1691
+ if (innerType?.name === "File" || checks.some((check) => check.kind === "instanceof")) {
1692
+ return "file";
1693
+ }
1694
+ }
1695
+ if (unwrappedType instanceof z.ZodString) {
1696
+ return mapZodStringType(unwrappedType);
1697
+ }
1698
+ if (unwrappedType instanceof z.ZodNumber) {
1699
+ return mapZodNumberType();
1700
+ }
1701
+ if (unwrappedType instanceof z.ZodBoolean) {
1702
+ return mapZodBooleanType();
1703
+ }
1704
+ if (unwrappedType instanceof z.ZodEnum) {
1705
+ return mapZodEnumType();
1706
+ }
1707
+ if (unwrappedType instanceof z.ZodArray) {
1708
+ return mapZodArrayType(unwrappedType);
1709
+ }
1710
+ if (unwrappedType instanceof z.ZodDate) {
1711
+ return mapZodDateType();
1712
+ }
1713
+ if (unwrappedType instanceof z.ZodRecord || unwrappedType instanceof z.ZodObject) {
1714
+ return mapZodRecordType();
1715
+ }
1716
+ return "text";
1717
+ }
1718
+ function extractFieldOptions(zodType) {
1719
+ const options = {};
1720
+ let unwrappedType = zodType;
1721
+ if (zodType instanceof z.ZodOptional) {
1722
+ unwrappedType = zodType._def.innerType;
1723
+ }
1724
+ if (unwrappedType instanceof z.ZodNullable) {
1725
+ unwrappedType = unwrappedType._def.innerType;
1726
+ }
1727
+ if (unwrappedType instanceof z.ZodDefault) {
1728
+ unwrappedType = unwrappedType._def.innerType;
1729
+ }
1730
+ const checks = unwrappedType._def?.checks || [];
1731
+ if (unwrappedType instanceof z.ZodString) {
1732
+ for (const check of checks) {
1733
+ if (check.kind === "min") {
1734
+ options.min = check.value;
1735
+ }
1736
+ if (check.kind === "max") {
1737
+ options.max = check.value;
1738
+ }
1739
+ if (check.kind === "regex") {
1740
+ options.pattern = check.regex.source;
1741
+ }
1742
+ }
1743
+ }
1744
+ if (unwrappedType instanceof z.ZodNumber) {
1745
+ for (const check of checks) {
1746
+ if (check.kind === "min") {
1747
+ options.min = check.value;
1748
+ }
1749
+ if (check.kind === "max") {
1750
+ options.max = check.value;
1751
+ }
1752
+ }
1753
+ }
1754
+ if (unwrappedType instanceof z.ZodEnum) {
1755
+ options.values = unwrappedType._def.values;
1756
+ }
1757
+ if (unwrappedType instanceof z.ZodArray) {
1758
+ const arrayChecks = unwrappedType._def?.checks || [];
1759
+ for (const check of arrayChecks) {
1760
+ if (check.kind === "min") {
1761
+ options.minSelect = check.value;
1762
+ }
1763
+ if (check.kind === "max") {
1764
+ options.maxSelect = check.value;
1765
+ }
1766
+ }
1767
+ }
1768
+ return options;
1769
+ }
1770
+ function isFieldRequired(zodType) {
1771
+ if (zodType instanceof z.ZodOptional) {
1772
+ return false;
1773
+ }
1774
+ if (zodType instanceof z.ZodDefault) {
1775
+ return false;
1776
+ }
1777
+ if (zodType instanceof z.ZodNullable) {
1778
+ return false;
1779
+ }
1780
+ return true;
1781
+ }
1782
+ function unwrapZodType(zodType) {
1783
+ let unwrapped = zodType;
1784
+ if (unwrapped instanceof z.ZodOptional) {
1785
+ unwrapped = unwrapped._def.innerType;
1786
+ }
1787
+ if (unwrapped instanceof z.ZodNullable) {
1788
+ unwrapped = unwrapped._def.innerType;
1789
+ }
1790
+ if (unwrapped instanceof z.ZodDefault) {
1791
+ unwrapped = unwrapped._def.innerType;
1792
+ }
1793
+ return unwrapped;
1794
+ }
1795
+ function getDefaultValue(zodType) {
1796
+ if (zodType instanceof z.ZodDefault) {
1797
+ return zodType._def.defaultValue();
1798
+ }
1799
+ return void 0;
1800
+ }
1801
+ function isArrayType(zodType) {
1802
+ const unwrapped = unwrapZodType(zodType);
1803
+ return unwrapped instanceof z.ZodArray;
1804
+ }
1805
+ function getArrayElementType(zodType) {
1806
+ const unwrapped = unwrapZodType(zodType);
1807
+ if (unwrapped instanceof z.ZodArray) {
1808
+ return unwrapped._def.type;
1809
+ }
1810
+ return null;
1811
+ }
1812
+ function isGeoPointType(zodType) {
1813
+ const unwrapped = unwrapZodType(zodType);
1814
+ if (!(unwrapped instanceof z.ZodObject)) {
1815
+ return false;
1816
+ }
1817
+ const shape = unwrapped._def.shape();
1818
+ const hasLon = "lon" in shape && shape.lon instanceof z.ZodNumber;
1819
+ const hasLat = "lat" in shape && shape.lat instanceof z.ZodNumber;
1820
+ return hasLon && hasLat;
1821
+ }
1822
+ function extractComprehensiveFieldOptions(zodType) {
1823
+ const options = {};
1824
+ const unwrapped = unwrapZodType(zodType);
1825
+ const checks = unwrapped._def?.checks || [];
1826
+ if (unwrapped instanceof z.ZodString) {
1827
+ for (const check of checks) {
1828
+ if (check.kind === "min") {
1829
+ options.min = check.value;
1830
+ }
1831
+ if (check.kind === "max") {
1832
+ options.max = check.value;
1833
+ }
1834
+ if (check.kind === "regex") {
1835
+ options.pattern = check.regex.source;
1836
+ }
1837
+ }
1838
+ }
1839
+ if (unwrapped instanceof z.ZodNumber) {
1840
+ for (const check of checks) {
1841
+ if (check.kind === "min") {
1842
+ options.min = check.value;
1843
+ }
1844
+ if (check.kind === "max") {
1845
+ options.max = check.value;
1846
+ }
1847
+ }
1848
+ }
1849
+ if (unwrapped instanceof z.ZodEnum) {
1850
+ options.values = unwrapped._def.values;
1851
+ }
1852
+ if (unwrapped instanceof z.ZodArray) {
1853
+ const arrayDef = unwrapped._def;
1854
+ if (arrayDef.minLength) {
1855
+ options.minSelect = arrayDef.minLength.value;
1856
+ }
1857
+ if (arrayDef.maxLength) {
1858
+ options.maxSelect = arrayDef.maxLength.value;
1859
+ }
1860
+ const elementType = arrayDef.type;
1861
+ if (elementType instanceof z.ZodEnum) {
1862
+ options.values = elementType._def.values;
1863
+ }
1864
+ }
1865
+ return options;
1866
+ }
1867
+ function isEditorField(fieldName) {
1868
+ const editorFieldNames = [
1869
+ "content",
1870
+ "body",
1871
+ "description",
1872
+ "bio",
1873
+ "about",
1874
+ "summary",
1875
+ "notes",
1876
+ "details",
1877
+ "html",
1878
+ "richtext",
1879
+ "editor"
1880
+ ];
1881
+ return editorFieldNames.some((name) => fieldName.toLowerCase().includes(name));
1882
+ }
1883
+ function isFileFieldByName(fieldName) {
1884
+ const fileFieldNames = [
1885
+ "avatar",
1886
+ "image",
1887
+ "file",
1888
+ "attachment",
1889
+ "photo",
1890
+ "picture",
1891
+ "document",
1892
+ "upload",
1893
+ "thumbnail",
1894
+ "cover",
1895
+ "banner",
1896
+ "logo",
1897
+ "icon",
1898
+ "media"
1899
+ ];
1900
+ return fileFieldNames.some((name) => fieldName.toLowerCase().includes(name));
1901
+ }
1902
+ function getFieldTypeInfo(zodType, fieldName) {
1903
+ const type = mapZodTypeToPocketBase(zodType, fieldName);
1904
+ const isMultiple = isArrayType(zodType);
1905
+ const options = extractComprehensiveFieldOptions(zodType);
1906
+ return {
1907
+ type,
1908
+ isMultiple,
1909
+ options
1910
+ };
1911
+ }
1912
+
1913
+ // src/migration/analyzer.ts
1914
+ var DEFAULT_CONFIG = {
1915
+ workspaceRoot: process.cwd(),
1916
+ excludePatterns: [
1917
+ "base.ts",
1918
+ "index.ts",
1919
+ "permissions.ts",
1920
+ "permission-templates.ts",
1921
+ "base.js",
1922
+ "index.js",
1923
+ "permissions.js",
1924
+ "permission-templates.js"
1925
+ ],
1926
+ includeExtensions: [".ts", ".js"],
1927
+ schemaPatterns: ["Schema", "InputSchema"],
1928
+ useCompiledFiles: true
1929
+ };
1930
+ function mergeConfig(config) {
1931
+ return {
1932
+ ...DEFAULT_CONFIG,
1933
+ ...config,
1934
+ excludePatterns: config.excludePatterns || DEFAULT_CONFIG.excludePatterns,
1935
+ includeExtensions: config.includeExtensions || DEFAULT_CONFIG.includeExtensions,
1936
+ schemaPatterns: config.schemaPatterns || DEFAULT_CONFIG.schemaPatterns
1937
+ };
1938
+ }
1939
+ function resolveSchemaDir(config) {
1940
+ const workspaceRoot = config.workspaceRoot || process.cwd();
1941
+ if (path4.isAbsolute(config.schemaDir)) {
1942
+ return config.schemaDir;
1943
+ }
1944
+ return path4.join(workspaceRoot, config.schemaDir);
1945
+ }
1946
+ function discoverSchemaFiles(config) {
1947
+ const normalizedConfig = typeof config === "string" ? { schemaDir: config } : config;
1948
+ const mergedConfig = mergeConfig(normalizedConfig);
1949
+ const schemaDir = resolveSchemaDir(normalizedConfig);
1950
+ try {
1951
+ if (!fs2.existsSync(schemaDir)) {
1952
+ throw new FileSystemError(`Schema directory not found: ${schemaDir}`, schemaDir, "access", "ENOENT");
1953
+ }
1954
+ const files = fs2.readdirSync(schemaDir);
1955
+ const schemaFiles = files.filter((file) => {
1956
+ const hasValidExtension = mergedConfig.includeExtensions.some((ext) => file.endsWith(ext));
1957
+ if (!hasValidExtension) return false;
1958
+ const isExcluded = mergedConfig.excludePatterns.some((pattern) => {
1959
+ if (pattern.includes("*")) {
1960
+ const regex = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
1961
+ return regex.test(file);
1962
+ }
1963
+ return file === pattern;
1964
+ });
1965
+ if (isExcluded) return false;
1966
+ return true;
1967
+ });
1968
+ return schemaFiles.map((file) => {
1969
+ const ext = mergedConfig.includeExtensions.find((ext2) => file.endsWith(ext2)) || ".ts";
1970
+ return path4.join(schemaDir, file.replace(new RegExp(`\\${ext}$`), ""));
1971
+ });
1972
+ } catch (error) {
1973
+ if (error instanceof FileSystemError) {
1974
+ throw error;
1975
+ }
1976
+ const fsError = error;
1977
+ if (fsError.code === "EACCES" || fsError.code === "EPERM") {
1978
+ throw new FileSystemError(
1979
+ `Permission denied reading schema directory: ${schemaDir}`,
1980
+ schemaDir,
1981
+ "read",
1982
+ fsError.code,
1983
+ error
1984
+ );
1985
+ }
1986
+ throw new FileSystemError(
1987
+ `Failed to read schema directory: ${schemaDir}`,
1988
+ schemaDir,
1989
+ "read",
1990
+ fsError.code,
1991
+ error
1992
+ );
1993
+ }
1994
+ }
1995
+ async function importSchemaModule(filePath, config) {
1996
+ try {
1997
+ let importPath = filePath;
1998
+ if (config?.pathTransformer) {
1999
+ importPath = config.pathTransformer(filePath);
2000
+ }
2001
+ if (!importPath.endsWith(".js")) {
2002
+ importPath = `${importPath}.js`;
2003
+ }
2004
+ const fileUrl = new URL(`file://${path4.resolve(importPath)}`);
2005
+ const module = await import(fileUrl.href);
2006
+ return module;
2007
+ } catch (error) {
2008
+ throw new SchemaParsingError(
2009
+ `Failed to import schema module. Make sure the schema files are compiled to JavaScript.`,
2010
+ filePath,
2011
+ error
2012
+ );
2013
+ }
2014
+ }
2015
+ function getCollectionNameFromFile(filePath) {
2016
+ const filename = path4.basename(filePath).replace(/\.(ts|js)$/, "");
2017
+ return toCollectionName(filename);
2018
+ }
2019
+ function extractSchemaDefinitions(module, patterns = ["Schema", "InputSchema"]) {
2020
+ const result = {};
2021
+ for (const [key, value] of Object.entries(module)) {
2022
+ if (value instanceof z.ZodObject) {
2023
+ if (patterns.includes("InputSchema") && key.endsWith("InputSchema")) {
2024
+ result.inputSchema = value;
2025
+ } else if (patterns.includes("Schema") && key.endsWith("Schema") && !key.endsWith("InputSchema")) {
2026
+ result.schema = value;
2027
+ }
2028
+ }
2029
+ }
2030
+ return result;
2031
+ }
2032
+ function selectSchemaForCollection(schemas) {
2033
+ if (schemas.schema) {
2034
+ return schemas.schema;
2035
+ }
2036
+ if (schemas.inputSchema) {
2037
+ return schemas.inputSchema;
2038
+ }
2039
+ return null;
2040
+ }
2041
+ function extractFieldDefinitions(zodSchema, excludeFields) {
2042
+ const shape = zodSchema.shape;
2043
+ const fields = [];
2044
+ const baseFields = ["id", "collectionId", "collectionName", "created", "updated", "expand"];
2045
+ const defaultExcludeFields = ["thumbnailURL", "imageFiles"];
2046
+ const allExclusions = /* @__PURE__ */ new Set([...baseFields, ...defaultExcludeFields, ...excludeFields || []]);
2047
+ for (const [fieldName, zodType] of Object.entries(shape)) {
2048
+ if (!allExclusions.has(fieldName)) {
2049
+ fields.push({ name: fieldName, zodType });
2050
+ }
2051
+ }
2052
+ return fields;
2053
+ }
2054
+ function isAuthCollection(fields) {
2055
+ const fieldNames = fields.map((f) => f.name.toLowerCase());
2056
+ const hasEmail = fieldNames.includes("email");
2057
+ const hasPassword = fieldNames.includes("password");
2058
+ return hasEmail && hasPassword;
2059
+ }
2060
+ function buildFieldDefinition(fieldName, zodType) {
2061
+ const fieldType = mapZodTypeToPocketBase(zodType, fieldName);
2062
+ const required = isFieldRequired(zodType);
2063
+ const options = extractFieldOptions(zodType);
2064
+ const fieldDef = {
2065
+ name: fieldName,
2066
+ type: fieldType,
2067
+ required,
2068
+ options
2069
+ };
2070
+ if (isRelationField(fieldName, zodType)) {
2071
+ fieldDef.type = "relation";
2072
+ const targetCollection = resolveTargetCollection(fieldName);
2073
+ const maxSelect = getMaxSelect(fieldName, zodType);
2074
+ const minSelect = getMinSelect(fieldName, zodType);
2075
+ fieldDef.relation = {
2076
+ collection: targetCollection,
2077
+ maxSelect,
2078
+ minSelect,
2079
+ cascadeDelete: false
2080
+ // Default to false, can be configured later
2081
+ };
2082
+ }
2083
+ return fieldDef;
2084
+ }
2085
+ function extractIndexes(schema) {
2086
+ const schemaDescription = schema.description;
2087
+ if (!schemaDescription) {
2088
+ return void 0;
2089
+ }
2090
+ try {
2091
+ const metadata = JSON.parse(schemaDescription);
2092
+ if (metadata.indexes && Array.isArray(metadata.indexes)) {
2093
+ return metadata.indexes;
2094
+ }
2095
+ } catch {
2096
+ }
2097
+ return void 0;
2098
+ }
2099
+ function convertZodSchemaToCollectionSchema(collectionName, zodSchema) {
2100
+ const rawFields = extractFieldDefinitions(zodSchema);
2101
+ const collectionType = isAuthCollection(rawFields) ? "auth" : "base";
2102
+ const fields = rawFields.map(({ name, zodType }) => buildFieldDefinition(name, zodType));
2103
+ const indexes = extractIndexes(zodSchema) || [];
2104
+ const permissionAnalyzer = new PermissionAnalyzer();
2105
+ let permissions = void 0;
2106
+ const schemaDescription = zodSchema.description;
2107
+ const extractedPermissions = permissionAnalyzer.extractPermissions(schemaDescription);
2108
+ if (extractedPermissions) {
2109
+ const resolvedPermissions = permissionAnalyzer.resolvePermissions(extractedPermissions);
2110
+ const validationResults = permissionAnalyzer.validatePermissions(
2111
+ collectionName,
2112
+ resolvedPermissions,
2113
+ fields,
2114
+ collectionType === "auth"
2115
+ );
2116
+ for (const [ruleType, result] of validationResults) {
2117
+ if (!result.valid) {
2118
+ console.error(`[${collectionName}] Permission validation failed for ${ruleType}:`);
2119
+ result.errors.forEach((error) => console.error(` - ${error}`));
2120
+ }
2121
+ if (result.warnings.length > 0) {
2122
+ console.warn(`[${collectionName}] Permission warnings for ${ruleType}:`);
2123
+ result.warnings.forEach((warning) => console.warn(` - ${warning}`));
2124
+ }
2125
+ }
2126
+ permissions = permissionAnalyzer.mergeWithDefaults(resolvedPermissions);
2127
+ }
2128
+ const collectionSchema = {
2129
+ name: collectionName,
2130
+ type: collectionType,
2131
+ fields,
2132
+ indexes,
2133
+ rules: {
2134
+ listRule: null,
2135
+ viewRule: null,
2136
+ createRule: null,
2137
+ updateRule: null,
2138
+ deleteRule: null
2139
+ },
2140
+ permissions
2141
+ };
2142
+ return collectionSchema;
2143
+ }
2144
+ async function buildSchemaDefinition(config) {
2145
+ const normalizedConfig = typeof config === "string" ? { schemaDir: config } : config;
2146
+ const mergedConfig = mergeConfig(normalizedConfig);
2147
+ const collections = /* @__PURE__ */ new Map();
2148
+ const schemaFiles = discoverSchemaFiles(normalizedConfig);
2149
+ if (schemaFiles.length === 0) {
2150
+ const schemaDir = resolveSchemaDir(normalizedConfig);
2151
+ throw new SchemaParsingError(
2152
+ `No schema files found in ${schemaDir}. Make sure you have schema files in the directory.`,
2153
+ schemaDir
2154
+ );
2155
+ }
2156
+ for (const filePath of schemaFiles) {
2157
+ try {
2158
+ let importPath = filePath;
2159
+ if (normalizedConfig.pathTransformer) {
2160
+ importPath = normalizedConfig.pathTransformer(filePath);
2161
+ } else if (mergedConfig.useCompiledFiles) {
2162
+ importPath = filePath.replace(/\/src\//, "/dist/");
2163
+ }
2164
+ const module = await importSchemaModule(importPath, normalizedConfig);
2165
+ const schemas = extractSchemaDefinitions(module, mergedConfig.schemaPatterns);
2166
+ const zodSchema = selectSchemaForCollection(schemas);
2167
+ if (!zodSchema) {
2168
+ console.warn(`No valid schema found in ${filePath}, skipping...`);
2169
+ continue;
2170
+ }
2171
+ const collectionName = getCollectionNameFromFile(filePath);
2172
+ const collectionSchema = convertZodSchemaToCollectionSchema(collectionName, zodSchema);
2173
+ collections.set(collectionName, collectionSchema);
2174
+ } catch (error) {
2175
+ if (error instanceof SchemaParsingError) {
2176
+ throw error;
2177
+ }
2178
+ throw new SchemaParsingError(
2179
+ `Error processing schema file: ${error instanceof Error ? error.message : String(error)}`,
2180
+ filePath,
2181
+ error
2182
+ );
2183
+ }
2184
+ }
2185
+ return { collections };
2186
+ }
2187
+ async function parseSchemaFiles(config) {
2188
+ return buildSchemaDefinition(config);
2189
+ }
2190
+ var SchemaAnalyzer = class {
2191
+ config;
2192
+ constructor(config) {
2193
+ this.config = mergeConfig(config);
2194
+ }
2195
+ /**
2196
+ * Discovers schema files in the configured directory
2197
+ */
2198
+ discoverSchemaFiles() {
2199
+ return discoverSchemaFiles(this.config);
2200
+ }
2201
+ /**
2202
+ * Parses all schema files and returns a SchemaDefinition
2203
+ */
2204
+ async parseSchemaFiles() {
2205
+ return buildSchemaDefinition(this.config);
2206
+ }
2207
+ /**
2208
+ * Converts a single Zod schema to a CollectionSchema
2209
+ */
2210
+ convertZodSchemaToCollectionSchema(name, schema) {
2211
+ return convertZodSchemaToCollectionSchema(name, schema);
2212
+ }
2213
+ };
2214
+ var SNAPSHOT_VERSION = "1.0.0";
2215
+ var DEFAULT_SNAPSHOT_FILENAME = ".migration-snapshot.json";
2216
+ var SNAPSHOT_MIGRATIONS = [
2217
+ // Add migrations here as the format evolves
2218
+ // Example:
2219
+ // {
2220
+ // fromVersion: '0.9.0',
2221
+ // toVersion: '1.0.0',
2222
+ // migrate: (data) => ({ ...data, newField: 'default' })
2223
+ // }
2224
+ ];
2225
+ var DEFAULT_CONFIG2 = {
2226
+ snapshotPath: DEFAULT_SNAPSHOT_FILENAME,
2227
+ workspaceRoot: process.cwd(),
2228
+ autoMigrate: true,
2229
+ version: SNAPSHOT_VERSION
2230
+ };
2231
+ function mergeConfig2(config = {}) {
2232
+ return {
2233
+ ...DEFAULT_CONFIG2,
2234
+ ...config
2235
+ };
2236
+ }
2237
+ function getSnapshotPath(config = {}) {
2238
+ const mergedConfig = mergeConfig2(config);
2239
+ const workspaceRoot = mergedConfig.workspaceRoot;
2240
+ const snapshotFilename = mergedConfig.snapshotPath;
2241
+ if (path4.isAbsolute(snapshotFilename)) {
2242
+ return snapshotFilename;
2243
+ }
2244
+ return path4.join(workspaceRoot, snapshotFilename);
2245
+ }
2246
+ function snapshotExists(config = {}) {
2247
+ try {
2248
+ const snapshotPath = getSnapshotPath(config);
2249
+ return fs2.existsSync(snapshotPath);
2250
+ } catch {
2251
+ return false;
2252
+ }
2253
+ }
2254
+ function handleFileSystemError(error, operation, filePath) {
2255
+ const fsError = error;
2256
+ if (fsError.code === "ENOENT") {
2257
+ throw new SnapshotError(`Snapshot file not found: ${filePath}`, filePath, operation, error);
2258
+ } else if (fsError.code === "EACCES" || fsError.code === "EPERM") {
2259
+ throw new FileSystemError(
2260
+ `Permission denied ${operation === "read" ? "reading" : "writing"} snapshot file. Check file permissions.`,
2261
+ filePath,
2262
+ operation,
2263
+ fsError.code,
2264
+ error
2265
+ );
2266
+ } else if (fsError.code === "ENOSPC") {
2267
+ throw new FileSystemError(
2268
+ `No space left on device when ${operation === "read" ? "reading" : "writing"} snapshot file.`,
2269
+ filePath,
2270
+ operation,
2271
+ fsError.code,
2272
+ error
2273
+ );
2274
+ } else {
2275
+ throw new SnapshotError(`Failed to ${operation} snapshot file: ${error.message}`, filePath, operation, error);
2276
+ }
2277
+ }
2278
+ function serializeMap(map) {
2279
+ const obj = {};
2280
+ for (const [key, value] of map.entries()) {
2281
+ obj[key] = value;
2282
+ }
2283
+ return obj;
2284
+ }
2285
+ function deserializeMap(obj) {
2286
+ const map = /* @__PURE__ */ new Map();
2287
+ for (const [key, value] of Object.entries(obj)) {
2288
+ map.set(key, value);
2289
+ }
2290
+ return map;
2291
+ }
2292
+ function serializeSchemaDefinition(schema) {
2293
+ return {
2294
+ collections: serializeMap(schema.collections)
2295
+ };
2296
+ }
2297
+ function addSnapshotMetadata(schema, config) {
2298
+ const mergedConfig = mergeConfig2(config);
2299
+ return {
2300
+ version: mergedConfig.version,
2301
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2302
+ ...serializeSchemaDefinition(schema)
2303
+ };
2304
+ }
2305
+ function saveSnapshot(schema, config = {}) {
2306
+ const snapshotPath = getSnapshotPath(config);
2307
+ try {
2308
+ const snapshotDir = path4.dirname(snapshotPath);
2309
+ if (!fs2.existsSync(snapshotDir)) {
2310
+ fs2.mkdirSync(snapshotDir, { recursive: true });
2311
+ }
2312
+ const snapshotData = addSnapshotMetadata(schema, config);
2313
+ const jsonContent = JSON.stringify(snapshotData, null, 2);
2314
+ fs2.writeFileSync(snapshotPath, jsonContent, "utf-8");
2315
+ } catch (error) {
2316
+ handleFileSystemError(error, "write", snapshotPath);
2317
+ }
2318
+ }
2319
+ function parseAndValidateSnapshot(jsonContent, snapshotPath) {
2320
+ try {
2321
+ const data = JSON.parse(jsonContent);
2322
+ if (!data.version) {
2323
+ throw new SnapshotError(
2324
+ "Snapshot file is missing version field. The snapshot may be corrupted.",
2325
+ snapshotPath,
2326
+ "validate"
2327
+ );
2328
+ }
2329
+ if (!data.timestamp) {
2330
+ throw new SnapshotError(
2331
+ "Snapshot file is missing timestamp field. The snapshot may be corrupted.",
2332
+ snapshotPath,
2333
+ "validate"
2334
+ );
2335
+ }
2336
+ if (!data.collections) {
2337
+ throw new SnapshotError(
2338
+ "Snapshot file is missing collections field. The snapshot may be corrupted.",
2339
+ snapshotPath,
2340
+ "validate"
2341
+ );
2342
+ }
2343
+ return data;
2344
+ } catch (error) {
2345
+ if (error instanceof SnapshotError) {
2346
+ throw error;
2347
+ }
2348
+ if (error instanceof SyntaxError) {
2349
+ throw new SnapshotError(
2350
+ `Invalid JSON in snapshot file. The file may be corrupted or manually edited incorrectly.`,
2351
+ snapshotPath,
2352
+ "parse",
2353
+ error
2354
+ );
2355
+ }
2356
+ throw error;
2357
+ }
2358
+ }
2359
+ function compareVersions(a, b) {
2360
+ const partsA = a.split(".").map(Number);
2361
+ const partsB = b.split(".").map(Number);
2362
+ for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
2363
+ const numA = partsA[i] || 0;
2364
+ const numB = partsB[i] || 0;
2365
+ if (numA < numB) return -1;
2366
+ if (numA > numB) return 1;
2367
+ }
2368
+ return 0;
2369
+ }
2370
+ function migrateSnapshotFormat(data, config) {
2371
+ const mergedConfig = mergeConfig2(config);
2372
+ const currentVersion = data.version;
2373
+ const targetVersion = mergedConfig.version;
2374
+ if (currentVersion === targetVersion) {
2375
+ return data;
2376
+ }
2377
+ if (!mergedConfig.autoMigrate) {
2378
+ console.warn(
2379
+ `Snapshot version ${currentVersion} differs from current ${targetVersion}, but auto-migrate is disabled.`
2380
+ );
2381
+ return data;
2382
+ }
2383
+ let migratedData = { ...data };
2384
+ let currentMigrationVersion = currentVersion;
2385
+ const sortedMigrations = [...SNAPSHOT_MIGRATIONS].sort((a, b) => compareVersions(a.fromVersion, b.fromVersion));
2386
+ for (const migration of sortedMigrations) {
2387
+ if (compareVersions(currentMigrationVersion, migration.fromVersion) === 0) {
2388
+ console.log(`Migrating snapshot from ${migration.fromVersion} to ${migration.toVersion}...`);
2389
+ migratedData = migration.migrate(migratedData);
2390
+ migratedData.version = migration.toVersion;
2391
+ currentMigrationVersion = migration.toVersion;
2392
+ }
2393
+ }
2394
+ if (compareVersions(currentMigrationVersion, targetVersion) !== 0) {
2395
+ console.warn(`Unknown snapshot version ${currentVersion}, attempting to load anyway...`);
2396
+ }
2397
+ return migratedData;
2398
+ }
2399
+ function deserializeSnapshot(data) {
2400
+ return {
2401
+ version: data.version,
2402
+ timestamp: data.timestamp,
2403
+ collections: deserializeMap(data.collections)
2404
+ };
2405
+ }
2406
+ function loadSnapshot(config = {}) {
2407
+ const snapshotPath = getSnapshotPath(config);
2408
+ try {
2409
+ const jsonContent = fs2.readFileSync(snapshotPath, "utf-8");
2410
+ const data = parseAndValidateSnapshot(jsonContent, snapshotPath);
2411
+ const migratedData = migrateSnapshotFormat(data, config);
2412
+ return deserializeSnapshot(migratedData);
2413
+ } catch (error) {
2414
+ if (error instanceof SnapshotError || error instanceof FileSystemError) {
2415
+ throw error;
2416
+ }
2417
+ if (error.code === "ENOENT") {
2418
+ throw new SnapshotError(
2419
+ `Snapshot file not found. This may be the first migration run.`,
2420
+ snapshotPath,
2421
+ "read",
2422
+ error
2423
+ );
2424
+ }
2425
+ handleFileSystemError(error, "read", snapshotPath);
2426
+ }
2427
+ }
2428
+ function mergeSnapshots(baseSnapshot, customSnapshot) {
2429
+ if (!customSnapshot) {
2430
+ return baseSnapshot;
2431
+ }
2432
+ const mergedCollections = new Map(baseSnapshot.collections);
2433
+ for (const [name, schema] of customSnapshot.collections.entries()) {
2434
+ mergedCollections.set(name, schema);
2435
+ }
2436
+ return {
2437
+ version: customSnapshot.version || baseSnapshot.version,
2438
+ timestamp: customSnapshot.timestamp || baseSnapshot.timestamp,
2439
+ collections: mergedCollections
2440
+ };
2441
+ }
2442
+ function findLatestSnapshot(migrationsPath) {
2443
+ try {
2444
+ if (!fs2.existsSync(migrationsPath)) {
2445
+ return null;
2446
+ }
2447
+ const files = fs2.readdirSync(migrationsPath);
2448
+ const snapshotFiles = files.filter(
2449
+ (file) => file.endsWith("_collections_snapshot.js") || file.endsWith("_snapshot.js")
2450
+ );
2451
+ if (snapshotFiles.length === 0) {
2452
+ return null;
2453
+ }
2454
+ snapshotFiles.sort().reverse();
2455
+ const latestSnapshot = snapshotFiles[0];
2456
+ if (!latestSnapshot) {
2457
+ return null;
2458
+ }
2459
+ return path4.join(migrationsPath, latestSnapshot);
2460
+ } catch (error) {
2461
+ console.warn(`Error finding latest snapshot: ${error}`);
2462
+ return null;
2463
+ }
2464
+ }
2465
+ function loadSnapshotIfExists(config = {}) {
2466
+ const migrationsPath = config.migrationsPath;
2467
+ if (!migrationsPath) {
2468
+ return null;
2469
+ }
2470
+ if (fs2.existsSync(migrationsPath) && fs2.statSync(migrationsPath).isFile()) {
2471
+ try {
2472
+ const migrationContent = fs2.readFileSync(migrationsPath, "utf-8");
2473
+ return convertPocketBaseMigration(migrationContent);
2474
+ } catch (error) {
2475
+ console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);
2476
+ return null;
2477
+ }
2478
+ }
2479
+ const latestSnapshotPath = findLatestSnapshot(migrationsPath);
2480
+ if (latestSnapshotPath) {
2481
+ try {
2482
+ const migrationContent = fs2.readFileSync(latestSnapshotPath, "utf-8");
2483
+ return convertPocketBaseMigration(migrationContent);
2484
+ } catch (error) {
2485
+ console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);
2486
+ return null;
2487
+ }
2488
+ }
2489
+ return null;
2490
+ }
2491
+ function convertPocketBaseCollection(pbCollection) {
2492
+ const fields = [];
2493
+ const systemFieldNames = ["id", "created", "updated", "collectionId", "collectionName", "expand"];
2494
+ const authSystemFieldNames = ["email", "emailVisibility", "verified", "password", "tokenKey"];
2495
+ if (pbCollection.fields && Array.isArray(pbCollection.fields)) {
2496
+ for (const pbField of pbCollection.fields) {
2497
+ if (pbField.system || systemFieldNames.includes(pbField.name)) {
2498
+ continue;
2499
+ }
2500
+ if (pbCollection.type === "auth" && authSystemFieldNames.includes(pbField.name)) {
2501
+ continue;
2502
+ }
2503
+ const field = {
2504
+ name: pbField.name,
2505
+ type: pbField.type,
2506
+ required: pbField.required || false
2507
+ };
2508
+ if (pbField.options) {
2509
+ field.options = pbField.options;
2510
+ }
2511
+ if (pbField.type === "relation") {
2512
+ field.relation = {
2513
+ collection: pbField.options?.collectionId || "",
2514
+ cascadeDelete: pbField.options?.cascadeDelete || false,
2515
+ maxSelect: pbField.options?.maxSelect,
2516
+ minSelect: pbField.options?.minSelect
2517
+ };
2518
+ }
2519
+ fields.push(field);
2520
+ }
2521
+ }
2522
+ const schema = {
2523
+ name: pbCollection.name,
2524
+ type: pbCollection.type || "base",
2525
+ fields
2526
+ };
2527
+ if (pbCollection.indexes && Array.isArray(pbCollection.indexes)) {
2528
+ schema.indexes = pbCollection.indexes;
2529
+ }
2530
+ const rules = {};
2531
+ if (pbCollection.listRule !== void 0) rules.listRule = pbCollection.listRule;
2532
+ if (pbCollection.viewRule !== void 0) rules.viewRule = pbCollection.viewRule;
2533
+ if (pbCollection.createRule !== void 0) rules.createRule = pbCollection.createRule;
2534
+ if (pbCollection.updateRule !== void 0) rules.updateRule = pbCollection.updateRule;
2535
+ if (pbCollection.deleteRule !== void 0) rules.deleteRule = pbCollection.deleteRule;
2536
+ if (pbCollection.manageRule !== void 0) rules.manageRule = pbCollection.manageRule;
2537
+ if (Object.keys(rules).length > 0) {
2538
+ schema.rules = rules;
2539
+ }
2540
+ return schema;
2541
+ }
2542
+ function convertPocketBaseMigration(migrationContent) {
2543
+ try {
2544
+ const snapshotMatch = migrationContent.match(/const\s+snapshot\s*=\s*(\[[\s\S]*?\]);/);
2545
+ if (!snapshotMatch) {
2546
+ throw new Error("Could not find snapshot array in migration file");
2547
+ }
2548
+ const snapshotArrayStr = snapshotMatch[1];
2549
+ let snapshotArray;
2550
+ try {
2551
+ snapshotArray = new Function(`return ${snapshotArrayStr}`)();
2552
+ } catch (parseError) {
2553
+ throw new Error(`Failed to parse snapshot array: ${parseError}`);
2554
+ }
2555
+ if (!Array.isArray(snapshotArray)) {
2556
+ throw new Error("Snapshot is not an array");
2557
+ }
2558
+ const collections = /* @__PURE__ */ new Map();
2559
+ for (const pbCollection of snapshotArray) {
2560
+ if (!pbCollection.name) {
2561
+ console.warn("Skipping collection without name");
2562
+ continue;
2563
+ }
2564
+ const schema = convertPocketBaseCollection(pbCollection);
2565
+ collections.set(pbCollection.name, schema);
2566
+ }
2567
+ return {
2568
+ version: SNAPSHOT_VERSION,
2569
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2570
+ collections
2571
+ };
2572
+ } catch (error) {
2573
+ throw new SnapshotError(
2574
+ `Failed to convert PocketBase migration: ${error instanceof Error ? error.message : String(error)}`,
2575
+ void 0,
2576
+ "parse",
2577
+ error instanceof Error ? error : void 0
2578
+ );
2579
+ }
2580
+ }
2581
+ function loadBaseMigration(migrationPath) {
2582
+ try {
2583
+ if (!fs2.existsSync(migrationPath)) {
2584
+ throw new SnapshotError(
2585
+ `Base migration file not found: ${migrationPath}
2586
+
2587
+ This file should contain PocketBase's initial schema.
2588
+ Please ensure PocketBase is properly set up by running 'yarn setup'.
2589
+ If the file exists in a different location, update the configuration.`,
2590
+ migrationPath,
2591
+ "read"
2592
+ );
2593
+ }
2594
+ const migrationContent = fs2.readFileSync(migrationPath, "utf-8");
2595
+ const snapshot = convertPocketBaseMigration(migrationContent);
2596
+ return snapshot;
2597
+ } catch (error) {
2598
+ if (error instanceof SnapshotError) {
2599
+ throw error;
2600
+ }
2601
+ if (error.code === "ENOENT") {
2602
+ throw new SnapshotError(
2603
+ `Base migration file not found: ${migrationPath}
2604
+
2605
+ This file should contain PocketBase's initial schema.
2606
+ Please ensure PocketBase is properly set up by running 'yarn setup'.`,
2607
+ migrationPath,
2608
+ "read",
2609
+ error
2610
+ );
2611
+ }
2612
+ if (error.code === "EACCES" || error.code === "EPERM") {
2613
+ throw new FileSystemError(
2614
+ `Permission denied reading base migration file. Check file permissions.`,
2615
+ migrationPath,
2616
+ "read",
2617
+ error.code,
2618
+ error
2619
+ );
2620
+ }
2621
+ throw new SnapshotError(
2622
+ `Failed to load base migration: ${error instanceof Error ? error.message : String(error)}`,
2623
+ migrationPath,
2624
+ "read",
2625
+ error instanceof Error ? error : void 0
2626
+ );
2627
+ }
2628
+ }
2629
+ function getSnapshotVersion() {
2630
+ return SNAPSHOT_VERSION;
2631
+ }
2632
+ function validateSnapshot(snapshot) {
2633
+ const issues = [];
2634
+ if (!snapshot.version) {
2635
+ issues.push("Missing version field");
2636
+ } else if (compareVersions(snapshot.version, SNAPSHOT_VERSION) > 0) {
2637
+ issues.push(`Snapshot version ${snapshot.version} is newer than supported version ${SNAPSHOT_VERSION}`);
2638
+ }
2639
+ if (!snapshot.timestamp) {
2640
+ issues.push("Missing timestamp field");
2641
+ }
2642
+ if (!snapshot.collections) {
2643
+ issues.push("Missing collections field");
2644
+ } else if (!(snapshot.collections instanceof Map)) {
2645
+ issues.push("Collections field is not a Map");
2646
+ }
2647
+ return {
2648
+ valid: issues.length === 0,
2649
+ issues
2650
+ };
2651
+ }
2652
+ var SnapshotManager = class {
2653
+ config;
2654
+ constructor(config = {}) {
2655
+ this.config = mergeConfig2(config);
2656
+ }
2657
+ /**
2658
+ * Loads the current snapshot
2659
+ */
2660
+ loadSnapshot() {
2661
+ return loadSnapshot(this.config);
2662
+ }
2663
+ /**
2664
+ * Saves a schema as a snapshot
2665
+ */
2666
+ saveSnapshot(schema) {
2667
+ saveSnapshot(schema, this.config);
2668
+ }
2669
+ /**
2670
+ * Loads snapshot if it exists, returns null otherwise
2671
+ */
2672
+ loadSnapshotIfExists() {
2673
+ return loadSnapshotIfExists(this.config);
2674
+ }
2675
+ /**
2676
+ * Checks if a snapshot exists
2677
+ */
2678
+ snapshotExists() {
2679
+ return snapshotExists(this.config);
2680
+ }
2681
+ /**
2682
+ * Converts a PocketBase migration to a snapshot
2683
+ */
2684
+ convertPocketBaseMigration(content) {
2685
+ return convertPocketBaseMigration(content);
2686
+ }
2687
+ /**
2688
+ * Gets the snapshot file path
2689
+ */
2690
+ getSnapshotPath() {
2691
+ return getSnapshotPath(this.config);
2692
+ }
2693
+ /**
2694
+ * Validates a snapshot
2695
+ */
2696
+ validateSnapshot(snapshot) {
2697
+ return validateSnapshot(snapshot);
2698
+ }
2699
+ };
2700
+
2701
+ // src/migration/diff.ts
2702
+ var DEFAULT_CONFIG3 = {
2703
+ warnOnDelete: true,
2704
+ requireForceForDestructive: true,
2705
+ severityThreshold: "high",
2706
+ systemCollections: ["_mfas", "_otps", "_externalAuths", "_authOrigins", "_superusers"],
2707
+ usersSystemFields: ["id", "password", "tokenKey", "email", "emailVisibility", "verified", "created", "updated"]
2708
+ };
2709
+ function mergeConfig3(config) {
2710
+ return {
2711
+ ...DEFAULT_CONFIG3,
2712
+ ...config
2713
+ };
2714
+ }
2715
+ function isSystemCollection(collectionName, config) {
2716
+ const mergedConfig = mergeConfig3(config);
2717
+ return mergedConfig.systemCollections.includes(collectionName);
2718
+ }
2719
+ function getUsersSystemFields(config) {
2720
+ const mergedConfig = mergeConfig3(config);
2721
+ return new Set(mergedConfig.usersSystemFields);
2722
+ }
2723
+ function filterSystemCollections(schema, config) {
2724
+ const filteredCollections = /* @__PURE__ */ new Map();
2725
+ for (const [collectionName, collectionSchema] of schema.collections) {
2726
+ if (!isSystemCollection(collectionName, config)) {
2727
+ filteredCollections.set(collectionName, collectionSchema);
2728
+ }
2729
+ }
2730
+ return {
2731
+ collections: filteredCollections
2732
+ };
2733
+ }
2734
+ function findNewCollections(currentSchema, previousSnapshot) {
2735
+ const newCollections = [];
2736
+ if (!previousSnapshot) {
2737
+ return Array.from(currentSchema.collections.values());
2738
+ }
2739
+ for (const [collectionName, collectionSchema] of currentSchema.collections) {
2740
+ if (!previousSnapshot.collections.has(collectionName)) {
2741
+ newCollections.push(collectionSchema);
2742
+ }
2743
+ }
2744
+ return newCollections;
2745
+ }
2746
+ function findRemovedCollections(currentSchema, previousSnapshot) {
2747
+ const removedCollections = [];
2748
+ if (!previousSnapshot) {
2749
+ return removedCollections;
2750
+ }
2751
+ for (const [collectionName, collectionSchema] of previousSnapshot.collections) {
2752
+ if (!currentSchema.collections.has(collectionName)) {
2753
+ removedCollections.push(collectionSchema);
2754
+ }
2755
+ }
2756
+ return removedCollections;
2757
+ }
2758
+ function matchCollectionsByName(currentSchema, previousSnapshot) {
2759
+ const matches = [];
2760
+ if (!previousSnapshot) {
2761
+ return matches;
2762
+ }
2763
+ for (const [collectionName, currentCollection] of currentSchema.collections) {
2764
+ const previousCollection = previousSnapshot.collections.get(collectionName);
2765
+ if (previousCollection) {
2766
+ matches.push([currentCollection, previousCollection]);
2767
+ }
2768
+ }
2769
+ return matches;
2770
+ }
2771
+ function findNewFields(currentFields, previousFields) {
2772
+ const newFields = [];
2773
+ const previousFieldNames = new Set(previousFields.map((f) => f.name));
2774
+ for (const currentField of currentFields) {
2775
+ if (!previousFieldNames.has(currentField.name)) {
2776
+ newFields.push(currentField);
2777
+ }
2778
+ }
2779
+ return newFields;
2780
+ }
2781
+ function findRemovedFields(currentFields, previousFields) {
2782
+ const removedFields = [];
2783
+ const currentFieldNames = new Set(currentFields.map((f) => f.name));
2784
+ for (const previousField of previousFields) {
2785
+ if (!currentFieldNames.has(previousField.name)) {
2786
+ removedFields.push(previousField);
2787
+ }
2788
+ }
2789
+ return removedFields;
2790
+ }
2791
+ function matchFieldsByName(currentFields, previousFields) {
2792
+ const matches = [];
2793
+ const previousFieldMap = /* @__PURE__ */ new Map();
2794
+ for (const previousField of previousFields) {
2795
+ previousFieldMap.set(previousField.name, previousField);
2796
+ }
2797
+ for (const currentField of currentFields) {
2798
+ const previousField = previousFieldMap.get(currentField.name);
2799
+ if (previousField) {
2800
+ matches.push([currentField, previousField]);
2801
+ }
2802
+ }
2803
+ return matches;
2804
+ }
2805
+ function areValuesEqual(a, b) {
2806
+ if (a === b) return true;
2807
+ if (a == null || b == null) return false;
2808
+ if (Array.isArray(a) && Array.isArray(b)) {
2809
+ if (a.length !== b.length) return false;
2810
+ return a.every((val, idx) => areValuesEqual(val, b[idx]));
2811
+ }
2812
+ if (typeof a === "object" && typeof b === "object") {
2813
+ const keysA = Object.keys(a);
2814
+ const keysB = Object.keys(b);
2815
+ if (keysA.length !== keysB.length) return false;
2816
+ return keysA.every((key) => areValuesEqual(a[key], b[key]));
2817
+ }
2818
+ return a === b;
2819
+ }
2820
+ function compareFieldTypes(currentField, previousField) {
2821
+ if (currentField.type !== previousField.type) {
2822
+ return {
2823
+ property: "type",
2824
+ oldValue: previousField.type,
2825
+ newValue: currentField.type
2826
+ };
2827
+ }
2828
+ return null;
2829
+ }
2830
+ function compareFieldConstraints(currentField, previousField) {
2831
+ const changes = [];
2832
+ if (currentField.required !== previousField.required) {
2833
+ changes.push({
2834
+ property: "required",
2835
+ oldValue: previousField.required,
2836
+ newValue: currentField.required
2837
+ });
2838
+ }
2839
+ if (currentField.unique !== previousField.unique) {
2840
+ changes.push({
2841
+ property: "unique",
2842
+ oldValue: previousField.unique,
2843
+ newValue: currentField.unique
2844
+ });
2845
+ }
2846
+ return changes;
2847
+ }
2848
+ function compareFieldOptions(currentField, previousField) {
2849
+ const changes = [];
2850
+ const currentOptions = currentField.options || {};
2851
+ const previousOptions = previousField.options || {};
2852
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(currentOptions), ...Object.keys(previousOptions)]);
2853
+ for (const key of allKeys) {
2854
+ const currentValue = currentOptions[key];
2855
+ const previousValue = previousOptions[key];
2856
+ if (!areValuesEqual(currentValue, previousValue)) {
2857
+ changes.push({
2858
+ property: `options.${key}`,
2859
+ oldValue: previousValue,
2860
+ newValue: currentValue
2861
+ });
2862
+ }
2863
+ }
2864
+ return changes;
2865
+ }
2866
+ function compareRelationConfigurations(currentField, previousField) {
2867
+ const changes = [];
2868
+ const currentRelation = currentField.relation;
2869
+ const previousRelation = previousField.relation;
2870
+ if (!currentRelation && !previousRelation) {
2871
+ return changes;
2872
+ }
2873
+ if (!currentRelation || !previousRelation) {
2874
+ return changes;
2875
+ }
2876
+ if (currentRelation.collection !== previousRelation.collection) {
2877
+ changes.push({
2878
+ property: "relation.collection",
2879
+ oldValue: previousRelation.collection,
2880
+ newValue: currentRelation.collection
2881
+ });
2882
+ }
2883
+ if (currentRelation.cascadeDelete !== previousRelation.cascadeDelete) {
2884
+ changes.push({
2885
+ property: "relation.cascadeDelete",
2886
+ oldValue: previousRelation.cascadeDelete,
2887
+ newValue: currentRelation.cascadeDelete
2888
+ });
2889
+ }
2890
+ if (currentRelation.maxSelect !== previousRelation.maxSelect) {
2891
+ changes.push({
2892
+ property: "relation.maxSelect",
2893
+ oldValue: previousRelation.maxSelect,
2894
+ newValue: currentRelation.maxSelect
2895
+ });
2896
+ }
2897
+ if (currentRelation.minSelect !== previousRelation.minSelect) {
2898
+ changes.push({
2899
+ property: "relation.minSelect",
2900
+ oldValue: previousRelation.minSelect,
2901
+ newValue: currentRelation.minSelect
2902
+ });
2903
+ }
2904
+ return changes;
2905
+ }
2906
+ function detectFieldChanges(currentField, previousField) {
2907
+ const changes = [];
2908
+ const typeChange = compareFieldTypes(currentField, previousField);
2909
+ if (typeChange) {
2910
+ changes.push(typeChange);
2911
+ }
2912
+ changes.push(...compareFieldConstraints(currentField, previousField));
2913
+ changes.push(...compareFieldOptions(currentField, previousField));
2914
+ if (currentField.type === "relation" && previousField.type === "relation") {
2915
+ changes.push(...compareRelationConfigurations(currentField, previousField));
2916
+ }
2917
+ return changes;
2918
+ }
2919
+ function compareIndexes(currentIndexes = [], previousIndexes = []) {
2920
+ const currentSet = new Set(currentIndexes);
2921
+ const previousSet = new Set(previousIndexes);
2922
+ const indexesToAdd = currentIndexes.filter((idx) => !previousSet.has(idx));
2923
+ const indexesToRemove = previousIndexes.filter((idx) => !currentSet.has(idx));
2924
+ return { indexesToAdd, indexesToRemove };
2925
+ }
2926
+ function compareRules(currentRules, previousRules) {
2927
+ const updates = [];
2928
+ const ruleTypes = [
2929
+ "listRule",
2930
+ "viewRule",
2931
+ "createRule",
2932
+ "updateRule",
2933
+ "deleteRule",
2934
+ "manageRule"
2935
+ ];
2936
+ for (const ruleType of ruleTypes) {
2937
+ const currentValue = currentRules?.[ruleType] ?? null;
2938
+ const previousValue = previousRules?.[ruleType] ?? null;
2939
+ if (currentValue !== previousValue) {
2940
+ updates.push({
2941
+ ruleType,
2942
+ oldValue: previousValue,
2943
+ newValue: currentValue
2944
+ });
2945
+ }
2946
+ }
2947
+ return updates;
2948
+ }
2949
+ function comparePermissions(currentPermissions, previousPermissions) {
2950
+ const changes = [];
2951
+ const ruleTypes = ["listRule", "viewRule", "createRule", "updateRule", "deleteRule", "manageRule"];
2952
+ for (const ruleType of ruleTypes) {
2953
+ const currentValue = currentPermissions?.[ruleType] ?? null;
2954
+ const previousValue = previousPermissions?.[ruleType] ?? null;
2955
+ if (currentValue !== previousValue) {
2956
+ changes.push({
2957
+ ruleType,
2958
+ oldValue: previousValue,
2959
+ newValue: currentValue
2960
+ });
2961
+ }
2962
+ }
2963
+ return changes;
2964
+ }
2965
+ function compareCollectionFields(currentCollection, previousCollection, config) {
2966
+ let fieldsToAdd = findNewFields(currentCollection.fields, previousCollection.fields);
2967
+ const fieldsToRemove = findRemovedFields(currentCollection.fields, previousCollection.fields);
2968
+ const fieldsToModify = [];
2969
+ if (currentCollection.name === "users") {
2970
+ const systemFields = getUsersSystemFields(config);
2971
+ fieldsToAdd = fieldsToAdd.filter((field) => !systemFields.has(field.name));
2972
+ }
2973
+ const matchedFields = matchFieldsByName(currentCollection.fields, previousCollection.fields);
2974
+ for (const [currentField, previousField] of matchedFields) {
2975
+ const changes = detectFieldChanges(currentField, previousField);
2976
+ if (changes.length > 0) {
2977
+ fieldsToModify.push({
2978
+ fieldName: currentField.name,
2979
+ currentDefinition: previousField,
2980
+ newDefinition: currentField,
2981
+ changes
2982
+ });
2983
+ }
2984
+ }
2985
+ return { fieldsToAdd, fieldsToRemove, fieldsToModify };
2986
+ }
2987
+ function buildCollectionModification(currentCollection, previousCollection, config) {
2988
+ const { fieldsToAdd, fieldsToRemove, fieldsToModify } = compareCollectionFields(
2989
+ currentCollection,
2990
+ previousCollection,
2991
+ config
2992
+ );
2993
+ const { indexesToAdd, indexesToRemove } = compareIndexes(currentCollection.indexes, previousCollection.indexes);
2994
+ const rulesToUpdate = compareRules(currentCollection.rules, previousCollection.rules);
2995
+ const permissionsToUpdate = comparePermissions(currentCollection.permissions, previousCollection.permissions);
2996
+ return {
2997
+ collection: currentCollection.name,
2998
+ fieldsToAdd,
2999
+ fieldsToRemove,
3000
+ fieldsToModify,
3001
+ indexesToAdd,
3002
+ indexesToRemove,
3003
+ rulesToUpdate,
3004
+ permissionsToUpdate
3005
+ };
3006
+ }
3007
+ function hasChanges(modification) {
3008
+ 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;
3009
+ }
3010
+ function aggregateChanges(currentSchema, previousSnapshot, config) {
3011
+ const collectionsToCreate = findNewCollections(currentSchema, previousSnapshot);
3012
+ const collectionsToDelete = findRemovedCollections(currentSchema, previousSnapshot);
3013
+ const filteredCollectionsToCreate = collectionsToCreate.filter(
3014
+ (collection) => !isSystemCollection(collection.name, config)
3015
+ );
3016
+ const filteredCollectionsToDelete = collectionsToDelete.filter(
3017
+ (collection) => !isSystemCollection(collection.name, config)
3018
+ );
3019
+ const collectionsToModify = [];
3020
+ const matchedCollections = matchCollectionsByName(currentSchema, previousSnapshot);
3021
+ for (const [currentCollection, previousCollection] of matchedCollections) {
3022
+ const modification = buildCollectionModification(currentCollection, previousCollection, config);
3023
+ if (hasChanges(modification)) {
3024
+ collectionsToModify.push(modification);
3025
+ }
3026
+ }
3027
+ return {
3028
+ collectionsToCreate: filteredCollectionsToCreate,
3029
+ collectionsToDelete: filteredCollectionsToDelete,
3030
+ collectionsToModify
3031
+ };
3032
+ }
3033
+ function detectDestructiveChanges(diff, config) {
3034
+ const destructiveChanges = [];
3035
+ const mergedConfig = mergeConfig3(config);
3036
+ for (const collection of diff.collectionsToDelete) {
3037
+ destructiveChanges.push({
3038
+ type: "collection_delete",
3039
+ severity: "high",
3040
+ collection: collection.name,
3041
+ description: `Delete collection: ${collection.name}`
3042
+ });
3043
+ }
3044
+ for (const modification of diff.collectionsToModify) {
3045
+ const collectionName = modification.collection;
3046
+ for (const field of modification.fieldsToRemove) {
3047
+ destructiveChanges.push({
3048
+ type: "field_delete",
3049
+ severity: "high",
3050
+ collection: collectionName,
3051
+ field: field.name,
3052
+ description: `Delete field: ${collectionName}.${field.name}`
3053
+ });
3054
+ }
3055
+ for (const fieldMod of modification.fieldsToModify) {
3056
+ const typeChange = fieldMod.changes.find((c) => c.property === "type");
3057
+ const requiredChange = fieldMod.changes.find((c) => c.property === "required" && c.newValue === true);
3058
+ if (typeChange) {
3059
+ destructiveChanges.push({
3060
+ type: "type_change",
3061
+ severity: "high",
3062
+ collection: collectionName,
3063
+ field: fieldMod.fieldName,
3064
+ description: `Change field type: ${collectionName}.${fieldMod.fieldName} (${typeChange.oldValue} \u2192 ${typeChange.newValue})`,
3065
+ oldValue: typeChange.oldValue,
3066
+ newValue: typeChange.newValue
3067
+ });
3068
+ }
3069
+ if (requiredChange && mergedConfig.severityThreshold !== "high") {
3070
+ destructiveChanges.push({
3071
+ type: "required_change",
3072
+ severity: "medium",
3073
+ collection: collectionName,
3074
+ field: fieldMod.fieldName,
3075
+ description: `Make field required: ${collectionName}.${fieldMod.fieldName}`,
3076
+ oldValue: false,
3077
+ newValue: true
3078
+ });
3079
+ }
3080
+ if (mergedConfig.severityThreshold === "low") {
3081
+ const otherChanges = fieldMod.changes.filter((c) => c.property !== "type" && c.property !== "required");
3082
+ for (const change of otherChanges) {
3083
+ destructiveChanges.push({
3084
+ type: "constraint_change",
3085
+ severity: "low",
3086
+ collection: collectionName,
3087
+ field: fieldMod.fieldName,
3088
+ description: `Change constraint: ${collectionName}.${fieldMod.fieldName}.${change.property}`,
3089
+ oldValue: change.oldValue,
3090
+ newValue: change.newValue
3091
+ });
3092
+ }
3093
+ }
3094
+ }
3095
+ }
3096
+ return destructiveChanges;
3097
+ }
3098
+ function categorizeChangesBySeverity(diff, _config) {
3099
+ const destructive = [];
3100
+ const nonDestructive = [];
3101
+ for (const collection of diff.collectionsToDelete) {
3102
+ destructive.push(`Delete collection: ${collection.name}`);
3103
+ }
3104
+ for (const collection of diff.collectionsToCreate) {
3105
+ nonDestructive.push(`Create collection: ${collection.name}`);
3106
+ }
3107
+ for (const modification of diff.collectionsToModify) {
3108
+ const collectionName = modification.collection;
3109
+ for (const field of modification.fieldsToRemove) {
3110
+ destructive.push(`Delete field: ${collectionName}.${field.name}`);
3111
+ }
3112
+ for (const field of modification.fieldsToAdd) {
3113
+ nonDestructive.push(`Add field: ${collectionName}.${field.name}`);
3114
+ }
3115
+ for (const fieldMod of modification.fieldsToModify) {
3116
+ const hasTypeChange = fieldMod.changes.some((c) => c.property === "type");
3117
+ const hasRequiredChange = fieldMod.changes.some((c) => c.property === "required" && c.newValue === true);
3118
+ if (hasTypeChange) {
3119
+ destructive.push(
3120
+ `Change field type: ${collectionName}.${fieldMod.fieldName} (${fieldMod.changes.find((c) => c.property === "type")?.oldValue} \u2192 ${fieldMod.changes.find((c) => c.property === "type")?.newValue})`
3121
+ );
3122
+ } else if (hasRequiredChange) {
3123
+ destructive.push(`Make field required: ${collectionName}.${fieldMod.fieldName}`);
3124
+ } else {
3125
+ nonDestructive.push(`Modify field: ${collectionName}.${fieldMod.fieldName}`);
3126
+ }
3127
+ }
3128
+ for (const _index of modification.indexesToAdd) {
3129
+ nonDestructive.push(`Add index: ${collectionName}`);
3130
+ }
3131
+ for (const _index of modification.indexesToRemove) {
3132
+ nonDestructive.push(`Remove index: ${collectionName}`);
3133
+ }
3134
+ for (const rule of modification.rulesToUpdate) {
3135
+ nonDestructive.push(`Update rule: ${collectionName}.${rule.ruleType}`);
3136
+ }
3137
+ }
3138
+ return { destructive, nonDestructive };
3139
+ }
3140
+ function generateChangeSummary(diff, config) {
3141
+ const destructiveChanges = detectDestructiveChanges(diff, config);
3142
+ const { nonDestructive } = categorizeChangesBySeverity(diff);
3143
+ let fieldsToAdd = 0;
3144
+ let fieldsToRemove = 0;
3145
+ let fieldsToModify = 0;
3146
+ let indexChanges = 0;
3147
+ let ruleChanges = 0;
3148
+ let permissionChanges = 0;
3149
+ for (const modification of diff.collectionsToModify) {
3150
+ fieldsToAdd += modification.fieldsToAdd.length;
3151
+ fieldsToRemove += modification.fieldsToRemove.length;
3152
+ fieldsToModify += modification.fieldsToModify.length;
3153
+ indexChanges += modification.indexesToAdd.length + modification.indexesToRemove.length;
3154
+ ruleChanges += modification.rulesToUpdate.length;
3155
+ permissionChanges += modification.permissionsToUpdate.length;
3156
+ }
3157
+ return {
3158
+ totalChanges: diff.collectionsToCreate.length + diff.collectionsToDelete.length + diff.collectionsToModify.length,
3159
+ collectionsToCreate: diff.collectionsToCreate.length,
3160
+ collectionsToDelete: diff.collectionsToDelete.length,
3161
+ collectionsToModify: diff.collectionsToModify.length,
3162
+ fieldsToAdd,
3163
+ fieldsToRemove,
3164
+ fieldsToModify,
3165
+ indexChanges,
3166
+ ruleChanges,
3167
+ permissionChanges,
3168
+ destructiveChanges,
3169
+ nonDestructiveChanges: nonDestructive
3170
+ };
3171
+ }
3172
+ function requiresForceFlag(diff, config) {
3173
+ const mergedConfig = mergeConfig3(config);
3174
+ if (!mergedConfig.requireForceForDestructive) {
3175
+ return false;
3176
+ }
3177
+ const destructiveChanges = detectDestructiveChanges(diff, config);
3178
+ const relevantChanges = destructiveChanges.filter((change) => {
3179
+ switch (mergedConfig.severityThreshold) {
3180
+ case "high":
3181
+ return change.severity === "high";
3182
+ case "medium":
3183
+ return change.severity === "high" || change.severity === "medium";
3184
+ case "low":
3185
+ return true;
3186
+ default:
3187
+ return change.severity === "high";
3188
+ }
3189
+ });
3190
+ return relevantChanges.length > 0;
3191
+ }
3192
+ function compare(currentSchema, previousSnapshot, config) {
3193
+ return aggregateChanges(currentSchema, previousSnapshot, config);
3194
+ }
3195
+ var DiffEngine = class {
3196
+ config;
3197
+ constructor(config) {
3198
+ this.config = mergeConfig3(config);
3199
+ }
3200
+ /**
3201
+ * Compares current schema with previous snapshot
3202
+ */
3203
+ compare(currentSchema, previousSnapshot) {
3204
+ return compare(currentSchema, previousSnapshot, this.config);
3205
+ }
3206
+ /**
3207
+ * Detects destructive changes in a diff
3208
+ */
3209
+ detectDestructiveChanges(diff) {
3210
+ return detectDestructiveChanges(diff, this.config);
3211
+ }
3212
+ /**
3213
+ * Categorizes changes by severity
3214
+ */
3215
+ categorizeChangesBySeverity(diff) {
3216
+ return categorizeChangesBySeverity(diff, this.config);
3217
+ }
3218
+ /**
3219
+ * Generates a summary of changes
3220
+ */
3221
+ generateChangeSummary(diff) {
3222
+ return generateChangeSummary(diff, this.config);
3223
+ }
3224
+ /**
3225
+ * Checks if force flag is required
3226
+ */
3227
+ requiresForceFlag(diff) {
3228
+ return requiresForceFlag(diff, this.config);
3229
+ }
3230
+ };
3231
+ var DEFAULT_TEMPLATE = `/// <reference path="{{TYPES_PATH}}" />
3232
+ migrate((app) => {
3233
+ {{UP_CODE}}
3234
+ return true;
3235
+ }, (app) => {
3236
+ {{DOWN_CODE}}
3237
+ return true;
3238
+ });
3239
+ `;
3240
+ var DEFAULT_CONFIG4 = {
3241
+ workspaceRoot: process.cwd(),
3242
+ timestampGenerator: () => Math.floor(Date.now() / 1e3).toString(),
3243
+ template: DEFAULT_TEMPLATE,
3244
+ includeTypeReference: true,
3245
+ typesPath: "../pb_data/types.d.ts"
3246
+ };
3247
+ function mergeConfig4(config) {
3248
+ return {
3249
+ ...DEFAULT_CONFIG4,
3250
+ ...config
3251
+ };
3252
+ }
3253
+ function resolveMigrationDir(config) {
3254
+ const workspaceRoot = config.workspaceRoot || process.cwd();
3255
+ if (path4.isAbsolute(config.migrationDir)) {
3256
+ return config.migrationDir;
3257
+ }
3258
+ return path4.join(workspaceRoot, config.migrationDir);
3259
+ }
3260
+ function generateTimestamp(config) {
3261
+ if (config?.timestampGenerator) {
3262
+ return config.timestampGenerator();
3263
+ }
3264
+ return Math.floor(Date.now() / 1e3).toString();
3265
+ }
3266
+ function generateMigrationDescription(diff) {
3267
+ const parts = [];
3268
+ if (diff.collectionsToCreate.length > 0) {
3269
+ if (diff.collectionsToCreate.length === 1) {
3270
+ parts.push(`created_${diff.collectionsToCreate[0].name}`);
3271
+ } else {
3272
+ parts.push(`created_${diff.collectionsToCreate.length}_collections`);
3273
+ }
3274
+ }
3275
+ if (diff.collectionsToDelete.length > 0) {
3276
+ if (diff.collectionsToDelete.length === 1) {
3277
+ parts.push(`deleted_${diff.collectionsToDelete[0].name}`);
3278
+ } else {
3279
+ parts.push(`deleted_${diff.collectionsToDelete.length}_collections`);
3280
+ }
3281
+ }
3282
+ if (diff.collectionsToModify.length > 0) {
3283
+ if (diff.collectionsToModify.length === 1) {
3284
+ parts.push(`updated_${diff.collectionsToModify[0].collection}`);
3285
+ } else {
3286
+ parts.push(`updated_${diff.collectionsToModify.length}_collections`);
3287
+ }
3288
+ }
3289
+ if (parts.length === 0) {
3290
+ return "no_changes";
3291
+ }
3292
+ let description = parts.join("_");
3293
+ if (description.length > 80) {
3294
+ description = description.substring(0, 77) + "...";
3295
+ }
3296
+ return description;
3297
+ }
3298
+ function generateMigrationFilename(diff, config) {
3299
+ const timestamp = generateTimestamp(config);
3300
+ const description = generateMigrationDescription(diff);
3301
+ return `${timestamp}_${description}.js`;
3302
+ }
3303
+ function createMigrationFileStructure(upCode, downCode, config) {
3304
+ const mergedConfig = config ? mergeConfig4(config) : DEFAULT_CONFIG4;
3305
+ let template = mergedConfig.template;
3306
+ template = template.replace("{{TYPES_PATH}}", mergedConfig.typesPath);
3307
+ template = template.replace("{{UP_CODE}}", upCode);
3308
+ template = template.replace("{{DOWN_CODE}}", downCode);
3309
+ if (!mergedConfig.includeTypeReference) {
3310
+ template = template.replace(/\/\/\/ <reference path="[^"]*" \/>\n?/, "");
3311
+ }
3312
+ return template;
3313
+ }
3314
+ function writeMigrationFile(migrationDir, filename, content) {
3315
+ try {
3316
+ if (!fs2.existsSync(migrationDir)) {
3317
+ try {
3318
+ fs2.mkdirSync(migrationDir, { recursive: true });
3319
+ } catch (error) {
3320
+ const fsError = error;
3321
+ if (fsError.code === "EACCES" || fsError.code === "EPERM") {
3322
+ throw new FileSystemError(
3323
+ `Permission denied creating migration directory. Check directory permissions.`,
3324
+ migrationDir,
3325
+ "create",
3326
+ fsError.code,
3327
+ error
3328
+ );
3329
+ }
3330
+ throw new FileSystemError(
3331
+ `Failed to create migration directory: ${fsError.message}`,
3332
+ migrationDir,
3333
+ "create",
3334
+ fsError.code,
3335
+ error
3336
+ );
3337
+ }
3338
+ }
3339
+ const filePath = path4.join(migrationDir, filename);
3340
+ fs2.writeFileSync(filePath, content, "utf-8");
3341
+ return filePath;
3342
+ } catch (error) {
3343
+ if (error instanceof FileSystemError) {
3344
+ throw error;
3345
+ }
3346
+ const fsError = error;
3347
+ const filePath = path4.join(migrationDir, filename);
3348
+ if (fsError.code === "EACCES" || fsError.code === "EPERM") {
3349
+ throw new FileSystemError(
3350
+ `Permission denied writing migration file. Check file and directory permissions.`,
3351
+ filePath,
3352
+ "write",
3353
+ fsError.code,
3354
+ error
3355
+ );
3356
+ } else if (fsError.code === "ENOSPC") {
3357
+ throw new FileSystemError(
3358
+ `No space left on device when writing migration file.`,
3359
+ filePath,
3360
+ "write",
3361
+ fsError.code,
3362
+ error
3363
+ );
3364
+ }
3365
+ throw new MigrationGenerationError(`Failed to write migration file: ${fsError.message}`, filePath, error);
3366
+ }
3367
+ }
3368
+ function formatValue(value) {
3369
+ if (value === null || value === void 0) {
3370
+ return "null";
3371
+ }
3372
+ if (typeof value === "string") {
3373
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
3374
+ }
3375
+ if (typeof value === "number" || typeof value === "boolean") {
3376
+ return String(value);
3377
+ }
3378
+ if (Array.isArray(value)) {
3379
+ const items = value.map((v) => formatValue(v)).join(", ");
3380
+ return `[${items}]`;
3381
+ }
3382
+ if (typeof value === "object") {
3383
+ const entries = Object.entries(value).map(([k, v]) => `${k}: ${formatValue(v)}`).join(", ");
3384
+ return `{ ${entries} }`;
3385
+ }
3386
+ return String(value);
3387
+ }
3388
+ function generateFieldDefinitionObject(field) {
3389
+ const parts = [];
3390
+ parts.push(` name: "${field.name}"`);
3391
+ parts.push(` type: "${field.type}"`);
3392
+ parts.push(` required: ${field.required}`);
3393
+ if (field.unique !== void 0) {
3394
+ parts.push(` unique: ${field.unique}`);
3395
+ }
3396
+ if (field.options && Object.keys(field.options).length > 0) {
3397
+ for (const [key, value] of Object.entries(field.options)) {
3398
+ parts.push(` ${key}: ${formatValue(value)}`);
3399
+ }
3400
+ }
3401
+ if (field.relation) {
3402
+ const collectionIdPlaceholder = field.relation.collection === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
3403
+ parts.push(` collectionId: ${collectionIdPlaceholder}`);
3404
+ if (field.relation.maxSelect !== void 0) {
3405
+ parts.push(` maxSelect: ${field.relation.maxSelect}`);
3406
+ }
3407
+ if (field.relation.minSelect !== void 0) {
3408
+ parts.push(` minSelect: ${field.relation.minSelect}`);
3409
+ }
3410
+ if (field.relation.cascadeDelete !== void 0) {
3411
+ parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
3412
+ }
3413
+ }
3414
+ return ` {
3415
+ ${parts.join(",\n")},
3416
+ }`;
3417
+ }
3418
+ function generateFieldsArray(fields) {
3419
+ if (fields.length === 0) {
3420
+ return "[]";
3421
+ }
3422
+ const fieldObjects = fields.map((field) => generateFieldDefinitionObject(field));
3423
+ return `[
3424
+ ${fieldObjects.join(",\n")},
3425
+ ]`;
3426
+ }
3427
+ function generateCollectionRules(rules) {
3428
+ if (!rules) {
3429
+ return "";
3430
+ }
3431
+ const parts = [];
3432
+ if (rules.listRule !== void 0) {
3433
+ parts.push(`listRule: ${formatValue(rules.listRule)}`);
3434
+ }
3435
+ if (rules.viewRule !== void 0) {
3436
+ parts.push(`viewRule: ${formatValue(rules.viewRule)}`);
3437
+ }
3438
+ if (rules.createRule !== void 0) {
3439
+ parts.push(`createRule: ${formatValue(rules.createRule)}`);
3440
+ }
3441
+ if (rules.updateRule !== void 0) {
3442
+ parts.push(`updateRule: ${formatValue(rules.updateRule)}`);
3443
+ }
3444
+ if (rules.deleteRule !== void 0) {
3445
+ parts.push(`deleteRule: ${formatValue(rules.deleteRule)}`);
3446
+ }
3447
+ if (rules.manageRule !== void 0) {
3448
+ parts.push(`manageRule: ${formatValue(rules.manageRule)}`);
3449
+ }
3450
+ return parts.join(",\n ");
3451
+ }
3452
+ function generateCollectionPermissions(permissions) {
3453
+ if (!permissions) {
3454
+ return "";
3455
+ }
3456
+ const parts = [];
3457
+ if (permissions.listRule !== void 0) {
3458
+ parts.push(`listRule: ${formatValue(permissions.listRule)}`);
3459
+ }
3460
+ if (permissions.viewRule !== void 0) {
3461
+ parts.push(`viewRule: ${formatValue(permissions.viewRule)}`);
3462
+ }
3463
+ if (permissions.createRule !== void 0) {
3464
+ parts.push(`createRule: ${formatValue(permissions.createRule)}`);
3465
+ }
3466
+ if (permissions.updateRule !== void 0) {
3467
+ parts.push(`updateRule: ${formatValue(permissions.updateRule)}`);
3468
+ }
3469
+ if (permissions.deleteRule !== void 0) {
3470
+ parts.push(`deleteRule: ${formatValue(permissions.deleteRule)}`);
3471
+ }
3472
+ if (permissions.manageRule !== void 0) {
3473
+ parts.push(`manageRule: ${formatValue(permissions.manageRule)}`);
3474
+ }
3475
+ return parts.join(",\n ");
3476
+ }
3477
+ function generateIndexesArray(indexes) {
3478
+ if (!indexes || indexes.length === 0) {
3479
+ return "[]";
3480
+ }
3481
+ const indexStrings = indexes.map((idx) => `"${idx}"`);
3482
+ return `[
3483
+ ${indexStrings.join(",\n ")},
3484
+ ]`;
3485
+ }
3486
+ function generateCollectionCreation(collection, varName = "collection") {
3487
+ const lines = [];
3488
+ lines.push(` const ${varName} = new Collection({`);
3489
+ lines.push(` name: "${collection.name}",`);
3490
+ lines.push(` type: "${collection.type}",`);
3491
+ const permissionsCode = generateCollectionPermissions(collection.permissions);
3492
+ const rulesCode = generateCollectionRules(collection.rules);
3493
+ if (permissionsCode) {
3494
+ lines.push(` ${permissionsCode},`);
3495
+ } else if (rulesCode) {
3496
+ lines.push(` ${rulesCode},`);
3497
+ }
3498
+ lines.push(` fields: ${generateFieldsArray(collection.fields)},`);
3499
+ lines.push(` indexes: ${generateIndexesArray(collection.indexes)},`);
3500
+ lines.push(` });`);
3501
+ lines.push(``);
3502
+ lines.push(` app.save(${varName});`);
3503
+ return lines.join("\n");
3504
+ }
3505
+ function getFieldConstructorName(fieldType) {
3506
+ const constructorMap = {
3507
+ text: "TextField",
3508
+ email: "EmailField",
3509
+ url: "URLField",
3510
+ number: "NumberField",
3511
+ bool: "BoolField",
3512
+ date: "DateField",
3513
+ select: "SelectField",
3514
+ relation: "RelationField",
3515
+ file: "FileField",
3516
+ json: "JSONField"
3517
+ };
3518
+ return constructorMap[fieldType] || "TextField";
3519
+ }
3520
+ function generateFieldConstructorOptions(field) {
3521
+ const parts = [];
3522
+ parts.push(` name: "${field.name}"`);
3523
+ parts.push(` required: ${field.required}`);
3524
+ if (field.unique !== void 0) {
3525
+ parts.push(` unique: ${field.unique}`);
3526
+ }
3527
+ if (field.options && Object.keys(field.options).length > 0) {
3528
+ for (const [key, value] of Object.entries(field.options)) {
3529
+ parts.push(` ${key}: ${formatValue(value)}`);
3530
+ }
3531
+ }
3532
+ if (field.relation && field.type === "relation") {
3533
+ const collectionIdPlaceholder = field.relation.collection === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
3534
+ parts.push(` collectionId: ${collectionIdPlaceholder}`);
3535
+ if (field.relation.maxSelect !== void 0) {
3536
+ parts.push(` maxSelect: ${field.relation.maxSelect}`);
3537
+ }
3538
+ if (field.relation.minSelect !== void 0) {
3539
+ parts.push(` minSelect: ${field.relation.minSelect}`);
3540
+ }
3541
+ if (field.relation.cascadeDelete !== void 0) {
3542
+ parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
3543
+ }
3544
+ }
3545
+ return parts.join(",\n");
3546
+ }
3547
+ function generateFieldAddition(collectionName, field, varName) {
3548
+ const lines = [];
3549
+ const constructorName = getFieldConstructorName(field.type);
3550
+ const collectionVar = varName || `collection_${collectionName}_${field.name}`;
3551
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
3552
+ lines.push(``);
3553
+ lines.push(` ${collectionVar}.fields.add(new ${constructorName}({`);
3554
+ lines.push(generateFieldConstructorOptions(field));
3555
+ lines.push(` }));`);
3556
+ lines.push(``);
3557
+ lines.push(` app.save(${collectionVar});`);
3558
+ return lines.join("\n");
3559
+ }
3560
+ function generateFieldModification(collectionName, modification, varName) {
3561
+ const lines = [];
3562
+ const collectionVar = varName || `collection_${collectionName}_${modification.fieldName}`;
3563
+ const fieldVar = `${collectionVar}_field`;
3564
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
3565
+ lines.push(` const ${fieldVar} = ${collectionVar}.fields.getByName("${modification.fieldName}");`);
3566
+ lines.push(``);
3567
+ for (const change of modification.changes) {
3568
+ if (change.property.startsWith("options.")) {
3569
+ const optionKey = change.property.replace("options.", "");
3570
+ lines.push(` ${fieldVar}.${optionKey} = ${formatValue(change.newValue)};`);
3571
+ } else if (change.property.startsWith("relation.")) {
3572
+ const relationKey = change.property.replace("relation.", "");
3573
+ if (relationKey === "collection") {
3574
+ const collectionIdValue = change.newValue === "Users" ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${change.newValue}").id`;
3575
+ lines.push(` ${fieldVar}.collectionId = ${collectionIdValue};`);
3576
+ } else {
3577
+ lines.push(` ${fieldVar}.${relationKey} = ${formatValue(change.newValue)};`);
3578
+ }
3579
+ } else {
3580
+ lines.push(` ${fieldVar}.${change.property} = ${formatValue(change.newValue)};`);
3581
+ }
3582
+ }
3583
+ lines.push(``);
3584
+ lines.push(` app.save(${collectionVar});`);
3585
+ return lines.join("\n");
3586
+ }
3587
+ function generateFieldDeletion(collectionName, fieldName, varName) {
3588
+ const lines = [];
3589
+ const collectionVar = varName || `collection_${collectionName}_${fieldName}`;
3590
+ const fieldVar = `${collectionVar}_field`;
3591
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
3592
+ lines.push(` const ${fieldVar} = ${collectionVar}.fields.getByName("${fieldName}");`);
3593
+ lines.push(``);
3594
+ lines.push(` ${collectionVar}.fields.remove(${fieldVar}.id);`);
3595
+ lines.push(``);
3596
+ lines.push(` app.save(${collectionVar});`);
3597
+ return lines.join("\n");
3598
+ }
3599
+ function generateIndexAddition(collectionName, index, varName) {
3600
+ const lines = [];
3601
+ const collectionVar = varName || `collection_${collectionName}_idx`;
3602
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
3603
+ lines.push(` ${collectionVar}.indexes.push("${index}");`);
3604
+ lines.push(` app.save(${collectionVar});`);
3605
+ return lines.join("\n");
3606
+ }
3607
+ function generateIndexRemoval(collectionName, index, varName) {
3608
+ const lines = [];
3609
+ const collectionVar = varName || `collection_${collectionName}_idx`;
3610
+ const indexVar = `${collectionVar}_indexToRemove`;
3611
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
3612
+ lines.push(` const ${indexVar} = ${collectionVar}.indexes.findIndex(idx => idx === "${index}");`);
3613
+ lines.push(` if (${indexVar} !== -1) {`);
3614
+ lines.push(` ${collectionVar}.indexes.splice(${indexVar}, 1);`);
3615
+ lines.push(` }`);
3616
+ lines.push(` app.save(${collectionVar});`);
3617
+ return lines.join("\n");
3618
+ }
3619
+ function generateRuleUpdate(collectionName, ruleType, newValue, varName) {
3620
+ const lines = [];
3621
+ const collectionVar = varName || `collection_${collectionName}_${ruleType}`;
3622
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
3623
+ lines.push(` ${collectionVar}.${ruleType} = ${formatValue(newValue)};`);
3624
+ lines.push(` app.save(${collectionVar});`);
3625
+ return lines.join("\n");
3626
+ }
3627
+ function generatePermissionUpdate(collectionName, ruleType, newValue, varName) {
3628
+ const lines = [];
3629
+ const collectionVar = varName || `collection_${collectionName}_${ruleType}`;
3630
+ lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
3631
+ lines.push(` ${collectionVar}.${ruleType} = ${formatValue(newValue)};`);
3632
+ lines.push(` app.save(${collectionVar});`);
3633
+ return lines.join("\n");
3634
+ }
3635
+ function generateCollectionDeletion(collectionName, varName = "collection") {
3636
+ const lines = [];
3637
+ lines.push(` const ${varName} = app.findCollectionByNameOrId("${collectionName}");`);
3638
+ lines.push(` app.delete(${varName});`);
3639
+ return lines.join("\n");
3640
+ }
3641
+ function generateUpMigration(diff) {
3642
+ const lines = [];
3643
+ lines.push(` // UP MIGRATION`);
3644
+ lines.push(``);
3645
+ if (diff.collectionsToCreate.length > 0) {
3646
+ lines.push(` // Create new collections`);
3647
+ for (let i = 0; i < diff.collectionsToCreate.length; i++) {
3648
+ const collection = diff.collectionsToCreate[i];
3649
+ const varName = `collection_${collection.name}_create`;
3650
+ lines.push(generateCollectionCreation(collection, varName));
3651
+ lines.push(``);
3652
+ }
3653
+ }
3654
+ if (diff.collectionsToModify.length > 0) {
3655
+ lines.push(` // Modify existing collections`);
3656
+ for (const modification of diff.collectionsToModify) {
3657
+ const collectionName = modification.collection;
3658
+ if (modification.fieldsToAdd.length > 0) {
3659
+ lines.push(` // Add fields to ${collectionName}`);
3660
+ for (const field of modification.fieldsToAdd) {
3661
+ const varName = `collection_${collectionName}_add_${field.name}`;
3662
+ lines.push(generateFieldAddition(collectionName, field, varName));
3663
+ lines.push(``);
3664
+ }
3665
+ }
3666
+ if (modification.fieldsToModify.length > 0) {
3667
+ lines.push(` // Modify fields in ${collectionName}`);
3668
+ for (const fieldMod of modification.fieldsToModify) {
3669
+ const varName = `collection_${collectionName}_modify_${fieldMod.fieldName}`;
3670
+ lines.push(generateFieldModification(collectionName, fieldMod, varName));
3671
+ lines.push(``);
3672
+ }
3673
+ }
3674
+ if (modification.fieldsToRemove.length > 0) {
3675
+ lines.push(` // Remove fields from ${collectionName}`);
3676
+ for (const field of modification.fieldsToRemove) {
3677
+ const varName = `collection_${collectionName}_remove_${field.name}`;
3678
+ lines.push(generateFieldDeletion(collectionName, field.name, varName));
3679
+ lines.push(``);
3680
+ }
3681
+ }
3682
+ if (modification.indexesToAdd.length > 0) {
3683
+ lines.push(` // Add indexes to ${collectionName}`);
3684
+ for (let i = 0; i < modification.indexesToAdd.length; i++) {
3685
+ const index = modification.indexesToAdd[i];
3686
+ const varName = `collection_${collectionName}_addidx_${i}`;
3687
+ lines.push(generateIndexAddition(collectionName, index, varName));
3688
+ lines.push(``);
3689
+ }
3690
+ }
3691
+ if (modification.indexesToRemove.length > 0) {
3692
+ lines.push(` // Remove indexes from ${collectionName}`);
3693
+ for (let i = 0; i < modification.indexesToRemove.length; i++) {
3694
+ const index = modification.indexesToRemove[i];
3695
+ const varName = `collection_${collectionName}_rmidx_${i}`;
3696
+ lines.push(generateIndexRemoval(collectionName, index, varName));
3697
+ lines.push(``);
3698
+ }
3699
+ }
3700
+ if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
3701
+ lines.push(` // Update permissions for ${collectionName}`);
3702
+ for (const permission of modification.permissionsToUpdate) {
3703
+ const varName = `collection_${collectionName}_perm_${permission.ruleType}`;
3704
+ lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.newValue, varName));
3705
+ lines.push(``);
3706
+ }
3707
+ } else if (modification.rulesToUpdate.length > 0) {
3708
+ lines.push(` // Update rules for ${collectionName}`);
3709
+ for (const rule of modification.rulesToUpdate) {
3710
+ const varName = `collection_${collectionName}_rule_${rule.ruleType}`;
3711
+ lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.newValue, varName));
3712
+ lines.push(``);
3713
+ }
3714
+ }
3715
+ }
3716
+ }
3717
+ if (diff.collectionsToDelete.length > 0) {
3718
+ lines.push(` // Delete collections`);
3719
+ for (let i = 0; i < diff.collectionsToDelete.length; i++) {
3720
+ const collection = diff.collectionsToDelete[i];
3721
+ const varName = `collection_${collection.name}_delete`;
3722
+ lines.push(generateCollectionDeletion(collection.name, varName));
3723
+ lines.push(``);
3724
+ }
3725
+ }
3726
+ if (lines.length === 2) {
3727
+ lines.push(` // No changes detected`);
3728
+ lines.push(``);
3729
+ }
3730
+ return lines.join("\n");
3731
+ }
3732
+ function generateDownMigration(diff) {
3733
+ const lines = [];
3734
+ lines.push(` // DOWN MIGRATION (ROLLBACK)`);
3735
+ lines.push(``);
3736
+ if (diff.collectionsToDelete.length > 0) {
3737
+ lines.push(` // Recreate deleted collections`);
3738
+ for (let i = 0; i < diff.collectionsToDelete.length; i++) {
3739
+ const collection = diff.collectionsToDelete[i];
3740
+ const varName = `collection_${collection.name}_recreate`;
3741
+ lines.push(generateCollectionCreation(collection, varName));
3742
+ lines.push(``);
3743
+ }
3744
+ }
3745
+ if (diff.collectionsToModify.length > 0) {
3746
+ lines.push(` // Revert modifications`);
3747
+ for (const modification of diff.collectionsToModify) {
3748
+ const collectionName = modification.collection;
3749
+ if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
3750
+ lines.push(` // Revert permissions for ${collectionName}`);
3751
+ for (const permission of modification.permissionsToUpdate) {
3752
+ const varName = `collection_${collectionName}_revert_perm_${permission.ruleType}`;
3753
+ lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.oldValue, varName));
3754
+ lines.push(``);
3755
+ }
3756
+ } else if (modification.rulesToUpdate.length > 0) {
3757
+ lines.push(` // Revert rules for ${collectionName}`);
3758
+ for (const rule of modification.rulesToUpdate) {
3759
+ const varName = `collection_${collectionName}_revert_rule_${rule.ruleType}`;
3760
+ lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.oldValue, varName));
3761
+ lines.push(``);
3762
+ }
3763
+ }
3764
+ if (modification.indexesToRemove.length > 0) {
3765
+ lines.push(` // Restore indexes to ${collectionName}`);
3766
+ for (let i = 0; i < modification.indexesToRemove.length; i++) {
3767
+ const index = modification.indexesToRemove[i];
3768
+ const varName = `collection_${collectionName}_restore_idx_${i}`;
3769
+ lines.push(generateIndexAddition(collectionName, index, varName));
3770
+ lines.push(``);
3771
+ }
3772
+ }
3773
+ if (modification.indexesToAdd.length > 0) {
3774
+ lines.push(` // Remove indexes from ${collectionName}`);
3775
+ for (let i = 0; i < modification.indexesToAdd.length; i++) {
3776
+ const index = modification.indexesToAdd[i];
3777
+ const varName = `collection_${collectionName}_revert_idx_${i}`;
3778
+ lines.push(generateIndexRemoval(collectionName, index, varName));
3779
+ lines.push(``);
3780
+ }
3781
+ }
3782
+ if (modification.fieldsToRemove.length > 0) {
3783
+ lines.push(` // Restore fields to ${collectionName}`);
3784
+ for (const field of modification.fieldsToRemove) {
3785
+ const varName = `collection_${collectionName}_restore_${field.name}`;
3786
+ lines.push(generateFieldAddition(collectionName, field, varName));
3787
+ lines.push(``);
3788
+ }
3789
+ }
3790
+ if (modification.fieldsToModify.length > 0) {
3791
+ lines.push(` // Revert field modifications in ${collectionName}`);
3792
+ for (const fieldMod of modification.fieldsToModify) {
3793
+ const reverseChanges = fieldMod.changes.map((change) => ({
3794
+ property: change.property,
3795
+ oldValue: change.newValue,
3796
+ newValue: change.oldValue
3797
+ }));
3798
+ const reverseMod = {
3799
+ fieldName: fieldMod.fieldName,
3800
+ currentDefinition: fieldMod.newDefinition,
3801
+ newDefinition: fieldMod.currentDefinition,
3802
+ changes: reverseChanges
3803
+ };
3804
+ const varName = `collection_${collectionName}_revert_${fieldMod.fieldName}`;
3805
+ lines.push(generateFieldModification(collectionName, reverseMod, varName));
3806
+ lines.push(``);
3807
+ }
3808
+ }
3809
+ if (modification.fieldsToAdd.length > 0) {
3810
+ lines.push(` // Remove added fields from ${collectionName}`);
3811
+ for (const field of modification.fieldsToAdd) {
3812
+ const varName = `collection_${collectionName}_revert_add_${field.name}`;
3813
+ lines.push(generateFieldDeletion(collectionName, field.name, varName));
3814
+ lines.push(``);
3815
+ }
3816
+ }
3817
+ }
3818
+ }
3819
+ if (diff.collectionsToCreate.length > 0) {
3820
+ lines.push(` // Delete created collections`);
3821
+ for (let i = 0; i < diff.collectionsToCreate.length; i++) {
3822
+ const collection = diff.collectionsToCreate[i];
3823
+ const varName = `collection_${collection.name}_rollback`;
3824
+ lines.push(generateCollectionDeletion(collection.name, varName));
3825
+ lines.push(``);
3826
+ }
3827
+ }
3828
+ if (lines.length === 2) {
3829
+ lines.push(` // No changes to revert`);
3830
+ lines.push(``);
3831
+ }
3832
+ return lines.join("\n");
3833
+ }
3834
+ function generate(diff, config) {
3835
+ const normalizedConfig = typeof config === "string" ? { migrationDir: config } : config;
3836
+ try {
3837
+ const migrationDir = resolveMigrationDir(normalizedConfig);
3838
+ const upCode = generateUpMigration(diff);
3839
+ const downCode = generateDownMigration(diff);
3840
+ const content = createMigrationFileStructure(upCode, downCode, normalizedConfig);
3841
+ const filename = generateMigrationFilename(diff, normalizedConfig);
3842
+ const filePath = writeMigrationFile(migrationDir, filename, content);
3843
+ return filePath;
3844
+ } catch (error) {
3845
+ if (error instanceof MigrationGenerationError || error instanceof FileSystemError) {
3846
+ throw error;
3847
+ }
3848
+ throw new MigrationGenerationError(
3849
+ `Failed to generate migration: ${error instanceof Error ? error.message : String(error)}`,
3850
+ normalizedConfig.migrationDir,
3851
+ error
3852
+ );
3853
+ }
3854
+ }
3855
+ var MigrationGenerator = class {
3856
+ config;
3857
+ constructor(config) {
3858
+ this.config = mergeConfig4(config);
3859
+ }
3860
+ /**
3861
+ * Generates a migration file from a schema diff
3862
+ */
3863
+ generate(diff) {
3864
+ return generate(diff, this.config);
3865
+ }
3866
+ /**
3867
+ * Generates the up migration code without writing to file
3868
+ */
3869
+ generateUpMigration(diff) {
3870
+ return generateUpMigration(diff);
3871
+ }
3872
+ /**
3873
+ * Generates the down migration code without writing to file
3874
+ */
3875
+ generateDownMigration(diff) {
3876
+ return generateDownMigration(diff);
3877
+ }
3878
+ /**
3879
+ * Generates a migration filename
3880
+ */
3881
+ generateMigrationFilename(diff) {
3882
+ return generateMigrationFilename(diff, this.config);
3883
+ }
3884
+ };
3885
+
3886
+ // src/migration/validation.ts
3887
+ function detectCollectionDeletions(diff) {
3888
+ const changes = [];
3889
+ for (const collection of diff.collectionsToDelete) {
3890
+ changes.push({
3891
+ type: "collection_deletion" /* COLLECTION_DELETION */,
3892
+ description: `Delete collection: ${collection.name}`,
3893
+ collection: collection.name,
3894
+ severity: "high",
3895
+ warning: `All data in the "${collection.name}" collection will be permanently deleted.`
3896
+ });
3897
+ }
3898
+ return changes;
3899
+ }
3900
+ function detectFieldDeletions(diff) {
3901
+ const changes = [];
3902
+ for (const modification of diff.collectionsToModify) {
3903
+ for (const field of modification.fieldsToRemove) {
3904
+ changes.push({
3905
+ type: "field_deletion" /* FIELD_DELETION */,
3906
+ description: `Delete field: ${modification.collection}.${field.name}`,
3907
+ collection: modification.collection,
3908
+ field: field.name,
3909
+ severity: "high",
3910
+ warning: `All data in the "${field.name}" field of "${modification.collection}" will be permanently deleted.`
3911
+ });
3912
+ }
3913
+ }
3914
+ return changes;
3915
+ }
3916
+ function detectFieldTypeChanges(diff) {
3917
+ const changes = [];
3918
+ for (const modification of diff.collectionsToModify) {
3919
+ for (const fieldMod of modification.fieldsToModify) {
3920
+ const typeChange = fieldMod.changes.find((c) => c.property === "type");
3921
+ if (typeChange) {
3922
+ changes.push({
3923
+ type: "field_type_change" /* FIELD_TYPE_CHANGE */,
3924
+ description: `Change field type: ${modification.collection}.${fieldMod.fieldName}`,
3925
+ collection: modification.collection,
3926
+ field: fieldMod.fieldName,
3927
+ details: {
3928
+ oldValue: typeChange.oldValue,
3929
+ newValue: typeChange.newValue
3930
+ },
3931
+ severity: "high",
3932
+ warning: `Changing field type from "${typeChange.oldValue}" to "${typeChange.newValue}" may cause data loss or conversion errors.`
3933
+ });
3934
+ }
3935
+ }
3936
+ }
3937
+ return changes;
3938
+ }
3939
+ function detectFieldRequiredChanges(diff) {
3940
+ const changes = [];
3941
+ for (const modification of diff.collectionsToModify) {
3942
+ for (const fieldMod of modification.fieldsToModify) {
3943
+ const requiredChange = fieldMod.changes.find(
3944
+ (c) => c.property === "required" && c.newValue === true && c.oldValue === false
3945
+ );
3946
+ if (requiredChange) {
3947
+ changes.push({
3948
+ type: "field_required_change" /* FIELD_REQUIRED_CHANGE */,
3949
+ description: `Make field required: ${modification.collection}.${fieldMod.fieldName}`,
3950
+ collection: modification.collection,
3951
+ field: fieldMod.fieldName,
3952
+ details: {
3953
+ oldValue: false,
3954
+ newValue: true
3955
+ },
3956
+ severity: "medium",
3957
+ warning: `Making "${fieldMod.fieldName}" required may cause issues with existing records that have null/empty values.`
3958
+ });
3959
+ }
3960
+ }
3961
+ }
3962
+ return changes;
3963
+ }
3964
+ function detectDestructiveChanges2(diff) {
3965
+ const changes = [];
3966
+ changes.push(...detectCollectionDeletions(diff));
3967
+ changes.push(...detectFieldDeletions(diff));
3968
+ changes.push(...detectFieldTypeChanges(diff));
3969
+ changes.push(...detectFieldRequiredChanges(diff));
3970
+ return changes;
3971
+ }
3972
+ function formatDestructiveChanges(changes) {
3973
+ if (changes.length === 0) {
3974
+ return "No destructive changes detected.";
3975
+ }
3976
+ const lines = [];
3977
+ const highSeverity = changes.filter((c) => c.severity === "high");
3978
+ const mediumSeverity = changes.filter((c) => c.severity === "medium");
3979
+ const lowSeverity = changes.filter((c) => c.severity === "low");
3980
+ if (highSeverity.length > 0) {
3981
+ lines.push("\u{1F534} HIGH SEVERITY CHANGES (Data Loss Risk):");
3982
+ lines.push("");
3983
+ for (const change of highSeverity) {
3984
+ lines.push(` \u2022 ${change.description}`);
3985
+ lines.push(` \u26A0\uFE0F ${change.warning}`);
3986
+ if (change.details) {
3987
+ if (change.details.oldValue !== void 0 && change.details.newValue !== void 0) {
3988
+ lines.push(` Old: ${change.details.oldValue} \u2192 New: ${change.details.newValue}`);
3989
+ }
3990
+ }
3991
+ lines.push("");
3992
+ }
3993
+ }
3994
+ if (mediumSeverity.length > 0) {
3995
+ lines.push("\u{1F7E1} MEDIUM SEVERITY CHANGES (Potential Issues):");
3996
+ lines.push("");
3997
+ for (const change of mediumSeverity) {
3998
+ lines.push(` \u2022 ${change.description}`);
3999
+ lines.push(` \u26A0\uFE0F ${change.warning}`);
4000
+ if (change.details) {
4001
+ if (change.details.oldValue !== void 0 && change.details.newValue !== void 0) {
4002
+ lines.push(` Old: ${change.details.oldValue} \u2192 New: ${change.details.newValue}`);
4003
+ }
4004
+ }
4005
+ lines.push("");
4006
+ }
4007
+ }
4008
+ if (lowSeverity.length > 0) {
4009
+ lines.push("\u{1F7E2} LOW SEVERITY CHANGES:");
4010
+ lines.push("");
4011
+ for (const change of lowSeverity) {
4012
+ lines.push(` \u2022 ${change.description}`);
4013
+ lines.push(` \u2139\uFE0F ${change.warning}`);
4014
+ lines.push("");
4015
+ }
4016
+ }
4017
+ return lines.join("\n");
4018
+ }
4019
+ function summarizeDestructiveChanges(changes) {
4020
+ return {
4021
+ total: changes.length,
4022
+ high: changes.filter((c) => c.severity === "high").length,
4023
+ medium: changes.filter((c) => c.severity === "medium").length,
4024
+ low: changes.filter((c) => c.severity === "low").length
4025
+ };
4026
+ }
4027
+ function requiresForceFlag2(changes) {
4028
+ return changes.some((c) => c.severity === "high" || c.severity === "medium");
4029
+ }
4030
+ var CONFIG_FILE_NAMES = [
4031
+ "pocketbase-migrate.config.js",
4032
+ "pocketbase-migrate.config.mjs",
4033
+ "pocketbase-migrate.config.json",
4034
+ "migrate.config.js",
4035
+ "migrate.config.mjs",
4036
+ "migrate.config.json"
4037
+ ];
4038
+ var DEFAULT_CONFIG5 = {
4039
+ schema: {
4040
+ directory: "src/schema",
4041
+ exclude: ["base.ts", "index.ts", "permissions.ts", "permission-templates.ts"]
4042
+ },
4043
+ migrations: {
4044
+ directory: "pocketbase/pb_migrations",
4045
+ format: "timestamp_description"
4046
+ },
4047
+ diff: {
4048
+ warnOnDelete: true,
4049
+ requireForceForDestructive: true
4050
+ }
4051
+ };
4052
+ function findConfigFile(directory) {
4053
+ for (const fileName of CONFIG_FILE_NAMES) {
4054
+ const filePath = path4.join(directory, fileName);
4055
+ if (fs2.existsSync(filePath)) {
4056
+ return filePath;
4057
+ }
4058
+ }
4059
+ return null;
4060
+ }
4061
+ function loadJsonConfig(configPath) {
4062
+ try {
4063
+ const content = fs2.readFileSync(configPath, "utf-8");
4064
+ return JSON.parse(content);
4065
+ } catch (error) {
4066
+ if (error instanceof SyntaxError) {
4067
+ throw new ConfigurationError("Invalid JSON syntax in configuration file", configPath, void 0, error);
4068
+ }
4069
+ throw new ConfigurationError(
4070
+ "Failed to read configuration file",
4071
+ configPath,
4072
+ void 0,
4073
+ error instanceof Error ? error : void 0
4074
+ );
4075
+ }
4076
+ }
4077
+ async function loadJsConfig(configPath) {
4078
+ try {
4079
+ const fileUrl = `file://${configPath}`;
4080
+ const module = await import(fileUrl);
4081
+ return module.default || module;
4082
+ } catch (error) {
4083
+ throw new ConfigurationError(
4084
+ "Failed to load JavaScript configuration file",
4085
+ configPath,
4086
+ void 0,
4087
+ error instanceof Error ? error : void 0
4088
+ );
4089
+ }
4090
+ }
4091
+ async function loadConfigFile(configPath) {
4092
+ if (!fs2.existsSync(configPath)) {
4093
+ return null;
4094
+ }
4095
+ const ext = path4.extname(configPath).toLowerCase();
4096
+ if (ext === ".json") {
4097
+ return loadJsonConfig(configPath);
4098
+ } else if (ext === ".js" || ext === ".mjs") {
4099
+ return loadJsConfig(configPath);
4100
+ } else {
4101
+ throw new ConfigurationError(`Unsupported configuration file format: ${ext}`, configPath, void 0);
4102
+ }
4103
+ }
4104
+ function mergeConfig5(base, override) {
4105
+ return {
4106
+ schema: { ...base.schema, ...override.schema },
4107
+ migrations: { ...base.migrations, ...override.migrations },
4108
+ diff: { ...base.diff, ...override.diff }
4109
+ };
4110
+ }
4111
+ function loadConfigFromEnv() {
4112
+ const config = {};
4113
+ if (process.env.MIGRATION_SCHEMA_DIR) {
4114
+ config.schema = { directory: process.env.MIGRATION_SCHEMA_DIR };
4115
+ }
4116
+ if (process.env.MIGRATION_SCHEMA_EXCLUDE) {
4117
+ config.schema = {
4118
+ ...config.schema,
4119
+ exclude: process.env.MIGRATION_SCHEMA_EXCLUDE.split(",").map((s) => s.trim())
4120
+ };
4121
+ }
4122
+ if (process.env.MIGRATION_OUTPUT_DIR) {
4123
+ config.migrations = { directory: process.env.MIGRATION_OUTPUT_DIR };
4124
+ }
4125
+ if (process.env.MIGRATION_REQUIRE_FORCE !== void 0) {
4126
+ config.diff = { requireForceForDestructive: process.env.MIGRATION_REQUIRE_FORCE === "true" };
4127
+ }
4128
+ return config;
4129
+ }
4130
+ function loadConfigFromArgs(options) {
4131
+ const config = {};
4132
+ if (options.output) {
4133
+ config.migrations = { directory: options.output };
4134
+ }
4135
+ if (options.schemaDir) {
4136
+ config.schema = { directory: options.schemaDir };
4137
+ }
4138
+ return config;
4139
+ }
4140
+ function validateConfig(config, configPath) {
4141
+ const invalidFields = [];
4142
+ if (typeof config.schema.directory !== "string" || config.schema.directory.trim() === "") {
4143
+ invalidFields.push("schema.directory (must be a non-empty string)");
4144
+ }
4145
+ if (!Array.isArray(config.schema.exclude)) {
4146
+ invalidFields.push("schema.exclude (must be an array of strings)");
4147
+ }
4148
+ if (typeof config.migrations.directory !== "string" || config.migrations.directory.trim() === "") {
4149
+ invalidFields.push("migrations.directory (must be a non-empty string)");
4150
+ }
4151
+ if (typeof config.diff.warnOnDelete !== "boolean") {
4152
+ invalidFields.push("diff.warnOnDelete (must be a boolean)");
4153
+ }
4154
+ if (typeof config.diff.requireForceForDestructive !== "boolean") {
4155
+ invalidFields.push("diff.requireForceForDestructive (must be a boolean)");
4156
+ }
4157
+ if (invalidFields.length > 0) {
4158
+ throw new ConfigurationError("Invalid configuration values", configPath, invalidFields);
4159
+ }
4160
+ const cwd = process.cwd();
4161
+ const possiblePaths = [
4162
+ path4.resolve(cwd, config.schema.directory),
4163
+ path4.resolve(cwd, "shared", config.schema.directory)
4164
+ ];
4165
+ const schemaDir = possiblePaths.find((p) => fs2.existsSync(p));
4166
+ if (!schemaDir) {
4167
+ throw new ConfigurationError(`Schema directory not found. Tried: ${possiblePaths.join(", ")}`, configPath, [
4168
+ "schema.directory"
4169
+ ]);
4170
+ }
4171
+ }
4172
+ async function loadConfig(options = {}) {
4173
+ let config = { ...DEFAULT_CONFIG5 };
4174
+ let configFilePath;
4175
+ const cwd = process.cwd();
4176
+ if (options.config) {
4177
+ const explicitPath = path4.resolve(cwd, options.config);
4178
+ if (!fs2.existsSync(explicitPath)) {
4179
+ throw new ConfigurationError(`Configuration file not found: ${explicitPath}`, explicitPath);
4180
+ }
4181
+ configFilePath = explicitPath;
4182
+ } else {
4183
+ const searchDirs = [cwd, path4.join(cwd, "shared")];
4184
+ for (const dir of searchDirs) {
4185
+ if (fs2.existsSync(dir)) {
4186
+ const found = findConfigFile(dir);
4187
+ if (found) {
4188
+ configFilePath = found;
4189
+ break;
4190
+ }
4191
+ }
4192
+ }
4193
+ }
4194
+ if (configFilePath) {
4195
+ const fileConfig = await loadConfigFile(configFilePath);
4196
+ if (fileConfig) {
4197
+ config = mergeConfig5(config, fileConfig);
4198
+ }
4199
+ }
4200
+ const envConfig = loadConfigFromEnv();
4201
+ if (Object.keys(envConfig).length > 0) {
4202
+ config = mergeConfig5(config, envConfig);
4203
+ }
4204
+ const argsConfig = loadConfigFromArgs(options);
4205
+ if (Object.keys(argsConfig).length > 0) {
4206
+ config = mergeConfig5(config, argsConfig);
4207
+ }
4208
+ validateConfig(config, configFilePath);
4209
+ return config;
4210
+ }
4211
+ function getSchemaDirectory(config) {
4212
+ const cwd = process.cwd();
4213
+ const possiblePaths = [
4214
+ path4.resolve(cwd, config.schema.directory),
4215
+ path4.resolve(cwd, "shared", config.schema.directory)
4216
+ ];
4217
+ return possiblePaths.find((p) => fs2.existsSync(p)) || possiblePaths[0];
4218
+ }
4219
+ function getMigrationsDirectory(config) {
4220
+ const cwd = process.cwd();
4221
+ const possiblePaths = [
4222
+ path4.resolve(cwd, config.migrations.directory),
4223
+ path4.resolve(cwd, "shared", config.migrations.directory)
4224
+ ];
4225
+ return possiblePaths.find((p) => fs2.existsSync(p)) || possiblePaths[0];
4226
+ }
4227
+ var currentVerbosity = "normal";
4228
+ function setVerbosity(level) {
4229
+ currentVerbosity = level;
4230
+ }
4231
+ function shouldLog(requiredLevel) {
4232
+ const levels = ["quiet", "normal", "verbose"];
4233
+ const currentIndex = levels.indexOf(currentVerbosity);
4234
+ const requiredIndex = levels.indexOf(requiredLevel);
4235
+ return currentIndex >= requiredIndex;
4236
+ }
4237
+ function createSpinner(text) {
4238
+ if (currentVerbosity === "quiet") {
4239
+ return ora({ text, isSilent: true });
4240
+ }
4241
+ return ora(text);
4242
+ }
4243
+ function logSuccess(message) {
4244
+ if (shouldLog("normal")) {
4245
+ console.log(chalk.green("\u2713"), message);
4246
+ }
4247
+ }
4248
+ function logError(message) {
4249
+ console.error(chalk.red("\u2717"), message);
4250
+ }
4251
+ function logWarning(message) {
4252
+ if (shouldLog("normal")) {
4253
+ console.warn(chalk.yellow("\u26A0"), message);
4254
+ }
4255
+ }
4256
+ function logInfo(message) {
4257
+ if (shouldLog("normal")) {
4258
+ console.log(chalk.blue("\u2139"), message);
4259
+ }
4260
+ }
4261
+ function logDebug(message) {
4262
+ if (shouldLog("verbose")) {
4263
+ console.log(chalk.gray("\u2699"), chalk.gray(message));
4264
+ }
4265
+ }
4266
+ function logSection(title) {
4267
+ if (shouldLog("normal")) {
4268
+ console.log();
4269
+ console.log(chalk.bold.cyan(title));
4270
+ console.log(chalk.cyan("\u2500".repeat(title.length)));
4271
+ }
4272
+ }
4273
+ function formatFieldChange(change) {
4274
+ const oldValue = change.oldValue === null ? "null" : JSON.stringify(change.oldValue);
4275
+ const newValue = change.newValue === null ? "null" : JSON.stringify(change.newValue);
4276
+ return `${change.property}: ${chalk.red(oldValue)} \u2192 ${chalk.green(newValue)}`;
4277
+ }
4278
+ function formatChangeSummary(diff) {
4279
+ const lines = [];
4280
+ const totalCollectionsToCreate = diff.collectionsToCreate.length;
4281
+ const totalCollectionsToDelete = diff.collectionsToDelete.length;
4282
+ const totalCollectionsToModify = diff.collectionsToModify.length;
4283
+ const totalChanges = totalCollectionsToCreate + totalCollectionsToDelete + totalCollectionsToModify;
4284
+ if (totalChanges === 0) {
4285
+ return chalk.gray("No changes detected");
4286
+ }
4287
+ lines.push(chalk.bold(`Found ${totalChanges} collection change(s):`));
4288
+ lines.push("");
4289
+ if (totalCollectionsToCreate > 0) {
4290
+ lines.push(chalk.green.bold(`\u2713 ${totalCollectionsToCreate} collection(s) to create:`));
4291
+ for (const collection of diff.collectionsToCreate) {
4292
+ lines.push(chalk.green(` + ${collection.name} (${collection.type})`));
4293
+ lines.push(chalk.gray(` ${collection.fields.length} field(s)`));
4294
+ }
4295
+ lines.push("");
4296
+ }
4297
+ if (totalCollectionsToDelete > 0) {
4298
+ lines.push(chalk.red.bold(`\u2717 ${totalCollectionsToDelete} collection(s) to delete:`));
4299
+ for (const collection of diff.collectionsToDelete) {
4300
+ lines.push(chalk.red(` - ${collection.name}`));
4301
+ }
4302
+ lines.push("");
4303
+ }
4304
+ if (totalCollectionsToModify > 0) {
4305
+ lines.push(chalk.yellow.bold(`\u26A1 ${totalCollectionsToModify} collection(s) to modify:`));
4306
+ for (const modification of diff.collectionsToModify) {
4307
+ lines.push(chalk.yellow(` ~ ${modification.collection}`));
4308
+ if (modification.fieldsToAdd.length > 0) {
4309
+ lines.push(chalk.green(` + ${modification.fieldsToAdd.length} field(s) to add:`));
4310
+ for (const field of modification.fieldsToAdd) {
4311
+ lines.push(chalk.green(` + ${field.name} (${field.type})`));
4312
+ }
4313
+ }
4314
+ if (modification.fieldsToRemove.length > 0) {
4315
+ lines.push(chalk.red(` - ${modification.fieldsToRemove.length} field(s) to remove:`));
4316
+ for (const field of modification.fieldsToRemove) {
4317
+ lines.push(chalk.red(` - ${field.name}`));
4318
+ }
4319
+ }
4320
+ if (modification.fieldsToModify.length > 0) {
4321
+ lines.push(chalk.yellow(` ~ ${modification.fieldsToModify.length} field(s) to modify:`));
4322
+ for (const fieldMod of modification.fieldsToModify) {
4323
+ lines.push(chalk.yellow(` ~ ${fieldMod.fieldName}`));
4324
+ for (const change of fieldMod.changes) {
4325
+ lines.push(chalk.gray(` ${formatFieldChange(change)}`));
4326
+ }
4327
+ }
4328
+ }
4329
+ if (modification.indexesToAdd.length > 0) {
4330
+ lines.push(chalk.green(` + ${modification.indexesToAdd.length} index(es) to add`));
4331
+ }
4332
+ if (modification.indexesToRemove.length > 0) {
4333
+ lines.push(chalk.red(` - ${modification.indexesToRemove.length} index(es) to remove`));
4334
+ }
4335
+ if (modification.rulesToUpdate.length > 0) {
4336
+ lines.push(chalk.yellow(` ~ ${modification.rulesToUpdate.length} rule(s) to update`));
4337
+ }
4338
+ lines.push("");
4339
+ }
4340
+ }
4341
+ return lines.join("\n");
4342
+ }
4343
+ async function withProgress(message, operation) {
4344
+ const spinner = createSpinner(message).start();
4345
+ try {
4346
+ const result = await operation();
4347
+ spinner.succeed();
4348
+ return result;
4349
+ } catch (error) {
4350
+ spinner.fail();
4351
+ throw error;
4352
+ }
4353
+ }
4354
+ function logKeyValue(key, value, indent = 2) {
4355
+ if (shouldLog("normal")) {
4356
+ const padding = " ".repeat(indent);
4357
+ console.log(`${padding}${chalk.gray(key + ":")} ${value}`);
4358
+ }
4359
+ }
4360
+ function logTable(headers, rows) {
4361
+ if (!shouldLog("normal")) return;
4362
+ const widths = headers.map((h, i) => {
4363
+ const maxRowWidth = Math.max(...rows.map((r) => (r[i] || "").length));
4364
+ return Math.max(h.length, maxRowWidth);
4365
+ });
4366
+ const headerLine = headers.map((h, i) => h.padEnd(widths[i])).join(" ");
4367
+ console.log(chalk.bold(headerLine));
4368
+ console.log(chalk.gray("\u2500".repeat(headerLine.length)));
4369
+ for (const row of rows) {
4370
+ const rowLine = row.map((cell, i) => (cell || "").padEnd(widths[i])).join(" ");
4371
+ console.log(rowLine);
4372
+ }
4373
+ }
4374
+ function formatStatusJson(output) {
4375
+ return JSON.stringify(output, null, 2);
4376
+ }
4377
+
4378
+ // src/cli/commands/generate.ts
4379
+ function hasChanges2(diff) {
4380
+ return diff.collectionsToCreate.length > 0 || diff.collectionsToDelete.length > 0 || diff.collectionsToModify.length > 0;
4381
+ }
4382
+ function handleDestructiveChanges(diff, config, force) {
4383
+ const destructiveChanges = detectDestructiveChanges2(diff);
4384
+ if (destructiveChanges.length === 0) {
4385
+ return true;
4386
+ }
4387
+ logSection("\u26A0\uFE0F Destructive Changes Detected");
4388
+ console.log();
4389
+ console.log(formatDestructiveChanges(destructiveChanges));
4390
+ const summary = summarizeDestructiveChanges(destructiveChanges);
4391
+ console.log("Summary:");
4392
+ console.log(` Total: ${summary.total} destructive change(s)`);
4393
+ if (summary.high > 0) {
4394
+ console.log(` High Severity: ${summary.high}`);
4395
+ }
4396
+ if (summary.medium > 0) {
4397
+ console.log(` Medium Severity: ${summary.medium}`);
4398
+ }
4399
+ if (summary.low > 0) {
4400
+ console.log(` Low Severity: ${summary.low}`);
4401
+ }
4402
+ console.log();
4403
+ const forceRequired = config.diff.requireForceForDestructive && requiresForceFlag2(destructiveChanges);
4404
+ if (forceRequired && !force) {
4405
+ logError("Destructive changes require the --force flag to proceed.");
4406
+ console.log();
4407
+ logInfo("To proceed with these changes, run the command again with --force:");
4408
+ console.log(" yarn migrate:generate --force");
4409
+ console.log();
4410
+ logWarning("\u26A0\uFE0F WARNING: Using --force will apply these changes and may result in data loss!");
4411
+ return false;
4412
+ }
4413
+ if (force) {
4414
+ logWarning("Proceeding with destructive changes (--force flag provided)");
4415
+ console.log();
4416
+ }
4417
+ return true;
4418
+ }
4419
+ async function executeGenerate(options) {
4420
+ try {
4421
+ const parentOpts = options.parent?.opts?.() || {};
4422
+ if (parentOpts.verbose) {
4423
+ setVerbosity("verbose");
4424
+ } else if (parentOpts.quiet) {
4425
+ setVerbosity("quiet");
4426
+ }
4427
+ logDebug("Starting migration generation...");
4428
+ logDebug(`Options: ${JSON.stringify(options, null, 2)}`);
4429
+ const config = await loadConfig(options);
4430
+ const schemaDir = getSchemaDirectory(config);
4431
+ const migrationsDir = getMigrationsDirectory(config);
4432
+ logSection("\u{1F50D} Analyzing Schema");
4433
+ const currentSchema = await withProgress("Parsing Zod schemas...", () => parseSchemaFiles(schemaDir));
4434
+ logSuccess(`Found ${currentSchema.collections.size} collection(s)`);
4435
+ logInfo("Loading previous snapshot...");
4436
+ const previousSnapshot = loadSnapshotIfExists({
4437
+ migrationsPath: migrationsDir,
4438
+ workspaceRoot: process.cwd()
4439
+ });
4440
+ if (!previousSnapshot) {
4441
+ logInfo("No previous snapshot found - treating as empty database (first-time generation)");
4442
+ } else {
4443
+ logSuccess("Loaded previous snapshot as base reference");
4444
+ }
4445
+ logSection("\u{1F4CA} Comparing Schemas");
4446
+ const diff = compare(currentSchema, previousSnapshot);
4447
+ if (!hasChanges2(diff)) {
4448
+ logInfo("No changes detected");
4449
+ console.log();
4450
+ logSuccess("Schema is up to date!");
4451
+ return;
4452
+ }
4453
+ console.log();
4454
+ console.log(formatChangeSummary(diff));
4455
+ if (!handleDestructiveChanges(diff, config, options.force)) {
4456
+ process.exit(1);
4457
+ }
4458
+ logSection("\u{1F4DD} Generating Migration");
4459
+ const migrationPath = await withProgress(
4460
+ "Creating migration file...",
4461
+ () => Promise.resolve(generate(diff, migrationsDir))
4462
+ );
4463
+ logSuccess(`Migration file created: ${path4.basename(migrationPath)}`);
4464
+ logSection("\u2705 Next Steps");
4465
+ console.log();
4466
+ console.log(" 1. Review the generated migration file:");
4467
+ console.log(` ${migrationPath}`);
4468
+ console.log();
4469
+ console.log(" 2. Apply the migration by running PocketBase:");
4470
+ console.log(" yarn pb");
4471
+ console.log();
4472
+ console.log(" Or apply migrations manually:");
4473
+ console.log(" cd pb && ./pocketbase migrate up");
4474
+ console.log();
4475
+ } catch (error) {
4476
+ if (error instanceof SchemaParsingError) {
4477
+ logError("Schema Parsing Error");
4478
+ console.error();
4479
+ console.error(error.getDetailedMessage());
4480
+ console.error();
4481
+ logInfo("Suggestions:");
4482
+ console.log(" \u2022 Make sure your schema files are valid Zod schemas");
4483
+ console.log(' \u2022 Run "yarn build" in the shared workspace to compile TypeScript files');
4484
+ console.log(' \u2022 Check that schema files export schemas ending with "Schema" or "InputSchema"');
4485
+ } else if (error instanceof SnapshotError) {
4486
+ logError("Snapshot Error");
4487
+ console.error();
4488
+ console.error(error.getDetailedMessage());
4489
+ console.error();
4490
+ logInfo("Suggestions:");
4491
+ console.log(" \u2022 Check that the snapshot file is not corrupted");
4492
+ console.log(" \u2022 Verify file permissions for the snapshot file");
4493
+ console.log(" \u2022 If this is the first run, this error should not occur");
4494
+ } else if (error instanceof MigrationGenerationError) {
4495
+ logError("Migration Generation Error");
4496
+ console.error();
4497
+ console.error(error.getDetailedMessage());
4498
+ console.error();
4499
+ logInfo("Suggestions:");
4500
+ console.log(" \u2022 Check that the migration directory exists and is writable");
4501
+ console.log(" \u2022 Verify you have sufficient disk space");
4502
+ console.log(" \u2022 Check file permissions for the migration directory");
4503
+ } else if (error instanceof FileSystemError) {
4504
+ logError("File System Error");
4505
+ console.error();
4506
+ console.error(error.getDetailedMessage());
4507
+ console.error();
4508
+ logInfo("Suggestions:");
4509
+ console.log(" \u2022 Check file and directory permissions");
4510
+ console.log(" \u2022 Verify you have sufficient disk space");
4511
+ console.log(" \u2022 Ensure the paths are correct and accessible");
4512
+ } else if (error instanceof ConfigurationError) {
4513
+ logError("Configuration Error");
4514
+ console.error();
4515
+ console.error(error.getDetailedMessage());
4516
+ console.error();
4517
+ logInfo("Suggestions:");
4518
+ console.log(" \u2022 Check your configuration file syntax");
4519
+ console.log(" \u2022 Verify all paths are correct and accessible");
4520
+ console.log(" \u2022 Run with --verbose flag for more details");
4521
+ } else {
4522
+ logError(`Failed to generate migration: ${error}`);
4523
+ if (error instanceof Error && error.stack) {
4524
+ console.error();
4525
+ console.error(error.stack);
4526
+ }
4527
+ }
4528
+ console.error();
4529
+ process.exit(1);
4530
+ }
4531
+ }
4532
+ function hasChanges3(diff) {
4533
+ return diff.collectionsToCreate.length > 0 || diff.collectionsToDelete.length > 0 || diff.collectionsToModify.length > 0;
4534
+ }
4535
+ function hasDestructiveChanges(diff) {
4536
+ const { destructive } = categorizeChangesBySeverity(diff);
4537
+ return destructive.length > 0;
4538
+ }
4539
+ function createStatusOutput(status, currentCount, snapshotCount, diff) {
4540
+ return {
4541
+ status,
4542
+ collections: {
4543
+ current: currentCount,
4544
+ snapshot: snapshotCount
4545
+ },
4546
+ changes: {
4547
+ create: diff?.collectionsToCreate.length ?? 0,
4548
+ delete: diff?.collectionsToDelete.length ?? 0,
4549
+ modify: diff?.collectionsToModify.length ?? 0
4550
+ },
4551
+ destructive: diff ? hasDestructiveChanges(diff) : false
4552
+ };
4553
+ }
4554
+ function displayDestructiveChangesSummary(diff) {
4555
+ const { destructive, nonDestructive } = categorizeChangesBySeverity(diff);
4556
+ if (destructive.length > 0) {
4557
+ logSection("\u26A0\uFE0F Destructive Changes");
4558
+ console.log();
4559
+ for (const change of destructive) {
4560
+ console.log(chalk.red(` ${change}`));
4561
+ }
4562
+ console.log();
4563
+ }
4564
+ if (nonDestructive.length > 0) {
4565
+ logSection("\u2713 Non-Destructive Changes");
4566
+ console.log();
4567
+ for (const change of nonDestructive) {
4568
+ console.log(chalk.green(` ${change}`));
4569
+ }
4570
+ console.log();
4571
+ }
4572
+ }
4573
+ function displayChangeTable(diff) {
4574
+ const rows = [];
4575
+ for (const collection of diff.collectionsToCreate) {
4576
+ rows.push([
4577
+ chalk.green("+"),
4578
+ collection.name,
4579
+ collection.type,
4580
+ `${collection.fields.length} fields`,
4581
+ chalk.green("Create")
4582
+ ]);
4583
+ }
4584
+ for (const collection of diff.collectionsToDelete) {
4585
+ rows.push([chalk.red("-"), collection.name, collection.type || "base", "-", chalk.red("Delete")]);
4586
+ }
4587
+ for (const mod of diff.collectionsToModify) {
4588
+ const changes = [];
4589
+ if (mod.fieldsToAdd.length > 0) changes.push(`+${mod.fieldsToAdd.length} fields`);
4590
+ if (mod.fieldsToRemove.length > 0) changes.push(`-${mod.fieldsToRemove.length} fields`);
4591
+ if (mod.fieldsToModify.length > 0) changes.push(`~${mod.fieldsToModify.length} fields`);
4592
+ if (mod.indexesToAdd.length > 0) changes.push(`+${mod.indexesToAdd.length} indexes`);
4593
+ if (mod.indexesToRemove.length > 0) changes.push(`-${mod.indexesToRemove.length} indexes`);
4594
+ if (mod.rulesToUpdate.length > 0) changes.push(`~${mod.rulesToUpdate.length} rules`);
4595
+ rows.push([chalk.yellow("~"), mod.collection, "-", changes.join(", ") || "No changes", chalk.yellow("Modify")]);
4596
+ }
4597
+ if (rows.length > 0) {
4598
+ logTable(["", "Collection", "Type", "Changes", "Action"], rows);
4599
+ }
4600
+ }
4601
+ async function executeStatus(options) {
4602
+ const isJsonMode = options.json === true;
4603
+ try {
4604
+ if (isJsonMode) {
4605
+ setVerbosity("quiet");
4606
+ } else {
4607
+ const parentOpts = options.parent?.opts?.() || {};
4608
+ if (parentOpts.verbose) {
4609
+ setVerbosity("verbose");
4610
+ } else if (parentOpts.quiet) {
4611
+ setVerbosity("quiet");
4612
+ }
4613
+ }
4614
+ logDebug("Checking migration status...");
4615
+ logDebug(`Options: ${JSON.stringify(options, null, 2)}`);
4616
+ const config = await loadConfig(options);
4617
+ const schemaDir = getSchemaDirectory(config);
4618
+ const migrationsDir = getMigrationsDirectory(config);
4619
+ logSection("\u{1F50D} Checking Migration Status");
4620
+ const currentSchema = await withProgress("Parsing Zod schemas...", () => parseSchemaFiles(schemaDir));
4621
+ logSuccess(`Found ${currentSchema.collections.size} collection(s) in schema`);
4622
+ logInfo("Loading previous snapshot...");
4623
+ const previousSnapshot = loadSnapshotIfExists({
4624
+ migrationsPath: migrationsDir,
4625
+ workspaceRoot: process.cwd()
4626
+ });
4627
+ if (!previousSnapshot) {
4628
+ if (isJsonMode) {
4629
+ const output = createStatusOutput("first-time-setup", currentSchema.collections.size, 0);
4630
+ console.log(formatStatusJson(output));
4631
+ return;
4632
+ }
4633
+ logSection("\u{1F195} First-Time Setup Detected");
4634
+ console.log();
4635
+ logInfo("No previous snapshot found. This appears to be a first-time setup.");
4636
+ console.log();
4637
+ logKeyValue("Collections in schema", String(currentSchema.collections.size));
4638
+ console.log();
4639
+ logInfo('Run "pocketbase-migrate generate" to create the initial migration.');
4640
+ return;
4641
+ }
4642
+ logSuccess(`Loaded snapshot with ${previousSnapshot.collections.size} collection(s)`);
4643
+ logSection("\u{1F4CA} Schema Comparison");
4644
+ const diff = compare(currentSchema, previousSnapshot);
4645
+ if (!hasChanges3(diff)) {
4646
+ if (isJsonMode) {
4647
+ const output = createStatusOutput(
4648
+ "up-to-date",
4649
+ currentSchema.collections.size,
4650
+ previousSnapshot.collections.size,
4651
+ diff
4652
+ );
4653
+ console.log(formatStatusJson(output));
4654
+ return;
4655
+ }
4656
+ console.log();
4657
+ logSuccess("\u2713 Schema is in sync with snapshot");
4658
+ logInfo("No pending changes detected");
4659
+ console.log();
4660
+ logKeyValue("Collections", String(currentSchema.collections.size));
4661
+ return;
4662
+ }
4663
+ if (isJsonMode) {
4664
+ const output = createStatusOutput(
4665
+ "changes-pending",
4666
+ currentSchema.collections.size,
4667
+ previousSnapshot.collections.size,
4668
+ diff
4669
+ );
4670
+ console.log(formatStatusJson(output));
4671
+ return;
4672
+ }
4673
+ console.log();
4674
+ console.log(formatChangeSummary(diff));
4675
+ logDebug("Detailed change table:");
4676
+ displayChangeTable(diff);
4677
+ displayDestructiveChangesSummary(diff);
4678
+ logSection("\u{1F4DD} Next Steps");
4679
+ console.log();
4680
+ console.log(" To generate a migration for these changes, run:");
4681
+ console.log(chalk.cyan(" pocketbase-migrate generate"));
4682
+ console.log();
4683
+ const { destructive } = categorizeChangesBySeverity(diff);
4684
+ if (destructive.length > 0) {
4685
+ console.log(chalk.yellow(" \u26A0\uFE0F Destructive changes detected. Use --force flag when generating:"));
4686
+ console.log(chalk.cyan(" pocketbase-migrate generate --force"));
4687
+ console.log();
4688
+ }
4689
+ } catch (error) {
4690
+ if (error instanceof SchemaParsingError) {
4691
+ logError("Schema Parsing Error");
4692
+ console.error();
4693
+ console.error(error.getDetailedMessage());
4694
+ console.error();
4695
+ logInfo("Suggestions:");
4696
+ console.log(" \u2022 Make sure your schema files are valid Zod schemas");
4697
+ console.log(' \u2022 Check that schema files export schemas ending with "Schema" or "InputSchema"');
4698
+ } else if (error instanceof SnapshotError) {
4699
+ logError("Snapshot Error");
4700
+ console.error();
4701
+ console.error(error.getDetailedMessage());
4702
+ console.error();
4703
+ logInfo("Suggestions:");
4704
+ console.log(" \u2022 Check that the snapshot file is not corrupted");
4705
+ console.log(" \u2022 Verify file permissions for the snapshot file");
4706
+ } else if (error instanceof ConfigurationError) {
4707
+ logError("Configuration Error");
4708
+ console.error();
4709
+ console.error(error.getDetailedMessage());
4710
+ console.error();
4711
+ logInfo("Suggestions:");
4712
+ console.log(" \u2022 Check your configuration file syntax");
4713
+ console.log(" \u2022 Verify all paths are correct and accessible");
4714
+ } else {
4715
+ logError(`Failed to check status: ${error}`);
4716
+ if (error instanceof Error && error.stack) {
4717
+ console.error(error.stack);
4718
+ }
4719
+ }
4720
+ process.exit(1);
4721
+ }
4722
+ }
4723
+
4724
+ export { CLIUsageError, ConfigurationError, DiffEngine, FIELD_TYPE_INFO, FileSystemError, MigrationError, MigrationGenerationError, MigrationGenerator, POCKETBASE_FIELD_TYPES, PermissionTemplates, ProjectInputSchema, ProjectSchema, SchemaAnalyzer, SchemaParsingError, SnapshotError, SnapshotManager, StatusEnum, UserInputSchema, UserMutator, UserSchema, aggregateChanges, baseImageFileSchema, baseSchema, baseSchemaWithTimestamps, boolField, buildFieldDefinition, buildSchemaDefinition, categorizeChangesBySeverity, compare, compareFieldConstraints, compareFieldOptions, compareFieldTypes, comparePermissions, compareRelationConfigurations, convertPocketBaseMigration, convertZodSchemaToCollectionSchema, createMigrationFileStructure, createPermissions, dateField, detectDestructiveChanges, detectFieldChanges, discoverSchemaFiles, editorField, emailField, extractComprehensiveFieldOptions, extractFieldDefinitions, extractFieldOptions, extractIndexes, extractSchemaDefinitions, fileField, filesField, filterSystemCollections, findLatestSnapshot, findNewCollections, findNewFields, findRemovedCollections, findRemovedFields, formatChangeSummary, generate, generateChangeSummary, generateCollectionCreation, generateCollectionPermissions, generateCollectionRules, generateDownMigration, generateFieldAddition, generateFieldDefinitionObject, generateFieldDeletion, generateFieldModification, generateFieldsArray, generateIndexesArray, executeGenerate as generateMigration, generateMigrationDescription, generateMigrationFilename, generatePermissionUpdate, generateTimestamp, generateUpMigration, geoPointField, getArrayElementType, getCollectionNameFromFile, getDefaultValue, getFieldTypeInfo, getMaxSelect, executeStatus as getMigrationStatus, getMinSelect, getSnapshotPath, getSnapshotVersion, getUsersSystemFields, importSchemaModule, inputImageFileSchema, isArrayType, isAuthCollection, isEditorField, isFieldRequired, isFileFieldByName, isGeoPointType, isMultipleRelationField, isPermissionSchema, isRelationField, isSingleRelationField, isSystemCollection, isTemplateConfig, jsonField, loadBaseMigration, loadConfig, loadSnapshot, loadSnapshotIfExists, logError, logInfo, logSection, logSuccess, logWarning, mapZodArrayType, mapZodBooleanType, mapZodDateType, mapZodEnumType, mapZodNumberType, mapZodRecordType, mapZodStringType, mapZodTypeToPocketBase, matchCollectionsByName, matchFieldsByName, mergePermissions, mergeSnapshots, numberField, omitImageFilesSchema, parseSchemaFiles, pluralize, relationField, relationsField, requiresForceFlag, resolveTargetCollection, resolveTemplate, saveSnapshot, selectField, selectSchemaForCollection, singularize, snapshotExists, textField, toCollectionName, unwrapZodType, urlField, validatePermissionConfig, validateRuleExpression, validateSnapshot, withIndexes, withPermissions, withProgress, writeMigrationFile };
4725
+ //# sourceMappingURL=index.js.map
4726
+ //# sourceMappingURL=index.js.map