pocketbase-zod-schema 0.1.3 → 0.1.4

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 (46) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/cli/index.cjs +406 -102
  3. package/dist/cli/index.cjs.map +1 -1
  4. package/dist/cli/index.js +404 -100
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/cli/migrate.cjs +409 -105
  7. package/dist/cli/migrate.cjs.map +1 -1
  8. package/dist/cli/migrate.js +404 -100
  9. package/dist/cli/migrate.js.map +1 -1
  10. package/dist/index.cjs +515 -159
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +3 -3
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.js +511 -158
  15. package/dist/index.js.map +1 -1
  16. package/dist/migration/diff.cjs +21 -3
  17. package/dist/migration/diff.cjs.map +1 -1
  18. package/dist/migration/diff.js +21 -3
  19. package/dist/migration/diff.js.map +1 -1
  20. package/dist/migration/index.cjs +457 -123
  21. package/dist/migration/index.cjs.map +1 -1
  22. package/dist/migration/index.d.cts +1 -1
  23. package/dist/migration/index.d.ts +1 -1
  24. package/dist/migration/index.js +456 -123
  25. package/dist/migration/index.js.map +1 -1
  26. package/dist/migration/snapshot.cjs +432 -118
  27. package/dist/migration/snapshot.cjs.map +1 -1
  28. package/dist/migration/snapshot.d.cts +34 -12
  29. package/dist/migration/snapshot.d.ts +34 -12
  30. package/dist/migration/snapshot.js +430 -117
  31. package/dist/migration/snapshot.js.map +1 -1
  32. package/dist/mutator.d.cts +3 -3
  33. package/dist/mutator.d.ts +3 -3
  34. package/dist/schema.cjs +34 -0
  35. package/dist/schema.cjs.map +1 -1
  36. package/dist/schema.d.cts +1 -1
  37. package/dist/schema.d.ts +1 -1
  38. package/dist/schema.js +33 -1
  39. package/dist/schema.js.map +1 -1
  40. package/dist/types.d.cts +5 -2
  41. package/dist/types.d.ts +5 -2
  42. package/dist/user-_AM523hb.d.cts +123 -0
  43. package/dist/user-_AM523hb.d.ts +123 -0
  44. package/package.json +2 -3
  45. package/dist/user-C39DQ40N.d.cts +0 -53
  46. package/dist/user-C39DQ40N.d.ts +0 -53
@@ -1,5 +1,5 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
1
+ import * as fs2 from 'fs';
2
+ import * as path2 from 'path';
3
3
 
4
4
  // src/migration/snapshot.ts
5
5
 
@@ -48,10 +48,10 @@ var FileSystemError = class _FileSystemError extends MigrationError {
48
48
  operation;
49
49
  code;
50
50
  originalError;
51
- constructor(message, path2, operation, code, originalError) {
51
+ constructor(message, path3, operation, code, originalError) {
52
52
  super(message);
53
53
  this.name = "FileSystemError";
54
- this.path = path2;
54
+ this.path = path3;
55
55
  this.operation = operation;
56
56
  this.code = code;
57
57
  this.originalError = originalError;
@@ -82,8 +82,358 @@ Cause: ${this.originalError.message}`);
82
82
  }
83
83
  };
84
84
 
85
- // src/migration/snapshot.ts
85
+ // src/migration/pocketbase-converter.ts
86
86
  var SNAPSHOT_VERSION = "1.0.0";
87
+ function resolveCollectionIdToName(collectionId) {
88
+ if (collectionId === "_pb_users_auth_") {
89
+ return "Users";
90
+ }
91
+ const nameMatch = collectionId.match(/app\.findCollectionByNameOrId\s*\(\s*["']([^"']+)["']\s*\)/);
92
+ if (nameMatch) {
93
+ return nameMatch[1];
94
+ }
95
+ return collectionId;
96
+ }
97
+ function convertPocketBaseCollection(pbCollection) {
98
+ const fields = [];
99
+ const systemFieldNames = ["id", "created", "updated", "collectionId", "collectionName", "expand"];
100
+ const authSystemFieldNames = ["email", "emailVisibility", "verified", "password", "tokenKey"];
101
+ if (pbCollection.fields && Array.isArray(pbCollection.fields)) {
102
+ for (const pbField of pbCollection.fields) {
103
+ if (pbField.system || systemFieldNames.includes(pbField.name)) {
104
+ continue;
105
+ }
106
+ if (pbCollection.type === "auth" && authSystemFieldNames.includes(pbField.name)) {
107
+ continue;
108
+ }
109
+ const field = {
110
+ name: pbField.name,
111
+ type: pbField.type,
112
+ required: pbField.required || false
113
+ };
114
+ field.options = pbField.options ? { ...pbField.options } : {};
115
+ if (pbField.type === "select") {
116
+ if (pbField.values && Array.isArray(pbField.values)) {
117
+ field.options.values = pbField.values;
118
+ } else if (pbField.options?.values && Array.isArray(pbField.options.values)) {
119
+ field.options.values = pbField.options.values;
120
+ }
121
+ }
122
+ if (pbField.type === "relation") {
123
+ const collectionId = pbField.collectionId || pbField.options?.collectionId || "";
124
+ const collectionName = resolveCollectionIdToName(collectionId);
125
+ field.relation = {
126
+ collection: collectionName,
127
+ cascadeDelete: pbField.cascadeDelete ?? pbField.options?.cascadeDelete ?? false,
128
+ maxSelect: pbField.maxSelect ?? pbField.options?.maxSelect,
129
+ minSelect: pbField.minSelect ?? pbField.options?.minSelect
130
+ };
131
+ }
132
+ const hasOnlyValues = Object.keys(field.options).length === 1 && field.options.values !== void 0;
133
+ if (Object.keys(field.options).length === 0) {
134
+ delete field.options;
135
+ } else if (pbField.type === "select" && hasOnlyValues) ;
136
+ fields.push(field);
137
+ }
138
+ }
139
+ const schema = {
140
+ name: pbCollection.name,
141
+ type: pbCollection.type || "base",
142
+ fields
143
+ };
144
+ if (pbCollection.indexes && Array.isArray(pbCollection.indexes)) {
145
+ schema.indexes = pbCollection.indexes;
146
+ }
147
+ const rules = {};
148
+ if (pbCollection.listRule !== void 0) rules.listRule = pbCollection.listRule;
149
+ if (pbCollection.viewRule !== void 0) rules.viewRule = pbCollection.viewRule;
150
+ if (pbCollection.createRule !== void 0) rules.createRule = pbCollection.createRule;
151
+ if (pbCollection.updateRule !== void 0) rules.updateRule = pbCollection.updateRule;
152
+ if (pbCollection.deleteRule !== void 0) rules.deleteRule = pbCollection.deleteRule;
153
+ if (pbCollection.manageRule !== void 0) rules.manageRule = pbCollection.manageRule;
154
+ if (Object.keys(rules).length > 0) {
155
+ schema.rules = rules;
156
+ schema.permissions = { ...rules };
157
+ }
158
+ return schema;
159
+ }
160
+ function convertPocketBaseMigration(migrationContent) {
161
+ try {
162
+ const snapshotMatch = migrationContent.match(/const\s+snapshot\s*=\s*(\[[\s\S]*?\]);/);
163
+ if (!snapshotMatch) {
164
+ throw new Error("Could not find snapshot array in migration file");
165
+ }
166
+ const snapshotArrayStr = snapshotMatch[1];
167
+ let snapshotArray;
168
+ try {
169
+ snapshotArray = new Function(`return ${snapshotArrayStr}`)();
170
+ } catch (parseError) {
171
+ throw new Error(`Failed to parse snapshot array: ${parseError}`);
172
+ }
173
+ if (!Array.isArray(snapshotArray)) {
174
+ throw new Error("Snapshot is not an array");
175
+ }
176
+ const collections = /* @__PURE__ */ new Map();
177
+ for (const pbCollection of snapshotArray) {
178
+ if (!pbCollection.name) {
179
+ console.warn("Skipping collection without name");
180
+ continue;
181
+ }
182
+ const schema = convertPocketBaseCollection(pbCollection);
183
+ collections.set(pbCollection.name, schema);
184
+ }
185
+ return {
186
+ version: SNAPSHOT_VERSION,
187
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
188
+ collections
189
+ };
190
+ } catch (error) {
191
+ throw new SnapshotError(
192
+ `Failed to convert PocketBase migration: ${error instanceof Error ? error.message : String(error)}`,
193
+ void 0,
194
+ "parse",
195
+ error instanceof Error ? error : void 0
196
+ );
197
+ }
198
+ }
199
+
200
+ // src/migration/migration-parser.ts
201
+ function extractTimestampFromFilename(filename) {
202
+ const match = filename.match(/^(\d+)_/);
203
+ if (match) {
204
+ return parseInt(match[1], 10);
205
+ }
206
+ return null;
207
+ }
208
+ function findMigrationsAfterSnapshot(migrationsPath, snapshotTimestamp) {
209
+ try {
210
+ if (!fs2.existsSync(migrationsPath)) {
211
+ return [];
212
+ }
213
+ const files = fs2.readdirSync(migrationsPath);
214
+ const migrationFiles = [];
215
+ for (const file of files) {
216
+ if (file.endsWith("_collections_snapshot.js") || file.endsWith("_snapshot.js")) {
217
+ continue;
218
+ }
219
+ if (!file.endsWith(".js")) {
220
+ continue;
221
+ }
222
+ const timestamp = extractTimestampFromFilename(file);
223
+ if (timestamp && timestamp > snapshotTimestamp) {
224
+ migrationFiles.push({
225
+ path: path2.join(migrationsPath, file),
226
+ timestamp
227
+ });
228
+ }
229
+ }
230
+ migrationFiles.sort((a, b) => a.timestamp - b.timestamp);
231
+ return migrationFiles.map((f) => f.path);
232
+ } catch (error) {
233
+ console.warn(`Error finding migrations after snapshot: ${error}`);
234
+ return [];
235
+ }
236
+ }
237
+ function parseMigrationOperationsFromContent(content) {
238
+ const collectionsToCreate = [];
239
+ const collectionsToDelete = [];
240
+ try {
241
+ let searchIndex = 0;
242
+ while (true) {
243
+ const collectionStart = content.indexOf("new Collection(", searchIndex);
244
+ if (collectionStart === -1) {
245
+ break;
246
+ }
247
+ const openParen = collectionStart + "new Collection(".length;
248
+ let braceCount = 0;
249
+ let parenCount = 1;
250
+ let inString = false;
251
+ let stringChar = null;
252
+ let i = openParen;
253
+ while (i < content.length && /\s/.test(content[i])) {
254
+ i++;
255
+ }
256
+ if (content[i] !== "{") {
257
+ searchIndex = i + 1;
258
+ continue;
259
+ }
260
+ const objectStart = i;
261
+ braceCount = 1;
262
+ i++;
263
+ while (i < content.length && (braceCount > 0 || parenCount > 0)) {
264
+ const char = content[i];
265
+ const prevChar = i > 0 ? content[i - 1] : "";
266
+ if (!inString && (char === '"' || char === "'")) {
267
+ inString = true;
268
+ stringChar = char;
269
+ } else if (inString && char === stringChar && prevChar !== "\\") {
270
+ inString = false;
271
+ stringChar = null;
272
+ }
273
+ if (!inString) {
274
+ if (char === "{") braceCount++;
275
+ if (char === "}") braceCount--;
276
+ if (char === "(") parenCount++;
277
+ if (char === ")") parenCount--;
278
+ }
279
+ i++;
280
+ }
281
+ if (braceCount === 0 && parenCount === 0) {
282
+ const objectContent = content.substring(objectStart, i - 1);
283
+ try {
284
+ const collectionObj = new Function(`return ${objectContent}`)();
285
+ if (collectionObj && collectionObj.name) {
286
+ const schema = convertPocketBaseCollection(collectionObj);
287
+ collectionsToCreate.push(schema);
288
+ }
289
+ } catch (error) {
290
+ console.warn(`Failed to parse collection definition: ${error}`);
291
+ }
292
+ }
293
+ searchIndex = i;
294
+ }
295
+ const deleteMatches = content.matchAll(
296
+ /app\.delete\s*\(\s*(?:collection_\w+|app\.findCollectionByNameOrId\s*\(\s*["']([^"']+)["']\s*\))\s*\)/g
297
+ );
298
+ for (const match of deleteMatches) {
299
+ if (match[1]) {
300
+ collectionsToDelete.push(match[1]);
301
+ } else {
302
+ const varNameMatch = match[0].match(/collection_(\w+)/);
303
+ if (varNameMatch) {
304
+ const varName = `collection_${varNameMatch[1]}`;
305
+ const deleteIndex = content.indexOf(match[0]);
306
+ const beforeDelete = content.substring(0, deleteIndex);
307
+ const varDefMatch = beforeDelete.match(
308
+ new RegExp(`const\\s+${varName}\\s*=\\s*new\\s+Collection\\(\\s*(\\{[\\s\\S]*?\\})\\s*\\)`, "g")
309
+ );
310
+ if (varDefMatch && varDefMatch.length > 0) {
311
+ const collectionDefMatch = beforeDelete.match(
312
+ new RegExp(`const\\s+${varName}\\s*=\\s*new\\s+Collection\\(\\s*(\\{[\\s\\S]*?\\})\\s*\\)`)
313
+ );
314
+ if (collectionDefMatch) {
315
+ try {
316
+ const collectionDefStr = collectionDefMatch[1];
317
+ const collectionObj = new Function(`return ${collectionDefStr}`)();
318
+ if (collectionObj && collectionObj.name) {
319
+ collectionsToDelete.push(collectionObj.name);
320
+ }
321
+ } catch {
322
+ }
323
+ }
324
+ }
325
+ }
326
+ }
327
+ }
328
+ const findAndDeleteMatches = content.matchAll(
329
+ /app\.findCollectionByNameOrId\s*\(\s*["']([^"']+)["']\s*\)[\s\S]*?app\.delete/g
330
+ );
331
+ for (const match of findAndDeleteMatches) {
332
+ collectionsToDelete.push(match[1]);
333
+ }
334
+ } catch (error) {
335
+ console.warn(`Failed to parse migration operations from content: ${error}`);
336
+ }
337
+ return { collectionsToCreate, collectionsToDelete };
338
+ }
339
+ function parseMigrationOperations(migrationContent) {
340
+ try {
341
+ const migrateMatch = migrationContent.match(/migrate\s*\(\s*/);
342
+ if (!migrateMatch) {
343
+ return parseMigrationOperationsFromContent(migrationContent);
344
+ }
345
+ const startIndex = migrateMatch.index + migrateMatch[0].length;
346
+ let i = startIndex;
347
+ let parenCount = 0;
348
+ let foundFirstParen = false;
349
+ while (i < migrationContent.length) {
350
+ const char = migrationContent[i];
351
+ if (char === "(") {
352
+ parenCount++;
353
+ foundFirstParen = true;
354
+ i++;
355
+ break;
356
+ }
357
+ i++;
358
+ }
359
+ if (!foundFirstParen) {
360
+ return parseMigrationOperationsFromContent(migrationContent);
361
+ }
362
+ let inString = false;
363
+ let stringChar = null;
364
+ let foundBrace = false;
365
+ let braceStart = -1;
366
+ while (i < migrationContent.length && !foundBrace) {
367
+ const char = migrationContent[i];
368
+ const prevChar = i > 0 ? migrationContent[i - 1] : "";
369
+ if (!inString && (char === '"' || char === "'")) {
370
+ inString = true;
371
+ stringChar = char;
372
+ } else if (inString && char === stringChar && prevChar !== "\\") {
373
+ inString = false;
374
+ stringChar = null;
375
+ }
376
+ if (!inString) {
377
+ if (char === "(") parenCount++;
378
+ if (char === ")") {
379
+ parenCount--;
380
+ if (parenCount === 0) {
381
+ i++;
382
+ while (i < migrationContent.length && /\s/.test(migrationContent[i])) {
383
+ i++;
384
+ }
385
+ if (i < migrationContent.length - 1 && migrationContent[i] === "=" && migrationContent[i + 1] === ">") {
386
+ i += 2;
387
+ while (i < migrationContent.length && /\s/.test(migrationContent[i])) {
388
+ i++;
389
+ }
390
+ if (i < migrationContent.length && migrationContent[i] === "{") {
391
+ foundBrace = true;
392
+ braceStart = i + 1;
393
+ break;
394
+ }
395
+ }
396
+ }
397
+ }
398
+ }
399
+ i++;
400
+ }
401
+ if (!foundBrace || braceStart === -1) {
402
+ return parseMigrationOperationsFromContent(migrationContent);
403
+ }
404
+ let braceCount = 1;
405
+ i = braceStart;
406
+ inString = false;
407
+ stringChar = null;
408
+ while (i < migrationContent.length && braceCount > 0) {
409
+ const char = migrationContent[i];
410
+ const prevChar = i > 0 ? migrationContent[i - 1] : "";
411
+ if (!inString && (char === '"' || char === "'")) {
412
+ inString = true;
413
+ stringChar = char;
414
+ } else if (inString && char === stringChar && prevChar !== "\\") {
415
+ inString = false;
416
+ stringChar = null;
417
+ }
418
+ if (!inString) {
419
+ if (char === "{") braceCount++;
420
+ if (char === "}") braceCount--;
421
+ }
422
+ i++;
423
+ }
424
+ if (braceCount === 0) {
425
+ const upMigrationContent = migrationContent.substring(braceStart, i - 1);
426
+ return parseMigrationOperationsFromContent(upMigrationContent);
427
+ }
428
+ return parseMigrationOperationsFromContent(migrationContent);
429
+ } catch (error) {
430
+ console.warn(`Failed to parse migration operations: ${error}`);
431
+ return { collectionsToCreate: [], collectionsToDelete: [] };
432
+ }
433
+ }
434
+
435
+ // src/migration/snapshot.ts
436
+ var SNAPSHOT_VERSION2 = "1.0.0";
87
437
  var DEFAULT_SNAPSHOT_FILENAME = ".migration-snapshot.json";
88
438
  var SNAPSHOT_MIGRATIONS = [
89
439
  // Add migrations here as the format evolves
@@ -98,7 +448,7 @@ var DEFAULT_CONFIG = {
98
448
  snapshotPath: DEFAULT_SNAPSHOT_FILENAME,
99
449
  workspaceRoot: process.cwd(),
100
450
  autoMigrate: true,
101
- version: SNAPSHOT_VERSION
451
+ version: SNAPSHOT_VERSION2
102
452
  };
103
453
  function mergeConfig(config = {}) {
104
454
  return {
@@ -110,15 +460,15 @@ function getSnapshotPath(config = {}) {
110
460
  const mergedConfig = mergeConfig(config);
111
461
  const workspaceRoot = mergedConfig.workspaceRoot;
112
462
  const snapshotFilename = mergedConfig.snapshotPath;
113
- if (path.isAbsolute(snapshotFilename)) {
463
+ if (path2.isAbsolute(snapshotFilename)) {
114
464
  return snapshotFilename;
115
465
  }
116
- return path.join(workspaceRoot, snapshotFilename);
466
+ return path2.join(workspaceRoot, snapshotFilename);
117
467
  }
118
468
  function snapshotExists(config = {}) {
119
469
  try {
120
470
  const snapshotPath = getSnapshotPath(config);
121
- return fs.existsSync(snapshotPath);
471
+ return fs2.existsSync(snapshotPath);
122
472
  } catch {
123
473
  return false;
124
474
  }
@@ -177,13 +527,13 @@ function addSnapshotMetadata(schema, config) {
177
527
  function saveSnapshot(schema, config = {}) {
178
528
  const snapshotPath = getSnapshotPath(config);
179
529
  try {
180
- const snapshotDir = path.dirname(snapshotPath);
181
- if (!fs.existsSync(snapshotDir)) {
182
- fs.mkdirSync(snapshotDir, { recursive: true });
530
+ const snapshotDir = path2.dirname(snapshotPath);
531
+ if (!fs2.existsSync(snapshotDir)) {
532
+ fs2.mkdirSync(snapshotDir, { recursive: true });
183
533
  }
184
534
  const snapshotData = addSnapshotMetadata(schema, config);
185
535
  const jsonContent = JSON.stringify(snapshotData, null, 2);
186
- fs.writeFileSync(snapshotPath, jsonContent, "utf-8");
536
+ fs2.writeFileSync(snapshotPath, jsonContent, "utf-8");
187
537
  } catch (error) {
188
538
  handleFileSystemError(error, "write", snapshotPath);
189
539
  }
@@ -278,7 +628,7 @@ function deserializeSnapshot(data) {
278
628
  function loadSnapshot(config = {}) {
279
629
  const snapshotPath = getSnapshotPath(config);
280
630
  try {
281
- const jsonContent = fs.readFileSync(snapshotPath, "utf-8");
631
+ const jsonContent = fs2.readFileSync(snapshotPath, "utf-8");
282
632
  const data = parseAndValidateSnapshot(jsonContent, snapshotPath);
283
633
  const migratedData = migrateSnapshotFormat(data, config);
284
634
  return deserializeSnapshot(migratedData);
@@ -313,10 +663,10 @@ function mergeSnapshots(baseSnapshot, customSnapshot) {
313
663
  }
314
664
  function findLatestSnapshot(migrationsPath) {
315
665
  try {
316
- if (!fs.existsSync(migrationsPath)) {
666
+ if (!fs2.existsSync(migrationsPath)) {
317
667
  return null;
318
668
  }
319
- const files = fs.readdirSync(migrationsPath);
669
+ const files = fs2.readdirSync(migrationsPath);
320
670
  const snapshotFiles = files.filter(
321
671
  (file) => file.endsWith("_collections_snapshot.js") || file.endsWith("_snapshot.js")
322
672
  );
@@ -328,20 +678,74 @@ function findLatestSnapshot(migrationsPath) {
328
678
  if (!latestSnapshot) {
329
679
  return null;
330
680
  }
331
- return path.join(migrationsPath, latestSnapshot);
681
+ return path2.join(migrationsPath, latestSnapshot);
332
682
  } catch (error) {
333
683
  console.warn(`Error finding latest snapshot: ${error}`);
334
684
  return null;
335
685
  }
336
686
  }
687
+ function applyMigrationOperations(snapshot, operations) {
688
+ const updatedCollections = new Map(snapshot.collections);
689
+ for (const collectionName of operations.collectionsToDelete) {
690
+ updatedCollections.delete(collectionName);
691
+ }
692
+ for (const collection of operations.collectionsToCreate) {
693
+ updatedCollections.set(collection.name, collection);
694
+ }
695
+ return {
696
+ ...snapshot,
697
+ collections: updatedCollections
698
+ };
699
+ }
700
+ function loadSnapshotWithMigrations(config = {}) {
701
+ const migrationsPath = config.migrationsPath;
702
+ if (!migrationsPath) {
703
+ return null;
704
+ }
705
+ if (fs2.existsSync(migrationsPath) && fs2.statSync(migrationsPath).isFile()) {
706
+ try {
707
+ const migrationContent = fs2.readFileSync(migrationsPath, "utf-8");
708
+ return convertPocketBaseMigration(migrationContent);
709
+ } catch (error) {
710
+ console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);
711
+ return null;
712
+ }
713
+ }
714
+ const latestSnapshotPath = findLatestSnapshot(migrationsPath);
715
+ if (!latestSnapshotPath) {
716
+ return null;
717
+ }
718
+ try {
719
+ const migrationContent = fs2.readFileSync(latestSnapshotPath, "utf-8");
720
+ let snapshot = convertPocketBaseMigration(migrationContent);
721
+ const snapshotFilename = path2.basename(latestSnapshotPath);
722
+ const snapshotTimestamp = extractTimestampFromFilename(snapshotFilename);
723
+ if (snapshotTimestamp) {
724
+ const migrationFiles = findMigrationsAfterSnapshot(migrationsPath, snapshotTimestamp);
725
+ for (const migrationFile of migrationFiles) {
726
+ try {
727
+ const migrationContent2 = fs2.readFileSync(migrationFile, "utf-8");
728
+ const operations = parseMigrationOperations(migrationContent2);
729
+ snapshot = applyMigrationOperations(snapshot, operations);
730
+ } catch (error) {
731
+ console.warn(`Failed to apply migration ${migrationFile}: ${error}`);
732
+ }
733
+ }
734
+ }
735
+ return snapshot;
736
+ } catch (error) {
737
+ console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);
738
+ return null;
739
+ }
740
+ }
337
741
  function loadSnapshotIfExists(config = {}) {
338
742
  const migrationsPath = config.migrationsPath;
339
743
  if (!migrationsPath) {
340
744
  return null;
341
745
  }
342
- if (fs.existsSync(migrationsPath) && fs.statSync(migrationsPath).isFile()) {
746
+ if (fs2.existsSync(migrationsPath) && fs2.statSync(migrationsPath).isFile()) {
343
747
  try {
344
- const migrationContent = fs.readFileSync(migrationsPath, "utf-8");
748
+ const migrationContent = fs2.readFileSync(migrationsPath, "utf-8");
345
749
  return convertPocketBaseMigration(migrationContent);
346
750
  } catch (error) {
347
751
  console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);
@@ -351,7 +755,7 @@ function loadSnapshotIfExists(config = {}) {
351
755
  const latestSnapshotPath = findLatestSnapshot(migrationsPath);
352
756
  if (latestSnapshotPath) {
353
757
  try {
354
- const migrationContent = fs.readFileSync(latestSnapshotPath, "utf-8");
758
+ const migrationContent = fs2.readFileSync(latestSnapshotPath, "utf-8");
355
759
  return convertPocketBaseMigration(migrationContent);
356
760
  } catch (error) {
357
761
  console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);
@@ -360,100 +764,9 @@ function loadSnapshotIfExists(config = {}) {
360
764
  }
361
765
  return null;
362
766
  }
363
- function convertPocketBaseCollection(pbCollection) {
364
- const fields = [];
365
- const systemFieldNames = ["id", "created", "updated", "collectionId", "collectionName", "expand"];
366
- const authSystemFieldNames = ["email", "emailVisibility", "verified", "password", "tokenKey"];
367
- if (pbCollection.fields && Array.isArray(pbCollection.fields)) {
368
- for (const pbField of pbCollection.fields) {
369
- if (pbField.system || systemFieldNames.includes(pbField.name)) {
370
- continue;
371
- }
372
- if (pbCollection.type === "auth" && authSystemFieldNames.includes(pbField.name)) {
373
- continue;
374
- }
375
- const field = {
376
- name: pbField.name,
377
- type: pbField.type,
378
- required: pbField.required || false
379
- };
380
- if (pbField.options) {
381
- field.options = pbField.options;
382
- }
383
- if (pbField.type === "relation") {
384
- field.relation = {
385
- collection: pbField.options?.collectionId || "",
386
- cascadeDelete: pbField.options?.cascadeDelete || false,
387
- maxSelect: pbField.options?.maxSelect,
388
- minSelect: pbField.options?.minSelect
389
- };
390
- }
391
- fields.push(field);
392
- }
393
- }
394
- const schema = {
395
- name: pbCollection.name,
396
- type: pbCollection.type || "base",
397
- fields
398
- };
399
- if (pbCollection.indexes && Array.isArray(pbCollection.indexes)) {
400
- schema.indexes = pbCollection.indexes;
401
- }
402
- const rules = {};
403
- if (pbCollection.listRule !== void 0) rules.listRule = pbCollection.listRule;
404
- if (pbCollection.viewRule !== void 0) rules.viewRule = pbCollection.viewRule;
405
- if (pbCollection.createRule !== void 0) rules.createRule = pbCollection.createRule;
406
- if (pbCollection.updateRule !== void 0) rules.updateRule = pbCollection.updateRule;
407
- if (pbCollection.deleteRule !== void 0) rules.deleteRule = pbCollection.deleteRule;
408
- if (pbCollection.manageRule !== void 0) rules.manageRule = pbCollection.manageRule;
409
- if (Object.keys(rules).length > 0) {
410
- schema.rules = rules;
411
- schema.permissions = { ...rules };
412
- }
413
- return schema;
414
- }
415
- function convertPocketBaseMigration(migrationContent) {
416
- try {
417
- const snapshotMatch = migrationContent.match(/const\s+snapshot\s*=\s*(\[[\s\S]*?\]);/);
418
- if (!snapshotMatch) {
419
- throw new Error("Could not find snapshot array in migration file");
420
- }
421
- const snapshotArrayStr = snapshotMatch[1];
422
- let snapshotArray;
423
- try {
424
- snapshotArray = new Function(`return ${snapshotArrayStr}`)();
425
- } catch (parseError) {
426
- throw new Error(`Failed to parse snapshot array: ${parseError}`);
427
- }
428
- if (!Array.isArray(snapshotArray)) {
429
- throw new Error("Snapshot is not an array");
430
- }
431
- const collections = /* @__PURE__ */ new Map();
432
- for (const pbCollection of snapshotArray) {
433
- if (!pbCollection.name) {
434
- console.warn("Skipping collection without name");
435
- continue;
436
- }
437
- const schema = convertPocketBaseCollection(pbCollection);
438
- collections.set(pbCollection.name, schema);
439
- }
440
- return {
441
- version: SNAPSHOT_VERSION,
442
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
443
- collections
444
- };
445
- } catch (error) {
446
- throw new SnapshotError(
447
- `Failed to convert PocketBase migration: ${error instanceof Error ? error.message : String(error)}`,
448
- void 0,
449
- "parse",
450
- error instanceof Error ? error : void 0
451
- );
452
- }
453
- }
454
767
  function loadBaseMigration(migrationPath) {
455
768
  try {
456
- if (!fs.existsSync(migrationPath)) {
769
+ if (!fs2.existsSync(migrationPath)) {
457
770
  throw new SnapshotError(
458
771
  `Base migration file not found: ${migrationPath}
459
772
 
@@ -464,7 +777,7 @@ If the file exists in a different location, update the configuration.`,
464
777
  "read"
465
778
  );
466
779
  }
467
- const migrationContent = fs.readFileSync(migrationPath, "utf-8");
780
+ const migrationContent = fs2.readFileSync(migrationPath, "utf-8");
468
781
  const snapshot = convertPocketBaseMigration(migrationContent);
469
782
  return snapshot;
470
783
  } catch (error) {
@@ -500,14 +813,14 @@ Please ensure PocketBase is properly set up by running 'yarn setup'.`,
500
813
  }
501
814
  }
502
815
  function getSnapshotVersion() {
503
- return SNAPSHOT_VERSION;
816
+ return SNAPSHOT_VERSION2;
504
817
  }
505
818
  function validateSnapshot(snapshot) {
506
819
  const issues = [];
507
820
  if (!snapshot.version) {
508
821
  issues.push("Missing version field");
509
- } else if (compareVersions(snapshot.version, SNAPSHOT_VERSION) > 0) {
510
- issues.push(`Snapshot version ${snapshot.version} is newer than supported version ${SNAPSHOT_VERSION}`);
822
+ } else if (compareVersions(snapshot.version, SNAPSHOT_VERSION2) > 0) {
823
+ issues.push(`Snapshot version ${snapshot.version} is newer than supported version ${SNAPSHOT_VERSION2}`);
511
824
  }
512
825
  if (!snapshot.timestamp) {
513
826
  issues.push("Missing timestamp field");
@@ -571,6 +884,6 @@ var SnapshotManager = class {
571
884
  }
572
885
  };
573
886
 
574
- export { SnapshotManager, convertPocketBaseMigration, findLatestSnapshot, getSnapshotPath, getSnapshotVersion, loadBaseMigration, loadSnapshot, loadSnapshotIfExists, mergeSnapshots, saveSnapshot, snapshotExists, validateSnapshot };
887
+ export { SnapshotManager, convertPocketBaseMigration, findLatestSnapshot, getSnapshotPath, getSnapshotVersion, loadBaseMigration, loadSnapshot, loadSnapshotIfExists, loadSnapshotWithMigrations, mergeSnapshots, saveSnapshot, snapshotExists, validateSnapshot };
575
888
  //# sourceMappingURL=snapshot.js.map
576
889
  //# sourceMappingURL=snapshot.js.map