pocketbase-zod-schema 0.2.4 → 0.3.0

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 (67) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +209 -24
  3. package/dist/cli/index.cjs +406 -294
  4. package/dist/cli/index.cjs.map +1 -1
  5. package/dist/cli/index.d.cts +3 -1
  6. package/dist/cli/index.d.ts +3 -1
  7. package/dist/cli/index.js +406 -294
  8. package/dist/cli/index.js.map +1 -1
  9. package/dist/cli/migrate.cjs +406 -294
  10. package/dist/cli/migrate.cjs.map +1 -1
  11. package/dist/cli/migrate.js +406 -294
  12. package/dist/cli/migrate.js.map +1 -1
  13. package/dist/cli/utils/index.d.cts +3 -1
  14. package/dist/cli/utils/index.d.ts +3 -1
  15. package/dist/fields-UcOPu1OQ.d.cts +364 -0
  16. package/dist/fields-UcOPu1OQ.d.ts +364 -0
  17. package/dist/index.cjs +633 -112
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +4 -3
  20. package/dist/index.d.ts +4 -3
  21. package/dist/index.js +619 -101
  22. package/dist/index.js.map +1 -1
  23. package/dist/migration/analyzer.cjs +44 -0
  24. package/dist/migration/analyzer.cjs.map +1 -1
  25. package/dist/migration/analyzer.d.cts +2 -1
  26. package/dist/migration/analyzer.d.ts +2 -1
  27. package/dist/migration/analyzer.js +44 -0
  28. package/dist/migration/analyzer.js.map +1 -1
  29. package/dist/migration/diff.cjs +76 -1
  30. package/dist/migration/diff.cjs.map +1 -1
  31. package/dist/migration/diff.d.cts +3 -1
  32. package/dist/migration/diff.d.ts +3 -1
  33. package/dist/migration/diff.js +76 -1
  34. package/dist/migration/diff.js.map +1 -1
  35. package/dist/migration/generator.cjs +323 -46
  36. package/dist/migration/generator.cjs.map +1 -1
  37. package/dist/migration/generator.d.cts +60 -11
  38. package/dist/migration/generator.d.ts +60 -11
  39. package/dist/migration/generator.js +319 -47
  40. package/dist/migration/generator.js.map +1 -1
  41. package/dist/migration/index.cjs +433 -47
  42. package/dist/migration/index.cjs.map +1 -1
  43. package/dist/migration/index.d.cts +3 -2
  44. package/dist/migration/index.d.ts +3 -2
  45. package/dist/migration/index.js +432 -48
  46. package/dist/migration/index.js.map +1 -1
  47. package/dist/migration/snapshot.cjs.map +1 -1
  48. package/dist/migration/snapshot.d.cts +3 -1
  49. package/dist/migration/snapshot.d.ts +3 -1
  50. package/dist/migration/snapshot.js.map +1 -1
  51. package/dist/migration/utils/index.cjs +80 -0
  52. package/dist/migration/utils/index.cjs.map +1 -1
  53. package/dist/migration/utils/index.d.cts +39 -202
  54. package/dist/migration/utils/index.d.ts +39 -202
  55. package/dist/migration/utils/index.js +77 -1
  56. package/dist/migration/utils/index.js.map +1 -1
  57. package/dist/schema.cjs +200 -61
  58. package/dist/schema.cjs.map +1 -1
  59. package/dist/schema.d.cts +2 -85
  60. package/dist/schema.d.ts +2 -85
  61. package/dist/schema.js +186 -50
  62. package/dist/schema.js.map +1 -1
  63. package/dist/type-mapper-DrQmtznD.d.cts +208 -0
  64. package/dist/type-mapper-n231Fspm.d.ts +208 -0
  65. package/dist/{types-z1Dkjg8m.d.ts → types-Ds3NQvny.d.ts} +33 -2
  66. package/dist/{types-BbTgmg6H.d.cts → types-YoBjsa-A.d.cts} +33 -2
  67. package/package.json +1 -1
@@ -110,6 +110,53 @@ function generateTimestamp(config) {
110
110
  }
111
111
  return Math.floor(Date.now() / 1e3).toString();
112
112
  }
113
+ function splitDiffByCollection(diff, baseTimestamp) {
114
+ const operations = [];
115
+ let currentTimestamp = parseInt(baseTimestamp, 10);
116
+ for (const collection of diff.collectionsToCreate) {
117
+ operations.push({
118
+ type: "create",
119
+ collection,
120
+ timestamp: currentTimestamp.toString()
121
+ });
122
+ currentTimestamp += 1;
123
+ }
124
+ for (const modification of diff.collectionsToModify) {
125
+ operations.push({
126
+ type: "modify",
127
+ collection: modification.collection,
128
+ modifications: modification,
129
+ timestamp: currentTimestamp.toString()
130
+ });
131
+ currentTimestamp += 1;
132
+ }
133
+ for (const collection of diff.collectionsToDelete) {
134
+ operations.push({
135
+ type: "delete",
136
+ collection: collection.name || collection,
137
+ // Handle both object and string
138
+ timestamp: currentTimestamp.toString()
139
+ });
140
+ currentTimestamp += 1;
141
+ }
142
+ return operations;
143
+ }
144
+ function generateCollectionMigrationFilename(operation) {
145
+ const timestamp = operation.timestamp;
146
+ const operationType = operation.type === "modify" ? "updated" : operation.type === "create" ? "created" : "deleted";
147
+ let collectionName;
148
+ if (typeof operation.collection === "string") {
149
+ collectionName = operation.collection;
150
+ } else {
151
+ collectionName = operation.collection.name;
152
+ }
153
+ const sanitizedName = collectionName.replace(/[^a-zA-Z0-9_]/g, "_").toLowerCase();
154
+ return `${timestamp}_${operationType}_${sanitizedName}.js`;
155
+ }
156
+ function incrementTimestamp(timestamp) {
157
+ const currentTimestamp = parseInt(timestamp, 10);
158
+ return (currentTimestamp + 1).toString();
159
+ }
113
160
  function generateMigrationDescription(diff) {
114
161
  const parts = [];
115
162
  if (diff.collectionsToCreate.length > 0) {
@@ -217,14 +264,13 @@ function formatValue(value) {
217
264
  return "null";
218
265
  }
219
266
  if (typeof value === "string") {
220
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
267
+ return JSON.stringify(value);
221
268
  }
222
269
  if (typeof value === "number" || typeof value === "boolean") {
223
270
  return String(value);
224
271
  }
225
272
  if (Array.isArray(value)) {
226
- const items = value.map((v) => formatValue(v)).join(", ");
227
- return `[${items}]`;
273
+ return JSON.stringify(value).replace(/","/g, '", "');
228
274
  }
229
275
  if (typeof value === "object") {
230
276
  const entries = Object.entries(value).map(([k, v]) => `${k}: ${formatValue(v)}`).join(", ");
@@ -232,7 +278,7 @@ function formatValue(value) {
232
278
  }
233
279
  return String(value);
234
280
  }
235
- function generateFieldDefinitionObject(field) {
281
+ function generateFieldDefinitionObject(field, collectionIdMap) {
236
282
  const parts = [];
237
283
  parts.push(` name: "${field.name}"`);
238
284
  parts.push(` type: "${field.type}"`);
@@ -240,34 +286,47 @@ function generateFieldDefinitionObject(field) {
240
286
  if (field.unique !== void 0) {
241
287
  parts.push(` unique: ${field.unique}`);
242
288
  }
289
+ if (field.type === "select") {
290
+ const maxSelect = field.options?.maxSelect ?? 1;
291
+ parts.push(` maxSelect: ${maxSelect}`);
292
+ const values = field.options?.values ?? [];
293
+ parts.push(` values: ${formatValue(values)}`);
294
+ }
243
295
  if (field.options && Object.keys(field.options).length > 0) {
244
296
  for (const [key, value] of Object.entries(field.options)) {
297
+ if (field.type === "select" && (key === "maxSelect" || key === "values")) {
298
+ continue;
299
+ }
245
300
  parts.push(` ${key}: ${formatValue(value)}`);
246
301
  }
247
302
  }
248
303
  if (field.relation) {
249
304
  const isUsersCollection = field.relation.collection.toLowerCase() === "users";
250
- const collectionIdPlaceholder = isUsersCollection ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
251
- parts.push(` collectionId: ${collectionIdPlaceholder}`);
252
- if (field.relation.maxSelect !== void 0) {
253
- parts.push(` maxSelect: ${field.relation.maxSelect}`);
254
- }
255
- if (field.relation.minSelect !== void 0) {
256
- parts.push(` minSelect: ${field.relation.minSelect}`);
257
- }
258
- if (field.relation.cascadeDelete !== void 0) {
259
- parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
305
+ let collectionIdValue;
306
+ if (isUsersCollection) {
307
+ collectionIdValue = '"_pb_users_auth_"';
308
+ } else if (collectionIdMap && collectionIdMap.has(field.relation.collection)) {
309
+ collectionIdValue = `"${collectionIdMap.get(field.relation.collection)}"`;
310
+ } else {
311
+ collectionIdValue = `app.findCollectionByNameOrId("${field.relation.collection}").id`;
260
312
  }
313
+ parts.push(` collectionId: ${collectionIdValue}`);
314
+ const maxSelect = field.relation.maxSelect ?? 1;
315
+ parts.push(` maxSelect: ${maxSelect}`);
316
+ const minSelect = field.relation.minSelect ?? null;
317
+ parts.push(` minSelect: ${minSelect}`);
318
+ const cascadeDelete = field.relation.cascadeDelete ?? false;
319
+ parts.push(` cascadeDelete: ${cascadeDelete}`);
261
320
  }
262
321
  return ` {
263
322
  ${parts.join(",\n")},
264
323
  }`;
265
324
  }
266
- function generateFieldsArray(fields) {
325
+ function generateFieldsArray(fields, collectionIdMap) {
267
326
  if (fields.length === 0) {
268
327
  return "[]";
269
328
  }
270
- const fieldObjects = fields.map((field) => generateFieldDefinitionObject(field));
329
+ const fieldObjects = fields.map((field) => generateFieldDefinitionObject(field, collectionIdMap));
271
330
  return `[
272
331
  ${fieldObjects.join(",\n")},
273
332
  ]`;
@@ -326,7 +385,7 @@ function generateIndexesArray(indexes) {
326
385
  if (!indexes || indexes.length === 0) {
327
386
  return "[]";
328
387
  }
329
- const indexStrings = indexes.map((idx) => `"${idx}"`);
388
+ const indexStrings = indexes.map((idx) => JSON.stringify(idx));
330
389
  return `[
331
390
  ${indexStrings.join(",\n ")},
332
391
  ]`;
@@ -380,7 +439,7 @@ function getSystemFields() {
380
439
  }
381
440
  ];
382
441
  }
383
- function generateCollectionCreation(collection, varName = "collection", isLast = false) {
442
+ function generateCollectionCreation(collection, varName = "collection", isLast = false, collectionIdMap) {
384
443
  const lines = [];
385
444
  lines.push(` const ${varName} = new Collection({`);
386
445
  lines.push(` name: "${collection.name}",`);
@@ -394,7 +453,7 @@ function generateCollectionCreation(collection, varName = "collection", isLast =
394
453
  }
395
454
  const systemFields = getSystemFields();
396
455
  const allFields = [...systemFields, ...collection.fields];
397
- lines.push(` fields: ${generateFieldsArray(allFields)},`);
456
+ lines.push(` fields: ${generateFieldsArray(allFields, collectionIdMap)},`);
398
457
  lines.push(` indexes: ${generateIndexesArray(collection.indexes)},`);
399
458
  lines.push(` });`);
400
459
  lines.push(``);
@@ -416,42 +475,59 @@ function getFieldConstructorName(fieldType) {
416
475
  };
417
476
  return constructorMap[fieldType] || "TextField";
418
477
  }
419
- function generateFieldConstructorOptions(field) {
478
+ function generateFieldConstructorOptions(field, collectionIdMap) {
420
479
  const parts = [];
421
480
  parts.push(` name: "${field.name}"`);
422
481
  parts.push(` required: ${field.required}`);
423
482
  if (field.unique !== void 0) {
424
483
  parts.push(` unique: ${field.unique}`);
425
484
  }
485
+ if (field.type === "select") {
486
+ const maxSelect = field.options?.maxSelect ?? 1;
487
+ parts.push(` maxSelect: ${maxSelect}`);
488
+ const values = field.options?.values ?? [];
489
+ parts.push(` values: ${formatValue(values)}`);
490
+ }
426
491
  if (field.options && Object.keys(field.options).length > 0) {
427
492
  for (const [key, value] of Object.entries(field.options)) {
428
- parts.push(` ${key}: ${formatValue(value)}`);
493
+ if (field.type === "select" && (key === "maxSelect" || key === "values")) {
494
+ continue;
495
+ }
496
+ if (field.type === "number" && key === "noDecimal") {
497
+ parts.push(` onlyInt: ${formatValue(value)}`);
498
+ } else {
499
+ parts.push(` ${key}: ${formatValue(value)}`);
500
+ }
429
501
  }
430
502
  }
431
503
  if (field.relation && field.type === "relation") {
432
504
  const isUsersCollection = field.relation.collection.toLowerCase() === "users";
433
- const collectionIdPlaceholder = isUsersCollection ? '"_pb_users_auth_"' : `app.findCollectionByNameOrId("${field.relation.collection}").id`;
434
- parts.push(` collectionId: ${collectionIdPlaceholder}`);
435
- if (field.relation.maxSelect !== void 0) {
436
- parts.push(` maxSelect: ${field.relation.maxSelect}`);
437
- }
438
- if (field.relation.minSelect !== void 0) {
439
- parts.push(` minSelect: ${field.relation.minSelect}`);
440
- }
441
- if (field.relation.cascadeDelete !== void 0) {
442
- parts.push(` cascadeDelete: ${field.relation.cascadeDelete}`);
505
+ let collectionIdValue;
506
+ if (isUsersCollection) {
507
+ collectionIdValue = '"_pb_users_auth_"';
508
+ } else if (collectionIdMap && collectionIdMap.has(field.relation.collection)) {
509
+ collectionIdValue = `"${collectionIdMap.get(field.relation.collection)}"`;
510
+ } else {
511
+ collectionIdValue = `app.findCollectionByNameOrId("${field.relation.collection}").id`;
443
512
  }
513
+ parts.push(` collectionId: ${collectionIdValue}`);
514
+ const maxSelect = field.relation.maxSelect ?? 1;
515
+ parts.push(` maxSelect: ${maxSelect}`);
516
+ const minSelect = field.relation.minSelect ?? null;
517
+ parts.push(` minSelect: ${minSelect}`);
518
+ const cascadeDelete = field.relation.cascadeDelete ?? false;
519
+ parts.push(` cascadeDelete: ${cascadeDelete}`);
444
520
  }
445
521
  return parts.join(",\n");
446
522
  }
447
- function generateFieldAddition(collectionName, field, varName, isLast = false) {
523
+ function generateFieldAddition(collectionName, field, varName, isLast = false, collectionIdMap) {
448
524
  const lines = [];
449
525
  const constructorName = getFieldConstructorName(field.type);
450
526
  const collectionVar = varName || `collection_${collectionName}_${field.name}`;
451
527
  lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
452
528
  lines.push(``);
453
529
  lines.push(` ${collectionVar}.fields.add(new ${constructorName}({`);
454
- lines.push(generateFieldConstructorOptions(field));
530
+ lines.push(generateFieldConstructorOptions(field, collectionIdMap));
455
531
  lines.push(` }));`);
456
532
  lines.push(``);
457
533
  lines.push(isLast ? ` return app.save(${collectionVar});` : ` app.save(${collectionVar});`);
@@ -501,7 +577,7 @@ function generateIndexAddition(collectionName, index, varName, isLast = false) {
501
577
  const lines = [];
502
578
  const collectionVar = varName || `collection_${collectionName}_idx`;
503
579
  lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
504
- lines.push(` ${collectionVar}.indexes.push("${index}");`);
580
+ lines.push(` ${collectionVar}.indexes.push(${JSON.stringify(index)});`);
505
581
  lines.push(isLast ? ` return app.save(${collectionVar});` : ` app.save(${collectionVar});`);
506
582
  return lines.join("\n");
507
583
  }
@@ -510,7 +586,7 @@ function generateIndexRemoval(collectionName, index, varName, isLast = false) {
510
586
  const collectionVar = varName || `collection_${collectionName}_idx`;
511
587
  const indexVar = `${collectionVar}_indexToRemove`;
512
588
  lines.push(` const ${collectionVar} = app.findCollectionByNameOrId("${collectionName}");`);
513
- lines.push(` const ${indexVar} = ${collectionVar}.indexes.findIndex(idx => idx === "${index}");`);
589
+ lines.push(` const ${indexVar} = ${collectionVar}.indexes.findIndex(idx => idx === ${JSON.stringify(index)});`);
514
590
  lines.push(` if (${indexVar} !== -1) {`);
515
591
  lines.push(` ${collectionVar}.indexes.splice(${indexVar}, 1);`);
516
592
  lines.push(` }`);
@@ -539,16 +615,179 @@ function generateCollectionDeletion(collectionName, varName = "collection", isLa
539
615
  lines.push(isLast ? ` return app.delete(${varName});` : ` app.delete(${varName});`);
540
616
  return lines.join("\n");
541
617
  }
618
+ function generateOperationUpMigration(operation, collectionIdMap) {
619
+ const lines = [];
620
+ if (operation.type === "create") {
621
+ const collection = operation.collection;
622
+ const varName = `collection_${collection.name}`;
623
+ lines.push(generateCollectionCreation(collection, varName, true, collectionIdMap));
624
+ } else if (operation.type === "modify") {
625
+ const modification = operation.modifications;
626
+ const collectionName = typeof operation.collection === "string" ? operation.collection : operation.collection?.name ?? modification.collection;
627
+ let operationCount = 0;
628
+ const totalOperations = modification.fieldsToAdd.length + modification.fieldsToModify.length + modification.fieldsToRemove.length + modification.indexesToAdd.length + modification.indexesToRemove.length + modification.rulesToUpdate.length + modification.permissionsToUpdate.length;
629
+ for (const field of modification.fieldsToAdd) {
630
+ operationCount++;
631
+ const varName = `collection_${collectionName}_add_${field.name}`;
632
+ const isLast = operationCount === totalOperations;
633
+ lines.push(generateFieldAddition(collectionName, field, varName, isLast, collectionIdMap));
634
+ if (!isLast) lines.push("");
635
+ }
636
+ for (const fieldMod of modification.fieldsToModify) {
637
+ operationCount++;
638
+ const varName = `collection_${collectionName}_modify_${fieldMod.fieldName}`;
639
+ const isLast = operationCount === totalOperations;
640
+ lines.push(generateFieldModification(collectionName, fieldMod, varName, isLast));
641
+ if (!isLast) lines.push("");
642
+ }
643
+ for (const field of modification.fieldsToRemove) {
644
+ operationCount++;
645
+ const varName = `collection_${collectionName}_remove_${field.name}`;
646
+ const isLast = operationCount === totalOperations;
647
+ lines.push(generateFieldDeletion(collectionName, field.name, varName, isLast));
648
+ if (!isLast) lines.push("");
649
+ }
650
+ for (let i = 0; i < modification.indexesToAdd.length; i++) {
651
+ operationCount++;
652
+ const index = modification.indexesToAdd[i];
653
+ const varName = `collection_${collectionName}_addidx_${i}`;
654
+ const isLast = operationCount === totalOperations;
655
+ lines.push(generateIndexAddition(collectionName, index, varName, isLast));
656
+ if (!isLast) lines.push("");
657
+ }
658
+ for (let i = 0; i < modification.indexesToRemove.length; i++) {
659
+ operationCount++;
660
+ const index = modification.indexesToRemove[i];
661
+ const varName = `collection_${collectionName}_rmidx_${i}`;
662
+ const isLast = operationCount === totalOperations;
663
+ lines.push(generateIndexRemoval(collectionName, index, varName, isLast));
664
+ if (!isLast) lines.push("");
665
+ }
666
+ if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
667
+ for (const permission of modification.permissionsToUpdate) {
668
+ operationCount++;
669
+ const varName = `collection_${collectionName}_perm_${permission.ruleType}`;
670
+ const isLast = operationCount === totalOperations;
671
+ lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.newValue, varName, isLast));
672
+ if (!isLast) lines.push("");
673
+ }
674
+ } else if (modification.rulesToUpdate.length > 0) {
675
+ for (const rule of modification.rulesToUpdate) {
676
+ operationCount++;
677
+ const varName = `collection_${collectionName}_rule_${rule.ruleType}`;
678
+ const isLast = operationCount === totalOperations;
679
+ lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.newValue, varName, isLast));
680
+ if (!isLast) lines.push("");
681
+ }
682
+ }
683
+ } else if (operation.type === "delete") {
684
+ const collectionName = typeof operation.collection === "string" ? operation.collection : operation.collection.name;
685
+ const varName = `collection_${collectionName}`;
686
+ lines.push(generateCollectionDeletion(collectionName, varName, true));
687
+ }
688
+ return lines.join("\n");
689
+ }
690
+ function generateOperationDownMigration(operation, collectionIdMap) {
691
+ const lines = [];
692
+ if (operation.type === "create") {
693
+ const collection = operation.collection;
694
+ const varName = `collection_${collection.name}`;
695
+ lines.push(generateCollectionDeletion(collection.name, varName, true));
696
+ } else if (operation.type === "modify") {
697
+ const modification = operation.modifications;
698
+ const collectionName = typeof operation.collection === "string" ? operation.collection : operation.collection?.name ?? modification.collection;
699
+ let operationCount = 0;
700
+ const totalOperations = modification.fieldsToAdd.length + modification.fieldsToModify.length + modification.fieldsToRemove.length + modification.indexesToAdd.length + modification.indexesToRemove.length + modification.rulesToUpdate.length + modification.permissionsToUpdate.length;
701
+ if (modification.permissionsToUpdate && modification.permissionsToUpdate.length > 0) {
702
+ for (const permission of modification.permissionsToUpdate) {
703
+ operationCount++;
704
+ const varName = `collection_${collectionName}_revert_perm_${permission.ruleType}`;
705
+ const isLast = operationCount === totalOperations;
706
+ lines.push(generatePermissionUpdate(collectionName, permission.ruleType, permission.oldValue, varName, isLast));
707
+ if (!isLast) lines.push("");
708
+ }
709
+ } else if (modification.rulesToUpdate.length > 0) {
710
+ for (const rule of modification.rulesToUpdate) {
711
+ operationCount++;
712
+ const varName = `collection_${collectionName}_revert_rule_${rule.ruleType}`;
713
+ const isLast = operationCount === totalOperations;
714
+ lines.push(generateRuleUpdate(collectionName, rule.ruleType, rule.oldValue, varName, isLast));
715
+ if (!isLast) lines.push("");
716
+ }
717
+ }
718
+ for (let i = 0; i < modification.indexesToRemove.length; i++) {
719
+ operationCount++;
720
+ const index = modification.indexesToRemove[i];
721
+ const varName = `collection_${collectionName}_restore_idx_${i}`;
722
+ const isLast = operationCount === totalOperations;
723
+ lines.push(generateIndexAddition(collectionName, index, varName, isLast));
724
+ if (!isLast) lines.push("");
725
+ }
726
+ for (let i = 0; i < modification.indexesToAdd.length; i++) {
727
+ operationCount++;
728
+ const index = modification.indexesToAdd[i];
729
+ const varName = `collection_${collectionName}_revert_idx_${i}`;
730
+ const isLast = operationCount === totalOperations;
731
+ lines.push(generateIndexRemoval(collectionName, index, varName, isLast));
732
+ if (!isLast) lines.push("");
733
+ }
734
+ for (const field of modification.fieldsToRemove) {
735
+ operationCount++;
736
+ const varName = `collection_${collectionName}_restore_${field.name}`;
737
+ const isLast = operationCount === totalOperations;
738
+ lines.push(generateFieldAddition(collectionName, field, varName, isLast, collectionIdMap));
739
+ if (!isLast) lines.push("");
740
+ }
741
+ for (const fieldMod of modification.fieldsToModify) {
742
+ operationCount++;
743
+ const reverseChanges = fieldMod.changes.map((change) => ({
744
+ property: change.property,
745
+ oldValue: change.newValue,
746
+ newValue: change.oldValue
747
+ }));
748
+ const reverseMod = {
749
+ fieldName: fieldMod.fieldName,
750
+ currentDefinition: fieldMod.newDefinition,
751
+ newDefinition: fieldMod.currentDefinition,
752
+ changes: reverseChanges
753
+ };
754
+ const varName = `collection_${collectionName}_revert_${fieldMod.fieldName}`;
755
+ const isLast = operationCount === totalOperations;
756
+ lines.push(generateFieldModification(collectionName, reverseMod, varName, isLast));
757
+ if (!isLast) lines.push("");
758
+ }
759
+ for (const field of modification.fieldsToAdd) {
760
+ operationCount++;
761
+ const varName = `collection_${collectionName}_revert_add_${field.name}`;
762
+ const isLast = operationCount === totalOperations;
763
+ lines.push(generateFieldDeletion(collectionName, field.name, varName, isLast));
764
+ if (!isLast) lines.push("");
765
+ }
766
+ } else if (operation.type === "delete") {
767
+ const collection = operation.collection;
768
+ if (typeof collection !== "string") {
769
+ const varName = `collection_${collection.name}`;
770
+ lines.push(generateCollectionCreation(collection, varName, true, collectionIdMap));
771
+ }
772
+ }
773
+ return lines.join("\n");
774
+ }
542
775
  function generateUpMigration(diff) {
543
776
  const lines = [];
544
777
  lines.push(` // UP MIGRATION`);
545
778
  lines.push(``);
779
+ const collectionIdMap = /* @__PURE__ */ new Map();
780
+ for (const collection of diff.collectionsToCreate) {
781
+ if (collection.id) {
782
+ collectionIdMap.set(collection.name, collection.id);
783
+ }
784
+ }
546
785
  if (diff.collectionsToCreate.length > 0) {
547
786
  lines.push(` // Create new collections`);
548
787
  for (let i = 0; i < diff.collectionsToCreate.length; i++) {
549
788
  const collection = diff.collectionsToCreate[i];
550
789
  const varName = `collection_${collection.name}_create`;
551
- lines.push(generateCollectionCreation(collection, varName));
790
+ lines.push(generateCollectionCreation(collection, varName, false, collectionIdMap));
552
791
  lines.push(``);
553
792
  }
554
793
  }
@@ -560,7 +799,7 @@ function generateUpMigration(diff) {
560
799
  lines.push(` // Add fields to ${collectionName}`);
561
800
  for (const field of modification.fieldsToAdd) {
562
801
  const varName = `collection_${collectionName}_add_${field.name}`;
563
- lines.push(generateFieldAddition(collectionName, field, varName));
802
+ lines.push(generateFieldAddition(collectionName, field, varName, false, collectionIdMap));
564
803
  lines.push(``);
565
804
  }
566
805
  }
@@ -651,12 +890,23 @@ function generateDownMigration(diff) {
651
890
  const lines = [];
652
891
  lines.push(` // DOWN MIGRATION (ROLLBACK)`);
653
892
  lines.push(``);
893
+ const collectionIdMap = /* @__PURE__ */ new Map();
894
+ for (const collection of diff.collectionsToCreate) {
895
+ if (collection.id) {
896
+ collectionIdMap.set(collection.name, collection.id);
897
+ }
898
+ }
899
+ for (const collection of diff.collectionsToDelete) {
900
+ if (collection.id) {
901
+ collectionIdMap.set(collection.name, collection.id);
902
+ }
903
+ }
654
904
  if (diff.collectionsToDelete.length > 0) {
655
905
  lines.push(` // Recreate deleted collections`);
656
906
  for (let i = 0; i < diff.collectionsToDelete.length; i++) {
657
907
  const collection = diff.collectionsToDelete[i];
658
908
  const varName = `collection_${collection.name}_recreate`;
659
- lines.push(generateCollectionCreation(collection, varName));
909
+ lines.push(generateCollectionCreation(collection, varName, false, collectionIdMap));
660
910
  lines.push(``);
661
911
  }
662
912
  }
@@ -701,7 +951,7 @@ function generateDownMigration(diff) {
701
951
  lines.push(` // Restore fields to ${collectionName}`);
702
952
  for (const field of modification.fieldsToRemove) {
703
953
  const varName = `collection_${collectionName}_restore_${field.name}`;
704
- lines.push(generateFieldAddition(collectionName, field, varName));
954
+ lines.push(generateFieldAddition(collectionName, field, varName, false, collectionIdMap));
705
955
  lines.push(``);
706
956
  }
707
957
  }
@@ -770,12 +1020,33 @@ function generate(diff, config) {
770
1020
  const normalizedConfig = typeof config === "string" ? { migrationDir: config } : config;
771
1021
  try {
772
1022
  const migrationDir = resolveMigrationDir(normalizedConfig);
773
- const upCode = generateUpMigration(diff);
774
- const downCode = generateDownMigration(diff);
775
- const content = createMigrationFileStructure(upCode, downCode, normalizedConfig);
776
- const filename = generateMigrationFilename(diff, normalizedConfig);
777
- const filePath = writeMigrationFile(migrationDir, filename, content);
778
- return filePath;
1023
+ const hasChanges = diff.collectionsToCreate.length > 0 || diff.collectionsToModify.length > 0 || diff.collectionsToDelete.length > 0;
1024
+ if (!hasChanges) {
1025
+ return [];
1026
+ }
1027
+ const collectionIdMap = /* @__PURE__ */ new Map();
1028
+ for (const collection of diff.collectionsToCreate) {
1029
+ if (collection.id) {
1030
+ collectionIdMap.set(collection.name, collection.id);
1031
+ }
1032
+ }
1033
+ for (const collection of diff.collectionsToDelete) {
1034
+ if (collection.id) {
1035
+ collectionIdMap.set(collection.name, collection.id);
1036
+ }
1037
+ }
1038
+ const baseTimestamp = generateTimestamp(normalizedConfig);
1039
+ const operations = splitDiffByCollection(diff, baseTimestamp);
1040
+ const filePaths = [];
1041
+ for (const operation of operations) {
1042
+ const upCode = generateOperationUpMigration(operation, collectionIdMap);
1043
+ const downCode = generateOperationDownMigration(operation, collectionIdMap);
1044
+ const content = createMigrationFileStructure(upCode, downCode, normalizedConfig);
1045
+ const filename = generateCollectionMigrationFilename(operation);
1046
+ const filePath = writeMigrationFile(migrationDir, filename, content);
1047
+ filePaths.push(filePath);
1048
+ }
1049
+ return filePaths;
779
1050
  } catch (error) {
780
1051
  if (error instanceof MigrationGenerationError || error instanceof FileSystemError) {
781
1052
  throw error;
@@ -793,7 +1064,8 @@ var MigrationGenerator = class {
793
1064
  this.config = mergeConfig(config);
794
1065
  }
795
1066
  /**
796
- * Generates a migration file from a schema diff
1067
+ * Generates migration files from a schema diff
1068
+ * Returns array of file paths (one per collection operation)
797
1069
  */
798
1070
  generate(diff) {
799
1071
  return generate(diff, this.config);
@@ -818,6 +1090,6 @@ var MigrationGenerator = class {
818
1090
  }
819
1091
  };
820
1092
 
821
- export { MigrationGenerator, createMigrationFileStructure, generate, generateCollectionCreation, generateCollectionPermissions, generateCollectionRules, generateDownMigration, generateFieldAddition, generateFieldDefinitionObject, generateFieldDeletion, generateFieldModification, generateFieldsArray, generateIndexesArray, generateMigrationDescription, generateMigrationFilename, generatePermissionUpdate, generateTimestamp, generateUpMigration, writeMigrationFile };
1093
+ export { MigrationGenerator, createMigrationFileStructure, generate, generateCollectionCreation, generateCollectionMigrationFilename, generateCollectionPermissions, generateCollectionRules, generateDownMigration, generateFieldAddition, generateFieldDefinitionObject, generateFieldDeletion, generateFieldModification, generateFieldsArray, generateIndexesArray, generateMigrationDescription, generateMigrationFilename, generateOperationDownMigration, generateOperationUpMigration, generatePermissionUpdate, generateTimestamp, generateUpMigration, incrementTimestamp, splitDiffByCollection, writeMigrationFile };
822
1094
  //# sourceMappingURL=generator.js.map
823
1095
  //# sourceMappingURL=generator.js.map