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
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/migration/errors.ts","../../src/migration/pocketbase-converter.ts","../../src/migration/migration-parser.ts","../../src/migration/snapshot.ts"],"names":["path","fs","SNAPSHOT_VERSION","path2","fs2","migrationContent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,cAAA,GAAN,MAAM,eAAA,SAAuB,KAAA,CAAM;AAAA,EACxC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAA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,MAAA,GAAyB,EAAC,EAAG;AACvC,IAAA,IAAA,CAAK,MAAA,GAAS,YAAY,MAAM,CAAA;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA,EAKA,YAAA,GAA+B;AAC7B,IAAA,OAAO,YAAA,CAAa,KAAK,MAAM,CAAA;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,MAAA,EAAgC;AAC3C,IAAA,YAAA,CAAa,MAAA,EAAQ,KAAK,MAAM,CAAA;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA,EAKA,oBAAA,GAA8C;AAC5C,IAAA,OAAO,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA,EAKA,cAAA,GAA0B;AACxB,IAAA,OAAO,cAAA,CAAe,KAAK,MAAM,CAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKA,2BAA2B,OAAA,EAAiC;AAC1D,IAAA,OAAO,2BAA2B,OAAO,CAAA;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA,EAKA,eAAA,GAA0B;AACxB,IAAA,OAAO,eAAA,CAAgB,KAAK,MAAM,CAAA;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA,EAKA,iBAAiB,QAAA,EAAgE;AAC/E,IAAA,OAAO,iBAAiB,QAAQ,CAAA;AAAA,EAClC;AACF","file":"snapshot.cjs","sourcesContent":["/**\n * Custom error classes for migration tool\n * Provides specific error types for better error handling and user feedback\n */\n\n/**\n * Base error class for all migration-related errors\n */\nexport class MigrationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MigrationError\";\n Object.setPrototypeOf(this, MigrationError.prototype);\n }\n}\n\n/**\n * Error thrown when schema parsing fails\n * Used when Zod schemas cannot be parsed or are invalid\n */\nexport class SchemaParsingError extends MigrationError {\n public readonly filePath?: string;\n public readonly originalError?: Error;\n\n constructor(message: string, filePath?: string, originalError?: Error) {\n super(message);\n this.name = \"SchemaParsingError\";\n this.filePath = filePath;\n this.originalError = originalError;\n Object.setPrototypeOf(this, SchemaParsingError.prototype);\n }\n\n /**\n * Creates a formatted error message with file path and original error details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.filePath) {\n parts.push(`\\nFile: ${this.filePath}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when snapshot operations fail\n * Used for snapshot file read/write/parse errors\n */\nexport class SnapshotError extends MigrationError {\n public readonly snapshotPath?: string;\n public readonly operation?: \"read\" | \"write\" | \"parse\" | \"validate\";\n public readonly originalError?: Error;\n\n constructor(\n message: string,\n snapshotPath?: string,\n operation?: \"read\" | \"write\" | \"parse\" | \"validate\",\n originalError?: Error\n ) {\n super(message);\n this.name = \"SnapshotError\";\n this.snapshotPath = snapshotPath;\n this.operation = operation;\n this.originalError = originalError;\n Object.setPrototypeOf(this, SnapshotError.prototype);\n }\n\n /**\n * Creates a formatted error message with snapshot path and operation details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.operation) {\n parts.push(`\\nOperation: ${this.operation}`);\n }\n\n if (this.snapshotPath) {\n parts.push(`\\nSnapshot: ${this.snapshotPath}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when migration file generation fails\n * Used when migration files cannot be created or written\n */\nexport class MigrationGenerationError extends MigrationError {\n public readonly migrationPath?: string;\n public readonly originalError?: Error;\n\n constructor(message: string, migrationPath?: string, originalError?: Error) {\n super(message);\n this.name = \"MigrationGenerationError\";\n this.migrationPath = migrationPath;\n this.originalError = originalError;\n Object.setPrototypeOf(this, MigrationGenerationError.prototype);\n }\n\n /**\n * Creates a formatted error message with migration path and original error details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.migrationPath) {\n parts.push(`\\nMigration: ${this.migrationPath}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when file system operations fail\n * Used for directory creation, file permissions, disk space issues\n */\nexport class FileSystemError extends MigrationError {\n public readonly path?: string;\n public readonly operation?: \"read\" | \"write\" | \"create\" | \"delete\" | \"access\";\n public readonly code?: string;\n public readonly originalError?: Error;\n\n constructor(\n message: string,\n path?: string,\n operation?: \"read\" | \"write\" | \"create\" | \"delete\" | \"access\",\n code?: string,\n originalError?: Error\n ) {\n super(message);\n this.name = \"FileSystemError\";\n this.path = path;\n this.operation = operation;\n this.code = code;\n this.originalError = originalError;\n Object.setPrototypeOf(this, FileSystemError.prototype);\n }\n\n /**\n * Creates a formatted error message with path, operation, and error code details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.operation) {\n parts.push(`\\nOperation: ${this.operation}`);\n }\n\n if (this.path) {\n parts.push(`\\nPath: ${this.path}`);\n }\n\n if (this.code) {\n parts.push(`\\nError Code: ${this.code}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when configuration is invalid\n * Used for configuration file parsing, validation, and path resolution errors\n */\nexport class ConfigurationError extends MigrationError {\n public readonly configPath?: string;\n public readonly invalidFields?: string[];\n public readonly originalError?: Error;\n\n constructor(message: string, configPath?: string, invalidFields?: string[], originalError?: Error) {\n super(message);\n this.name = \"ConfigurationError\";\n this.configPath = configPath;\n this.invalidFields = invalidFields;\n this.originalError = originalError;\n Object.setPrototypeOf(this, ConfigurationError.prototype);\n }\n\n /**\n * Creates a formatted error message with configuration details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.configPath) {\n parts.push(`\\nConfiguration File: ${this.configPath}`);\n }\n\n if (this.invalidFields && this.invalidFields.length > 0) {\n parts.push(`\\nInvalid Fields: ${this.invalidFields.join(\", \")}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when CLI command usage is incorrect\n * Used for invalid arguments, missing required options, etc.\n */\nexport class CLIUsageError extends MigrationError {\n public readonly command?: string;\n public readonly suggestion?: string;\n\n constructor(message: string, command?: string, suggestion?: string) {\n super(message);\n this.name = \"CLIUsageError\";\n this.command = command;\n this.suggestion = suggestion;\n Object.setPrototypeOf(this, CLIUsageError.prototype);\n }\n\n /**\n * Creates a formatted error message with usage suggestions\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.command) {\n parts.push(`\\nCommand: ${this.command}`);\n }\n\n if (this.suggestion) {\n parts.push(`\\nSuggestion: ${this.suggestion}`);\n }\n\n return parts.join(\"\");\n }\n}\n","/**\n * PocketBase Format Converter\n * Converts PocketBase collection objects to our internal CollectionSchema format\n *\n * This module handles conversion between PocketBase's native collection format\n * (as found in migration files and snapshots) and our internal schema representation.\n */\n\nimport { SnapshotError } from \"./errors\";\nimport type { CollectionSchema, SchemaSnapshot } from \"./types\";\n\nconst SNAPSHOT_VERSION = \"1.0.0\";\n\n/**\n * Resolves a collection ID to a collection name\n * Uses known constants and parses migration expressions to resolve IDs\n *\n * @param collectionId - The collection ID to resolve\n * @returns The collection name, or the original ID if it can't be resolved\n */\nexport function resolveCollectionIdToName(collectionId: string): string {\n // Known PocketBase constants\n // Note: We return \"Users\" (title case) for consistency, but this should be\n // normalized during comparison to handle case differences\n if (collectionId === \"_pb_users_auth_\") {\n return \"Users\";\n }\n\n // Try to extract collection name from expressions like app.findCollectionByNameOrId(\"Name\").id\n const nameMatch = collectionId.match(/app\\.findCollectionByNameOrId\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/);\n if (nameMatch) {\n return nameMatch[1];\n }\n\n // If we can't resolve it, return the original ID\n // This will cause a comparison issue, but it's better than failing\n return collectionId;\n}\n\n/**\n * Converts a PocketBase collection object to CollectionSchema format\n *\n * @param pbCollection - PocketBase collection object from migration file\n * @returns CollectionSchema object\n */\nexport function convertPocketBaseCollection(pbCollection: any): CollectionSchema {\n const fields: any[] = [];\n\n // System field names that should always be excluded\n const systemFieldNames = [\"id\", \"created\", \"updated\", \"collectionId\", \"collectionName\", \"expand\"];\n\n // Auth collection system field names\n const authSystemFieldNames = [\"email\", \"emailVisibility\", \"verified\", \"password\", \"tokenKey\"];\n\n // Convert PocketBase fields to our FieldDefinition format\n if (pbCollection.fields && Array.isArray(pbCollection.fields)) {\n for (const pbField of pbCollection.fields) {\n // Skip system fields by checking both the system flag and field name\n // Some PocketBase exports mark created/updated as system: false\n if (pbField.system || systemFieldNames.includes(pbField.name)) {\n continue;\n }\n\n // Skip auth system fields for auth collections\n if (pbCollection.type === \"auth\" && authSystemFieldNames.includes(pbField.name)) {\n continue;\n }\n\n const field: any = {\n name: pbField.name,\n type: pbField.type,\n required: pbField.required || false,\n };\n\n // Initialize options object\n field.options = pbField.options ? { ...pbField.options } : {};\n\n // Extract values for select/enum fields (values can be directly on field or in options)\n // This must be done before cleaning up empty options to ensure values are preserved\n if (pbField.type === \"select\") {\n // Check for values directly on the field first (common in migration files)\n if (pbField.values && Array.isArray(pbField.values)) {\n field.options.values = pbField.values;\n } else if (pbField.options?.values && Array.isArray(pbField.options.values)) {\n // Already in options, keep it\n field.options.values = pbField.options.values;\n }\n }\n\n // Handle relation fields\n if (pbField.type === \"relation\") {\n // Support both formats: collectionId directly on field or in options\n const collectionId = pbField.collectionId || pbField.options?.collectionId || \"\";\n // Resolve collectionId to collection name\n // collectionId is a system field (like _pb_users_auth_), not the collection name\n // We need to resolve it to the actual collection name for comparison\n const collectionName = resolveCollectionIdToName(collectionId);\n field.relation = {\n collection: collectionName,\n cascadeDelete: pbField.cascadeDelete ?? pbField.options?.cascadeDelete ?? false,\n maxSelect: pbField.maxSelect ?? pbField.options?.maxSelect,\n minSelect: pbField.minSelect ?? pbField.options?.minSelect,\n };\n }\n\n // Clean up empty options object, but preserve values for select fields\n // If options only contains values for a select field, keep it\n const hasOnlyValues = Object.keys(field.options).length === 1 && field.options.values !== undefined;\n if (Object.keys(field.options).length === 0) {\n delete field.options;\n } else if (pbField.type === \"select\" && hasOnlyValues) {\n // Keep options object if it only contains values for a select field\n // This ensures values are preserved for comparison\n }\n\n fields.push(field);\n }\n }\n\n const schema: CollectionSchema = {\n name: pbCollection.name,\n type: pbCollection.type || \"base\",\n fields,\n };\n\n // Add indexes if present\n if (pbCollection.indexes && Array.isArray(pbCollection.indexes)) {\n schema.indexes = pbCollection.indexes;\n }\n\n // Add rules/permissions\n const rules: any = {};\n if (pbCollection.listRule !== undefined) rules.listRule = pbCollection.listRule;\n if (pbCollection.viewRule !== undefined) rules.viewRule = pbCollection.viewRule;\n if (pbCollection.createRule !== undefined) rules.createRule = pbCollection.createRule;\n if (pbCollection.updateRule !== undefined) rules.updateRule = pbCollection.updateRule;\n if (pbCollection.deleteRule !== undefined) rules.deleteRule = pbCollection.deleteRule;\n if (pbCollection.manageRule !== undefined) rules.manageRule = pbCollection.manageRule;\n\n if (Object.keys(rules).length > 0) {\n schema.rules = rules;\n // Also set permissions to match rules (they're the same thing)\n schema.permissions = { ...rules };\n }\n\n return schema;\n}\n\n/**\n * Converts PocketBase migration format to SchemaSnapshot\n * Extracts the snapshot array from the migration file content\n *\n * @param migrationContent - Raw migration file content\n * @returns SchemaSnapshot with collections map\n */\nexport function convertPocketBaseMigration(migrationContent: string): SchemaSnapshot {\n try {\n // Extract the snapshot array from the migration file\n // The format is: migrate((app) => { const snapshot = [...]; ... })\n const snapshotMatch = migrationContent.match(/const\\s+snapshot\\s*=\\s*(\\[[\\s\\S]*?\\]);/);\n\n if (!snapshotMatch) {\n throw new Error(\"Could not find snapshot array in migration file\");\n }\n\n // Parse the snapshot array as JSON\n // We need to evaluate it as JavaScript since it's not pure JSON\n const snapshotArrayStr = snapshotMatch[1];\n let snapshotArray: any[];\n\n try {\n // Use Function constructor to safely evaluate the array\n // This is safer than eval() and works for our use case\n snapshotArray = new Function(`return ${snapshotArrayStr}`)();\n } catch (parseError) {\n throw new Error(`Failed to parse snapshot array: ${parseError}`);\n }\n\n if (!Array.isArray(snapshotArray)) {\n throw new Error(\"Snapshot is not an array\");\n }\n\n // Convert each collection to our format\n const collections = new Map<string, CollectionSchema>();\n\n for (const pbCollection of snapshotArray) {\n if (!pbCollection.name) {\n console.warn(\"Skipping collection without name\");\n continue;\n }\n\n const schema = convertPocketBaseCollection(pbCollection);\n collections.set(pbCollection.name, schema);\n }\n\n return {\n version: SNAPSHOT_VERSION,\n timestamp: new Date().toISOString(),\n collections,\n };\n } catch (error) {\n throw new SnapshotError(\n `Failed to convert PocketBase migration: ${error instanceof Error ? error.message : String(error)}`,\n undefined,\n \"parse\",\n error instanceof Error ? error : undefined\n );\n }\n}\n","/**\n * Migration File Parser\n * Parses PocketBase migration files to extract collection operations\n *\n * This module handles parsing migration files to extract:\n * - Collection creations (new Collection(...))\n * - Collection deletions (app.delete(...))\n * - Field modifications (field.property = value)\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { convertPocketBaseCollection } from \"./pocketbase-converter\";\nimport type { CollectionSchema } from \"./types\";\n\n/**\n * Extracts timestamp from migration filename\n * Migration files are named: [timestamp]_[description].js\n *\n * @param filename - Migration filename\n * @returns Timestamp as number or null if not found\n */\nexport function extractTimestampFromFilename(filename: string): number | null {\n const match = filename.match(/^(\\d+)_/);\n if (match) {\n return parseInt(match[1], 10);\n }\n return null;\n}\n\n/**\n * Finds all migration files after a given snapshot timestamp\n * Excludes snapshot files themselves\n *\n * @param migrationsPath - Path to migrations directory\n * @param snapshotTimestamp - Timestamp of the snapshot file\n * @returns Array of migration file paths sorted by timestamp\n */\nexport function findMigrationsAfterSnapshot(migrationsPath: string, snapshotTimestamp: number): string[] {\n try {\n if (!fs.existsSync(migrationsPath)) {\n return [];\n }\n\n const files = fs.readdirSync(migrationsPath);\n const migrationFiles: { path: string; timestamp: number }[] = [];\n\n for (const file of files) {\n // Skip snapshot files\n if (file.endsWith(\"_collections_snapshot.js\") || file.endsWith(\"_snapshot.js\")) {\n continue;\n }\n\n // Skip non-JS files\n if (!file.endsWith(\".js\")) {\n continue;\n }\n\n const timestamp = extractTimestampFromFilename(file);\n if (timestamp && timestamp > snapshotTimestamp) {\n migrationFiles.push({\n path: path.join(migrationsPath, file),\n timestamp,\n });\n }\n }\n\n // Sort by timestamp (ascending order)\n migrationFiles.sort((a, b) => a.timestamp - b.timestamp);\n\n return migrationFiles.map((f) => f.path);\n } catch (error) {\n console.warn(`Error finding migrations after snapshot: ${error}`);\n return [];\n }\n}\n\n/**\n * Helper function to parse collection operations from migration content\n *\n * @param content - Migration content (should be just the UP migration)\n * @returns Object with collections to create and collections to delete\n */\nfunction parseMigrationOperationsFromContent(content: string): {\n collectionsToCreate: CollectionSchema[];\n collectionsToDelete: string[];\n} {\n const collectionsToCreate: CollectionSchema[] = [];\n const collectionsToDelete: string[] = [];\n\n try {\n // Extract collection definitions from `new Collection({...})`\n // Use a more robust approach: find all \"new Collection(\" and then parse until matching closing paren\n let searchIndex = 0;\n while (true) {\n const collectionStart = content.indexOf(\"new Collection(\", searchIndex);\n if (collectionStart === -1) {\n break;\n }\n\n // Find the opening brace after \"new Collection(\"\n const openParen = collectionStart + \"new Collection(\".length;\n let braceCount = 0;\n let parenCount = 1; // We're already inside the opening paren\n let inString = false;\n let stringChar = null;\n let i = openParen;\n\n // Skip whitespace to find the opening brace\n while (i < content.length && /\\s/.test(content[i])) {\n i++;\n }\n\n if (content[i] !== \"{\") {\n searchIndex = i + 1;\n continue;\n }\n\n const objectStart = i;\n braceCount = 1;\n i++;\n\n // Find the matching closing brace and paren\n while (i < content.length && (braceCount > 0 || parenCount > 0)) {\n const char = content[i];\n const prevChar = i > 0 ? content[i - 1] : \"\";\n\n // Handle strings\n if (!inString && (char === '\"' || char === \"'\")) {\n inString = true;\n stringChar = char;\n } else if (inString && char === stringChar && prevChar !== \"\\\\\") {\n inString = false;\n stringChar = null;\n }\n\n if (!inString) {\n if (char === \"{\") braceCount++;\n if (char === \"}\") braceCount--;\n if (char === \"(\") parenCount++;\n if (char === \")\") parenCount--;\n }\n\n i++;\n }\n\n if (braceCount === 0 && parenCount === 0) {\n const objectContent = content.substring(objectStart, i - 1); // -1 to exclude the closing paren\n try {\n // Use Function constructor to parse the JavaScript object\n const collectionObj = new Function(`return ${objectContent}`)();\n if (collectionObj && collectionObj.name) {\n const schema = convertPocketBaseCollection(collectionObj);\n collectionsToCreate.push(schema);\n }\n } catch (error) {\n // Skip malformed collection definitions\n console.warn(`Failed to parse collection definition: ${error}`);\n }\n }\n\n searchIndex = i;\n }\n\n // Extract collection deletions from `app.delete(...)`\n // Look for patterns like: app.delete(collection_xxx) or app.delete(app.findCollectionByNameOrId(\"name\"))\n const deleteMatches = content.matchAll(\n /app\\.delete\\s*\\(\\s*(?:collection_\\w+|app\\.findCollectionByNameOrId\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\))\\s*\\)/g\n );\n for (const match of deleteMatches) {\n // If we have a collection name from findCollectionByNameOrId, use it\n if (match[1]) {\n collectionsToDelete.push(match[1]);\n } else {\n // Try to find the collection name from the variable name\n // Look backwards for the collection variable definition\n const varNameMatch = match[0].match(/collection_(\\w+)/);\n if (varNameMatch) {\n // Try to find the collection name from the variable definition\n const varName = `collection_${varNameMatch[1]}`;\n // Search backwards from the delete call to find the variable definition\n const deleteIndex = content.indexOf(match[0]);\n const beforeDelete = content.substring(0, deleteIndex);\n const varDefMatch = beforeDelete.match(\n new RegExp(`const\\\\s+${varName}\\\\s*=\\\\s*new\\\\s+Collection\\\\(\\\\s*(\\\\{[\\\\s\\\\S]*?\\\\})\\\\s*\\\\)`, \"g\")\n );\n if (varDefMatch && varDefMatch.length > 0) {\n // Find the collection definition (get the last match closest to the delete)\n const collectionDefMatch = beforeDelete.match(\n new RegExp(`const\\\\s+${varName}\\\\s*=\\\\s*new\\\\s+Collection\\\\(\\\\s*(\\\\{[\\\\s\\\\S]*?\\\\})\\\\s*\\\\)`)\n );\n if (collectionDefMatch) {\n try {\n const collectionDefStr = collectionDefMatch[1];\n const collectionObj = new Function(`return ${collectionDefStr}`)();\n if (collectionObj && collectionObj.name) {\n collectionsToDelete.push(collectionObj.name);\n }\n } catch {\n // Skip if we can't parse\n }\n }\n }\n }\n }\n }\n\n // Also look for direct collection name in findCollectionByNameOrId followed by delete\n const findAndDeleteMatches = content.matchAll(\n /app\\.findCollectionByNameOrId\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)[\\s\\S]*?app\\.delete/g\n );\n for (const match of findAndDeleteMatches) {\n collectionsToDelete.push(match[1]);\n }\n } catch (error) {\n console.warn(`Failed to parse migration operations from content: ${error}`);\n }\n\n return { collectionsToCreate, collectionsToDelete };\n}\n\n/**\n * Parses a migration file to extract collection operations\n * Extracts collections created with `new Collection(...)` and collections deleted with `app.delete(...)`\n * Only parses the UP migration (first function), not the down migration\n *\n * @param migrationContent - Raw migration file content\n * @returns Object with collections to create and collections to delete\n */\nexport function parseMigrationOperations(migrationContent: string): {\n collectionsToCreate: CollectionSchema[];\n collectionsToDelete: string[];\n} {\n try {\n // Extract only the UP migration (first function argument to migrate())\n // Find the migrate call and extract the first function body\n const migrateMatch = migrationContent.match(/migrate\\s*\\(\\s*/);\n if (!migrateMatch) {\n // If we can't find the migrate pattern, try to parse the whole file\n return parseMigrationOperationsFromContent(migrationContent);\n }\n\n const startIndex = migrateMatch.index! + migrateMatch[0].length;\n\n // Find the opening paren of the first function\n let i = startIndex;\n let parenCount = 0;\n let foundFirstParen = false;\n\n while (i < migrationContent.length) {\n const char = migrationContent[i];\n if (char === \"(\") {\n parenCount++;\n foundFirstParen = true;\n i++;\n break;\n }\n i++;\n }\n\n if (!foundFirstParen) {\n return parseMigrationOperationsFromContent(migrationContent);\n }\n\n // Skip the function parameters: (app) => {\n let inString = false;\n let stringChar = null;\n let foundBrace = false;\n let braceStart = -1;\n\n while (i < migrationContent.length && !foundBrace) {\n const char = migrationContent[i];\n const prevChar = i > 0 ? migrationContent[i - 1] : \"\";\n\n if (!inString && (char === '\"' || char === \"'\")) {\n inString = true;\n stringChar = char;\n } else if (inString && char === stringChar && prevChar !== \"\\\\\") {\n inString = false;\n stringChar = null;\n }\n\n if (!inString) {\n if (char === \"(\") parenCount++;\n if (char === \")\") {\n parenCount--;\n if (parenCount === 0) {\n // Found end of function parameters, look for =>\n i++;\n while (i < migrationContent.length && /\\s/.test(migrationContent[i])) {\n i++;\n }\n if (i < migrationContent.length - 1 && migrationContent[i] === \"=\" && migrationContent[i + 1] === \">\") {\n i += 2;\n while (i < migrationContent.length && /\\s/.test(migrationContent[i])) {\n i++;\n }\n if (i < migrationContent.length && migrationContent[i] === \"{\") {\n foundBrace = true;\n braceStart = i + 1;\n break;\n }\n }\n }\n }\n }\n i++;\n }\n\n if (!foundBrace || braceStart === -1) {\n return parseMigrationOperationsFromContent(migrationContent);\n }\n\n // Find the matching closing brace\n let braceCount = 1;\n i = braceStart;\n inString = false;\n stringChar = null;\n\n while (i < migrationContent.length && braceCount > 0) {\n const char = migrationContent[i];\n const prevChar = i > 0 ? migrationContent[i - 1] : \"\";\n\n if (!inString && (char === '\"' || char === \"'\")) {\n inString = true;\n stringChar = char;\n } else if (inString && char === stringChar && prevChar !== \"\\\\\") {\n inString = false;\n stringChar = null;\n }\n\n if (!inString) {\n if (char === \"{\") braceCount++;\n if (char === \"}\") braceCount--;\n }\n\n i++;\n }\n\n if (braceCount === 0) {\n const upMigrationContent = migrationContent.substring(braceStart, i - 1);\n return parseMigrationOperationsFromContent(upMigrationContent);\n }\n\n // Fallback: parse the whole file\n return parseMigrationOperationsFromContent(migrationContent);\n } catch (error) {\n console.warn(`Failed to parse migration operations: ${error}`);\n return { collectionsToCreate: [], collectionsToDelete: [] };\n }\n}\n\n\n","/**\n * Snapshot Manager\n * Handles saving and loading schema snapshots from JSON files\n *\n * This module provides a standalone, configurable snapshot manager that can be used\n * by consumer projects to manage schema snapshots. It focuses on JSON snapshot file\n * management, delegating migration file parsing and PocketBase format conversion\n * to specialized modules.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { FileSystemError, SnapshotError } from \"./errors\";\nimport {\n extractTimestampFromFilename,\n findMigrationsAfterSnapshot,\n parseMigrationOperations,\n} from \"./migration-parser\";\nimport { convertPocketBaseMigration } from \"./pocketbase-converter\";\nimport type { CollectionSchema, SchemaDefinition, SchemaSnapshot } from \"./types\";\n\nconst SNAPSHOT_VERSION = \"1.0.0\";\nconst DEFAULT_SNAPSHOT_FILENAME = \".migration-snapshot.json\";\n\n/**\n * Configuration for snapshot operations\n */\nexport interface SnapshotConfig {\n /**\n * Path to the snapshot file\n * Can be absolute or relative to workspaceRoot\n */\n snapshotPath?: string;\n\n /**\n * Workspace root directory for resolving relative paths\n * Defaults to process.cwd()\n */\n workspaceRoot?: string;\n\n /**\n * Path to the migrations directory for finding PocketBase snapshots\n */\n migrationsPath?: string;\n\n /**\n * Whether to auto-migrate old snapshot formats\n * Defaults to true\n */\n autoMigrate?: boolean;\n\n /**\n * Custom snapshot version for testing\n */\n version?: string;\n}\n\n/**\n * Snapshot format versions and their migration functions\n */\ninterface SnapshotMigration {\n fromVersion: string;\n toVersion: string;\n migrate: (data: any) => any;\n}\n\n/**\n * Registry of snapshot format migrations\n */\nconst SNAPSHOT_MIGRATIONS: SnapshotMigration[] = [\n // Add migrations here as the format evolves\n // Example:\n // {\n // fromVersion: '0.9.0',\n // toVersion: '1.0.0',\n // migrate: (data) => ({ ...data, newField: 'default' })\n // }\n];\n\n/**\n * Default configuration values\n */\nconst DEFAULT_CONFIG: Omit<Required<SnapshotConfig>, \"migrationsPath\"> & { migrationsPath?: string } = {\n snapshotPath: DEFAULT_SNAPSHOT_FILENAME,\n workspaceRoot: process.cwd(),\n autoMigrate: true,\n version: SNAPSHOT_VERSION,\n};\n\n/**\n * Merges user config with defaults\n */\nfunction mergeConfig(config: SnapshotConfig = {}): typeof DEFAULT_CONFIG {\n return {\n ...DEFAULT_CONFIG,\n ...config,\n };\n}\n\n/**\n * Gets the snapshot file path from configuration\n *\n * @param config - Snapshot configuration\n * @returns Absolute path to the snapshot file\n */\nexport function getSnapshotPath(config: SnapshotConfig = {}): string {\n const mergedConfig = mergeConfig(config);\n const workspaceRoot = mergedConfig.workspaceRoot;\n const snapshotFilename = mergedConfig.snapshotPath;\n\n // If snapshotPath is absolute, use it directly\n if (path.isAbsolute(snapshotFilename)) {\n return snapshotFilename;\n }\n\n // Otherwise, resolve relative to workspaceRoot\n return path.join(workspaceRoot, snapshotFilename);\n}\n\n/**\n * Checks if snapshot file exists\n *\n * @param config - Snapshot configuration\n * @returns True if snapshot file exists\n */\nexport function snapshotExists(config: SnapshotConfig = {}): boolean {\n try {\n const snapshotPath = getSnapshotPath(config);\n return fs.existsSync(snapshotPath);\n } catch {\n // If there's any error checking existence, treat as non-existent\n return false;\n }\n}\n\n/**\n * Handles file system errors with descriptive messages\n *\n * @param error - The error object\n * @param operation - The operation being performed\n * @param filePath - The file path involved\n * @throws SnapshotError or FileSystemError with descriptive message\n */\nfunction handleFileSystemError(error: any, operation: \"read\" | \"write\", filePath: string): never {\n const fsError = error as NodeJS.ErrnoException;\n\n if (fsError.code === \"ENOENT\") {\n throw new SnapshotError(`Snapshot file not found: ${filePath}`, filePath, operation, error);\n } else if (fsError.code === \"EACCES\" || fsError.code === \"EPERM\") {\n throw new FileSystemError(\n `Permission denied ${operation === \"read\" ? \"reading\" : \"writing\"} snapshot file. Check file permissions.`,\n filePath,\n operation,\n fsError.code,\n error\n );\n } else if (fsError.code === \"ENOSPC\") {\n throw new FileSystemError(\n `No space left on device when ${operation === \"read\" ? \"reading\" : \"writing\"} snapshot file.`,\n filePath,\n operation,\n fsError.code,\n error\n );\n } else {\n throw new SnapshotError(`Failed to ${operation} snapshot file: ${error.message}`, filePath, operation, error);\n }\n}\n\n/**\n * Serializes a Map to a plain object for JSON serialization\n *\n * @param map - Map to serialize\n * @returns Plain object representation\n */\nfunction serializeMap<K extends string, V>(map: Map<K, V>): Record<K, V> {\n const obj: Record<string, V> = {};\n for (const [key, value] of map.entries()) {\n obj[key] = value;\n }\n return obj as Record<K, V>;\n}\n\n/**\n * Deserializes a plain object to a Map\n *\n * @param obj - Plain object to deserialize\n * @returns Map representation\n */\nfunction deserializeMap<K extends string, V>(obj: Record<K, V>): Map<K, V> {\n const map = new Map<K, V>();\n for (const [key, value] of Object.entries(obj)) {\n map.set(key as K, value as V);\n }\n return map;\n}\n\n/**\n * Serializes SchemaDefinition to JSON format\n * Converts Map to plain object for JSON compatibility\n *\n * @param schema - Schema definition to serialize\n * @returns JSON-serializable object\n */\nfunction serializeSchemaDefinition(schema: SchemaDefinition): any {\n return {\n collections: serializeMap(schema.collections),\n };\n}\n\n/**\n * Adds version and timestamp metadata to snapshot\n *\n * @param schema - Schema definition\n * @param config - Optional configuration with custom version\n * @returns Snapshot with metadata\n */\nfunction addSnapshotMetadata(schema: SchemaDefinition, config?: SnapshotConfig): any {\n const mergedConfig = mergeConfig(config);\n return {\n version: mergedConfig.version,\n timestamp: new Date().toISOString(),\n ...serializeSchemaDefinition(schema),\n };\n}\n\n/**\n * Saves schema snapshot to file\n * Serializes SchemaDefinition to JSON with version and timestamp metadata\n * Writes with pretty printing for readability\n *\n * @param schema - Schema definition to save\n * @param config - Snapshot configuration\n */\nexport function saveSnapshot(schema: SchemaDefinition, config: SnapshotConfig = {}): void {\n const snapshotPath = getSnapshotPath(config);\n\n try {\n // Ensure directory exists\n const snapshotDir = path.dirname(snapshotPath);\n if (!fs.existsSync(snapshotDir)) {\n fs.mkdirSync(snapshotDir, { recursive: true });\n }\n\n // Add metadata and serialize\n const snapshotData = addSnapshotMetadata(schema, config);\n\n // Write with pretty printing (2 spaces indentation)\n const jsonContent = JSON.stringify(snapshotData, null, 2);\n fs.writeFileSync(snapshotPath, jsonContent, \"utf-8\");\n } catch (error) {\n handleFileSystemError(error, \"write\", snapshotPath);\n }\n}\n\n/**\n * Parses JSON and validates snapshot format\n *\n * @param jsonContent - Raw JSON content\n * @param snapshotPath - Path to snapshot file (for error messages)\n * @returns Parsed snapshot data\n */\nfunction parseAndValidateSnapshot(jsonContent: string, snapshotPath: string): any {\n try {\n const data = JSON.parse(jsonContent);\n\n // Validate required fields\n if (!data.version) {\n throw new SnapshotError(\n \"Snapshot file is missing version field. The snapshot may be corrupted.\",\n snapshotPath,\n \"validate\"\n );\n }\n\n if (!data.timestamp) {\n throw new SnapshotError(\n \"Snapshot file is missing timestamp field. The snapshot may be corrupted.\",\n snapshotPath,\n \"validate\"\n );\n }\n\n if (!data.collections) {\n throw new SnapshotError(\n \"Snapshot file is missing collections field. The snapshot may be corrupted.\",\n snapshotPath,\n \"validate\"\n );\n }\n\n return data;\n } catch (error) {\n if (error instanceof SnapshotError) {\n throw error;\n }\n\n if (error instanceof SyntaxError) {\n throw new SnapshotError(\n `Invalid JSON in snapshot file. The file may be corrupted or manually edited incorrectly.`,\n snapshotPath,\n \"parse\",\n error\n );\n }\n throw error;\n }\n}\n\n/**\n * Compares two version strings\n * Returns -1 if a < b, 0 if a == b, 1 if a > b\n */\nfunction compareVersions(a: string, b: string): number {\n const partsA = a.split(\".\").map(Number);\n const partsB = b.split(\".\").map(Number);\n\n for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {\n const numA = partsA[i] || 0;\n const numB = partsB[i] || 0;\n\n if (numA < numB) return -1;\n if (numA > numB) return 1;\n }\n\n return 0;\n}\n\n/**\n * Migrates old snapshot formats to current version\n * Applies migrations in sequence from old version to current\n *\n * @param data - Parsed snapshot data\n * @param config - Optional configuration\n * @returns Migrated snapshot data\n */\nfunction migrateSnapshotFormat(data: any, config?: SnapshotConfig): any {\n const mergedConfig = mergeConfig(config);\n const currentVersion = data.version;\n const targetVersion = mergedConfig.version;\n\n // If versions match, no migration needed\n if (currentVersion === targetVersion) {\n return data;\n }\n\n // If auto-migrate is disabled, just return the data with a warning\n if (!mergedConfig.autoMigrate) {\n console.warn(\n `Snapshot version ${currentVersion} differs from current ${targetVersion}, but auto-migrate is disabled.`\n );\n return data;\n }\n\n // Find and apply migrations in sequence\n let migratedData = { ...data };\n let currentMigrationVersion = currentVersion;\n\n // Sort migrations by fromVersion\n const sortedMigrations = [...SNAPSHOT_MIGRATIONS].sort((a, b) => compareVersions(a.fromVersion, b.fromVersion));\n\n for (const migration of sortedMigrations) {\n if (compareVersions(currentMigrationVersion, migration.fromVersion) === 0) {\n console.log(`Migrating snapshot from ${migration.fromVersion} to ${migration.toVersion}...`);\n migratedData = migration.migrate(migratedData);\n migratedData.version = migration.toVersion;\n currentMigrationVersion = migration.toVersion;\n }\n }\n\n // If we couldn't migrate to the target version, log a warning\n if (compareVersions(currentMigrationVersion, targetVersion) !== 0) {\n console.warn(`Unknown snapshot version ${currentVersion}, attempting to load anyway...`);\n }\n\n return migratedData;\n}\n\n/**\n * Deserializes snapshot data to SchemaSnapshot\n *\n * @param data - Parsed and validated snapshot data\n * @returns SchemaSnapshot object\n */\nfunction deserializeSnapshot(data: any): SchemaSnapshot {\n return {\n version: data.version,\n timestamp: data.timestamp,\n collections: deserializeMap<string, CollectionSchema>(data.collections),\n };\n}\n\n/**\n * Loads schema snapshot from file\n * Reads snapshot file, parses JSON, validates format, and handles migrations\n *\n * @param config - Snapshot configuration\n * @returns SchemaSnapshot object\n * @throws Error if snapshot file doesn't exist or is invalid\n */\nexport function loadSnapshot(config: SnapshotConfig = {}): SchemaSnapshot {\n const snapshotPath = getSnapshotPath(config);\n\n try {\n // Read file\n const jsonContent = fs.readFileSync(snapshotPath, \"utf-8\");\n\n // Parse and validate\n const data = parseAndValidateSnapshot(jsonContent, snapshotPath);\n\n // Migrate format if needed\n const migratedData = migrateSnapshotFormat(data, config);\n\n // Deserialize to SchemaSnapshot\n return deserializeSnapshot(migratedData);\n } catch (error) {\n // If it's already a SnapshotError or FileSystemError, re-throw it\n if (error instanceof SnapshotError || error instanceof FileSystemError) {\n throw error;\n }\n\n // If file doesn't exist, throw specific error\n if ((error as any).code === \"ENOENT\") {\n throw new SnapshotError(\n `Snapshot file not found. This may be the first migration run.`,\n snapshotPath,\n \"read\",\n error as Error\n );\n }\n\n // Handle other file system errors\n handleFileSystemError(error, \"read\", snapshotPath);\n }\n}\n\n/**\n * Merges base schema with custom snapshot\n * Base schema collections are preserved, custom collections are added\n * Custom collections override base collections if they have the same name\n *\n * @param baseSnapshot - PocketBase base schema\n * @param customSnapshot - User's custom schema snapshot (may be null)\n * @returns Merged SchemaSnapshot\n */\nexport function mergeSnapshots(baseSnapshot: SchemaSnapshot, customSnapshot: SchemaSnapshot | null): SchemaSnapshot {\n // If no custom snapshot, return base snapshot\n if (!customSnapshot) {\n return baseSnapshot;\n }\n\n // Create a new collections map starting with base collections\n const mergedCollections = new Map<string, CollectionSchema>(baseSnapshot.collections);\n\n // Add or override with custom collections\n for (const [name, schema] of customSnapshot.collections.entries()) {\n mergedCollections.set(name, schema);\n }\n\n return {\n version: customSnapshot.version || baseSnapshot.version,\n timestamp: customSnapshot.timestamp || baseSnapshot.timestamp,\n collections: mergedCollections,\n };\n}\n\n/**\n * Finds the most recent snapshot file in the migrations directory\n * Identifies snapshot files by naming pattern (e.g., *_collections_snapshot.js)\n *\n * @param migrationsPath - Path to pb_migrations directory\n * @returns Path to most recent snapshot file or null if none exist\n */\nexport function findLatestSnapshot(migrationsPath: string): string | null {\n try {\n // Check if migrations directory exists\n if (!fs.existsSync(migrationsPath)) {\n return null;\n }\n\n // Read all files in migrations directory\n const files = fs.readdirSync(migrationsPath);\n\n // Filter for snapshot files (files ending with _collections_snapshot.js or _snapshot.js)\n const snapshotFiles = files.filter(\n (file) => file.endsWith(\"_collections_snapshot.js\") || file.endsWith(\"_snapshot.js\")\n );\n\n if (snapshotFiles.length === 0) {\n return null;\n }\n\n // Sort by filename (timestamp prefix) to get most recent\n // Snapshot files are named with timestamp prefix: [timestamp]_collections_snapshot.js\n snapshotFiles.sort().reverse();\n\n // Return full path to most recent snapshot\n const latestSnapshot = snapshotFiles[0];\n if (!latestSnapshot) {\n return null;\n }\n return path.join(migrationsPath, latestSnapshot);\n } catch (error) {\n // If there's any error reading directory, return null\n console.warn(`Error finding latest snapshot: ${error}`);\n return null;\n }\n}\n\n/**\n * Applies migration operations to a snapshot state\n * Creates new collections and deletes collections as specified\n *\n * @param snapshot - Base snapshot state\n * @param operations - Migration operations to apply\n * @returns Updated snapshot with operations applied\n */\nfunction applyMigrationOperations(\n snapshot: SchemaSnapshot,\n operations: { collectionsToCreate: CollectionSchema[]; collectionsToDelete: string[] }\n): SchemaSnapshot {\n const updatedCollections = new Map(snapshot.collections);\n\n // Apply deletions first\n for (const collectionName of operations.collectionsToDelete) {\n updatedCollections.delete(collectionName);\n }\n\n // Apply creations/updates\n for (const collection of operations.collectionsToCreate) {\n updatedCollections.set(collection.name, collection);\n }\n\n return {\n ...snapshot,\n collections: updatedCollections,\n };\n}\n\n/**\n * Loads snapshot and applies all migrations that come after it\n * This gives us the current state of the database schema\n *\n * @param config - Snapshot configuration (must include migrationsPath)\n * @returns SchemaSnapshot object representing current state or null if snapshot doesn't exist\n */\nexport function loadSnapshotWithMigrations(config: SnapshotConfig = {}): SchemaSnapshot | null {\n const migrationsPath = config.migrationsPath;\n\n if (!migrationsPath) {\n return null;\n }\n\n // Check if migrationsPath is actually a file (for backward compatibility with tests)\n if (fs.existsSync(migrationsPath) && fs.statSync(migrationsPath).isFile()) {\n try {\n const migrationContent = fs.readFileSync(migrationsPath, \"utf-8\");\n return convertPocketBaseMigration(migrationContent);\n } catch (error) {\n console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);\n return null;\n }\n }\n\n // It's a directory, find the latest snapshot\n const latestSnapshotPath = findLatestSnapshot(migrationsPath);\n\n if (!latestSnapshotPath) {\n // No snapshot found - return null (empty database)\n return null;\n }\n\n try {\n // Read and convert the PocketBase snapshot file\n const migrationContent = fs.readFileSync(latestSnapshotPath, \"utf-8\");\n let snapshot = convertPocketBaseMigration(migrationContent);\n\n // Extract timestamp from snapshot filename\n const snapshotFilename = path.basename(latestSnapshotPath);\n const snapshotTimestamp = extractTimestampFromFilename(snapshotFilename);\n\n if (snapshotTimestamp) {\n // Find all migration files after the snapshot\n const migrationFiles = findMigrationsAfterSnapshot(migrationsPath, snapshotTimestamp);\n\n // Apply each migration in order\n for (const migrationFile of migrationFiles) {\n try {\n const migrationContent = fs.readFileSync(migrationFile, \"utf-8\");\n const operations = parseMigrationOperations(migrationContent);\n snapshot = applyMigrationOperations(snapshot, operations);\n } catch (error) {\n console.warn(`Failed to apply migration ${migrationFile}: ${error}`);\n // Continue with other migrations even if one fails\n }\n }\n }\n\n return snapshot;\n } catch (error) {\n console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);\n return null;\n }\n}\n\n/**\n * Loads snapshot if it exists, returns null for first run\n * Convenience method that handles missing snapshot gracefully\n * Finds the most recent snapshot file from migrations directory\n * NOTE: This function only loads the snapshot, not migrations after it.\n * Use loadSnapshotWithMigrations() if you need the current state including migrations.\n *\n * @param config - Snapshot configuration (must include migrationsPath)\n * @returns SchemaSnapshot object or null if snapshot doesn't exist\n */\nexport function loadSnapshotIfExists(config: SnapshotConfig = {}): SchemaSnapshot | null {\n const migrationsPath = config.migrationsPath;\n\n if (!migrationsPath) {\n // No migrations path provided - return null\n return null;\n }\n\n // Check if migrationsPath is actually a file (for backward compatibility with tests)\n // If it's a file, treat it as a direct snapshot file path\n if (fs.existsSync(migrationsPath) && fs.statSync(migrationsPath).isFile()) {\n try {\n const migrationContent = fs.readFileSync(migrationsPath, \"utf-8\");\n return convertPocketBaseMigration(migrationContent);\n } catch (error) {\n console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);\n return null;\n }\n }\n\n // It's a directory, find the latest snapshot\n const latestSnapshotPath = findLatestSnapshot(migrationsPath);\n\n if (latestSnapshotPath) {\n try {\n // Read and convert the PocketBase snapshot file\n const migrationContent = fs.readFileSync(latestSnapshotPath, \"utf-8\");\n return convertPocketBaseMigration(migrationContent);\n } catch (error) {\n console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);\n return null;\n }\n }\n\n // No snapshot found - return null (empty database)\n return null;\n}\n\n/**\n * Loads the base PocketBase schema from the initial migration file\n *\n * @param migrationPath - Path to pocketbase/pb_migrations/000000000_collections_snapshot.js\n * @returns SchemaSnapshot representing PocketBase's initial state\n * @throws SnapshotError if file not found or invalid format\n */\nexport function loadBaseMigration(migrationPath: string): SchemaSnapshot {\n try {\n // Check if file exists\n if (!fs.existsSync(migrationPath)) {\n throw new SnapshotError(\n `Base migration file not found: ${migrationPath}\\n\\n` +\n `This file should contain PocketBase's initial schema.\\n` +\n `Please ensure PocketBase is properly set up by running 'yarn setup'.\\n` +\n `If the file exists in a different location, update the configuration.`,\n migrationPath,\n \"read\"\n );\n }\n\n // Read the migration file\n const migrationContent = fs.readFileSync(migrationPath, \"utf-8\");\n\n // Convert to SchemaSnapshot\n const snapshot = convertPocketBaseMigration(migrationContent);\n\n return snapshot;\n } catch (error) {\n // If it's already a SnapshotError, re-throw it\n if (error instanceof SnapshotError) {\n throw error;\n }\n\n // Handle file system errors\n if ((error as any).code === \"ENOENT\") {\n throw new SnapshotError(\n `Base migration file not found: ${migrationPath}\\n\\n` +\n `This file should contain PocketBase's initial schema.\\n` +\n `Please ensure PocketBase is properly set up by running 'yarn setup'.`,\n migrationPath,\n \"read\",\n error as Error\n );\n }\n\n if ((error as any).code === \"EACCES\" || (error as any).code === \"EPERM\") {\n throw new FileSystemError(\n `Permission denied reading base migration file. Check file permissions.`,\n migrationPath,\n \"read\",\n (error as any).code,\n error as Error\n );\n }\n\n // Other errors\n throw new SnapshotError(\n `Failed to load base migration: ${error instanceof Error ? error.message : String(error)}`,\n migrationPath,\n \"read\",\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Gets the current snapshot version\n */\nexport function getSnapshotVersion(): string {\n return SNAPSHOT_VERSION;\n}\n\n/**\n * Validates a snapshot against the current version\n * Returns validation result with any issues found\n */\nexport function validateSnapshot(snapshot: SchemaSnapshot): { valid: boolean; issues: string[] } {\n const issues: string[] = [];\n\n // Check version\n if (!snapshot.version) {\n issues.push(\"Missing version field\");\n } else if (compareVersions(snapshot.version, SNAPSHOT_VERSION) > 0) {\n issues.push(`Snapshot version ${snapshot.version} is newer than supported version ${SNAPSHOT_VERSION}`);\n }\n\n // Check timestamp\n if (!snapshot.timestamp) {\n issues.push(\"Missing timestamp field\");\n }\n\n // Check collections\n if (!snapshot.collections) {\n issues.push(\"Missing collections field\");\n } else if (!(snapshot.collections instanceof Map)) {\n issues.push(\"Collections field is not a Map\");\n }\n\n return {\n valid: issues.length === 0,\n issues,\n };\n}\n\n/**\n * Re-exports convertPocketBaseMigration for backward compatibility\n */\nexport { convertPocketBaseMigration } from \"./pocketbase-converter\";\n\n/**\n * SnapshotManager class for object-oriented usage\n * Provides a stateful interface for snapshot management\n */\nexport class SnapshotManager {\n private config: SnapshotConfig;\n\n constructor(config: SnapshotConfig = {}) {\n this.config = mergeConfig(config);\n }\n\n /**\n * Loads the current snapshot\n */\n loadSnapshot(): SchemaSnapshot {\n return loadSnapshot(this.config);\n }\n\n /**\n * Saves a schema as a snapshot\n */\n saveSnapshot(schema: SchemaDefinition): void {\n saveSnapshot(schema, this.config);\n }\n\n /**\n * Loads snapshot if it exists, returns null otherwise\n */\n loadSnapshotIfExists(): SchemaSnapshot | null {\n return loadSnapshotIfExists(this.config);\n }\n\n /**\n * Checks if a snapshot exists\n */\n snapshotExists(): boolean {\n return snapshotExists(this.config);\n }\n\n /**\n * Converts a PocketBase migration to a snapshot\n */\n convertPocketBaseMigration(content: string): SchemaSnapshot {\n return convertPocketBaseMigration(content);\n }\n\n /**\n * Gets the snapshot file path\n */\n getSnapshotPath(): string {\n return getSnapshotPath(this.config);\n }\n\n /**\n * Validates a snapshot\n */\n validateSnapshot(snapshot: SchemaSnapshot): { valid: boolean; issues: string[] } {\n return validateSnapshot(snapshot);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/migration/errors.ts","../../src/migration/pocketbase-converter.ts","../../src/migration/migration-parser.ts","../../src/migration/snapshot.ts"],"names":["path","fs","SNAPSHOT_VERSION","path2","fs2","migrationContent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,cAAA,GAAN,MAAM,eAAA,SAAuB,KAAA,CAAM;AAAA,EACxC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,eAAA,CAAe,SAAS,CAAA;AAAA,EACtD;AACF,CAAA;AAwCO,IAAM,aAAA,GAAN,MAAM,cAAA,SAAsB,cAAA,CAAe;AAAA,EAChC,YAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA,EAEhB,WAAA,CACE,OAAA,EACA,YAAA,EACA,SAAA,EACA,aAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,YAAA,GAAe,YAAA;AACpB,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,aAAA,GAAgB,aAAA;AACrB,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,cAAA,CAAc,SAAS,CAAA;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA,EAKO,kBAAA,GAA6B;AAClC,IAAA,MAAM,KAAA,GAAkB,CAAC,IAAA,CAAK,OAAO,CAAA;AAErC,IAAA,IAAI,KAAK,SAAA,EAAW;AAClB,MAAA,KAAA,CAAM,IAAA,CAAK;AAAA,WAAA,EAAgB,IAAA,CAAK,SAAS,CAAA,CAAE,CAAA;AAAA,IAC7C;AAEA,IAAA,IAAI,KAAK,YAAA,EAAc;AACrB,MAAA,KAAA,CAAM,IAAA,CAAK;AAAA,UAAA,EAAe,IAAA,CAAK,YAAY,CAAA,CAAE,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ration tool\n * Provides specific error types for better error handling and user feedback\n */\n\n/**\n * Base error class for all migration-related errors\n */\nexport class MigrationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MigrationError\";\n Object.setPrototypeOf(this, MigrationError.prototype);\n }\n}\n\n/**\n * Error thrown when schema parsing fails\n * Used when Zod schemas cannot be parsed or are invalid\n */\nexport class SchemaParsingError extends MigrationError {\n public readonly filePath?: string;\n public readonly originalError?: Error;\n\n constructor(message: string, filePath?: string, originalError?: Error) {\n super(message);\n this.name = \"SchemaParsingError\";\n this.filePath = filePath;\n this.originalError = originalError;\n Object.setPrototypeOf(this, SchemaParsingError.prototype);\n }\n\n /**\n * Creates a formatted error message with file path and original error details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.filePath) {\n parts.push(`\\nFile: ${this.filePath}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when snapshot operations fail\n * Used for snapshot file read/write/parse errors\n */\nexport class SnapshotError extends MigrationError {\n public readonly snapshotPath?: string;\n public readonly operation?: \"read\" | \"write\" | \"parse\" | \"validate\";\n public readonly originalError?: Error;\n\n constructor(\n message: string,\n snapshotPath?: string,\n operation?: \"read\" | \"write\" | \"parse\" | \"validate\",\n originalError?: Error\n ) {\n super(message);\n this.name = \"SnapshotError\";\n this.snapshotPath = snapshotPath;\n this.operation = operation;\n this.originalError = originalError;\n Object.setPrototypeOf(this, SnapshotError.prototype);\n }\n\n /**\n * Creates a formatted error message with snapshot path and operation details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.operation) {\n parts.push(`\\nOperation: ${this.operation}`);\n }\n\n if (this.snapshotPath) {\n parts.push(`\\nSnapshot: ${this.snapshotPath}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when migration file generation fails\n * Used when migration files cannot be created or written\n */\nexport class MigrationGenerationError extends MigrationError {\n public readonly migrationPath?: string;\n public readonly originalError?: Error;\n\n constructor(message: string, migrationPath?: string, originalError?: Error) {\n super(message);\n this.name = \"MigrationGenerationError\";\n this.migrationPath = migrationPath;\n this.originalError = originalError;\n Object.setPrototypeOf(this, MigrationGenerationError.prototype);\n }\n\n /**\n * Creates a formatted error message with migration path and original error details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.migrationPath) {\n parts.push(`\\nMigration: ${this.migrationPath}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when file system operations fail\n * Used for directory creation, file permissions, disk space issues\n */\nexport class FileSystemError extends MigrationError {\n public readonly path?: string;\n public readonly operation?: \"read\" | \"write\" | \"create\" | \"delete\" | \"access\";\n public readonly code?: string;\n public readonly originalError?: Error;\n\n constructor(\n message: string,\n path?: string,\n operation?: \"read\" | \"write\" | \"create\" | \"delete\" | \"access\",\n code?: string,\n originalError?: Error\n ) {\n super(message);\n this.name = \"FileSystemError\";\n this.path = path;\n this.operation = operation;\n this.code = code;\n this.originalError = originalError;\n Object.setPrototypeOf(this, FileSystemError.prototype);\n }\n\n /**\n * Creates a formatted error message with path, operation, and error code details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.operation) {\n parts.push(`\\nOperation: ${this.operation}`);\n }\n\n if (this.path) {\n parts.push(`\\nPath: ${this.path}`);\n }\n\n if (this.code) {\n parts.push(`\\nError Code: ${this.code}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when configuration is invalid\n * Used for configuration file parsing, validation, and path resolution errors\n */\nexport class ConfigurationError extends MigrationError {\n public readonly configPath?: string;\n public readonly invalidFields?: string[];\n public readonly originalError?: Error;\n\n constructor(message: string, configPath?: string, invalidFields?: string[], originalError?: Error) {\n super(message);\n this.name = \"ConfigurationError\";\n this.configPath = configPath;\n this.invalidFields = invalidFields;\n this.originalError = originalError;\n Object.setPrototypeOf(this, ConfigurationError.prototype);\n }\n\n /**\n * Creates a formatted error message with configuration details\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.configPath) {\n parts.push(`\\nConfiguration File: ${this.configPath}`);\n }\n\n if (this.invalidFields && this.invalidFields.length > 0) {\n parts.push(`\\nInvalid Fields: ${this.invalidFields.join(\", \")}`);\n }\n\n if (this.originalError) {\n parts.push(`\\nCause: ${this.originalError.message}`);\n }\n\n return parts.join(\"\");\n }\n}\n\n/**\n * Error thrown when CLI command usage is incorrect\n * Used for invalid arguments, missing required options, etc.\n */\nexport class CLIUsageError extends MigrationError {\n public readonly command?: string;\n public readonly suggestion?: string;\n\n constructor(message: string, command?: string, suggestion?: string) {\n super(message);\n this.name = \"CLIUsageError\";\n this.command = command;\n this.suggestion = suggestion;\n Object.setPrototypeOf(this, CLIUsageError.prototype);\n }\n\n /**\n * Creates a formatted error message with usage suggestions\n */\n public getDetailedMessage(): string {\n const parts: string[] = [this.message];\n\n if (this.command) {\n parts.push(`\\nCommand: ${this.command}`);\n }\n\n if (this.suggestion) {\n parts.push(`\\nSuggestion: ${this.suggestion}`);\n }\n\n return parts.join(\"\");\n }\n}\n","/**\n * PocketBase Format Converter\n * Converts PocketBase collection objects to our internal CollectionSchema format\n *\n * This module handles conversion between PocketBase's native collection format\n * (as found in migration files and snapshots) and our internal schema representation.\n */\n\nimport { SnapshotError } from \"./errors\";\nimport type { CollectionSchema, SchemaSnapshot } from \"./types\";\n\nconst SNAPSHOT_VERSION = \"1.0.0\";\n\n/**\n * Resolves a collection ID to a collection name\n * Uses known constants and parses migration expressions to resolve IDs\n *\n * @param collectionId - The collection ID to resolve\n * @returns The collection name, or the original ID if it can't be resolved\n */\nexport function resolveCollectionIdToName(collectionId: string): string {\n // Known PocketBase constants\n // Note: We return \"Users\" (title case) for consistency, but this should be\n // normalized during comparison to handle case differences\n if (collectionId === \"_pb_users_auth_\") {\n return \"Users\";\n }\n\n // Try to extract collection name from expressions like app.findCollectionByNameOrId(\"Name\").id\n const nameMatch = collectionId.match(/app\\.findCollectionByNameOrId\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/);\n if (nameMatch) {\n return nameMatch[1];\n }\n\n // If we can't resolve it, return the original ID\n // This will cause a comparison issue, but it's better than failing\n return collectionId;\n}\n\n/**\n * Converts a PocketBase collection object to CollectionSchema format\n *\n * @param pbCollection - PocketBase collection object from migration file\n * @returns CollectionSchema object\n */\nexport function convertPocketBaseCollection(pbCollection: any): CollectionSchema {\n const fields: any[] = [];\n\n // System field names that should always be excluded\n const systemFieldNames = [\"id\", \"created\", \"updated\", \"collectionId\", \"collectionName\", \"expand\"];\n\n // Auth collection system field names\n const authSystemFieldNames = [\"email\", \"emailVisibility\", \"verified\", \"password\", \"tokenKey\"];\n\n // Convert PocketBase fields to our FieldDefinition format\n if (pbCollection.fields && Array.isArray(pbCollection.fields)) {\n for (const pbField of pbCollection.fields) {\n // Skip system fields by checking both the system flag and field name\n // Some PocketBase exports mark created/updated as system: false\n if (pbField.system || systemFieldNames.includes(pbField.name)) {\n continue;\n }\n\n // Skip auth system fields for auth collections\n if (pbCollection.type === \"auth\" && authSystemFieldNames.includes(pbField.name)) {\n continue;\n }\n\n const field: any = {\n name: pbField.name,\n type: pbField.type,\n required: pbField.required || false,\n };\n\n // Initialize options object\n field.options = pbField.options ? { ...pbField.options } : {};\n\n // Extract values for select/enum fields (values can be directly on field or in options)\n // This must be done before cleaning up empty options to ensure values are preserved\n if (pbField.type === \"select\") {\n // Check for values directly on the field first (common in migration files)\n if (pbField.values && Array.isArray(pbField.values)) {\n field.options.values = pbField.values;\n } else if (pbField.options?.values && Array.isArray(pbField.options.values)) {\n // Already in options, keep it\n field.options.values = pbField.options.values;\n }\n }\n\n // Handle relation fields\n if (pbField.type === \"relation\") {\n // Support both formats: collectionId directly on field or in options\n const collectionId = pbField.collectionId || pbField.options?.collectionId || \"\";\n // Resolve collectionId to collection name\n // collectionId is a system field (like _pb_users_auth_), not the collection name\n // We need to resolve it to the actual collection name for comparison\n const collectionName = resolveCollectionIdToName(collectionId);\n field.relation = {\n collection: collectionName,\n cascadeDelete: pbField.cascadeDelete ?? pbField.options?.cascadeDelete ?? false,\n maxSelect: pbField.maxSelect ?? pbField.options?.maxSelect,\n minSelect: pbField.minSelect ?? pbField.options?.minSelect,\n };\n }\n\n // Clean up empty options object, but preserve values for select fields\n // If options only contains values for a select field, keep it\n const hasOnlyValues = Object.keys(field.options).length === 1 && field.options.values !== undefined;\n if (Object.keys(field.options).length === 0) {\n delete field.options;\n } else if (pbField.type === \"select\" && hasOnlyValues) {\n // Keep options object if it only contains values for a select field\n // This ensures values are preserved for comparison\n }\n\n fields.push(field);\n }\n }\n\n const schema: CollectionSchema = {\n name: pbCollection.name,\n type: pbCollection.type || \"base\",\n fields,\n };\n\n // Add indexes if present\n if (pbCollection.indexes && Array.isArray(pbCollection.indexes)) {\n schema.indexes = pbCollection.indexes;\n }\n\n // Add rules/permissions\n const rules: any = {};\n if (pbCollection.listRule !== undefined) rules.listRule = pbCollection.listRule;\n if (pbCollection.viewRule !== undefined) rules.viewRule = pbCollection.viewRule;\n if (pbCollection.createRule !== undefined) rules.createRule = pbCollection.createRule;\n if (pbCollection.updateRule !== undefined) rules.updateRule = pbCollection.updateRule;\n if (pbCollection.deleteRule !== undefined) rules.deleteRule = pbCollection.deleteRule;\n if (pbCollection.manageRule !== undefined) rules.manageRule = pbCollection.manageRule;\n\n if (Object.keys(rules).length > 0) {\n schema.rules = rules;\n // Also set permissions to match rules (they're the same thing)\n schema.permissions = { ...rules };\n }\n\n return schema;\n}\n\n/**\n * Converts PocketBase migration format to SchemaSnapshot\n * Extracts the snapshot array from the migration file content\n *\n * @param migrationContent - Raw migration file content\n * @returns SchemaSnapshot with collections map\n */\nexport function convertPocketBaseMigration(migrationContent: string): SchemaSnapshot {\n try {\n // Extract the snapshot array from the migration file\n // The format is: migrate((app) => { const snapshot = [...]; ... })\n const snapshotMatch = migrationContent.match(/const\\s+snapshot\\s*=\\s*(\\[[\\s\\S]*?\\]);/);\n\n if (!snapshotMatch) {\n throw new Error(\"Could not find snapshot array in migration file\");\n }\n\n // Parse the snapshot array as JSON\n // We need to evaluate it as JavaScript since it's not pure JSON\n const snapshotArrayStr = snapshotMatch[1];\n let snapshotArray: any[];\n\n try {\n // Use Function constructor to safely evaluate the array\n // This is safer than eval() and works for our use case\n snapshotArray = new Function(`return ${snapshotArrayStr}`)();\n } catch (parseError) {\n throw new Error(`Failed to parse snapshot array: ${parseError}`);\n }\n\n if (!Array.isArray(snapshotArray)) {\n throw new Error(\"Snapshot is not an array\");\n }\n\n // Convert each collection to our format\n const collections = new Map<string, CollectionSchema>();\n\n for (const pbCollection of snapshotArray) {\n if (!pbCollection.name) {\n console.warn(\"Skipping collection without name\");\n continue;\n }\n\n const schema = convertPocketBaseCollection(pbCollection);\n collections.set(pbCollection.name, schema);\n }\n\n return {\n version: SNAPSHOT_VERSION,\n timestamp: new Date().toISOString(),\n collections,\n };\n } catch (error) {\n throw new SnapshotError(\n `Failed to convert PocketBase migration: ${error instanceof Error ? error.message : String(error)}`,\n undefined,\n \"parse\",\n error instanceof Error ? error : undefined\n );\n }\n}\n","/**\n * Migration File Parser\n * Parses PocketBase migration files to extract collection operations\n *\n * This module handles parsing migration files to extract:\n * - Collection creations (new Collection(...))\n * - Collection deletions (app.delete(...))\n * - Field modifications (field.property = value)\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { convertPocketBaseCollection } from \"./pocketbase-converter\";\nimport type { CollectionSchema } from \"./types\";\n\n/**\n * Extracts timestamp from migration filename\n * Migration files are named: [timestamp]_[description].js\n *\n * @param filename - Migration filename\n * @returns Timestamp as number or null if not found\n */\nexport function extractTimestampFromFilename(filename: string): number | null {\n const match = filename.match(/^(\\d+)_/);\n if (match) {\n return parseInt(match[1], 10);\n }\n return null;\n}\n\n/**\n * Finds all migration files after a given snapshot timestamp\n * Excludes snapshot files themselves\n *\n * @param migrationsPath - Path to migrations directory\n * @param snapshotTimestamp - Timestamp of the snapshot file\n * @returns Array of migration file paths sorted by timestamp\n */\nexport function findMigrationsAfterSnapshot(migrationsPath: string, snapshotTimestamp: number): string[] {\n try {\n if (!fs.existsSync(migrationsPath)) {\n return [];\n }\n\n const files = fs.readdirSync(migrationsPath);\n const migrationFiles: { path: string; timestamp: number }[] = [];\n\n for (const file of files) {\n // Skip snapshot files\n if (file.endsWith(\"_collections_snapshot.js\") || file.endsWith(\"_snapshot.js\")) {\n continue;\n }\n\n // Skip non-JS files\n if (!file.endsWith(\".js\")) {\n continue;\n }\n\n const timestamp = extractTimestampFromFilename(file);\n if (timestamp && timestamp > snapshotTimestamp) {\n migrationFiles.push({\n path: path.join(migrationsPath, file),\n timestamp,\n });\n }\n }\n\n // Sort by timestamp (ascending order)\n migrationFiles.sort((a, b) => a.timestamp - b.timestamp);\n\n return migrationFiles.map((f) => f.path);\n } catch (error) {\n console.warn(`Error finding migrations after snapshot: ${error}`);\n return [];\n }\n}\n\n/**\n * Helper function to parse collection operations from migration content\n *\n * @param content - Migration content (should be just the UP migration)\n * @returns Object with collections to create and collections to delete\n */\nfunction parseMigrationOperationsFromContent(content: string): {\n collectionsToCreate: CollectionSchema[];\n collectionsToDelete: string[];\n} {\n const collectionsToCreate: CollectionSchema[] = [];\n const collectionsToDelete: string[] = [];\n\n try {\n // Extract collection definitions from `new Collection({...})`\n // Use a more robust approach: find all \"new Collection(\" and then parse until matching closing paren\n let searchIndex = 0;\n while (true) {\n const collectionStart = content.indexOf(\"new Collection(\", searchIndex);\n if (collectionStart === -1) {\n break;\n }\n\n // Find the opening brace after \"new Collection(\"\n const openParen = collectionStart + \"new Collection(\".length;\n let braceCount = 0;\n let parenCount = 1; // We're already inside the opening paren\n let inString = false;\n let stringChar = null;\n let i = openParen;\n\n // Skip whitespace to find the opening brace\n while (i < content.length && /\\s/.test(content[i])) {\n i++;\n }\n\n if (content[i] !== \"{\") {\n searchIndex = i + 1;\n continue;\n }\n\n const objectStart = i;\n braceCount = 1;\n i++;\n\n // Find the matching closing brace and paren\n while (i < content.length && (braceCount > 0 || parenCount > 0)) {\n const char = content[i];\n const prevChar = i > 0 ? content[i - 1] : \"\";\n\n // Handle strings\n if (!inString && (char === '\"' || char === \"'\")) {\n inString = true;\n stringChar = char;\n } else if (inString && char === stringChar && prevChar !== \"\\\\\") {\n inString = false;\n stringChar = null;\n }\n\n if (!inString) {\n if (char === \"{\") braceCount++;\n if (char === \"}\") braceCount--;\n if (char === \"(\") parenCount++;\n if (char === \")\") parenCount--;\n }\n\n i++;\n }\n\n if (braceCount === 0 && parenCount === 0) {\n const objectContent = content.substring(objectStart, i - 1); // -1 to exclude the closing paren\n try {\n // Use Function constructor to parse the JavaScript object\n const collectionObj = new Function(`return ${objectContent}`)();\n if (collectionObj && collectionObj.name) {\n const schema = convertPocketBaseCollection(collectionObj);\n collectionsToCreate.push(schema);\n }\n } catch (error) {\n // Skip malformed collection definitions\n console.warn(`Failed to parse collection definition: ${error}`);\n }\n }\n\n searchIndex = i;\n }\n\n // Extract collection deletions from `app.delete(...)`\n // Look for patterns like: app.delete(collection_xxx) or app.delete(app.findCollectionByNameOrId(\"name\"))\n const deleteMatches = content.matchAll(\n /app\\.delete\\s*\\(\\s*(?:collection_\\w+|app\\.findCollectionByNameOrId\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\))\\s*\\)/g\n );\n for (const match of deleteMatches) {\n // If we have a collection name from findCollectionByNameOrId, use it\n if (match[1]) {\n collectionsToDelete.push(match[1]);\n } else {\n // Try to find the collection name from the variable name\n // Look backwards for the collection variable definition\n const varNameMatch = match[0].match(/collection_(\\w+)/);\n if (varNameMatch) {\n // Try to find the collection name from the variable definition\n const varName = `collection_${varNameMatch[1]}`;\n // Search backwards from the delete call to find the variable definition\n const deleteIndex = content.indexOf(match[0]);\n const beforeDelete = content.substring(0, deleteIndex);\n const varDefMatch = beforeDelete.match(\n new RegExp(`const\\\\s+${varName}\\\\s*=\\\\s*new\\\\s+Collection\\\\(\\\\s*(\\\\{[\\\\s\\\\S]*?\\\\})\\\\s*\\\\)`, \"g\")\n );\n if (varDefMatch && varDefMatch.length > 0) {\n // Find the collection definition (get the last match closest to the delete)\n const collectionDefMatch = beforeDelete.match(\n new RegExp(`const\\\\s+${varName}\\\\s*=\\\\s*new\\\\s+Collection\\\\(\\\\s*(\\\\{[\\\\s\\\\S]*?\\\\})\\\\s*\\\\)`)\n );\n if (collectionDefMatch) {\n try {\n const collectionDefStr = collectionDefMatch[1];\n const collectionObj = new Function(`return ${collectionDefStr}`)();\n if (collectionObj && collectionObj.name) {\n collectionsToDelete.push(collectionObj.name);\n }\n } catch {\n // Skip if we can't parse\n }\n }\n }\n }\n }\n }\n\n // Also look for direct collection name in findCollectionByNameOrId followed by delete\n const findAndDeleteMatches = content.matchAll(\n /app\\.findCollectionByNameOrId\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)[\\s\\S]*?app\\.delete/g\n );\n for (const match of findAndDeleteMatches) {\n collectionsToDelete.push(match[1]);\n }\n } catch (error) {\n console.warn(`Failed to parse migration operations from content: ${error}`);\n }\n\n return { collectionsToCreate, collectionsToDelete };\n}\n\n/**\n * Parses a migration file to extract collection operations\n * Extracts collections created with `new Collection(...)` and collections deleted with `app.delete(...)`\n * Only parses the UP migration (first function), not the down migration\n *\n * @param migrationContent - Raw migration file content\n * @returns Object with collections to create and collections to delete\n */\nexport function parseMigrationOperations(migrationContent: string): {\n collectionsToCreate: CollectionSchema[];\n collectionsToDelete: string[];\n} {\n try {\n // Extract only the UP migration (first function argument to migrate())\n // Find the migrate call and extract the first function body\n const migrateMatch = migrationContent.match(/migrate\\s*\\(\\s*/);\n if (!migrateMatch) {\n // If we can't find the migrate pattern, try to parse the whole file\n return parseMigrationOperationsFromContent(migrationContent);\n }\n\n const startIndex = migrateMatch.index! + migrateMatch[0].length;\n\n // Find the opening paren of the first function\n let i = startIndex;\n let parenCount = 0;\n let foundFirstParen = false;\n\n while (i < migrationContent.length) {\n const char = migrationContent[i];\n if (char === \"(\") {\n parenCount++;\n foundFirstParen = true;\n i++;\n break;\n }\n i++;\n }\n\n if (!foundFirstParen) {\n return parseMigrationOperationsFromContent(migrationContent);\n }\n\n // Skip the function parameters: (app) => {\n let inString = false;\n let stringChar = null;\n let foundBrace = false;\n let braceStart = -1;\n\n while (i < migrationContent.length && !foundBrace) {\n const char = migrationContent[i];\n const prevChar = i > 0 ? migrationContent[i - 1] : \"\";\n\n if (!inString && (char === '\"' || char === \"'\")) {\n inString = true;\n stringChar = char;\n } else if (inString && char === stringChar && prevChar !== \"\\\\\") {\n inString = false;\n stringChar = null;\n }\n\n if (!inString) {\n if (char === \"(\") parenCount++;\n if (char === \")\") {\n parenCount--;\n if (parenCount === 0) {\n // Found end of function parameters, look for =>\n i++;\n while (i < migrationContent.length && /\\s/.test(migrationContent[i])) {\n i++;\n }\n if (i < migrationContent.length - 1 && migrationContent[i] === \"=\" && migrationContent[i + 1] === \">\") {\n i += 2;\n while (i < migrationContent.length && /\\s/.test(migrationContent[i])) {\n i++;\n }\n if (i < migrationContent.length && migrationContent[i] === \"{\") {\n foundBrace = true;\n braceStart = i + 1;\n break;\n }\n }\n }\n }\n }\n i++;\n }\n\n if (!foundBrace || braceStart === -1) {\n return parseMigrationOperationsFromContent(migrationContent);\n }\n\n // Find the matching closing brace\n let braceCount = 1;\n i = braceStart;\n inString = false;\n stringChar = null;\n\n while (i < migrationContent.length && braceCount > 0) {\n const char = migrationContent[i];\n const prevChar = i > 0 ? migrationContent[i - 1] : \"\";\n\n if (!inString && (char === '\"' || char === \"'\")) {\n inString = true;\n stringChar = char;\n } else if (inString && char === stringChar && prevChar !== \"\\\\\") {\n inString = false;\n stringChar = null;\n }\n\n if (!inString) {\n if (char === \"{\") braceCount++;\n if (char === \"}\") braceCount--;\n }\n\n i++;\n }\n\n if (braceCount === 0) {\n const upMigrationContent = migrationContent.substring(braceStart, i - 1);\n return parseMigrationOperationsFromContent(upMigrationContent);\n }\n\n // Fallback: parse the whole file\n return parseMigrationOperationsFromContent(migrationContent);\n } catch (error) {\n console.warn(`Failed to parse migration operations: ${error}`);\n return { collectionsToCreate: [], collectionsToDelete: [] };\n }\n}\n","/**\n * Snapshot Manager\n * Handles saving and loading schema snapshots from JSON files\n *\n * This module provides a standalone, configurable snapshot manager that can be used\n * by consumer projects to manage schema snapshots. It focuses on JSON snapshot file\n * management, delegating migration file parsing and PocketBase format conversion\n * to specialized modules.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { FileSystemError, SnapshotError } from \"./errors\";\nimport {\n extractTimestampFromFilename,\n findMigrationsAfterSnapshot,\n parseMigrationOperations,\n} from \"./migration-parser\";\nimport { convertPocketBaseMigration } from \"./pocketbase-converter\";\nimport type { CollectionSchema, SchemaDefinition, SchemaSnapshot } from \"./types\";\n\nconst SNAPSHOT_VERSION = \"1.0.0\";\nconst DEFAULT_SNAPSHOT_FILENAME = \".migration-snapshot.json\";\n\n/**\n * Configuration for snapshot operations\n */\nexport interface SnapshotConfig {\n /**\n * Path to the snapshot file\n * Can be absolute or relative to workspaceRoot\n */\n snapshotPath?: string;\n\n /**\n * Workspace root directory for resolving relative paths\n * Defaults to process.cwd()\n */\n workspaceRoot?: string;\n\n /**\n * Path to the migrations directory for finding PocketBase snapshots\n */\n migrationsPath?: string;\n\n /**\n * Whether to auto-migrate old snapshot formats\n * Defaults to true\n */\n autoMigrate?: boolean;\n\n /**\n * Custom snapshot version for testing\n */\n version?: string;\n}\n\n/**\n * Snapshot format versions and their migration functions\n */\ninterface SnapshotMigration {\n fromVersion: string;\n toVersion: string;\n migrate: (data: any) => any;\n}\n\n/**\n * Registry of snapshot format migrations\n */\nconst SNAPSHOT_MIGRATIONS: SnapshotMigration[] = [\n // Add migrations here as the format evolves\n // Example:\n // {\n // fromVersion: '0.9.0',\n // toVersion: '1.0.0',\n // migrate: (data) => ({ ...data, newField: 'default' })\n // }\n];\n\n/**\n * Default configuration values\n */\nconst DEFAULT_CONFIG: Omit<Required<SnapshotConfig>, \"migrationsPath\"> & { migrationsPath?: string } = {\n snapshotPath: DEFAULT_SNAPSHOT_FILENAME,\n workspaceRoot: process.cwd(),\n autoMigrate: true,\n version: SNAPSHOT_VERSION,\n};\n\n/**\n * Merges user config with defaults\n */\nfunction mergeConfig(config: SnapshotConfig = {}): typeof DEFAULT_CONFIG {\n return {\n ...DEFAULT_CONFIG,\n ...config,\n };\n}\n\n/**\n * Gets the snapshot file path from configuration\n *\n * @param config - Snapshot configuration\n * @returns Absolute path to the snapshot file\n */\nexport function getSnapshotPath(config: SnapshotConfig = {}): string {\n const mergedConfig = mergeConfig(config);\n const workspaceRoot = mergedConfig.workspaceRoot;\n const snapshotFilename = mergedConfig.snapshotPath;\n\n // If snapshotPath is absolute, use it directly\n if (path.isAbsolute(snapshotFilename)) {\n return snapshotFilename;\n }\n\n // Otherwise, resolve relative to workspaceRoot\n return path.join(workspaceRoot, snapshotFilename);\n}\n\n/**\n * Checks if snapshot file exists\n *\n * @param config - Snapshot configuration\n * @returns True if snapshot file exists\n */\nexport function snapshotExists(config: SnapshotConfig = {}): boolean {\n try {\n const snapshotPath = getSnapshotPath(config);\n return fs.existsSync(snapshotPath);\n } catch {\n // If there's any error checking existence, treat as non-existent\n return false;\n }\n}\n\n/**\n * Handles file system errors with descriptive messages\n *\n * @param error - The error object\n * @param operation - The operation being performed\n * @param filePath - The file path involved\n * @throws SnapshotError or FileSystemError with descriptive message\n */\nfunction handleFileSystemError(error: any, operation: \"read\" | \"write\", filePath: string): never {\n const fsError = error as NodeJS.ErrnoException;\n\n if (fsError.code === \"ENOENT\") {\n throw new SnapshotError(`Snapshot file not found: ${filePath}`, filePath, operation, error);\n } else if (fsError.code === \"EACCES\" || fsError.code === \"EPERM\") {\n throw new FileSystemError(\n `Permission denied ${operation === \"read\" ? \"reading\" : \"writing\"} snapshot file. Check file permissions.`,\n filePath,\n operation,\n fsError.code,\n error\n );\n } else if (fsError.code === \"ENOSPC\") {\n throw new FileSystemError(\n `No space left on device when ${operation === \"read\" ? \"reading\" : \"writing\"} snapshot file.`,\n filePath,\n operation,\n fsError.code,\n error\n );\n } else {\n throw new SnapshotError(`Failed to ${operation} snapshot file: ${error.message}`, filePath, operation, error);\n }\n}\n\n/**\n * Serializes a Map to a plain object for JSON serialization\n *\n * @param map - Map to serialize\n * @returns Plain object representation\n */\nfunction serializeMap<K extends string, V>(map: Map<K, V>): Record<K, V> {\n const obj: Record<string, V> = {};\n for (const [key, value] of map.entries()) {\n obj[key] = value;\n }\n return obj as Record<K, V>;\n}\n\n/**\n * Deserializes a plain object to a Map\n *\n * @param obj - Plain object to deserialize\n * @returns Map representation\n */\nfunction deserializeMap<K extends string, V>(obj: Record<K, V>): Map<K, V> {\n const map = new Map<K, V>();\n for (const [key, value] of Object.entries(obj)) {\n map.set(key as K, value as V);\n }\n return map;\n}\n\n/**\n * Serializes SchemaDefinition to JSON format\n * Converts Map to plain object for JSON compatibility\n *\n * @param schema - Schema definition to serialize\n * @returns JSON-serializable object\n */\nfunction serializeSchemaDefinition(schema: SchemaDefinition): any {\n return {\n collections: serializeMap(schema.collections),\n };\n}\n\n/**\n * Adds version and timestamp metadata to snapshot\n *\n * @param schema - Schema definition\n * @param config - Optional configuration with custom version\n * @returns Snapshot with metadata\n */\nfunction addSnapshotMetadata(schema: SchemaDefinition, config?: SnapshotConfig): any {\n const mergedConfig = mergeConfig(config);\n return {\n version: mergedConfig.version,\n timestamp: new Date().toISOString(),\n ...serializeSchemaDefinition(schema),\n };\n}\n\n/**\n * Saves schema snapshot to file\n * Serializes SchemaDefinition to JSON with version and timestamp metadata\n * Writes with pretty printing for readability\n *\n * @param schema - Schema definition to save\n * @param config - Snapshot configuration\n */\nexport function saveSnapshot(schema: SchemaDefinition, config: SnapshotConfig = {}): void {\n const snapshotPath = getSnapshotPath(config);\n\n try {\n // Ensure directory exists\n const snapshotDir = path.dirname(snapshotPath);\n if (!fs.existsSync(snapshotDir)) {\n fs.mkdirSync(snapshotDir, { recursive: true });\n }\n\n // Add metadata and serialize\n const snapshotData = addSnapshotMetadata(schema, config);\n\n // Write with pretty printing (2 spaces indentation)\n const jsonContent = JSON.stringify(snapshotData, null, 2);\n fs.writeFileSync(snapshotPath, jsonContent, \"utf-8\");\n } catch (error) {\n handleFileSystemError(error, \"write\", snapshotPath);\n }\n}\n\n/**\n * Parses JSON and validates snapshot format\n *\n * @param jsonContent - Raw JSON content\n * @param snapshotPath - Path to snapshot file (for error messages)\n * @returns Parsed snapshot data\n */\nfunction parseAndValidateSnapshot(jsonContent: string, snapshotPath: string): any {\n try {\n const data = JSON.parse(jsonContent);\n\n // Validate required fields\n if (!data.version) {\n throw new SnapshotError(\n \"Snapshot file is missing version field. The snapshot may be corrupted.\",\n snapshotPath,\n \"validate\"\n );\n }\n\n if (!data.timestamp) {\n throw new SnapshotError(\n \"Snapshot file is missing timestamp field. The snapshot may be corrupted.\",\n snapshotPath,\n \"validate\"\n );\n }\n\n if (!data.collections) {\n throw new SnapshotError(\n \"Snapshot file is missing collections field. The snapshot may be corrupted.\",\n snapshotPath,\n \"validate\"\n );\n }\n\n return data;\n } catch (error) {\n if (error instanceof SnapshotError) {\n throw error;\n }\n\n if (error instanceof SyntaxError) {\n throw new SnapshotError(\n `Invalid JSON in snapshot file. The file may be corrupted or manually edited incorrectly.`,\n snapshotPath,\n \"parse\",\n error\n );\n }\n throw error;\n }\n}\n\n/**\n * Compares two version strings\n * Returns -1 if a < b, 0 if a == b, 1 if a > b\n */\nfunction compareVersions(a: string, b: string): number {\n const partsA = a.split(\".\").map(Number);\n const partsB = b.split(\".\").map(Number);\n\n for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {\n const numA = partsA[i] || 0;\n const numB = partsB[i] || 0;\n\n if (numA < numB) return -1;\n if (numA > numB) return 1;\n }\n\n return 0;\n}\n\n/**\n * Migrates old snapshot formats to current version\n * Applies migrations in sequence from old version to current\n *\n * @param data - Parsed snapshot data\n * @param config - Optional configuration\n * @returns Migrated snapshot data\n */\nfunction migrateSnapshotFormat(data: any, config?: SnapshotConfig): any {\n const mergedConfig = mergeConfig(config);\n const currentVersion = data.version;\n const targetVersion = mergedConfig.version;\n\n // If versions match, no migration needed\n if (currentVersion === targetVersion) {\n return data;\n }\n\n // If auto-migrate is disabled, just return the data with a warning\n if (!mergedConfig.autoMigrate) {\n console.warn(\n `Snapshot version ${currentVersion} differs from current ${targetVersion}, but auto-migrate is disabled.`\n );\n return data;\n }\n\n // Find and apply migrations in sequence\n let migratedData = { ...data };\n let currentMigrationVersion = currentVersion;\n\n // Sort migrations by fromVersion\n const sortedMigrations = [...SNAPSHOT_MIGRATIONS].sort((a, b) => compareVersions(a.fromVersion, b.fromVersion));\n\n for (const migration of sortedMigrations) {\n if (compareVersions(currentMigrationVersion, migration.fromVersion) === 0) {\n console.log(`Migrating snapshot from ${migration.fromVersion} to ${migration.toVersion}...`);\n migratedData = migration.migrate(migratedData);\n migratedData.version = migration.toVersion;\n currentMigrationVersion = migration.toVersion;\n }\n }\n\n // If we couldn't migrate to the target version, log a warning\n if (compareVersions(currentMigrationVersion, targetVersion) !== 0) {\n console.warn(`Unknown snapshot version ${currentVersion}, attempting to load anyway...`);\n }\n\n return migratedData;\n}\n\n/**\n * Deserializes snapshot data to SchemaSnapshot\n *\n * @param data - Parsed and validated snapshot data\n * @returns SchemaSnapshot object\n */\nfunction deserializeSnapshot(data: any): SchemaSnapshot {\n return {\n version: data.version,\n timestamp: data.timestamp,\n collections: deserializeMap<string, CollectionSchema>(data.collections),\n };\n}\n\n/**\n * Loads schema snapshot from file\n * Reads snapshot file, parses JSON, validates format, and handles migrations\n *\n * @param config - Snapshot configuration\n * @returns SchemaSnapshot object\n * @throws Error if snapshot file doesn't exist or is invalid\n */\nexport function loadSnapshot(config: SnapshotConfig = {}): SchemaSnapshot {\n const snapshotPath = getSnapshotPath(config);\n\n try {\n // Read file\n const jsonContent = fs.readFileSync(snapshotPath, \"utf-8\");\n\n // Parse and validate\n const data = parseAndValidateSnapshot(jsonContent, snapshotPath);\n\n // Migrate format if needed\n const migratedData = migrateSnapshotFormat(data, config);\n\n // Deserialize to SchemaSnapshot\n return deserializeSnapshot(migratedData);\n } catch (error) {\n // If it's already a SnapshotError or FileSystemError, re-throw it\n if (error instanceof SnapshotError || error instanceof FileSystemError) {\n throw error;\n }\n\n // If file doesn't exist, throw specific error\n if ((error as any).code === \"ENOENT\") {\n throw new SnapshotError(\n `Snapshot file not found. This may be the first migration run.`,\n snapshotPath,\n \"read\",\n error as Error\n );\n }\n\n // Handle other file system errors\n handleFileSystemError(error, \"read\", snapshotPath);\n }\n}\n\n/**\n * Merges base schema with custom snapshot\n * Base schema collections are preserved, custom collections are added\n * Custom collections override base collections if they have the same name\n *\n * @param baseSnapshot - PocketBase base schema\n * @param customSnapshot - User's custom schema snapshot (may be null)\n * @returns Merged SchemaSnapshot\n */\nexport function mergeSnapshots(baseSnapshot: SchemaSnapshot, customSnapshot: SchemaSnapshot | null): SchemaSnapshot {\n // If no custom snapshot, return base snapshot\n if (!customSnapshot) {\n return baseSnapshot;\n }\n\n // Create a new collections map starting with base collections\n const mergedCollections = new Map<string, CollectionSchema>(baseSnapshot.collections);\n\n // Add or override with custom collections\n for (const [name, schema] of customSnapshot.collections.entries()) {\n mergedCollections.set(name, schema);\n }\n\n return {\n version: customSnapshot.version || baseSnapshot.version,\n timestamp: customSnapshot.timestamp || baseSnapshot.timestamp,\n collections: mergedCollections,\n };\n}\n\n/**\n * Finds the most recent snapshot file in the migrations directory\n * Identifies snapshot files by naming pattern (e.g., *_collections_snapshot.js)\n *\n * @param migrationsPath - Path to pb_migrations directory\n * @returns Path to most recent snapshot file or null if none exist\n */\nexport function findLatestSnapshot(migrationsPath: string): string | null {\n try {\n // Check if migrations directory exists\n if (!fs.existsSync(migrationsPath)) {\n return null;\n }\n\n // Read all files in migrations directory\n const files = fs.readdirSync(migrationsPath);\n\n // Filter for snapshot files (files ending with _collections_snapshot.js or _snapshot.js)\n const snapshotFiles = files.filter(\n (file) => file.endsWith(\"_collections_snapshot.js\") || file.endsWith(\"_snapshot.js\")\n );\n\n if (snapshotFiles.length === 0) {\n return null;\n }\n\n // Sort by filename (timestamp prefix) to get most recent\n // Snapshot files are named with timestamp prefix: [timestamp]_collections_snapshot.js\n snapshotFiles.sort().reverse();\n\n // Return full path to most recent snapshot\n const latestSnapshot = snapshotFiles[0];\n if (!latestSnapshot) {\n return null;\n }\n return path.join(migrationsPath, latestSnapshot);\n } catch (error) {\n // If there's any error reading directory, return null\n console.warn(`Error finding latest snapshot: ${error}`);\n return null;\n }\n}\n\n/**\n * Applies migration operations to a snapshot state\n * Creates new collections and deletes collections as specified\n *\n * @param snapshot - Base snapshot state\n * @param operations - Migration operations to apply\n * @returns Updated snapshot with operations applied\n */\nfunction applyMigrationOperations(\n snapshot: SchemaSnapshot,\n operations: { collectionsToCreate: CollectionSchema[]; collectionsToDelete: string[] }\n): SchemaSnapshot {\n const updatedCollections = new Map(snapshot.collections);\n\n // Apply deletions first\n for (const collectionName of operations.collectionsToDelete) {\n updatedCollections.delete(collectionName);\n }\n\n // Apply creations/updates\n for (const collection of operations.collectionsToCreate) {\n updatedCollections.set(collection.name, collection);\n }\n\n return {\n ...snapshot,\n collections: updatedCollections,\n };\n}\n\n/**\n * Loads snapshot and applies all migrations that come after it\n * This gives us the current state of the database schema\n *\n * @param config - Snapshot configuration (must include migrationsPath)\n * @returns SchemaSnapshot object representing current state or null if snapshot doesn't exist\n */\nexport function loadSnapshotWithMigrations(config: SnapshotConfig = {}): SchemaSnapshot | null {\n const migrationsPath = config.migrationsPath;\n\n if (!migrationsPath) {\n return null;\n }\n\n // Check if migrationsPath is actually a file (for backward compatibility with tests)\n if (fs.existsSync(migrationsPath) && fs.statSync(migrationsPath).isFile()) {\n try {\n const migrationContent = fs.readFileSync(migrationsPath, \"utf-8\");\n return convertPocketBaseMigration(migrationContent);\n } catch (error) {\n console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);\n return null;\n }\n }\n\n // It's a directory, find the latest snapshot\n const latestSnapshotPath = findLatestSnapshot(migrationsPath);\n\n if (!latestSnapshotPath) {\n // No snapshot found - return null (empty database)\n return null;\n }\n\n try {\n // Read and convert the PocketBase snapshot file\n const migrationContent = fs.readFileSync(latestSnapshotPath, \"utf-8\");\n let snapshot = convertPocketBaseMigration(migrationContent);\n\n // Extract timestamp from snapshot filename\n const snapshotFilename = path.basename(latestSnapshotPath);\n const snapshotTimestamp = extractTimestampFromFilename(snapshotFilename);\n\n if (snapshotTimestamp) {\n // Find all migration files after the snapshot\n const migrationFiles = findMigrationsAfterSnapshot(migrationsPath, snapshotTimestamp);\n\n // Apply each migration in order\n for (const migrationFile of migrationFiles) {\n try {\n const migrationContent = fs.readFileSync(migrationFile, \"utf-8\");\n const operations = parseMigrationOperations(migrationContent);\n snapshot = applyMigrationOperations(snapshot, operations);\n } catch (error) {\n console.warn(`Failed to apply migration ${migrationFile}: ${error}`);\n // Continue with other migrations even if one fails\n }\n }\n }\n\n return snapshot;\n } catch (error) {\n console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);\n return null;\n }\n}\n\n/**\n * Loads snapshot if it exists, returns null for first run\n * Convenience method that handles missing snapshot gracefully\n * Finds the most recent snapshot file from migrations directory\n * NOTE: This function only loads the snapshot, not migrations after it.\n * Use loadSnapshotWithMigrations() if you need the current state including migrations.\n *\n * @param config - Snapshot configuration (must include migrationsPath)\n * @returns SchemaSnapshot object or null if snapshot doesn't exist\n */\nexport function loadSnapshotIfExists(config: SnapshotConfig = {}): SchemaSnapshot | null {\n const migrationsPath = config.migrationsPath;\n\n if (!migrationsPath) {\n // No migrations path provided - return null\n return null;\n }\n\n // Check if migrationsPath is actually a file (for backward compatibility with tests)\n // If it's a file, treat it as a direct snapshot file path\n if (fs.existsSync(migrationsPath) && fs.statSync(migrationsPath).isFile()) {\n try {\n const migrationContent = fs.readFileSync(migrationsPath, \"utf-8\");\n return convertPocketBaseMigration(migrationContent);\n } catch (error) {\n console.warn(`Failed to load snapshot from ${migrationsPath}: ${error}`);\n return null;\n }\n }\n\n // It's a directory, find the latest snapshot\n const latestSnapshotPath = findLatestSnapshot(migrationsPath);\n\n if (latestSnapshotPath) {\n try {\n // Read and convert the PocketBase snapshot file\n const migrationContent = fs.readFileSync(latestSnapshotPath, \"utf-8\");\n return convertPocketBaseMigration(migrationContent);\n } catch (error) {\n console.warn(`Failed to load snapshot from ${latestSnapshotPath}: ${error}`);\n return null;\n }\n }\n\n // No snapshot found - return null (empty database)\n return null;\n}\n\n/**\n * Loads the base PocketBase schema from the initial migration file\n *\n * @param migrationPath - Path to pocketbase/pb_migrations/000000000_collections_snapshot.js\n * @returns SchemaSnapshot representing PocketBase's initial state\n * @throws SnapshotError if file not found or invalid format\n */\nexport function loadBaseMigration(migrationPath: string): SchemaSnapshot {\n try {\n // Check if file exists\n if (!fs.existsSync(migrationPath)) {\n throw new SnapshotError(\n `Base migration file not found: ${migrationPath}\\n\\n` +\n `This file should contain PocketBase's initial schema.\\n` +\n `Please ensure PocketBase is properly set up by running 'yarn setup'.\\n` +\n `If the file exists in a different location, update the configuration.`,\n migrationPath,\n \"read\"\n );\n }\n\n // Read the migration file\n const migrationContent = fs.readFileSync(migrationPath, \"utf-8\");\n\n // Convert to SchemaSnapshot\n const snapshot = convertPocketBaseMigration(migrationContent);\n\n return snapshot;\n } catch (error) {\n // If it's already a SnapshotError, re-throw it\n if (error instanceof SnapshotError) {\n throw error;\n }\n\n // Handle file system errors\n if ((error as any).code === \"ENOENT\") {\n throw new SnapshotError(\n `Base migration file not found: ${migrationPath}\\n\\n` +\n `This file should contain PocketBase's initial schema.\\n` +\n `Please ensure PocketBase is properly set up by running 'yarn setup'.`,\n migrationPath,\n \"read\",\n error as Error\n );\n }\n\n if ((error as any).code === \"EACCES\" || (error as any).code === \"EPERM\") {\n throw new FileSystemError(\n `Permission denied reading base migration file. Check file permissions.`,\n migrationPath,\n \"read\",\n (error as any).code,\n error as Error\n );\n }\n\n // Other errors\n throw new SnapshotError(\n `Failed to load base migration: ${error instanceof Error ? error.message : String(error)}`,\n migrationPath,\n \"read\",\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Gets the current snapshot version\n */\nexport function getSnapshotVersion(): string {\n return SNAPSHOT_VERSION;\n}\n\n/**\n * Validates a snapshot against the current version\n * Returns validation result with any issues found\n */\nexport function validateSnapshot(snapshot: SchemaSnapshot): { valid: boolean; issues: string[] } {\n const issues: string[] = [];\n\n // Check version\n if (!snapshot.version) {\n issues.push(\"Missing version field\");\n } else if (compareVersions(snapshot.version, SNAPSHOT_VERSION) > 0) {\n issues.push(`Snapshot version ${snapshot.version} is newer than supported version ${SNAPSHOT_VERSION}`);\n }\n\n // Check timestamp\n if (!snapshot.timestamp) {\n issues.push(\"Missing timestamp field\");\n }\n\n // Check collections\n if (!snapshot.collections) {\n issues.push(\"Missing collections field\");\n } else if (!(snapshot.collections instanceof Map)) {\n issues.push(\"Collections field is not a Map\");\n }\n\n return {\n valid: issues.length === 0,\n issues,\n };\n}\n\n/**\n * Re-exports convertPocketBaseMigration for backward compatibility\n */\nexport { convertPocketBaseMigration } from \"./pocketbase-converter\";\n\n/**\n * SnapshotManager class for object-oriented usage\n * Provides a stateful interface for snapshot management\n */\nexport class SnapshotManager {\n private config: SnapshotConfig;\n\n constructor(config: SnapshotConfig = {}) {\n this.config = mergeConfig(config);\n }\n\n /**\n * Loads the current snapshot\n */\n loadSnapshot(): SchemaSnapshot {\n return loadSnapshot(this.config);\n }\n\n /**\n * Saves a schema as a snapshot\n */\n saveSnapshot(schema: SchemaDefinition): void {\n saveSnapshot(schema, this.config);\n }\n\n /**\n * Loads snapshot if it exists, returns null otherwise\n */\n loadSnapshotIfExists(): SchemaSnapshot | null {\n return loadSnapshotIfExists(this.config);\n }\n\n /**\n * Checks if a snapshot exists\n */\n snapshotExists(): boolean {\n return snapshotExists(this.config);\n }\n\n /**\n * Converts a PocketBase migration to a snapshot\n */\n convertPocketBaseMigration(content: string): SchemaSnapshot {\n return convertPocketBaseMigration(content);\n }\n\n /**\n * Gets the snapshot file path\n */\n getSnapshotPath(): string {\n return getSnapshotPath(this.config);\n }\n\n /**\n * Validates a snapshot\n */\n validateSnapshot(snapshot: SchemaSnapshot): { valid: boolean; issues: string[] } {\n return validateSnapshot(snapshot);\n }\n}\n"]}
@@ -1,4 +1,6 @@
1
- import { a as SchemaSnapshot, S as SchemaDefinition } from '../types-BbTgmg6H.cjs';
1
+ import { a as SchemaSnapshot, S as SchemaDefinition } from '../types-YoBjsa-A.cjs';
2
+ import '../fields-UcOPu1OQ.cjs';
3
+ import 'zod';
2
4
  import '../permissions-ZHafVSIx.cjs';
3
5
 
4
6
  /**
@@ -1,4 +1,6 @@
1
- import { a as SchemaSnapshot, S as SchemaDefinition } from '../types-z1Dkjg8m.js';
1
+ import { a as SchemaSnapshot, S as SchemaDefinition } from '../types-Ds3NQvny.js';
2
+ import '../fields-UcOPu1OQ.js';
3
+ import 'zod';
2
4
  import '../permissions-ZHafVSIx.js';
3
5
 
4
6
  /**