native-update 1.1.4 → 1.2.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 (58) hide show
  1. package/NativeUpdate.podspec +1 -0
  2. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +41 -0
  3. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +12 -0
  4. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +52 -1
  5. package/backend-template/README.md +56 -0
  6. package/backend-template/package.json +20 -0
  7. package/backend-template/server.js +121 -0
  8. package/dist/esm/__tests__/bundle-manager.test.js +1 -0
  9. package/dist/esm/__tests__/bundle-manager.test.js.map +1 -1
  10. package/dist/esm/__tests__/config.test.js +1 -0
  11. package/dist/esm/__tests__/config.test.js.map +1 -1
  12. package/dist/esm/__tests__/integration.test.js.map +1 -1
  13. package/dist/esm/__tests__/security.test.js.map +1 -1
  14. package/dist/esm/app-review/app-review-manager.d.ts +2 -2
  15. package/dist/esm/app-review/app-review-manager.js.map +1 -1
  16. package/dist/esm/app-review/platform-review-handler.js.map +1 -1
  17. package/dist/esm/app-review/review-conditions-checker.d.ts +1 -1
  18. package/dist/esm/app-review/review-conditions-checker.js.map +1 -1
  19. package/dist/esm/app-review/types.d.ts +1 -1
  20. package/dist/esm/app-update/app-update-manager.d.ts +1 -1
  21. package/dist/esm/app-update/app-update-manager.js.map +1 -1
  22. package/dist/esm/app-update/app-update-notifier.js.map +1 -1
  23. package/dist/esm/app-update/platform-app-update.js.map +1 -1
  24. package/dist/esm/background-update/background-scheduler.js.map +1 -1
  25. package/dist/esm/core/analytics.d.ts +7 -7
  26. package/dist/esm/core/analytics.js.map +1 -1
  27. package/dist/esm/core/event-emitter.d.ts +2 -2
  28. package/dist/esm/core/event-emitter.js.map +1 -1
  29. package/dist/esm/core/performance.js +16 -2
  30. package/dist/esm/core/performance.js.map +1 -1
  31. package/dist/esm/core/security.d.ts +13 -2
  32. package/dist/esm/core/security.js +13 -3
  33. package/dist/esm/core/security.js.map +1 -1
  34. package/dist/esm/index.d.ts +1 -1
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/live-update/bundle-manager.js +16 -1
  37. package/dist/esm/live-update/bundle-manager.js.map +1 -1
  38. package/dist/esm/live-update/download-manager.d.ts +8 -0
  39. package/dist/esm/live-update/download-manager.js +54 -7
  40. package/dist/esm/live-update/download-manager.js.map +1 -1
  41. package/dist/esm/plugin.js +3 -1
  42. package/dist/esm/plugin.js.map +1 -1
  43. package/dist/plugin.cjs.js +1 -1
  44. package/dist/plugin.cjs.js.map +1 -1
  45. package/dist/plugin.esm.js +1 -1
  46. package/dist/plugin.esm.js.map +1 -1
  47. package/dist/plugin.js +2 -2
  48. package/dist/plugin.js.map +1 -1
  49. package/docs/COMPREHENSIVE_AUDIT_REPORT.md +526 -0
  50. package/docs/FIREBASE_INTEGRATION_TRACKER.md +321 -0
  51. package/docs/KNOWN_LIMITATIONS.md +203 -0
  52. package/docs/PROJECT_COMPLETION_TRACKER.md +243 -0
  53. package/docs/api/background-update-api.md +157 -0
  54. package/docs/api/live-update-api.md +16 -0
  55. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +15 -0
  56. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +74 -26
  57. package/ios/Plugin/NativeUpdatePlugin.swift +45 -0
  58. package/package.json +28 -27
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.cjs.js","sources":["esm/definitions.js","esm/core/logger.js","esm/core/errors.js","esm/app-update/types.js","esm/core/config.js","esm/core/security.js","esm/live-update/bundle-manager.js","esm/live-update/download-manager.js","esm/live-update/version-manager.js","esm/app-update/app-update-checker.js","esm/app-update/app-update-installer.js","esm/app-update/platform-app-update.js","esm/app-update/app-update-manager.js","esm/core/event-emitter.js","esm/core/plugin-manager.js","esm/plugin.js","esm/core/cache-manager.js","esm/live-update/update-manager.js"],"sourcesContent":["// Core plugin interface will be defined later after other interfaces\n/**\n * Enums\n */\nexport var BackgroundUpdateType;\n(function (BackgroundUpdateType) {\n BackgroundUpdateType[\"APP_UPDATE\"] = \"app_update\";\n BackgroundUpdateType[\"LIVE_UPDATE\"] = \"live_update\";\n BackgroundUpdateType[\"BOTH\"] = \"both\";\n})(BackgroundUpdateType || (BackgroundUpdateType = {}));\nexport var NotificationPriority;\n(function (NotificationPriority) {\n NotificationPriority[\"MIN\"] = \"min\";\n NotificationPriority[\"LOW\"] = \"low\";\n NotificationPriority[\"DEFAULT\"] = \"default\";\n NotificationPriority[\"HIGH\"] = \"high\";\n NotificationPriority[\"MAX\"] = \"max\";\n})(NotificationPriority || (NotificationPriority = {}));\nexport var UpdateStrategy;\n(function (UpdateStrategy) {\n UpdateStrategy[\"IMMEDIATE\"] = \"immediate\";\n UpdateStrategy[\"BACKGROUND\"] = \"background\";\n UpdateStrategy[\"MANUAL\"] = \"manual\";\n})(UpdateStrategy || (UpdateStrategy = {}));\nexport var UpdateMode;\n(function (UpdateMode) {\n UpdateMode[\"IMMEDIATE\"] = \"immediate\";\n UpdateMode[\"ON_NEXT_RESTART\"] = \"on_next_restart\";\n UpdateMode[\"ON_NEXT_RESUME\"] = \"on_next_resume\";\n})(UpdateMode || (UpdateMode = {}));\nexport var InstallMode;\n(function (InstallMode) {\n InstallMode[\"IMMEDIATE\"] = \"immediate\";\n InstallMode[\"ON_NEXT_RESTART\"] = \"on_next_restart\";\n InstallMode[\"ON_NEXT_RESUME\"] = \"on_next_resume\";\n})(InstallMode || (InstallMode = {}));\nexport var ChecksumAlgorithm;\n(function (ChecksumAlgorithm) {\n ChecksumAlgorithm[\"SHA256\"] = \"SHA-256\";\n ChecksumAlgorithm[\"SHA512\"] = \"SHA-512\";\n})(ChecksumAlgorithm || (ChecksumAlgorithm = {}));\nexport var SyncStatus;\n(function (SyncStatus) {\n SyncStatus[\"UP_TO_DATE\"] = \"UP_TO_DATE\";\n SyncStatus[\"UPDATE_AVAILABLE\"] = \"UPDATE_AVAILABLE\";\n SyncStatus[\"UPDATE_INSTALLED\"] = \"UPDATE_INSTALLED\";\n SyncStatus[\"ERROR\"] = \"ERROR\";\n})(SyncStatus || (SyncStatus = {}));\nexport var BundleStatus;\n(function (BundleStatus) {\n BundleStatus[\"PENDING\"] = \"PENDING\";\n BundleStatus[\"DOWNLOADING\"] = \"DOWNLOADING\";\n BundleStatus[\"READY\"] = \"READY\";\n BundleStatus[\"ACTIVE\"] = \"ACTIVE\";\n BundleStatus[\"FAILED\"] = \"FAILED\";\n})(BundleStatus || (BundleStatus = {}));\nexport var InstallStatus;\n(function (InstallStatus) {\n InstallStatus[\"UNKNOWN\"] = \"UNKNOWN\";\n InstallStatus[\"PENDING\"] = \"PENDING\";\n InstallStatus[\"DOWNLOADING\"] = \"DOWNLOADING\";\n InstallStatus[\"DOWNLOADED\"] = \"DOWNLOADED\";\n InstallStatus[\"INSTALLING\"] = \"INSTALLING\";\n InstallStatus[\"INSTALLED\"] = \"INSTALLED\";\n InstallStatus[\"FAILED\"] = \"FAILED\";\n InstallStatus[\"CANCELED\"] = \"CANCELED\";\n})(InstallStatus || (InstallStatus = {}));\nexport var UpdateErrorCode;\n(function (UpdateErrorCode) {\n // Network errors\n UpdateErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n UpdateErrorCode[\"SERVER_ERROR\"] = \"SERVER_ERROR\";\n UpdateErrorCode[\"TIMEOUT_ERROR\"] = \"TIMEOUT_ERROR\";\n // Download errors\n UpdateErrorCode[\"DOWNLOAD_ERROR\"] = \"DOWNLOAD_ERROR\";\n UpdateErrorCode[\"STORAGE_ERROR\"] = \"STORAGE_ERROR\";\n UpdateErrorCode[\"SIZE_LIMIT_EXCEEDED\"] = \"SIZE_LIMIT_EXCEEDED\";\n // Security errors\n UpdateErrorCode[\"VERIFICATION_ERROR\"] = \"VERIFICATION_ERROR\";\n UpdateErrorCode[\"CHECKSUM_ERROR\"] = \"CHECKSUM_ERROR\";\n UpdateErrorCode[\"SIGNATURE_ERROR\"] = \"SIGNATURE_ERROR\";\n UpdateErrorCode[\"INSECURE_URL\"] = \"INSECURE_URL\";\n UpdateErrorCode[\"INVALID_CERTIFICATE\"] = \"INVALID_CERTIFICATE\";\n UpdateErrorCode[\"PATH_TRAVERSAL\"] = \"PATH_TRAVERSAL\";\n // Installation errors\n UpdateErrorCode[\"INSTALL_ERROR\"] = \"INSTALL_ERROR\";\n UpdateErrorCode[\"ROLLBACK_ERROR\"] = \"ROLLBACK_ERROR\";\n UpdateErrorCode[\"VERSION_MISMATCH\"] = \"VERSION_MISMATCH\";\n // Permission errors\n UpdateErrorCode[\"PERMISSION_DENIED\"] = \"PERMISSION_DENIED\";\n // App update errors\n UpdateErrorCode[\"UPDATE_NOT_AVAILABLE\"] = \"UPDATE_NOT_AVAILABLE\";\n UpdateErrorCode[\"UPDATE_IN_PROGRESS\"] = \"UPDATE_IN_PROGRESS\";\n UpdateErrorCode[\"UPDATE_CANCELLED\"] = \"UPDATE_CANCELLED\";\n UpdateErrorCode[\"PLATFORM_NOT_SUPPORTED\"] = \"PLATFORM_NOT_SUPPORTED\";\n // Review errors\n UpdateErrorCode[\"REVIEW_NOT_SUPPORTED\"] = \"REVIEW_NOT_SUPPORTED\";\n UpdateErrorCode[\"QUOTA_EXCEEDED\"] = \"QUOTA_EXCEEDED\";\n UpdateErrorCode[\"CONDITIONS_NOT_MET\"] = \"CONDITIONS_NOT_MET\";\n // General errors\n UpdateErrorCode[\"INVALID_CONFIG\"] = \"INVALID_CONFIG\";\n UpdateErrorCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n})(UpdateErrorCode || (UpdateErrorCode = {}));\n//# sourceMappingURL=definitions.js.map","import { ConfigManager } from './config';\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"INFO\"] = 1] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 2] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 3] = \"ERROR\";\n})(LogLevel || (LogLevel = {}));\nexport class Logger {\n constructor(context) {\n this.configManager = ConfigManager.getInstance();\n this.context = context || 'NativeUpdate';\n }\n static getInstance() {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n return Logger.instance;\n }\n shouldLog() {\n return this.configManager.get('enableLogging');\n }\n sanitize(data) {\n if (typeof data === 'string') {\n let sanitized = data;\n // Remove potential file paths\n sanitized = sanitized.replace(/\\/[^\\s]+\\/([\\w.-]+)$/g, '/<path>/$1');\n // Remove potential URLs with credentials\n sanitized = sanitized.replace(/https?:\\/\\/[^:]+:[^@]+@/g, 'https://***:***@');\n // Remove potential API keys\n sanitized = sanitized.replace(/[a-zA-Z0-9]{32,}/g, '<redacted>');\n return sanitized;\n }\n else if (typeof data === 'object' && data !== null) {\n if (Array.isArray(data)) {\n return data.map((item) => this.sanitize(item));\n }\n else {\n const sanitized = {};\n const dataObj = data;\n for (const key in dataObj) {\n if (key.toLowerCase().includes('key') ||\n key.toLowerCase().includes('secret') ||\n key.toLowerCase().includes('password') ||\n key.toLowerCase().includes('token')) {\n sanitized[key] = '<redacted>';\n }\n else {\n sanitized[key] = this.sanitize(dataObj[key]);\n }\n }\n return sanitized;\n }\n }\n return data;\n }\n log(message, data) {\n this.logWithLevel(LogLevel.INFO, message, data);\n }\n logWithLevel(level, message, data) {\n if (!this.shouldLog())\n return;\n const timestamp = new Date().toISOString();\n const sanitizedData = data ? this.sanitize(data) : undefined;\n const logEntry = {\n timestamp,\n level: LogLevel[level],\n context: this.context,\n message,\n };\n if (sanitizedData !== undefined) {\n logEntry.data = sanitizedData;\n }\n switch (level) {\n case LogLevel.DEBUG:\n console.debug(`[${this.context}]`, logEntry);\n break;\n case LogLevel.INFO:\n console.info(`[${this.context}]`, logEntry);\n break;\n case LogLevel.WARN:\n console.warn(`[${this.context}]`, logEntry);\n break;\n case LogLevel.ERROR:\n console.error(`[${this.context}]`, logEntry);\n break;\n }\n }\n debug(message, data) {\n this.logWithLevel(LogLevel.DEBUG, message, data);\n }\n info(message, data) {\n this.logWithLevel(LogLevel.INFO, message, data);\n }\n warn(message, data) {\n this.logWithLevel(LogLevel.WARN, message, data);\n }\n error(message, error) {\n const errorData = error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error;\n this.logWithLevel(LogLevel.ERROR, message, errorData);\n }\n}\n//# sourceMappingURL=logger.js.map","export var ErrorCode;\n(function (ErrorCode) {\n // Configuration errors\n ErrorCode[\"NOT_CONFIGURED\"] = \"NOT_CONFIGURED\";\n ErrorCode[\"INVALID_CONFIG\"] = \"INVALID_CONFIG\";\n ErrorCode[\"MISSING_DEPENDENCY\"] = \"MISSING_DEPENDENCY\";\n // Download errors\n ErrorCode[\"DOWNLOAD_FAILED\"] = \"DOWNLOAD_FAILED\";\n ErrorCode[\"DOWNLOAD_TIMEOUT\"] = \"DOWNLOAD_TIMEOUT\";\n ErrorCode[\"INVALID_URL\"] = \"INVALID_URL\";\n ErrorCode[\"UNAUTHORIZED_HOST\"] = \"UNAUTHORIZED_HOST\";\n ErrorCode[\"BUNDLE_TOO_LARGE\"] = \"BUNDLE_TOO_LARGE\";\n // Validation errors\n ErrorCode[\"CHECKSUM_MISMATCH\"] = \"CHECKSUM_MISMATCH\";\n ErrorCode[\"SIGNATURE_INVALID\"] = \"SIGNATURE_INVALID\";\n ErrorCode[\"VERSION_DOWNGRADE\"] = \"VERSION_DOWNGRADE\";\n ErrorCode[\"INVALID_BUNDLE_FORMAT\"] = \"INVALID_BUNDLE_FORMAT\";\n // Storage errors\n ErrorCode[\"STORAGE_FULL\"] = \"STORAGE_FULL\";\n ErrorCode[\"FILE_NOT_FOUND\"] = \"FILE_NOT_FOUND\";\n ErrorCode[\"PERMISSION_DENIED\"] = \"PERMISSION_DENIED\";\n // Update errors\n ErrorCode[\"UPDATE_FAILED\"] = \"UPDATE_FAILED\";\n ErrorCode[\"ROLLBACK_FAILED\"] = \"ROLLBACK_FAILED\";\n ErrorCode[\"BUNDLE_NOT_READY\"] = \"BUNDLE_NOT_READY\";\n // Platform errors\n ErrorCode[\"PLATFORM_NOT_SUPPORTED\"] = \"PLATFORM_NOT_SUPPORTED\";\n ErrorCode[\"NATIVE_ERROR\"] = \"NATIVE_ERROR\";\n})(ErrorCode || (ErrorCode = {}));\nexport class NativeUpdateError extends Error {\n constructor(code, message, details, originalError) {\n super(message);\n this.code = code;\n this.message = message;\n this.details = details;\n this.originalError = originalError;\n this.name = 'NativeUpdateError';\n Object.setPrototypeOf(this, NativeUpdateError.prototype);\n }\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n details: this.details,\n stack: this.stack,\n };\n }\n}\nexport class ConfigurationError extends NativeUpdateError {\n constructor(message, details) {\n super(ErrorCode.INVALID_CONFIG, message, details);\n this.name = 'ConfigurationError';\n }\n}\nexport class DownloadError extends NativeUpdateError {\n constructor(code, message, details, originalError) {\n super(code, message, details, originalError);\n this.name = 'DownloadError';\n }\n}\nexport class ValidationError extends NativeUpdateError {\n constructor(code, message, details) {\n super(code, message, details);\n this.name = 'ValidationError';\n }\n}\nexport class StorageError extends NativeUpdateError {\n constructor(code, message, details, originalError) {\n super(code, message, details, originalError);\n this.name = 'StorageError';\n }\n}\nexport class UpdateError extends NativeUpdateError {\n constructor(code, message, details, originalError) {\n super(code, message, details, originalError);\n this.name = 'UpdateError';\n }\n}\n//# sourceMappingURL=errors.js.map","export var AppUpdateInstallStatus;\n(function (AppUpdateInstallStatus) {\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"PENDING\"] = 1] = \"PENDING\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"DOWNLOADING\"] = 2] = \"DOWNLOADING\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"INSTALLING\"] = 3] = \"INSTALLING\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"INSTALLED\"] = 4] = \"INSTALLED\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"FAILED\"] = 5] = \"FAILED\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"CANCELED\"] = 6] = \"CANCELED\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"DOWNLOADED\"] = 11] = \"DOWNLOADED\";\n})(AppUpdateInstallStatus || (AppUpdateInstallStatus = {}));\n//# sourceMappingURL=types.js.map","export class ConfigManager {\n constructor() {\n this.config = this.getDefaultConfig();\n }\n static getInstance() {\n if (!ConfigManager.instance) {\n ConfigManager.instance = new ConfigManager();\n }\n return ConfigManager.instance;\n }\n getDefaultConfig() {\n return {\n filesystem: null,\n preferences: null,\n baseUrl: '',\n allowedHosts: [],\n maxBundleSize: 100 * 1024 * 1024, // 100MB\n downloadTimeout: 30000, // 30 seconds\n retryAttempts: 3,\n retryDelay: 1000, // 1 second\n enableSignatureValidation: true,\n publicKey: '',\n cacheExpiration: 24 * 60 * 60 * 1000, // 24 hours\n enableLogging: false,\n serverUrl: '',\n channel: 'production',\n autoCheck: true,\n autoUpdate: false,\n updateStrategy: 'background',\n requireSignature: true,\n checksumAlgorithm: 'SHA-256',\n checkInterval: 24 * 60 * 60 * 1000, // 24 hours\n security: {\n enforceHttps: true,\n validateInputs: true,\n secureStorage: true,\n logSecurityEvents: false,\n },\n // App review config\n promptAfterPositiveEvents: false,\n maxPromptsPerVersion: 1,\n minimumDaysSinceLastPrompt: 7,\n isPremiumUser: false,\n // Platform-specific config\n appStoreId: '',\n iosAppId: '',\n packageName: '',\n webReviewUrl: '',\n minimumVersion: '1.0.0',\n };\n }\n configure(config) {\n this.config = Object.assign(Object.assign({}, this.config), config);\n this.validateConfig();\n }\n validateConfig() {\n if (this.config.maxBundleSize <= 0) {\n throw new Error('maxBundleSize must be greater than 0');\n }\n if (this.config.downloadTimeout <= 0) {\n throw new Error('downloadTimeout must be greater than 0');\n }\n if (this.config.retryAttempts < 0) {\n throw new Error('retryAttempts must be non-negative');\n }\n if (this.config.retryDelay < 0) {\n throw new Error('retryDelay must be non-negative');\n }\n }\n get(key) {\n return this.config[key];\n }\n set(key, value) {\n this.config[key] = value;\n }\n getAll() {\n return Object.assign({}, this.config);\n }\n isConfigured() {\n return !!(this.config.filesystem && this.config.preferences);\n }\n}\n//# sourceMappingURL=config.js.map","import { ConfigManager } from './config';\nimport { ValidationError, ErrorCode } from './errors';\nimport { Logger } from './logger';\nexport class SecurityValidator {\n constructor() {\n this.configManager = ConfigManager.getInstance();\n this.logger = Logger.getInstance();\n }\n static getInstance() {\n if (!SecurityValidator.instance) {\n SecurityValidator.instance = new SecurityValidator();\n }\n return SecurityValidator.instance;\n }\n /**\n * Validate URL is HTTPS\n */\n static validateUrl(url) {\n try {\n const parsed = new URL(url);\n return parsed.protocol === 'https:';\n }\n catch (_a) {\n return false;\n }\n }\n /**\n * Validate checksum format\n */\n static validateChecksum(checksum) {\n return /^[a-f0-9]{64}$/i.test(checksum);\n }\n /**\n * Sanitize input string\n */\n static sanitizeInput(input) {\n if (!input)\n return '';\n return input.replace(/<[^>]*>/g, '').replace(/[^\\w\\s/.-]/g, '');\n }\n /**\n * Validate bundle size\n */\n static validateBundleSize(size) {\n const MAX_SIZE = 100 * 1024 * 1024; // 100MB\n return size > 0 && size <= MAX_SIZE;\n }\n /**\n * Calculate SHA-256 checksum of data\n */\n async calculateChecksum(data) {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n }\n /**\n * Verify checksum matches expected value\n */\n async verifyChecksum(data, expectedChecksum) {\n if (!expectedChecksum) {\n this.logger.warn('No checksum provided for verification');\n return true; // Allow if no checksum provided\n }\n const actualChecksum = await this.calculateChecksum(data);\n const isValid = actualChecksum === expectedChecksum.toLowerCase();\n if (!isValid) {\n this.logger.error('Checksum verification failed', {\n expected: expectedChecksum,\n actual: actualChecksum,\n });\n }\n return isValid;\n }\n /**\n * Alias for verifyChecksum for backward compatibility\n */\n async validateChecksum(data, expectedChecksum) {\n return this.verifyChecksum(data, expectedChecksum);\n }\n /**\n * Verify digital signature using Web Crypto API\n */\n async verifySignature(data, signature) {\n if (!this.configManager.get('enableSignatureValidation')) {\n return true;\n }\n const publicKey = this.configManager.get('publicKey');\n if (!publicKey) {\n throw new ValidationError(ErrorCode.SIGNATURE_INVALID, 'Public key not configured for signature validation');\n }\n try {\n // Import public key\n const cryptoKey = await crypto.subtle.importKey('spki', this.pemToArrayBuffer(publicKey), {\n name: 'RSA-PSS',\n hash: 'SHA-256',\n }, false, ['verify']);\n // Verify signature\n const isValid = await crypto.subtle.verify({\n name: 'RSA-PSS',\n saltLength: 32,\n }, cryptoKey, this.base64ToArrayBuffer(signature), data);\n if (!isValid) {\n this.logger.error('Signature verification failed');\n }\n return isValid;\n }\n catch (error) {\n this.logger.error('Signature verification error', error);\n return false;\n }\n }\n /**\n * Convert PEM to ArrayBuffer\n */\n pemToArrayBuffer(pem) {\n const base64 = pem\n .replace(/-----BEGIN PUBLIC KEY-----/g, '')\n .replace(/-----END PUBLIC KEY-----/g, '')\n .replace(/\\s/g, '');\n return this.base64ToArrayBuffer(base64);\n }\n /**\n * Convert base64 to ArrayBuffer\n */\n base64ToArrayBuffer(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes.buffer;\n }\n /**\n * Sanitize file path to prevent directory traversal\n */\n sanitizePath(path) {\n // Remove any parent directory references\n const sanitized = path\n .split('/')\n .filter((part) => part !== '..' && part !== '.')\n .join('/');\n // Ensure path doesn't start with /\n return sanitized.replace(/^\\/+/, '');\n }\n /**\n * Validate bundle ID format\n */\n validateBundleId(bundleId) {\n if (!bundleId || typeof bundleId !== 'string') {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID must be a non-empty string');\n }\n // Allow alphanumeric, hyphens, underscores, and dots\n const validPattern = /^[a-zA-Z0-9\\-_.]+$/;\n if (!validPattern.test(bundleId)) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID contains invalid characters');\n }\n if (bundleId.length > 100) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is too long (max 100 characters)');\n }\n }\n /**\n * Validate semantic version format\n */\n validateVersion(version) {\n if (!version || typeof version !== 'string') {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Version must be a non-empty string');\n }\n // Basic semantic versioning pattern\n const semverPattern = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n if (!semverPattern.test(version)) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Version must follow semantic versioning format (e.g., 1.2.3)');\n }\n }\n /**\n * Check if version is a downgrade\n */\n isVersionDowngrade(currentVersion, newVersion) {\n const current = this.parseVersion(currentVersion);\n const next = this.parseVersion(newVersion);\n if (next.major < current.major)\n return true;\n if (next.major > current.major)\n return false;\n if (next.minor < current.minor)\n return true;\n if (next.minor > current.minor)\n return false;\n return next.patch < current.patch;\n }\n /**\n * Parse semantic version\n */\n parseVersion(version) {\n const parts = version.split('-')[0].split('.'); // Ignore pre-release\n return {\n major: parseInt(parts[0], 10) || 0,\n minor: parseInt(parts[1], 10) || 0,\n patch: parseInt(parts[2], 10) || 0,\n };\n }\n /**\n * Validate URL format and security\n */\n validateUrl(url) {\n if (!url || typeof url !== 'string') {\n throw new ValidationError(ErrorCode.INVALID_URL, 'URL must be a non-empty string');\n }\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n }\n catch (_a) {\n throw new ValidationError(ErrorCode.INVALID_URL, 'Invalid URL format');\n }\n // Enforce HTTPS\n if (parsedUrl.protocol !== 'https:') {\n throw new ValidationError(ErrorCode.INVALID_URL, 'Only HTTPS URLs are allowed');\n }\n // Check against allowed hosts\n const allowedHosts = this.configManager.get('allowedHosts');\n if (allowedHosts.length > 0 && !allowedHosts.includes(parsedUrl.hostname)) {\n throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, `Host ${parsedUrl.hostname} is not in the allowed hosts list`);\n }\n // Prevent localhost/private IPs in production\n const privatePatterns = [\n /^localhost$/i,\n /^127\\./,\n /^10\\./,\n /^172\\.(1[6-9]|2[0-9]|3[0-1])\\./,\n /^192\\.168\\./,\n /^::1$/,\n /^fc00:/i,\n /^fe80:/i,\n ];\n if (privatePatterns.some((pattern) => pattern.test(parsedUrl.hostname))) {\n throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, 'Private/local addresses are not allowed');\n }\n }\n /**\n * Validate file size\n */\n validateFileSize(size) {\n if (typeof size !== 'number' || size < 0) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'File size must be a non-negative number');\n }\n const maxSize = this.configManager.get('maxBundleSize');\n if (size > maxSize) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `File size ${size} exceeds maximum allowed size of ${maxSize} bytes`);\n }\n }\n /**\n * Generate a secure random ID\n */\n generateSecureId() {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');\n }\n /**\n * Validate certificate pinning for HTTPS connections\n * Note: This is a placeholder for web implementation as certificate pinning\n * is primarily implemented at the native layer\n */\n async validateCertificatePin(hostname, certificate) {\n // Certificate pinning is not available in PluginConfig type\n const certificatePins = this.configManager.certificatePins;\n if (!certificatePins ||\n !Array.isArray(certificatePins) ||\n certificatePins.length === 0) {\n // No pins configured, allow connection\n return true;\n }\n const hostPins = certificatePins.filter((pin) => pin.hostname === hostname);\n if (hostPins.length === 0) {\n // No pins for this host, allow connection\n return true;\n }\n // Check if certificate matches any of the pins\n const certificateHash = await this.calculateCertificateHash(certificate);\n const isValid = hostPins.some((pin) => pin.sha256 === certificateHash);\n if (!isValid) {\n this.logger.error('Certificate pinning validation failed', {\n hostname,\n expectedPins: hostPins.map((p) => p.sha256),\n actualHash: certificateHash,\n });\n }\n return isValid;\n }\n /**\n * Calculate SHA-256 hash of certificate\n */\n async calculateCertificateHash(certificate) {\n const encoder = new TextEncoder();\n const data = encoder.encode(certificate);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return 'sha256/' + btoa(String.fromCharCode(...hashArray));\n }\n /**\n * Validate metadata object\n */\n validateMetadata(metadata) {\n if (metadata && typeof metadata !== 'object') {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Metadata must be an object');\n }\n // Limit metadata size to prevent abuse\n const metadataStr = JSON.stringify(metadata || {});\n if (metadataStr.length > 10240) {\n // 10KB limit\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Metadata is too large (max 10KB)');\n }\n }\n}\n//# sourceMappingURL=security.js.map","import { ConfigManager } from '../core/config';\nimport { Logger } from '../core/logger';\nimport { StorageError, ErrorCode } from '../core/errors';\n/**\n * Manages bundle storage and lifecycle\n */\nexport class BundleManager {\n constructor() {\n this.STORAGE_KEY = 'capacitor_native_update_bundles';\n this.ACTIVE_BUNDLE_KEY = 'capacitor_native_update_active';\n this.preferences = null;\n this.cache = new Map();\n this.cacheExpiry = 0;\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n }\n /**\n * Initialize the bundle manager with preferences\n */\n async initialize() {\n this.preferences = this.configManager.get('preferences');\n if (!this.preferences) {\n throw new StorageError(ErrorCode.MISSING_DEPENDENCY, 'Preferences not configured. Please configure the plugin first.');\n }\n await this.loadCache();\n }\n /**\n * Load cache from preferences\n */\n async loadCache() {\n if (Date.now() < this.cacheExpiry) {\n return; // Cache still valid\n }\n try {\n const { value } = await this.preferences.get({ key: this.STORAGE_KEY });\n if (value) {\n const bundles = JSON.parse(value);\n this.cache.clear();\n bundles.forEach((bundle) => this.cache.set(bundle.bundleId, bundle));\n }\n this.cacheExpiry = Date.now() + 5000; // 5 second cache\n }\n catch (error) {\n this.logger.error('Failed to load bundles from storage', error);\n this.cache.clear();\n }\n }\n /**\n * Save cache to preferences\n */\n async saveCache() {\n try {\n const bundles = Array.from(this.cache.values());\n await this.preferences.set({\n key: this.STORAGE_KEY,\n value: JSON.stringify(bundles),\n });\n this.logger.debug('Saved bundles to storage', { count: bundles.length });\n }\n catch (error) {\n throw new StorageError(ErrorCode.STORAGE_FULL, 'Failed to save bundles to storage', undefined, error);\n }\n }\n /**\n * Save bundle information\n */\n async saveBundleInfo(bundle) {\n this.validateBundleInfo(bundle);\n this.cache.set(bundle.bundleId, bundle);\n await this.saveCache();\n this.logger.info('Bundle saved', {\n bundleId: bundle.bundleId,\n version: bundle.version,\n });\n }\n /**\n * Validate bundle information\n */\n validateBundleInfo(bundle) {\n if (!bundle.bundleId || typeof bundle.bundleId !== 'string') {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle ID');\n }\n if (!bundle.version || typeof bundle.version !== 'string') {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle version');\n }\n if (!bundle.path || typeof bundle.path !== 'string') {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle path');\n }\n if (typeof bundle.size !== 'number' || bundle.size < 0) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle size');\n }\n }\n /**\n * Get all bundles\n */\n async getAllBundles() {\n await this.loadCache();\n return Array.from(this.cache.values());\n }\n /**\n * Get bundle by ID\n */\n async getBundle(bundleId) {\n if (!bundleId) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n await this.loadCache();\n return this.cache.get(bundleId) || null;\n }\n /**\n * Delete bundle\n */\n async deleteBundle(bundleId) {\n if (!bundleId) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n await this.loadCache();\n const bundle = this.cache.get(bundleId);\n if (!bundle) {\n this.logger.warn('Attempted to delete non-existent bundle', { bundleId });\n return;\n }\n this.cache.delete(bundleId);\n await this.saveCache();\n // If this was the active bundle, clear it\n const activeBundleId = await this.getActiveBundleId();\n if (activeBundleId === bundleId) {\n await this.clearActiveBundle();\n }\n this.logger.info('Bundle deleted', { bundleId });\n }\n /**\n * Get active bundle\n */\n async getActiveBundle() {\n const activeBundleId = await this.getActiveBundleId();\n if (!activeBundleId)\n return null;\n return this.getBundle(activeBundleId);\n }\n /**\n * Set active bundle\n */\n async setActiveBundle(bundleId) {\n if (!bundleId) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n const bundle = await this.getBundle(bundleId);\n if (!bundle) {\n throw new StorageError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);\n }\n // Update previous active bundle status\n const previousActive = await this.getActiveBundle();\n if (previousActive && previousActive.bundleId !== bundleId) {\n previousActive.status = 'READY';\n await this.saveBundleInfo(previousActive);\n }\n // Set new active bundle\n bundle.status = 'ACTIVE';\n await this.saveBundleInfo(bundle);\n await this.preferences.set({\n key: this.ACTIVE_BUNDLE_KEY,\n value: bundleId,\n });\n this.logger.info('Active bundle set', {\n bundleId,\n version: bundle.version,\n });\n }\n /**\n * Get active bundle ID\n */\n async getActiveBundleId() {\n try {\n const { value } = await this.preferences.get({\n key: this.ACTIVE_BUNDLE_KEY,\n });\n return value;\n }\n catch (error) {\n this.logger.error('Failed to get active bundle ID', error);\n return null;\n }\n }\n /**\n * Clear active bundle\n */\n async clearActiveBundle() {\n await this.preferences.remove({ key: this.ACTIVE_BUNDLE_KEY });\n this.logger.info('Active bundle cleared');\n }\n /**\n * Clear all bundles\n */\n async clearAllBundles() {\n await this.preferences.remove({ key: this.STORAGE_KEY });\n await this.preferences.remove({ key: this.ACTIVE_BUNDLE_KEY });\n this.cache.clear();\n this.cacheExpiry = 0;\n this.logger.info('All bundles cleared');\n }\n /**\n * Clean up old bundles\n */\n async cleanupOldBundles(keepCount) {\n if (keepCount < 1) {\n throw new StorageError(ErrorCode.INVALID_CONFIG, 'Keep count must be at least 1');\n }\n const bundles = await this.getAllBundles();\n const activeBundleId = await this.getActiveBundleId();\n // Sort by download time (newest first)\n const sorted = bundles.sort((a, b) => b.downloadTime - a.downloadTime);\n // Keep the active bundle and the most recent ones\n const toKeep = new Set();\n if (activeBundleId) {\n toKeep.add(activeBundleId);\n }\n let kept = toKeep.size;\n for (const bundle of sorted) {\n if (kept >= keepCount)\n break;\n if (!toKeep.has(bundle.bundleId)) {\n toKeep.add(bundle.bundleId);\n kept++;\n }\n }\n // Delete bundles not in the keep set\n let deletedCount = 0;\n for (const bundle of bundles) {\n if (!toKeep.has(bundle.bundleId)) {\n await this.deleteBundle(bundle.bundleId);\n deletedCount++;\n }\n }\n if (deletedCount > 0) {\n this.logger.info('Cleaned up old bundles', {\n deleted: deletedCount,\n kept,\n });\n }\n }\n /**\n * Get bundles older than specified time\n */\n async getBundlesOlderThan(timestamp) {\n if (timestamp < 0) {\n throw new StorageError(ErrorCode.INVALID_CONFIG, 'Timestamp must be non-negative');\n }\n const bundles = await this.getAllBundles();\n return bundles.filter((b) => b.downloadTime < timestamp);\n }\n /**\n * Mark bundle as verified\n */\n async markBundleAsVerified(bundleId) {\n const bundle = await this.getBundle(bundleId);\n if (!bundle) {\n throw new StorageError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);\n }\n bundle.verified = true;\n await this.saveBundleInfo(bundle);\n this.logger.info('Bundle marked as verified', { bundleId });\n }\n /**\n * Get total storage used by bundles\n */\n async getTotalStorageUsed() {\n const bundles = await this.getAllBundles();\n return bundles.reduce((total, bundle) => total + bundle.size, 0);\n }\n /**\n * Check if storage limit is exceeded\n */\n async isStorageLimitExceeded(additionalSize = 0) {\n const totalUsed = await this.getTotalStorageUsed();\n const maxStorage = this.configManager.get('maxBundleSize') * 3; // Allow 3x max bundle size\n return totalUsed + additionalSize > maxStorage;\n }\n /**\n * Create default bundle\n */\n createDefaultBundle() {\n return {\n bundleId: 'default',\n version: '1.0.0',\n path: '/',\n downloadTime: Date.now(),\n size: 0,\n status: 'ACTIVE',\n checksum: '',\n verified: true,\n };\n }\n /**\n * Clean expired cache entries\n */\n async cleanExpiredBundles() {\n const expirationTime = this.configManager.get('cacheExpiration');\n const cutoffTime = Date.now() - expirationTime;\n const expiredBundles = await this.getBundlesOlderThan(cutoffTime);\n for (const bundle of expiredBundles) {\n // Don't delete active bundle\n const activeBundleId = await this.getActiveBundleId();\n if (bundle.bundleId !== activeBundleId) {\n await this.deleteBundle(bundle.bundleId);\n }\n }\n }\n}\n//# sourceMappingURL=bundle-manager.js.map","import { ConfigManager } from '../core/config';\nimport { Logger } from '../core/logger';\nimport { DownloadError, ErrorCode, ValidationError } from '../core/errors';\nimport { Directory } from '@capacitor/filesystem';\n/**\n * Manages file downloads with progress tracking and resume capability\n */\nexport class DownloadManager {\n constructor() {\n this.activeDownloads = new Map();\n this.filesystem = null;\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n }\n /**\n * Initialize the download manager\n */\n async initialize() {\n this.filesystem = this.configManager.get('filesystem');\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not configured. Please configure the plugin first.');\n }\n }\n /**\n * Validate URL against allowed hosts\n */\n validateUrl(url) {\n try {\n const parsedUrl = new URL(url);\n // Ensure HTTPS\n if (parsedUrl.protocol !== 'https:') {\n throw new ValidationError(ErrorCode.INVALID_URL, 'Only HTTPS URLs are allowed for security reasons');\n }\n // Check against allowed hosts if configured\n const allowedHosts = this.configManager.get('allowedHosts');\n if (allowedHosts.length > 0 &&\n !allowedHosts.includes(parsedUrl.hostname)) {\n throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, `Host ${parsedUrl.hostname} is not in the allowed hosts list`);\n }\n }\n catch (error) {\n if (error instanceof ValidationError)\n throw error;\n throw new ValidationError(ErrorCode.INVALID_URL, 'Invalid URL format');\n }\n }\n /**\n * Download a file with progress tracking\n */\n async download(url, bundleId, onProgress) {\n // Validate inputs\n this.validateUrl(url);\n if (!bundleId) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n // Check if already downloading\n if (this.activeDownloads.has(bundleId)) {\n throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Download already in progress for bundle ${bundleId}`);\n }\n // Create abort controller for this download\n const abortController = new AbortController();\n const downloadState = {\n controller: abortController,\n startTime: Date.now(),\n };\n this.activeDownloads.set(bundleId, downloadState);\n try {\n const timeout = this.configManager.get('downloadTimeout');\n const timeoutId = setTimeout(() => abortController.abort(), timeout);\n const response = await fetch(url, {\n signal: abortController.signal,\n headers: {\n 'Cache-Control': 'no-cache',\n Accept: 'application/octet-stream, application/zip',\n },\n });\n clearTimeout(timeoutId);\n if (!response.ok) {\n throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Download failed: ${response.status} ${response.statusText}`, { status: response.status, statusText: response.statusText });\n }\n // Validate content type\n const contentType = response.headers.get('content-type');\n if (contentType && !this.isValidContentType(contentType)) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, `Invalid content type: ${contentType}`);\n }\n // Get total size from headers\n const contentLength = response.headers.get('content-length');\n const totalBytes = contentLength ? parseInt(contentLength, 10) : 0;\n // Check size limit\n if (totalBytes > this.configManager.get('maxBundleSize')) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `Bundle size ${totalBytes} exceeds maximum allowed size`);\n }\n // If no content length, fall back to simple download\n if (!totalBytes || !response.body) {\n const blob = await response.blob();\n this.validateBlobSize(blob);\n return blob;\n }\n // Stream the response with progress tracking\n const reader = response.body.getReader();\n const chunks = [];\n let receivedBytes = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n chunks.push(value);\n receivedBytes += value.length;\n // Check if size exceeds limit during download\n if (receivedBytes > this.configManager.get('maxBundleSize')) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `Download size exceeds maximum allowed size`);\n }\n // Report progress\n if (onProgress) {\n const percent = Math.round((receivedBytes / totalBytes) * 100);\n onProgress({\n percent,\n bytesDownloaded: receivedBytes,\n totalBytes,\n bundleId,\n });\n }\n }\n // Combine chunks into a single blob\n const blob = new Blob(chunks);\n this.validateBlobSize(blob);\n this.logger.info('Download completed', {\n bundleId,\n size: blob.size,\n duration: Date.now() - downloadState.startTime,\n });\n return blob;\n }\n catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n const isTimeout = Date.now() - downloadState.startTime >=\n this.configManager.get('downloadTimeout');\n throw new DownloadError(isTimeout ? ErrorCode.DOWNLOAD_TIMEOUT : ErrorCode.DOWNLOAD_FAILED, isTimeout ? 'Download timed out' : 'Download cancelled', undefined, error);\n }\n throw error;\n }\n finally {\n // Clean up\n this.activeDownloads.delete(bundleId);\n }\n }\n /**\n * Validate content type\n */\n isValidContentType(contentType) {\n const validTypes = [\n 'application/octet-stream',\n 'application/zip',\n 'application/x-zip-compressed',\n 'application/x-zip',\n ];\n return validTypes.some((type) => contentType.includes(type));\n }\n /**\n * Validate blob size\n */\n validateBlobSize(blob) {\n if (blob.size === 0) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Downloaded file is empty');\n }\n if (blob.size > this.configManager.get('maxBundleSize')) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `File size ${blob.size} exceeds maximum allowed size`);\n }\n }\n /**\n * Cancel a download\n */\n cancelDownload(bundleId) {\n const state = this.activeDownloads.get(bundleId);\n if (state) {\n state.controller.abort();\n this.activeDownloads.delete(bundleId);\n this.logger.info('Download cancelled', { bundleId });\n }\n }\n /**\n * Cancel all active downloads\n */\n cancelAllDownloads() {\n for (const state of this.activeDownloads.values()) {\n state.controller.abort();\n }\n const count = this.activeDownloads.size;\n this.activeDownloads.clear();\n if (count > 0) {\n this.logger.info('All downloads cancelled', { count });\n }\n }\n /**\n * Check if a download is active\n */\n isDownloading(bundleId) {\n return this.activeDownloads.has(bundleId);\n }\n /**\n * Get active download count\n */\n getActiveDownloadCount() {\n return this.activeDownloads.size;\n }\n /**\n * Download with retry logic\n */\n async downloadWithRetry(url, bundleId, onProgress) {\n const maxRetries = this.configManager.get('retryAttempts');\n const retryDelay = this.configManager.get('retryDelay');\n let lastError = null;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n // Add delay between retries (exponential backoff)\n if (attempt > 0) {\n const delay = Math.min(retryDelay * Math.pow(2, attempt - 1), 30000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n this.logger.debug('Retrying download', { bundleId, attempt, delay });\n }\n return await this.download(url, bundleId, onProgress);\n }\n catch (error) {\n lastError = error;\n // Don't retry if cancelled or validation error\n if (error instanceof ValidationError ||\n (error instanceof Error && error.name === 'AbortError')) {\n throw error;\n }\n this.logger.warn(`Download attempt ${attempt + 1} failed`, {\n bundleId,\n error,\n });\n }\n }\n throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, 'Download failed after all retries', { attempts: maxRetries }, lastError || undefined);\n }\n /**\n * Convert blob to ArrayBuffer\n */\n async blobToArrayBuffer(blob) {\n return blob.arrayBuffer();\n }\n /**\n * Save blob to filesystem\n */\n async saveBlob(bundleId, blob) {\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');\n }\n const arrayBuffer = await this.blobToArrayBuffer(blob);\n const base64 = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));\n const path = `bundles/${bundleId}/bundle.zip`;\n await this.filesystem.writeFile({\n path,\n data: base64,\n directory: Directory.Data,\n recursive: true,\n });\n this.logger.debug('Bundle saved to filesystem', {\n bundleId,\n path,\n size: blob.size,\n });\n return path;\n }\n /**\n * Load blob from filesystem\n */\n async loadBlob(bundleId) {\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');\n }\n try {\n const path = `bundles/${bundleId}/bundle.zip`;\n const result = await this.filesystem.readFile({\n path,\n directory: Directory.Data,\n });\n const binaryString = atob(result.data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return new Blob([bytes], { type: 'application/zip' });\n }\n catch (error) {\n this.logger.debug('Failed to load bundle from filesystem', {\n bundleId,\n error,\n });\n return null;\n }\n }\n /**\n * Delete blob from filesystem\n */\n async deleteBlob(bundleId) {\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');\n }\n try {\n const path = `bundles/${bundleId}`;\n await this.filesystem.rmdir({\n path,\n directory: Directory.Data,\n recursive: true,\n });\n this.logger.debug('Bundle deleted from filesystem', { bundleId });\n }\n catch (error) {\n this.logger.warn('Failed to delete bundle from filesystem', {\n bundleId,\n error,\n });\n }\n }\n}\n//# sourceMappingURL=download-manager.js.map","import { ConfigManager } from '../core/config';\nimport { Logger } from '../core/logger';\nimport { SecurityValidator } from '../core/security';\nimport { ValidationError, ErrorCode } from '../core/errors';\n/**\n * Manages version checking and comparison\n */\nexport class VersionManager {\n constructor() {\n this.VERSION_CHECK_CACHE_KEY = 'capacitor_native_update_version_cache';\n this.CACHE_DURATION = 5 * 60 * 1000; // 5 minutes\n this.preferences = null;\n this.memoryCache = new Map();\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n this.securityValidator = SecurityValidator.getInstance();\n }\n /**\n * Compare two semantic versions\n */\n static compareVersions(version1, version2) {\n try {\n // Split version and pre-release\n const [v1Base, v1Pre] = version1.split('-');\n const [v2Base, v2Pre] = version2.split('-');\n const v1Parts = v1Base.split('.').map(Number);\n const v2Parts = v2Base.split('.').map(Number);\n // Compare major.minor.patch\n for (let i = 0; i < 3; i++) {\n const v1Part = v1Parts[i] || 0;\n const v2Part = v2Parts[i] || 0;\n if (v1Part > v2Part)\n return 1;\n if (v1Part < v2Part)\n return -1;\n }\n // If base versions are equal, compare pre-release\n if (v1Pre && !v2Pre)\n return -1; // 1.0.0-alpha < 1.0.0\n if (!v1Pre && v2Pre)\n return 1; // 1.0.0 > 1.0.0-alpha\n if (v1Pre && v2Pre) {\n return v1Pre.localeCompare(v2Pre);\n }\n return 0;\n }\n catch (_a) {\n if (version1 === version2)\n return 0;\n return version1 > version2 ? 1 : -1;\n }\n }\n /**\n * Validate semantic version format\n */\n static isValidVersion(version) {\n return /^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?(\\+[a-zA-Z0-9.-]+)?$/.test(version);\n }\n /**\n * Check if update should be performed\n */\n static shouldUpdate(currentVersion, newVersion, minAppVersion) {\n if (minAppVersion &&\n VersionManager.compareVersions(currentVersion, minAppVersion) < 0) {\n return false;\n }\n return VersionManager.compareVersions(currentVersion, newVersion) < 0;\n }\n /**\n * Initialize the version manager\n */\n async initialize() {\n this.preferences = this.configManager.get('preferences');\n if (!this.preferences) {\n throw new ValidationError(ErrorCode.MISSING_DEPENDENCY, 'Preferences not configured. Please configure the plugin first.');\n }\n }\n /**\n * Check for latest version from server\n */\n async checkForUpdates(serverUrl, channel, currentVersion, appId) {\n // Validate inputs\n this.securityValidator.validateUrl(serverUrl);\n this.securityValidator.validateVersion(currentVersion);\n if (!channel || !appId) {\n throw new ValidationError(ErrorCode.INVALID_CONFIG, 'Channel and appId are required');\n }\n // Check cache first\n const cacheKey = `${channel}-${appId}`;\n const cached = await this.getCachedVersionInfo(cacheKey);\n if (cached &&\n cached.channel === channel &&\n Date.now() - cached.timestamp < this.CACHE_DURATION) {\n this.logger.debug('Returning cached version info', {\n channel,\n version: cached.data.version,\n });\n return cached.data;\n }\n try {\n const url = new URL(`${serverUrl}/check`);\n url.searchParams.append('channel', channel);\n url.searchParams.append('version', currentVersion);\n url.searchParams.append('appId', appId);\n url.searchParams.append('platform', 'web'); // Will be overridden by native platforms\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'X-App-Version': currentVersion,\n 'X-App-Id': appId,\n },\n signal: AbortSignal.timeout(this.configManager.get('downloadTimeout')),\n });\n if (!response.ok) {\n throw new Error(`Version check failed: ${response.status}`);\n }\n const data = await response.json();\n // Validate response\n if (!data.version) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'No version in server response');\n }\n this.securityValidator.validateVersion(data.version);\n // Additional validation\n if (data.bundleUrl) {\n this.securityValidator.validateUrl(data.bundleUrl);\n }\n if (data.minAppVersion) {\n this.securityValidator.validateVersion(data.minAppVersion);\n }\n // Cache the result\n await this.cacheVersionInfo(cacheKey, channel, data);\n this.logger.info('Version check completed', {\n channel,\n currentVersion,\n latestVersion: data.version,\n updateAvailable: this.isNewerVersion(data.version, currentVersion),\n });\n return data;\n }\n catch (error) {\n this.logger.error('Failed to check for updates', error);\n return null;\n }\n }\n /**\n * Compare two versions\n */\n isNewerVersion(version1, version2) {\n try {\n const v1 = this.parseVersion(version1);\n const v2 = this.parseVersion(version2);\n if (v1.major !== v2.major)\n return v1.major > v2.major;\n if (v1.minor !== v2.minor)\n return v1.minor > v2.minor;\n if (v1.patch !== v2.patch)\n return v1.patch > v2.patch;\n // If main versions are equal, check pre-release\n if (v1.prerelease && !v2.prerelease)\n return false; // v1 is pre-release, v2 is not\n if (!v1.prerelease && v2.prerelease)\n return true; // v1 is not pre-release, v2 is\n if (v1.prerelease && v2.prerelease) {\n return v1.prerelease > v2.prerelease;\n }\n return false; // Versions are equal\n }\n catch (error) {\n this.logger.error('Failed to compare versions', {\n version1,\n version2,\n error,\n });\n return false;\n }\n }\n /**\n * Check if update is mandatory based on minimum version\n */\n isUpdateMandatory(currentVersion, minimumVersion) {\n if (!minimumVersion)\n return false;\n try {\n this.securityValidator.validateVersion(currentVersion);\n this.securityValidator.validateVersion(minimumVersion);\n return (!this.isNewerVersion(currentVersion, minimumVersion) &&\n currentVersion !== minimumVersion);\n }\n catch (error) {\n this.logger.error('Failed to check mandatory update', error);\n return false;\n }\n }\n /**\n * Parse version metadata\n */\n parseVersion(version) {\n const match = version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$/);\n if (!match) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid version format');\n }\n return {\n major: parseInt(match[1], 10),\n minor: parseInt(match[2], 10),\n patch: parseInt(match[3], 10),\n prerelease: match[4],\n build: match[5],\n };\n }\n /**\n * Generate version string from components\n */\n buildVersionString(components) {\n let version = `${components.major}.${components.minor}.${components.patch}`;\n if (components.prerelease) {\n version += `-${components.prerelease}`;\n }\n if (components.build) {\n version += `+${components.build}`;\n }\n return version;\n }\n /**\n * Check if version is compatible with native version requirements\n */\n isCompatibleWithNativeVersion(bundleVersion, nativeVersion, compatibility) {\n if (!compatibility)\n return true;\n try {\n // Check if there's a specific native version requirement for this bundle version\n const requiredNativeVersion = compatibility[bundleVersion];\n if (!requiredNativeVersion)\n return true;\n this.securityValidator.validateVersion(nativeVersion);\n this.securityValidator.validateVersion(requiredNativeVersion);\n return !this.isNewerVersion(requiredNativeVersion, nativeVersion);\n }\n catch (error) {\n this.logger.error('Failed to check compatibility', error);\n return false;\n }\n }\n /**\n * Get version from cache\n */\n async getCachedVersionInfo(cacheKey) {\n // Check memory cache first\n const memCached = this.memoryCache.get(cacheKey);\n if (memCached && Date.now() - memCached.timestamp < this.CACHE_DURATION) {\n return memCached;\n }\n // Check persistent cache\n try {\n const { value } = await this.preferences.get({\n key: this.VERSION_CHECK_CACHE_KEY,\n });\n if (!value)\n return null;\n const allCached = JSON.parse(value);\n const cached = allCached[cacheKey];\n if (cached && Date.now() - cached.timestamp < this.CACHE_DURATION) {\n // Update memory cache\n this.memoryCache.set(cacheKey, cached);\n return cached;\n }\n }\n catch (error) {\n this.logger.debug('Failed to load cached version info', error);\n }\n return null;\n }\n /**\n * Cache version info\n */\n async cacheVersionInfo(cacheKey, channel, data) {\n const cacheEntry = {\n channel,\n data,\n timestamp: Date.now(),\n };\n // Update memory cache\n this.memoryCache.set(cacheKey, cacheEntry);\n // Update persistent cache\n try {\n const { value } = await this.preferences.get({\n key: this.VERSION_CHECK_CACHE_KEY,\n });\n const allCached = value\n ? JSON.parse(value)\n : {};\n // Clean old entries\n const now = Date.now();\n for (const key in allCached) {\n if (now - allCached[key].timestamp > this.CACHE_DURATION * 2) {\n delete allCached[key];\n }\n }\n allCached[cacheKey] = cacheEntry;\n await this.preferences.set({\n key: this.VERSION_CHECK_CACHE_KEY,\n value: JSON.stringify(allCached),\n });\n }\n catch (error) {\n this.logger.warn('Failed to cache version info', error);\n }\n }\n /**\n * Clear version cache\n */\n async clearVersionCache() {\n this.memoryCache.clear();\n try {\n await this.preferences.remove({ key: this.VERSION_CHECK_CACHE_KEY });\n }\n catch (error) {\n this.logger.warn('Failed to clear version cache', error);\n }\n }\n /**\n * Check if downgrade protection should block update\n */\n shouldBlockDowngrade(currentVersion, newVersion) {\n try {\n return this.securityValidator.isVersionDowngrade(currentVersion, newVersion);\n }\n catch (error) {\n this.logger.error('Failed to check downgrade', error);\n // Default to safe behavior - block if we can't determine\n return true;\n }\n }\n}\n//# sourceMappingURL=version-manager.js.map","import { Logger } from '../core/logger';\nexport class AppUpdateChecker {\n constructor(config) {\n this.config = config;\n this.logger = new Logger('AppUpdateChecker');\n }\n async checkServerVersion(_) {\n if (!this.config.updateUrl) {\n return {};\n }\n try {\n const url = new URL(`${this.config.updateUrl}/app-version`);\n url.searchParams.append('platform', this.getPlatform());\n url.searchParams.append('current', await this.getCurrentVersion());\n if (this.config.channel) {\n url.searchParams.append('channel', this.config.channel);\n }\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n 'X-App-Version': await this.getCurrentVersion(),\n 'X-App-Platform': this.getPlatform(),\n },\n });\n if (!response.ok) {\n throw new Error(`Server returned ${response.status}`);\n }\n const data = await response.json();\n return {\n availableVersion: data.version,\n updatePriority: data.priority,\n releaseNotes: data.releaseNotes,\n updateSize: data.size,\n updateURL: data.downloadUrl,\n };\n }\n catch (error) {\n this.logger.error('Failed to check server version', error);\n return {};\n }\n }\n compareVersions(version1, version2) {\n const v1Parts = version1.split('.').map(Number);\n const v2Parts = version2.split('.').map(Number);\n for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {\n const v1Part = v1Parts[i] || 0;\n const v2Part = v2Parts[i] || 0;\n if (v1Part > v2Part)\n return 1;\n if (v1Part < v2Part)\n return -1;\n }\n return 0;\n }\n isUpdateRequired(currentVersion, availableVersion, minimumVersion) {\n // Check if current version is less than available\n if (this.compareVersions(currentVersion, availableVersion) < 0) {\n return true;\n }\n // Check if current version meets minimum requirement\n if (minimumVersion &&\n this.compareVersions(currentVersion, minimumVersion) < 0) {\n return true;\n }\n return false;\n }\n determineUpdatePriority(versionDiff, stalenessDays) {\n // Parse version difference\n const [major, minor] = versionDiff.split('.').map(Number);\n // Major version change = IMMEDIATE (priority 5)\n if (major > 0) {\n return 5;\n }\n // Minor version with high staleness = HIGH (priority 4)\n if (minor > 0 && stalenessDays && stalenessDays > 30) {\n return 4;\n }\n // Minor version = MEDIUM (priority 3)\n if (minor > 0) {\n return 3;\n }\n // Patch version = LOW (priority 1)\n return 1;\n }\n async getCurrentVersion() {\n // This would be implemented by the native platform\n return '1.0.0';\n }\n getPlatform() {\n // Detect platform\n if (typeof window !== 'undefined') {\n const userAgent = window.navigator.userAgent;\n if (/android/i.test(userAgent)) {\n return 'android';\n }\n else if (/iPad|iPhone|iPod/.test(userAgent)) {\n return 'ios';\n }\n }\n return 'web';\n }\n}\n//# sourceMappingURL=app-update-checker.js.map","import { Logger } from '../core/logger';\nimport { AppUpdateInstallStatus, } from './types';\nexport class AppUpdateInstaller {\n constructor(_) {\n // config parameter is kept for compatibility but not used\n this.logger = new Logger('AppUpdateInstaller');\n this.currentState = {\n installStatus: AppUpdateInstallStatus.UNKNOWN,\n packageName: '',\n availableVersion: '',\n };\n }\n async startImmediateUpdate() {\n this.logger.log('Starting immediate update installation');\n // Update state\n this.updateState(AppUpdateInstallStatus.PENDING);\n // On Android, this would trigger Play Core immediate update\n // On iOS, this would open App Store\n if (this.isAndroid()) {\n // Android implementation would use Play Core Library\n this.logger.log('Triggering Android immediate update');\n }\n else if (this.isIOS()) {\n // iOS implementation would open App Store\n this.logger.log('Opening iOS App Store for update');\n }\n else {\n // Web fallback\n throw new Error('Immediate updates not supported on web platform');\n }\n }\n async startFlexibleUpdate() {\n this.logger.log('Starting flexible update download');\n // Update state\n this.updateState(AppUpdateInstallStatus.DOWNLOADING);\n // Start download simulation for web\n if (this.isWeb()) {\n this.simulateFlexibleUpdate();\n }\n else if (this.isAndroid()) {\n // Android implementation would use Play Core Library\n this.logger.log('Starting Android flexible update');\n }\n else {\n // iOS doesn't support flexible updates\n throw new Error('Flexible updates not supported on iOS');\n }\n }\n async completeFlexibleUpdate() {\n this.logger.log('Completing flexible update installation');\n if (this.currentState.installStatus !== AppUpdateInstallStatus.DOWNLOADED) {\n throw new Error('Update not ready for installation');\n }\n // Update state\n this.updateState(AppUpdateInstallStatus.INSTALLING);\n // Trigger installation\n if (this.isAndroid()) {\n // Android implementation would complete the update\n this.logger.log('Completing Android update installation');\n }\n else {\n // Simulate completion\n setTimeout(() => {\n this.updateState(AppUpdateInstallStatus.INSTALLED);\n }, 1000);\n }\n }\n async cancelUpdate() {\n this.logger.log('Cancelling update');\n if (this.currentState.installStatus === AppUpdateInstallStatus.DOWNLOADING) {\n this.updateState(AppUpdateInstallStatus.CANCELED);\n }\n }\n async getInstallState() {\n return Object.assign({}, this.currentState);\n }\n onProgress(callback) {\n this.progressCallback = callback;\n }\n updateState(status, errorCode) {\n this.currentState.installStatus = status;\n if (errorCode !== undefined) {\n this.currentState.installErrorCode = errorCode;\n }\n this.logger.log('Update state changed', this.currentState);\n }\n simulateFlexibleUpdate() {\n // Simulate download progress for web platform\n let downloaded = 0;\n const totalSize = 50 * 1024 * 1024; // 50MB\n const chunkSize = 1024 * 1024; // 1MB per tick\n const interval = setInterval(() => {\n downloaded += chunkSize;\n if (downloaded >= totalSize) {\n downloaded = totalSize;\n clearInterval(interval);\n this.updateState(AppUpdateInstallStatus.DOWNLOADED);\n }\n const progress = {\n bytesDownloaded: downloaded,\n totalBytesToDownload: totalSize,\n percentComplete: Math.round((downloaded / totalSize) * 100),\n downloadSpeed: chunkSize, // 1MB/s\n estimatedTime: Math.ceil((totalSize - downloaded) / chunkSize),\n };\n if (this.progressCallback) {\n this.progressCallback(progress);\n }\n }, 1000);\n }\n isAndroid() {\n return (typeof window !== 'undefined' &&\n /android/i.test(window.navigator.userAgent));\n }\n isIOS() {\n return (typeof window !== 'undefined' &&\n /iPad|iPhone|iPod/.test(window.navigator.userAgent));\n }\n isWeb() {\n return !this.isAndroid() && !this.isIOS();\n }\n}\n//# sourceMappingURL=app-update-installer.js.map","import { Logger } from '../core/logger';\nimport { Capacitor } from '@capacitor/core';\nexport class PlatformAppUpdate {\n constructor(config) {\n this.config = config;\n this.logger = new Logger('PlatformAppUpdate');\n this.platform = Capacitor.getPlatform();\n }\n async checkForUpdate(_) {\n // options parameter is kept for future use\n this.logger.log('Checking for platform update: ' + this.platform);\n const versionInfo = await this.getVersionInfo();\n // Default response\n const updateInfo = {\n updateAvailable: false,\n currentVersion: versionInfo.currentVersion,\n availableVersion: versionInfo.currentVersion,\n };\n // Platform-specific checks\n if (this.platform === 'android') {\n // Android would check Play Store via Play Core Library\n // This is handled by native implementation\n return updateInfo;\n }\n else if (this.platform === 'ios') {\n // iOS would check App Store via iTunes API\n // This is handled by native implementation\n return updateInfo;\n }\n else {\n // Web platform - check configured update URL\n if (this.config.webUpdateUrl) {\n try {\n const response = await fetch(this.config.webUpdateUrl);\n const data = await response.json();\n if (data.version && data.version !== versionInfo.currentVersion) {\n updateInfo.updateAvailable = true;\n updateInfo.availableVersion = data.version;\n updateInfo.releaseNotes = data.releaseNotes;\n updateInfo.updateURL = data.downloadUrl;\n }\n }\n catch (error) {\n this.logger.error('Failed to check web update', error);\n }\n }\n }\n return updateInfo;\n }\n async getVersionInfo() {\n // getAppInfo is not available in standard Capacitor, using default values\n const appInfo = {\n version: '1.0.0',\n build: '1',\n id: 'com.example.app',\n };\n return {\n currentVersion: appInfo.version,\n buildNumber: appInfo.build,\n packageName: appInfo.id,\n platform: this.platform,\n minimumVersion: this.config.minimumVersion,\n };\n }\n async getAppStoreUrl() {\n const platform = this.platform;\n let url = '';\n if (platform === 'ios') {\n // iOS App Store URL\n const appStoreId = this.config.appStoreId || this.config.iosAppId;\n if (!appStoreId) {\n throw new Error('App Store ID not configured');\n }\n url = `https://apps.apple.com/app/id${appStoreId}`;\n }\n else if (platform === 'android') {\n // Google Play Store URL\n const packageName = this.config.packageName || (await this.getVersionInfo()).packageName;\n url = `https://play.google.com/store/apps/details?id=${packageName}`;\n }\n else {\n // Web URL\n url = this.config.webUpdateUrl || window.location.origin;\n }\n return { url, platform: platform };\n }\n async openUrl(url) {\n if (typeof window !== 'undefined' && window.open) {\n window.open(url, '_blank');\n }\n else {\n throw new Error('Cannot open URL on this platform');\n }\n }\n isUpdateSupported() {\n // Check if platform supports in-app updates\n if (this.platform === 'android') {\n // Android supports in-app updates via Play Core\n return true;\n }\n else if (this.platform === 'ios') {\n // iOS only supports opening App Store\n return false;\n }\n else {\n // Web can redirect to update URL\n return true;\n }\n }\n getUpdateCapabilities() {\n const capabilities = {\n immediateUpdate: false,\n flexibleUpdate: false,\n backgroundDownload: false,\n inAppReview: false,\n };\n if (this.platform === 'android') {\n capabilities.immediateUpdate = true;\n capabilities.flexibleUpdate = true;\n capabilities.backgroundDownload = true;\n capabilities.inAppReview = true;\n }\n else if (this.platform === 'ios') {\n capabilities.inAppReview = true;\n }\n return capabilities;\n }\n}\n//# sourceMappingURL=platform-app-update.js.map","import { Logger } from '../core/logger';\nimport { AppUpdateChecker } from './app-update-checker';\nimport { AppUpdateInstaller } from './app-update-installer';\nimport { PlatformAppUpdate } from './platform-app-update';\nexport class AppUpdateManager {\n constructor(config) {\n this.listeners = new Map();\n this.config = config;\n this.logger = new Logger('AppUpdateManager');\n this.checker = new AppUpdateChecker(config);\n this.installer = new AppUpdateInstaller(config);\n this.platformUpdate = new PlatformAppUpdate(config);\n }\n async checkAppUpdate(options) {\n try {\n this.logger.log('Checking for app updates', options);\n // Check with native platform\n const nativeInfo = await this.platformUpdate.checkForUpdate(options);\n // If no native info, check with server\n if (!nativeInfo.updateAvailable && this.config.updateUrl) {\n const serverInfo = await this.checker.checkServerVersion(options);\n return this.mergeUpdateInfo(nativeInfo, serverInfo);\n }\n return nativeInfo;\n }\n catch (error) {\n this.logger.error('Failed to check app update', error);\n throw error;\n }\n }\n async startImmediateUpdate() {\n try {\n this.logger.log('Starting immediate update');\n // Check if immediate update is allowed\n const updateInfo = await this.checkAppUpdate();\n if (!updateInfo.immediateUpdateAllowed) {\n throw new Error('Immediate update not allowed');\n }\n // Start the update\n await this.installer.startImmediateUpdate();\n // Notify listeners\n this.emit('appUpdateStateChanged', {\n installStatus: 1, // PENDING\n packageName: this.config.packageName || '',\n availableVersion: updateInfo.availableVersion || '',\n });\n }\n catch (error) {\n this.logger.error('Failed to start immediate update', error);\n throw error;\n }\n }\n async startFlexibleUpdate() {\n try {\n this.logger.log('Starting flexible update');\n // Check if flexible update is allowed\n const updateInfo = await this.checkAppUpdate();\n if (!updateInfo.flexibleUpdateAllowed) {\n throw new Error('Flexible update not allowed');\n }\n // Start the update\n await this.installer.startFlexibleUpdate();\n // Set up progress monitoring\n this.installer.onProgress((progress) => {\n this.emit('appUpdateProgress', progress);\n });\n // Notify listeners\n this.emit('appUpdateStateChanged', {\n installStatus: 2, // DOWNLOADING\n packageName: this.config.packageName || '',\n availableVersion: updateInfo.availableVersion || '',\n });\n }\n catch (error) {\n this.logger.error('Failed to start flexible update', error);\n throw error;\n }\n }\n async completeFlexibleUpdate() {\n try {\n this.logger.log('Completing flexible update');\n await this.installer.completeFlexibleUpdate();\n // App will restart after this\n this.emit('appUpdateStateChanged', {\n installStatus: 3, // INSTALLING\n packageName: this.config.packageName || '',\n availableVersion: '',\n });\n }\n catch (error) {\n this.logger.error('Failed to complete flexible update', error);\n throw error;\n }\n }\n async getVersionInfo() {\n try {\n this.logger.log('Getting version info');\n return await this.platformUpdate.getVersionInfo();\n }\n catch (error) {\n this.logger.error('Failed to get version info', error);\n throw error;\n }\n }\n async isMinimumVersionMet() {\n try {\n this.logger.log('Checking minimum version');\n const versionInfo = await this.getVersionInfo();\n const minimumVersion = this.config.minimumVersion || '0.0.0';\n const isMet = this.checker.compareVersions(versionInfo.currentVersion, minimumVersion) >= 0;\n return {\n isMet,\n currentVersion: versionInfo.currentVersion,\n minimumVersion,\n updateRequired: !isMet && this.config.enforceMinVersion === true,\n };\n }\n catch (error) {\n this.logger.error('Failed to check minimum version', error);\n throw error;\n }\n }\n async getAppUpdateInfo() {\n return this.checkAppUpdate();\n }\n async performImmediateUpdate() {\n return this.startImmediateUpdate();\n }\n async openAppStore(_options) {\n try {\n this.logger.log('Opening app store');\n const storeInfo = await this.getAppStoreUrl();\n await this.platformUpdate.openUrl(storeInfo.url);\n }\n catch (error) {\n this.logger.error('Failed to open app store', error);\n throw error;\n }\n }\n async getAppStoreUrl() {\n try {\n this.logger.log('Getting app store URL');\n return await this.platformUpdate.getAppStoreUrl();\n }\n catch (error) {\n this.logger.error('Failed to get app store URL', error);\n throw error;\n }\n }\n async getUpdateInstallState() {\n try {\n this.logger.log('Getting update install state');\n return await this.installer.getInstallState();\n }\n catch (error) {\n this.logger.error('Failed to get update install state', error);\n throw error;\n }\n }\n addListener(eventName, listenerFunc) {\n if (!this.listeners.has(eventName)) {\n this.listeners.set(eventName, new Set());\n }\n this.listeners.get(eventName).add(listenerFunc);\n return {\n remove: async () => {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.delete(listenerFunc);\n }\n },\n };\n }\n async removeAllListeners(eventName) {\n if (eventName) {\n this.listeners.delete(eventName);\n }\n else {\n this.listeners.clear();\n }\n }\n emit(eventName, data) {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.forEach((listener) => {\n try {\n listener(data);\n }\n catch (error) {\n this.logger.error(`Error in ${eventName} listener`, error);\n }\n });\n }\n }\n mergeUpdateInfo(nativeInfo, serverInfo) {\n return Object.assign(Object.assign(Object.assign({}, nativeInfo), serverInfo), { updateAvailable: nativeInfo.updateAvailable || !!serverInfo.availableVersion, availableVersion: serverInfo.availableVersion || nativeInfo.availableVersion });\n }\n}\n//# sourceMappingURL=app-update-manager.js.map","/**\n * Centralized event emitter for the Native Update plugin\n */\nexport class EventEmitter {\n constructor() {\n this.listeners = new Map();\n }\n static getInstance() {\n if (!EventEmitter.instance) {\n EventEmitter.instance = new EventEmitter();\n }\n return EventEmitter.instance;\n }\n /**\n * Add a listener for an event\n */\n addListener(eventName, listener) {\n if (!this.listeners.has(eventName)) {\n this.listeners.set(eventName, new Set());\n }\n this.listeners.get(eventName).add(listener);\n // Return remove function\n return () => {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.delete(listener);\n if (listeners.size === 0) {\n this.listeners.delete(eventName);\n }\n }\n };\n }\n /**\n * Emit an event to all listeners\n */\n emit(eventName, data) {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.forEach(listener => {\n try {\n listener(data);\n }\n catch (error) {\n console.error(`Error in event listener for ${eventName}:`, error);\n }\n });\n }\n }\n /**\n * Remove all listeners for a specific event\n */\n removeListeners(eventName) {\n this.listeners.delete(eventName);\n }\n /**\n * Remove all listeners\n */\n removeAllListeners() {\n this.listeners.clear();\n }\n /**\n * Get the number of listeners for an event\n */\n listenerCount(eventName) {\n var _a;\n return ((_a = this.listeners.get(eventName)) === null || _a === void 0 ? void 0 : _a.size) || 0;\n }\n /**\n * Get all event names that have listeners\n */\n eventNames() {\n return Array.from(this.listeners.keys());\n }\n}\n//# sourceMappingURL=event-emitter.js.map","import { Filesystem } from '@capacitor/filesystem';\nimport { Preferences } from '@capacitor/preferences';\nimport { ConfigManager } from './config';\nimport { Logger } from './logger';\nimport { SecurityValidator } from './security';\nimport { BundleManager } from '../live-update/bundle-manager';\nimport { DownloadManager } from '../live-update/download-manager';\nimport { VersionManager } from '../live-update/version-manager';\nimport { AppUpdateManager } from '../app-update/app-update-manager';\nimport { EventEmitter } from './event-emitter';\nimport { NativeUpdateError, ErrorCode } from './errors';\n/**\n * Central manager for all plugin components\n */\nexport class PluginManager {\n constructor() {\n this.bundleManager = null;\n this.downloadManager = null;\n this.versionManager = null;\n this.appUpdateManager = null;\n this.initialized = false;\n this.configManager = ConfigManager.getInstance();\n this.logger = Logger.getInstance();\n this.securityValidator = SecurityValidator.getInstance();\n this.eventEmitter = EventEmitter.getInstance();\n }\n static getInstance() {\n if (!PluginManager.instance) {\n PluginManager.instance = new PluginManager();\n }\n return PluginManager.instance;\n }\n /**\n * Initialize the plugin with configuration\n */\n async initialize(config) {\n var _a, _b;\n if (this.initialized) {\n this.logger.warn('Plugin already initialized');\n return;\n }\n try {\n // Configure the plugin\n this.configManager.configure(config);\n // Use Capacitor plugins directly if not provided\n if (!config.filesystem) {\n config.filesystem = Filesystem;\n }\n if (!config.preferences) {\n config.preferences = Preferences;\n }\n // Initialize managers\n this.bundleManager = new BundleManager();\n await this.bundleManager.initialize();\n this.downloadManager = new DownloadManager();\n await this.downloadManager.initialize();\n this.versionManager = new VersionManager();\n await this.versionManager.initialize();\n this.appUpdateManager = new AppUpdateManager({\n serverUrl: config.serverUrl || config.baseUrl || '',\n channel: config.channel || 'production',\n autoCheck: (_a = config.autoCheck) !== null && _a !== void 0 ? _a : true,\n autoUpdate: (_b = config.autoUpdate) !== null && _b !== void 0 ? _b : false,\n updateStrategy: config.updateStrategy,\n publicKey: config.publicKey,\n requireSignature: config.requireSignature,\n checksumAlgorithm: config.checksumAlgorithm,\n checkInterval: config.checkInterval,\n security: config.security,\n });\n // Wire up app update manager events to central event emitter\n this.setupAppUpdateEventBridge();\n this.initialized = true;\n this.logger.info('Plugin initialized successfully');\n }\n catch (error) {\n this.logger.error('Failed to initialize plugin', error);\n throw error;\n }\n }\n /**\n * Check if plugin is initialized\n */\n isInitialized() {\n return this.initialized && this.configManager.isConfigured();\n }\n /**\n * Ensure plugin is initialized\n */\n ensureInitialized() {\n if (!this.isInitialized()) {\n throw new NativeUpdateError(ErrorCode.NOT_CONFIGURED, 'Plugin not initialized. Please call initialize() first.');\n }\n }\n /**\n * Get bundle manager\n */\n getBundleManager() {\n this.ensureInitialized();\n return this.bundleManager;\n }\n /**\n * Get download manager\n */\n getDownloadManager() {\n this.ensureInitialized();\n return this.downloadManager;\n }\n /**\n * Get version manager\n */\n getVersionManager() {\n this.ensureInitialized();\n return this.versionManager;\n }\n /**\n * Get configuration manager\n */\n getConfigManager() {\n return this.configManager;\n }\n /**\n * Get logger\n */\n getLogger() {\n return this.logger;\n }\n /**\n * Get security validator\n */\n getSecurityValidator() {\n return this.securityValidator;\n }\n /**\n * Get app update manager\n */\n getAppUpdateManager() {\n this.ensureInitialized();\n return this.appUpdateManager;\n }\n /**\n * Get event emitter\n */\n getEventEmitter() {\n return this.eventEmitter;\n }\n /**\n * Reset plugin state\n */\n async reset() {\n this.logger.info('Resetting plugin state');\n // Clear all data\n if (this.bundleManager) {\n await this.bundleManager.clearAllBundles();\n }\n if (this.versionManager) {\n await this.versionManager.clearVersionCache();\n }\n if (this.downloadManager) {\n this.downloadManager.cancelAllDownloads();\n }\n // Reset initialization state\n this.bundleManager = null;\n this.downloadManager = null;\n this.versionManager = null;\n this.appUpdateManager = null;\n this.initialized = false;\n // Clear all event listeners\n this.eventEmitter.removeAllListeners();\n this.logger.info('Plugin reset complete');\n }\n /**\n * Clean up resources\n */\n async cleanup() {\n this.logger.info('Cleaning up plugin resources');\n // Cancel any active downloads\n if (this.downloadManager) {\n this.downloadManager.cancelAllDownloads();\n }\n // Clean expired bundles\n if (this.bundleManager) {\n await this.bundleManager.cleanExpiredBundles();\n }\n this.logger.info('Cleanup complete');\n }\n /**\n * Setup event bridge between AppUpdateManager and central EventEmitter\n */\n setupAppUpdateEventBridge() {\n if (!this.appUpdateManager)\n return;\n // Bridge appUpdateStateChanged events\n this.appUpdateManager.addListener('appUpdateStateChanged', (event) => {\n this.eventEmitter.emit('appUpdateStateChanged', event);\n });\n // Bridge appUpdateProgress events\n this.appUpdateManager.addListener('appUpdateProgress', (event) => {\n this.eventEmitter.emit('appUpdateProgress', event);\n });\n }\n}\n//# sourceMappingURL=plugin-manager.js.map","import { registerPlugin } from '@capacitor/core';\nimport { SyncStatus, BundleStatus, UpdateErrorCode } from './definitions';\nimport { PluginManager } from './core/plugin-manager';\nimport { NativeUpdateError, ErrorCode } from './core/errors';\n/**\n * Web implementation of the Native Update Plugin\n */\nclass NativeUpdatePluginWeb {\n constructor() {\n this.initialized = false;\n this.windowEventListeners = new Map();\n this.pluginManager = PluginManager.getInstance();\n }\n // Main plugin methods\n async initialize(config) {\n await this.pluginManager.initialize(config);\n this.initialized = true;\n // Setup window event bridge for AppUpdateNotifier events\n this.setupWindowEventBridge();\n }\n isInitialized() {\n return this.initialized && this.pluginManager.isInitialized();\n }\n async reset() {\n await this.pluginManager.reset();\n }\n async cleanup() {\n await this.pluginManager.cleanup();\n }\n // NativeUpdatePlugin methods\n async configure(config) {\n var _a;\n // Handle both UpdateConfig and wrapped PluginInitConfig formats\n let initConfig;\n if ('config' in config && typeof config.config === 'object') {\n // Format: { config: PluginInitConfig }\n initConfig = config.config;\n }\n else {\n // Format: UpdateConfig - convert to PluginInitConfig\n initConfig = {\n // Auto-imported Capacitor plugins will be added by plugin-manager\n baseUrl: (_a = config.liveUpdate) === null || _a === void 0 ? void 0 : _a.serverUrl,\n };\n }\n if (!this.initialized) {\n // Auto-initialize with the provided config\n await this.initialize(initConfig);\n }\n else {\n // Apply plugin configuration\n const configManager = this.pluginManager.getConfigManager();\n configManager.configure(initConfig);\n }\n }\n async getSecurityInfo() {\n return {\n enforceHttps: true,\n certificatePinning: {\n enabled: false,\n pins: [],\n },\n validateInputs: true,\n secureStorage: true,\n };\n }\n // LiveUpdatePlugin methods\n async sync(_options) {\n const bundleManager = this.pluginManager.getBundleManager();\n try {\n // Check for updates\n const currentBundle = await bundleManager.getActiveBundle();\n const currentVersion = (currentBundle === null || currentBundle === void 0 ? void 0 : currentBundle.version) || '1.0.0';\n // For now, return up-to-date status\n return {\n status: SyncStatus.UP_TO_DATE,\n version: currentVersion,\n };\n }\n catch (error) {\n return {\n status: SyncStatus.ERROR,\n error: {\n code: UpdateErrorCode.UNKNOWN_ERROR,\n message: error instanceof Error ? error.message : 'Sync failed',\n },\n };\n }\n }\n async download(options) {\n const downloadManager = this.pluginManager.getDownloadManager();\n const bundleManager = this.pluginManager.getBundleManager();\n const blob = await downloadManager.downloadWithRetry(options.url, options.version);\n const path = await downloadManager.saveBlob(options.version, blob);\n const bundleInfo = {\n bundleId: options.version,\n version: options.version,\n path,\n downloadTime: Date.now(),\n size: blob.size,\n status: BundleStatus.READY,\n checksum: options.checksum,\n signature: options.signature,\n verified: false,\n };\n await bundleManager.saveBundleInfo(bundleInfo);\n return bundleInfo;\n }\n async set(bundle) {\n const bundleManager = this.pluginManager.getBundleManager();\n await bundleManager.setActiveBundle(bundle.bundleId);\n }\n async reload() {\n // In web implementation, we can reload the page\n if (typeof window !== 'undefined') {\n window.location.reload();\n }\n }\n async current() {\n const bundleManager = this.pluginManager.getBundleManager();\n const bundle = await bundleManager.getActiveBundle();\n if (!bundle) {\n throw new NativeUpdateError(ErrorCode.FILE_NOT_FOUND, 'No active bundle found');\n }\n return bundle;\n }\n async list() {\n const bundleManager = this.pluginManager.getBundleManager();\n return bundleManager.getAllBundles();\n }\n async delete(options) {\n const bundleManager = this.pluginManager.getBundleManager();\n if (options.bundleId) {\n await bundleManager.deleteBundle(options.bundleId);\n }\n else if (options.keepVersions !== undefined) {\n // Delete old versions keeping the specified number\n const bundles = await bundleManager.getAllBundles();\n const sortedBundles = bundles.sort((a, b) => b.downloadTime - a.downloadTime);\n for (let i = options.keepVersions; i < sortedBundles.length; i++) {\n await bundleManager.deleteBundle(sortedBundles[i].bundleId);\n }\n }\n }\n async notifyAppReady() {\n // Mark the current bundle as stable\n const bundleManager = this.pluginManager.getBundleManager();\n const activeBundle = await bundleManager.getActiveBundle();\n if (activeBundle) {\n activeBundle.status = BundleStatus.ACTIVE;\n await bundleManager.saveBundleInfo(activeBundle);\n }\n }\n async getLatest() {\n // For web, we'll return no update available\n return {\n available: false,\n };\n }\n async setChannel(channel) {\n // Store the channel preference\n const preferences = this.pluginManager\n .getConfigManager()\n .get('preferences');\n if (preferences) {\n await preferences.set({\n key: 'update_channel',\n value: channel,\n });\n }\n }\n async setUpdateUrl(url) {\n const configManager = this.pluginManager.getConfigManager();\n configManager.configure({ baseUrl: url });\n }\n async validateUpdate(options) {\n const securityValidator = this.pluginManager.getSecurityValidator();\n try {\n // Validate checksum\n const isValid = await securityValidator.validateChecksum(new ArrayBuffer(0), // Placeholder for bundle data\n options.checksum);\n return {\n isValid,\n details: {\n checksumValid: isValid,\n signatureValid: true,\n sizeValid: true,\n versionValid: true,\n },\n };\n }\n catch (error) {\n return {\n isValid: false,\n error: error instanceof Error ? error.message : 'Validation failed',\n };\n }\n }\n // AppUpdatePlugin methods\n async getAppUpdateInfo() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.getAppUpdateInfo();\n }\n async performImmediateUpdate() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.performImmediateUpdate();\n }\n async startFlexibleUpdate() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.startFlexibleUpdate();\n }\n async completeFlexibleUpdate() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.completeFlexibleUpdate();\n }\n async openAppStore(options) {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.openAppStore(options);\n }\n // AppReviewPlugin methods\n async requestReview() {\n return {\n displayed: false,\n error: 'Reviews are not supported on web',\n };\n }\n async canRequestReview() {\n return {\n canRequest: false,\n reason: 'Reviews are not supported on web',\n };\n }\n // BackgroundUpdatePlugin methods\n async enableBackgroundUpdates(config) {\n // Store the configuration\n const preferences = this.pluginManager\n .getConfigManager()\n .get('preferences');\n if (preferences) {\n await preferences.set({\n key: 'background_update_config',\n value: JSON.stringify(config),\n });\n }\n }\n async disableBackgroundUpdates() {\n const preferences = this.pluginManager\n .getConfigManager()\n .get('preferences');\n if (preferences) {\n await preferences.remove({ key: 'background_update_config' });\n }\n }\n async getBackgroundUpdateStatus() {\n return {\n enabled: false,\n isRunning: false,\n checkCount: 0,\n failureCount: 0,\n };\n }\n async scheduleBackgroundCheck(_interval) {\n // Not supported on web\n throw new NativeUpdateError(ErrorCode.PLATFORM_NOT_SUPPORTED, 'Background updates are not supported on web');\n }\n async triggerBackgroundCheck() {\n return {\n success: false,\n updatesFound: false,\n notificationSent: false,\n error: {\n code: UpdateErrorCode.PLATFORM_NOT_SUPPORTED,\n message: 'Background updates are not supported on web',\n },\n };\n }\n async setNotificationPreferences(preferences) {\n // Store preferences but notifications aren't supported on web\n const prefs = this.pluginManager.getConfigManager().get('preferences');\n if (prefs) {\n await prefs.set({\n key: 'notification_preferences',\n value: JSON.stringify(preferences),\n });\n }\n }\n async getNotificationPermissions() {\n return {\n granted: false,\n canRequest: false,\n };\n }\n async requestNotificationPermissions() {\n return false;\n }\n // Event listener methods\n async addListener(eventName, listenerFunc) {\n const eventEmitter = this.pluginManager.getEventEmitter();\n // Add listener to central event emitter\n const removeListener = eventEmitter.addListener(eventName, listenerFunc);\n return {\n remove: async () => {\n removeListener();\n },\n };\n }\n async removeAllListeners() {\n const eventEmitter = this.pluginManager.getEventEmitter();\n eventEmitter.removeAllListeners();\n }\n /**\n * Setup bridge between window custom events and central event emitter\n */\n setupWindowEventBridge() {\n const eventEmitter = this.pluginManager.getEventEmitter();\n // List of events emitted by AppUpdateNotifier via window\n const windowEvents = [\n 'appUpdateAvailable',\n 'appUpdateProgress',\n 'appUpdateReady',\n 'appUpdateFailed',\n 'appUpdateNotificationClicked',\n 'appUpdateInstallClicked'\n ];\n windowEvents.forEach(eventName => {\n const listener = (event) => {\n eventEmitter.emit(eventName, event.detail);\n };\n window.addEventListener(eventName, listener);\n this.windowEventListeners.set(eventName, listener);\n });\n }\n}\n/**\n * Register the plugin\n */\nconst NativeUpdate = registerPlugin('NativeUpdate', {\n web: () => new NativeUpdatePluginWeb(),\n});\nexport { NativeUpdate };\n//# sourceMappingURL=plugin.js.map","import { ConfigManager } from './config';\nimport { Logger } from './logger';\nimport { Directory, Encoding } from '@capacitor/filesystem';\n/**\n * Manages caching with expiration for various data types\n */\nexport class CacheManager {\n constructor() {\n this.filesystem = null;\n this.memoryCache = new Map();\n this.CACHE_DIR = 'cache';\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n }\n /**\n * Initialize cache manager\n */\n async initialize() {\n this.filesystem = this.configManager.get('filesystem');\n if (!this.filesystem) {\n throw new Error('Filesystem not configured');\n }\n // Create cache directory if it doesn't exist\n try {\n await this.filesystem.mkdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n recursive: true,\n });\n }\n catch (error) {\n this.logger.debug('Cache directory may already exist', error);\n }\n // Clean expired cache on initialization\n await this.cleanExpiredCache();\n }\n /**\n * Set cache entry with expiration\n */\n async set(key, data, ttlMs) {\n const expiry = Date.now() + (ttlMs || this.configManager.get('cacheExpiration'));\n const entry = {\n data,\n timestamp: Date.now(),\n expiry,\n };\n // Update memory cache\n this.memoryCache.set(key, entry);\n // Persist to filesystem for larger data\n if (this.shouldPersist(data)) {\n await this.persistToFile(key, entry);\n }\n this.logger.debug('Cache entry set', { key, expiry: new Date(expiry) });\n }\n /**\n * Get cache entry\n */\n async get(key) {\n // Check memory cache first\n const memEntry = this.memoryCache.get(key);\n if (memEntry) {\n if (Date.now() < memEntry.expiry) {\n return memEntry.data;\n }\n else {\n // Expired - remove from memory\n this.memoryCache.delete(key);\n }\n }\n // Check filesystem cache\n const fileEntry = await this.loadFromFile(key);\n if (fileEntry) {\n if (Date.now() < fileEntry.expiry) {\n // Update memory cache\n this.memoryCache.set(key, fileEntry);\n return fileEntry.data;\n }\n else {\n // Expired - remove file\n await this.removeFile(key);\n }\n }\n return null;\n }\n /**\n * Check if cache entry exists and is valid\n */\n async has(key) {\n const value = await this.get(key);\n return value !== null;\n }\n /**\n * Remove cache entry\n */\n async remove(key) {\n this.memoryCache.delete(key);\n await this.removeFile(key);\n this.logger.debug('Cache entry removed', { key });\n }\n /**\n * Clear all cache\n */\n async clear() {\n this.memoryCache.clear();\n // Remove cache directory\n try {\n await this.filesystem.rmdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n recursive: true,\n });\n // Recreate empty cache directory\n await this.filesystem.mkdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n recursive: true,\n });\n }\n catch (error) {\n this.logger.warn('Failed to clear cache directory', error);\n }\n this.logger.info('Cache cleared');\n }\n /**\n * Clean expired cache entries\n */\n async cleanExpiredCache() {\n const now = Date.now();\n let cleanedCount = 0;\n // Clean memory cache\n for (const [key, entry] of this.memoryCache) {\n if (now >= entry.expiry) {\n this.memoryCache.delete(key);\n cleanedCount++;\n }\n }\n // Clean filesystem cache\n try {\n const files = await this.filesystem.readdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n });\n for (const file of files.files) {\n const key = file.name.replace('.json', '');\n const entry = await this.loadFromFile(key);\n if (!entry || now >= entry.expiry) {\n await this.removeFile(key);\n cleanedCount++;\n }\n }\n }\n catch (error) {\n this.logger.debug('Failed to clean filesystem cache', error);\n }\n if (cleanedCount > 0) {\n this.logger.info('Cleaned expired cache entries', {\n count: cleanedCount,\n });\n }\n }\n /**\n * Get cache statistics\n */\n async getStats() {\n let fileEntries = 0;\n let totalSize = 0;\n try {\n const files = await this.filesystem.readdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n });\n fileEntries = files.files.length;\n // Estimate size (this is approximate)\n for (const file of files.files) {\n const stat = await this.filesystem.stat({\n path: `${this.CACHE_DIR}/${file.name}`,\n directory: Directory.Data,\n });\n totalSize += stat.size || 0;\n }\n }\n catch (error) {\n this.logger.debug('Failed to get cache stats', error);\n }\n return {\n memoryEntries: this.memoryCache.size,\n fileEntries,\n totalSize,\n };\n }\n /**\n * Cache bundle metadata\n */\n async cacheBundleMetadata(bundle) {\n const key = `bundle_meta_${bundle.bundleId}`;\n await this.set(key, bundle, 24 * 60 * 60 * 1000); // 24 hours\n }\n /**\n * Get cached bundle metadata\n */\n async getCachedBundleMetadata(bundleId) {\n const key = `bundle_meta_${bundleId}`;\n return this.get(key);\n }\n /**\n * Check if data should be persisted to filesystem\n */\n shouldPersist(data) {\n // Persist objects and large strings\n if (typeof data === 'object')\n return true;\n if (typeof data === 'string' && data.length > 1024)\n return true;\n return false;\n }\n /**\n * Persist cache entry to file\n */\n async persistToFile(key, entry) {\n if (!this.filesystem)\n return;\n try {\n const path = `${this.CACHE_DIR}/${key}.json`;\n const data = JSON.stringify(entry);\n await this.filesystem.writeFile({\n path,\n data,\n directory: Directory.Data,\n encoding: Encoding.UTF8,\n });\n }\n catch (error) {\n this.logger.warn('Failed to persist cache to file', { key, error });\n }\n }\n /**\n * Load cache entry from file\n */\n async loadFromFile(key) {\n if (!this.filesystem)\n return null;\n try {\n const path = `${this.CACHE_DIR}/${key}.json`;\n const result = await this.filesystem.readFile({\n path,\n directory: Directory.Data,\n encoding: Encoding.UTF8,\n });\n return JSON.parse(result.data);\n }\n catch (_a) {\n // File doesn't exist or is corrupted\n return null;\n }\n }\n /**\n * Remove cache file\n */\n async removeFile(key) {\n if (!this.filesystem)\n return;\n try {\n const path = `${this.CACHE_DIR}/${key}.json`;\n await this.filesystem.deleteFile({\n path,\n directory: Directory.Data,\n });\n }\n catch (error) {\n // File may not exist\n this.logger.debug('Failed to remove cache file', { key, error });\n }\n }\n}\n//# sourceMappingURL=cache-manager.js.map","import { PluginManager } from '../core/plugin-manager';\nimport { UpdateError, ValidationError, ErrorCode } from '../core/errors';\nimport { SecurityValidator } from '../core/security';\nimport { Directory } from '@capacitor/filesystem';\n/**\n * Manages atomic bundle installation with rollback capability\n */\nexport class UpdateManager {\n constructor() {\n this.filesystem = null;\n this.updateInProgress = false;\n this.currentState = null;\n this.pluginManager = PluginManager.getInstance();\n this.securityValidator = SecurityValidator.getInstance();\n }\n /**\n * Initialize update manager\n */\n async initialize() {\n this.filesystem = this.pluginManager.getConfigManager().get('filesystem');\n if (!this.filesystem) {\n throw new UpdateError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not configured');\n }\n }\n /**\n * Apply bundle update atomically\n */\n async applyUpdate(bundleId, options) {\n if (this.updateInProgress) {\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Another update is already in progress');\n }\n const logger = this.pluginManager.getLogger();\n const bundleManager = this.pluginManager.getBundleManager();\n try {\n this.updateInProgress = true;\n logger.info('Starting bundle update', { bundleId });\n // Get the new bundle\n const newBundle = await bundleManager.getBundle(bundleId);\n if (!newBundle) {\n throw new UpdateError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);\n }\n // Verify bundle is ready\n if (newBundle.status !== 'READY' && newBundle.status !== 'ACTIVE') {\n throw new UpdateError(ErrorCode.BUNDLE_NOT_READY, `Bundle ${bundleId} is not ready for installation`);\n }\n // Get current active bundle\n const currentBundle = await bundleManager.getActiveBundle();\n // Initialize update state\n this.currentState = {\n currentBundle,\n newBundle,\n backupPath: null,\n startTime: Date.now(),\n };\n // Validate update\n await this.validateUpdate(currentBundle, newBundle, options);\n // Create backup of current state\n if (currentBundle && currentBundle.bundleId !== 'default') {\n this.currentState.backupPath = await this.createBackup(currentBundle);\n }\n // Apply the update\n await this.performUpdate(newBundle);\n // Verify the update\n await this.verifyUpdate(newBundle);\n // Mark as active\n await bundleManager.setActiveBundle(bundleId);\n // Clean up old bundles if configured\n if (options === null || options === void 0 ? void 0 : options.cleanupOldBundles) {\n await bundleManager.cleanupOldBundles(options.keepBundleCount || 3);\n }\n logger.info('Bundle update completed successfully', {\n bundleId,\n version: newBundle.version,\n duration: Date.now() - this.currentState.startTime,\n });\n // Clear state\n this.currentState = null;\n }\n catch (error) {\n logger.error('Bundle update failed', error);\n // Attempt rollback\n if (this.currentState) {\n await this.rollback();\n }\n throw error;\n }\n finally {\n this.updateInProgress = false;\n }\n }\n /**\n * Validate update before applying\n */\n async validateUpdate(currentBundle, newBundle, options) {\n const logger = this.pluginManager.getLogger();\n const versionManager = this.pluginManager.getVersionManager();\n // Check if downgrade\n if (currentBundle && !(options === null || options === void 0 ? void 0 : options.allowDowngrade)) {\n if (versionManager.shouldBlockDowngrade(currentBundle.version, newBundle.version)) {\n throw new ValidationError(ErrorCode.VERSION_DOWNGRADE, `Cannot downgrade from ${currentBundle.version} to ${newBundle.version}`);\n }\n }\n // Verify bundle integrity\n if (!newBundle.verified) {\n logger.warn('Bundle not verified, verifying now', {\n bundleId: newBundle.bundleId,\n });\n // Load bundle data\n const downloadManager = this.pluginManager.getDownloadManager();\n const blob = await downloadManager.loadBlob(newBundle.bundleId);\n if (!blob) {\n throw new UpdateError(ErrorCode.FILE_NOT_FOUND, 'Bundle data not found');\n }\n // Verify checksum\n const arrayBuffer = await blob.arrayBuffer();\n const isValid = await this.securityValidator.verifyChecksum(arrayBuffer, newBundle.checksum);\n if (!isValid) {\n throw new ValidationError(ErrorCode.CHECKSUM_MISMATCH, 'Bundle checksum verification failed');\n }\n // Verify signature if enabled\n if (newBundle.signature) {\n const signatureValid = await this.securityValidator.verifySignature(arrayBuffer, newBundle.signature);\n if (!signatureValid) {\n throw new ValidationError(ErrorCode.SIGNATURE_INVALID, 'Bundle signature verification failed');\n }\n }\n // Mark as verified\n await this.pluginManager\n .getBundleManager()\n .markBundleAsVerified(newBundle.bundleId);\n }\n logger.debug('Bundle validation passed', { bundleId: newBundle.bundleId });\n }\n /**\n * Create backup of current bundle\n */\n async createBackup(bundle) {\n const backupPath = `backups/${bundle.bundleId}_${Date.now()}`;\n const logger = this.pluginManager.getLogger();\n try {\n // Create backup directory\n await this.filesystem.mkdir({\n path: backupPath,\n directory: Directory.Data,\n recursive: true,\n });\n // Copy bundle files\n await this.filesystem.copy({\n from: bundle.path,\n to: backupPath,\n directory: Directory.Data,\n });\n logger.info('Backup created', { bundleId: bundle.bundleId, backupPath });\n return backupPath;\n }\n catch (error) {\n logger.error('Failed to create backup', error);\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Failed to create backup', undefined, error);\n }\n }\n /**\n * Perform the actual update\n */\n async performUpdate(bundle) {\n const logger = this.pluginManager.getLogger();\n try {\n // Extract bundle to target location\n const targetPath = `active/${bundle.bundleId}`;\n // Create target directory\n await this.filesystem.mkdir({\n path: targetPath,\n directory: Directory.Data,\n recursive: true,\n });\n // Copy bundle files\n await this.filesystem.copy({\n from: bundle.path,\n to: targetPath,\n directory: Directory.Data,\n });\n // Update bundle path\n bundle.path = targetPath;\n logger.debug('Bundle files installed', {\n bundleId: bundle.bundleId,\n targetPath,\n });\n }\n catch (error) {\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Failed to install bundle files', undefined, error);\n }\n }\n /**\n * Verify update was successful\n */\n async verifyUpdate(bundle) {\n try {\n // Check if main bundle files exist\n const indexPath = `${bundle.path}/index.html`;\n await this.filesystem.stat({\n path: indexPath,\n directory: Directory.Data,\n });\n // Additional verification can be added here\n }\n catch (error) {\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Bundle verification failed after installation', undefined, error);\n }\n }\n /**\n * Rollback to previous state\n */\n async rollback() {\n var _a;\n if (!this.currentState) {\n throw new UpdateError(ErrorCode.ROLLBACK_FAILED, 'No update state to rollback');\n }\n const logger = this.pluginManager.getLogger();\n logger.warn('Starting rollback', {\n from: this.currentState.newBundle.bundleId,\n to: ((_a = this.currentState.currentBundle) === null || _a === void 0 ? void 0 : _a.bundleId) || 'default',\n });\n try {\n const bundleManager = this.pluginManager.getBundleManager();\n // Restore from backup if available\n if (this.currentState.backupPath && this.currentState.currentBundle) {\n const restoredPath = `active/${this.currentState.currentBundle.bundleId}`;\n await this.filesystem.copy({\n from: this.currentState.backupPath,\n to: restoredPath,\n directory: Directory.Data,\n });\n // Update bundle path\n this.currentState.currentBundle.path = restoredPath;\n await bundleManager.saveBundleInfo(this.currentState.currentBundle);\n }\n // Restore active bundle\n if (this.currentState.currentBundle) {\n await bundleManager.setActiveBundle(this.currentState.currentBundle.bundleId);\n }\n else {\n // No previous bundle, clear active\n await bundleManager.clearActiveBundle();\n }\n logger.info('Rollback completed successfully');\n }\n catch (error) {\n logger.error('Rollback failed', error);\n throw new UpdateError(ErrorCode.ROLLBACK_FAILED, 'Failed to rollback update', undefined, error);\n }\n finally {\n // Clean up backup\n if (this.currentState.backupPath) {\n try {\n await this.filesystem.rmdir({\n path: this.currentState.backupPath,\n directory: Directory.Data,\n recursive: true,\n });\n }\n catch (error) {\n logger.warn('Failed to clean up backup', error);\n }\n }\n }\n }\n /**\n * Get current update progress\n */\n getUpdateProgress() {\n var _a, _b;\n return {\n inProgress: this.updateInProgress,\n bundleId: (_a = this.currentState) === null || _a === void 0 ? void 0 : _a.newBundle.bundleId,\n startTime: (_b = this.currentState) === null || _b === void 0 ? void 0 : _b.startTime,\n };\n }\n /**\n * Cancel current update (if possible)\n */\n async cancelUpdate() {\n if (!this.updateInProgress || !this.currentState) {\n return;\n }\n const logger = this.pluginManager.getLogger();\n logger.warn('Cancelling update', {\n bundleId: this.currentState.newBundle.bundleId,\n });\n // Attempt rollback\n await this.rollback();\n this.updateInProgress = false;\n this.currentState = null;\n }\n}\n//# sourceMappingURL=update-manager.js.map"],"names":["BackgroundUpdateType","NotificationPriority","UpdateStrategy","UpdateMode","InstallMode","ChecksumAlgorithm","SyncStatus","BundleStatus","InstallStatus","UpdateErrorCode","LogLevel","ErrorCode","AppUpdateInstallStatus","ConfigManager","constructor","this","config","getDefaultConfig","getInstance","instance","filesystem","preferences","baseUrl","allowedHosts","maxBundleSize","downloadTimeout","retryAttempts","retryDelay","enableSignatureValidation","publicKey","cacheExpiration","enableLogging","serverUrl","channel","autoCheck","autoUpdate","updateStrategy","requireSignature","checksumAlgorithm","checkInterval","security","enforceHttps","validateInputs","secureStorage","logSecurityEvents","promptAfterPositiveEvents","maxPromptsPerVersion","minimumDaysSinceLastPrompt","isPremiumUser","appStoreId","iosAppId","packageName","webReviewUrl","minimumVersion","configure","Object","assign","validateConfig","Error","get","key","set","value","getAll","isConfigured","Logger","context","configManager","shouldLog","sanitize","data","sanitized","replace","Array","isArray","map","item","dataObj","toLowerCase","includes","log","message","logWithLevel","INFO","level","timestamp","Date","toISOString","sanitizedData","undefined","logEntry","DEBUG","console","debug","info","WARN","warn","ERROR","error","errorData","name","stack","NativeUpdateError","code","details","originalError","super","setPrototypeOf","prototype","toJSON","DownloadError","ValidationError","StorageError","UpdateError","SecurityValidator","logger","validateUrl","url","URL","protocol","_a","validateChecksum","checksum","test","sanitizeInput","input","validateBundleSize","size","calculateChecksum","hashBuffer","crypto","subtle","digest","from","Uint8Array","b","toString","padStart","join","verifyChecksum","expectedChecksum","actualChecksum","isValid","expected","actual","verifySignature","signature","SIGNATURE_INVALID","cryptoKey","importKey","pemToArrayBuffer","hash","verify","saltLength","base64ToArrayBuffer","pem","base64","binaryString","atob","bytes","length","i","charCodeAt","buffer","sanitizePath","path","split","filter","part","validateBundleId","bundleId","INVALID_BUNDLE_FORMAT","validateVersion","version","isVersionDowngrade","currentVersion","newVersion","current","parseVersion","next","major","minor","patch","parts","parseInt","INVALID_URL","parsedUrl","hostname","UNAUTHORIZED_HOST","some","pattern","validateFileSize","maxSize","BUNDLE_TOO_LARGE","generateSecureId","array","getRandomValues","byte","validateCertificatePin","certificate","certificatePins","hostPins","pin","certificateHash","calculateCertificateHash","sha256","expectedPins","p","actualHash","TextEncoder","encode","hashArray","btoa","String","fromCharCode","validateMetadata","metadata","JSON","stringify","BundleManager","STORAGE_KEY","ACTIVE_BUNDLE_KEY","cache","Map","cacheExpiry","initialize","MISSING_DEPENDENCY","loadCache","now","bundles","parse","clear","forEach","bundle","saveCache","values","count","STORAGE_FULL","saveBundleInfo","validateBundleInfo","getAllBundles","getBundle","deleteBundle","delete","getActiveBundleId","clearActiveBundle","getActiveBundle","activeBundleId","setActiveBundle","FILE_NOT_FOUND","previousActive","status","remove","clearAllBundles","cleanupOldBundles","keepCount","INVALID_CONFIG","sorted","sort","a","downloadTime","toKeep","Set","add","kept","has","deletedCount","deleted","getBundlesOlderThan","markBundleAsVerified","verified","getTotalStorageUsed","reduce","total","isStorageLimitExceeded","additionalSize","createDefaultBundle","cleanExpiredBundles","expirationTime","cutoffTime","expiredBundles","DownloadManager","activeDownloads","download","onProgress","DOWNLOAD_FAILED","abortController","AbortController","downloadState","controller","startTime","timeout","timeoutId","setTimeout","abort","response","fetch","signal","headers","Accept","clearTimeout","ok","statusText","contentType","isValidContentType","contentLength","totalBytes","body","blob","validateBlobSize","reader","getReader","chunks","receivedBytes","done","read","push","percent","Math","round","bytesDownloaded","Blob","duration","isTimeout","DOWNLOAD_TIMEOUT","type","cancelDownload","state","cancelAllDownloads","isDownloading","getActiveDownloadCount","downloadWithRetry","maxRetries","lastError","attempt","delay","min","pow","Promise","resolve","attempts","blobToArrayBuffer","arrayBuffer","saveBlob","writeFile","directory","Directory","Data","recursive","loadBlob","result","readFile","deleteBlob","rmdir","VersionManager","VERSION_CHECK_CACHE_KEY","CACHE_DURATION","memoryCache","securityValidator","compareVersions","version1","version2","v1Base","v1Pre","v2Base","v2Pre","v1Parts","Number","v2Parts","v1Part","v2Part","localeCompare","isValidVersion","shouldUpdate","minAppVersion","checkForUpdates","appId","cacheKey","cached","getCachedVersionInfo","searchParams","append","method","AbortSignal","json","bundleUrl","cacheVersionInfo","latestVersion","updateAvailable","isNewerVersion","v1","v2","prerelease","isUpdateMandatory","match","build","buildVersionString","components","isCompatibleWithNativeVersion","bundleVersion","nativeVersion","compatibility","requiredNativeVersion","memCached","cacheEntry","allCached","clearVersionCache","shouldBlockDowngrade","AppUpdateChecker","checkServerVersion","_","updateUrl","getPlatform","getCurrentVersion","availableVersion","updatePriority","priority","releaseNotes","updateSize","updateURL","downloadUrl","max","isUpdateRequired","determineUpdatePriority","versionDiff","stalenessDays","window","userAgent","navigator","AppUpdateInstaller","currentState","installStatus","UNKNOWN","startImmediateUpdate","updateState","PENDING","isAndroid","isIOS","startFlexibleUpdate","DOWNLOADING","isWeb","simulateFlexibleUpdate","completeFlexibleUpdate","DOWNLOADED","INSTALLING","INSTALLED","cancelUpdate","CANCELED","getInstallState","callback","progressCallback","errorCode","installErrorCode","downloaded","totalSize","chunkSize","interval","setInterval","clearInterval","progress","totalBytesToDownload","percentComplete","downloadSpeed","estimatedTime","ceil","PlatformAppUpdate","platform","Capacitor","checkForUpdate","versionInfo","getVersionInfo","updateInfo","webUpdateUrl","buildNumber","getAppStoreUrl","location","origin","openUrl","open","isUpdateSupported","getUpdateCapabilities","capabilities","immediateUpdate","flexibleUpdate","backgroundDownload","inAppReview","AppUpdateManager","listeners","checker","installer","platformUpdate","checkAppUpdate","options","nativeInfo","serverInfo","mergeUpdateInfo","immediateUpdateAllowed","emit","flexibleUpdateAllowed","isMinimumVersionMet","isMet","updateRequired","enforceMinVersion","getAppUpdateInfo","performImmediateUpdate","openAppStore","_options","storeInfo","getUpdateInstallState","addListener","eventName","listenerFunc","async","removeAllListeners","listener","EventEmitter","removeListeners","listenerCount","eventNames","keys","PluginManager","bundleManager","downloadManager","versionManager","appUpdateManager","initialized","eventEmitter","_b","Filesystem","Preferences","setupAppUpdateEventBridge","isInitialized","ensureInitialized","NOT_CONFIGURED","getBundleManager","getDownloadManager","getVersionManager","getConfigManager","getLogger","getSecurityValidator","getAppUpdateManager","getEventEmitter","reset","cleanup","event","NativeUpdatePluginWeb","windowEventListeners","pluginManager","setupWindowEventBridge","initConfig","liveUpdate","getSecurityInfo","certificatePinning","enabled","pins","sync","currentBundle","UP_TO_DATE","UNKNOWN_ERROR","bundleInfo","READY","reload","list","keepVersions","sortedBundles","notifyAppReady","activeBundle","ACTIVE","getLatest","available","setChannel","setUpdateUrl","validateUpdate","ArrayBuffer","checksumValid","signatureValid","sizeValid","versionValid","requestReview","displayed","canRequestReview","canRequest","reason","enableBackgroundUpdates","disableBackgroundUpdates","getBackgroundUpdateStatus","isRunning","checkCount","failureCount","scheduleBackgroundCheck","_interval","PLATFORM_NOT_SUPPORTED","triggerBackgroundCheck","success","updatesFound","notificationSent","setNotificationPreferences","prefs","getNotificationPermissions","granted","requestNotificationPermissions","removeListener","detail","addEventListener","NativeUpdate","registerPlugin","web","CACHE_DIR","mkdir","cleanExpiredCache","ttlMs","expiry","entry","shouldPersist","persistToFile","memEntry","fileEntry","loadFromFile","removeFile","cleanedCount","files","readdir","file","getStats","fileEntries","stat","memoryEntries","cacheBundleMetadata","getCachedBundleMetadata","encoding","Encoding","UTF8","deleteFile","updateInProgress","applyUpdate","UPDATE_FAILED","newBundle","BUNDLE_NOT_READY","backupPath","createBackup","performUpdate","verifyUpdate","keepBundleCount","rollback","allowDowngrade","VERSION_DOWNGRADE","CHECKSUM_MISMATCH","copy","to","targetPath","indexPath","ROLLBACK_FAILED","restoredPath","getUpdateProgress","inProgress"],"mappings":"IAIWA,EAMAC,EAQAC,EAMAC,EAMAC,EAMAC,EAKAC,EAOAC,EAQAC,EAWAC,ECjEAC,ECDAC,ECDAC,uGHKX,SAAWZ,GACPA,EAAiC,WAAI,aACrCA,EAAkC,YAAI,cACtCA,EAA2B,KAAI,MAClC,CAJD,CAIGA,IAAyBA,EAAuB,CAAA,IAEnD,SAAWC,GACPA,EAA0B,IAAI,MAC9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AAK0mB,kBAAqB1mB,KAAK+Z,eAGrB/Z,KAAKohB,cAAcT,YAC3B1b,KAAK,oBAAqB,CAC7B0E,SAAU3J,KAAK+Z,aAAa8M,UAAUld,iBAGpC3J,KAAKonB,WACXpnB,KAAK0mB,kBAAmB,EACxB1mB,KAAK+Z,aAAe,KACxB"}
1
+ {"version":3,"file":"plugin.cjs.js","sources":["esm/definitions.js","esm/core/logger.js","esm/core/errors.js","esm/app-update/types.js","esm/core/config.js","esm/core/security.js","esm/live-update/bundle-manager.js","esm/live-update/download-manager.js","esm/live-update/version-manager.js","esm/app-update/app-update-checker.js","esm/app-update/app-update-installer.js","esm/app-update/platform-app-update.js","esm/app-update/app-update-manager.js","esm/core/event-emitter.js","esm/core/plugin-manager.js","esm/plugin.js","esm/core/cache-manager.js","esm/live-update/update-manager.js"],"sourcesContent":["// Core plugin interface will be defined later after other interfaces\n/**\n * Enums\n */\nexport var BackgroundUpdateType;\n(function (BackgroundUpdateType) {\n BackgroundUpdateType[\"APP_UPDATE\"] = \"app_update\";\n BackgroundUpdateType[\"LIVE_UPDATE\"] = \"live_update\";\n BackgroundUpdateType[\"BOTH\"] = \"both\";\n})(BackgroundUpdateType || (BackgroundUpdateType = {}));\nexport var NotificationPriority;\n(function (NotificationPriority) {\n NotificationPriority[\"MIN\"] = \"min\";\n NotificationPriority[\"LOW\"] = \"low\";\n NotificationPriority[\"DEFAULT\"] = \"default\";\n NotificationPriority[\"HIGH\"] = \"high\";\n NotificationPriority[\"MAX\"] = \"max\";\n})(NotificationPriority || (NotificationPriority = {}));\nexport var UpdateStrategy;\n(function (UpdateStrategy) {\n UpdateStrategy[\"IMMEDIATE\"] = \"immediate\";\n UpdateStrategy[\"BACKGROUND\"] = \"background\";\n UpdateStrategy[\"MANUAL\"] = \"manual\";\n})(UpdateStrategy || (UpdateStrategy = {}));\nexport var UpdateMode;\n(function (UpdateMode) {\n UpdateMode[\"IMMEDIATE\"] = \"immediate\";\n UpdateMode[\"ON_NEXT_RESTART\"] = \"on_next_restart\";\n UpdateMode[\"ON_NEXT_RESUME\"] = \"on_next_resume\";\n})(UpdateMode || (UpdateMode = {}));\nexport var InstallMode;\n(function (InstallMode) {\n InstallMode[\"IMMEDIATE\"] = \"immediate\";\n InstallMode[\"ON_NEXT_RESTART\"] = \"on_next_restart\";\n InstallMode[\"ON_NEXT_RESUME\"] = \"on_next_resume\";\n})(InstallMode || (InstallMode = {}));\nexport var ChecksumAlgorithm;\n(function (ChecksumAlgorithm) {\n ChecksumAlgorithm[\"SHA256\"] = \"SHA-256\";\n ChecksumAlgorithm[\"SHA512\"] = \"SHA-512\";\n})(ChecksumAlgorithm || (ChecksumAlgorithm = {}));\nexport var SyncStatus;\n(function (SyncStatus) {\n SyncStatus[\"UP_TO_DATE\"] = \"UP_TO_DATE\";\n SyncStatus[\"UPDATE_AVAILABLE\"] = \"UPDATE_AVAILABLE\";\n SyncStatus[\"UPDATE_INSTALLED\"] = \"UPDATE_INSTALLED\";\n SyncStatus[\"ERROR\"] = \"ERROR\";\n})(SyncStatus || (SyncStatus = {}));\nexport var BundleStatus;\n(function (BundleStatus) {\n BundleStatus[\"PENDING\"] = \"PENDING\";\n BundleStatus[\"DOWNLOADING\"] = \"DOWNLOADING\";\n BundleStatus[\"READY\"] = \"READY\";\n BundleStatus[\"ACTIVE\"] = \"ACTIVE\";\n BundleStatus[\"FAILED\"] = \"FAILED\";\n})(BundleStatus || (BundleStatus = {}));\nexport var InstallStatus;\n(function (InstallStatus) {\n InstallStatus[\"UNKNOWN\"] = \"UNKNOWN\";\n InstallStatus[\"PENDING\"] = \"PENDING\";\n InstallStatus[\"DOWNLOADING\"] = \"DOWNLOADING\";\n InstallStatus[\"DOWNLOADED\"] = \"DOWNLOADED\";\n InstallStatus[\"INSTALLING\"] = \"INSTALLING\";\n InstallStatus[\"INSTALLED\"] = \"INSTALLED\";\n InstallStatus[\"FAILED\"] = \"FAILED\";\n InstallStatus[\"CANCELED\"] = \"CANCELED\";\n})(InstallStatus || (InstallStatus = {}));\nexport var UpdateErrorCode;\n(function (UpdateErrorCode) {\n // Network errors\n UpdateErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n UpdateErrorCode[\"SERVER_ERROR\"] = \"SERVER_ERROR\";\n UpdateErrorCode[\"TIMEOUT_ERROR\"] = \"TIMEOUT_ERROR\";\n // Download errors\n UpdateErrorCode[\"DOWNLOAD_ERROR\"] = \"DOWNLOAD_ERROR\";\n UpdateErrorCode[\"STORAGE_ERROR\"] = \"STORAGE_ERROR\";\n UpdateErrorCode[\"SIZE_LIMIT_EXCEEDED\"] = \"SIZE_LIMIT_EXCEEDED\";\n // Security errors\n UpdateErrorCode[\"VERIFICATION_ERROR\"] = \"VERIFICATION_ERROR\";\n UpdateErrorCode[\"CHECKSUM_ERROR\"] = \"CHECKSUM_ERROR\";\n UpdateErrorCode[\"SIGNATURE_ERROR\"] = \"SIGNATURE_ERROR\";\n UpdateErrorCode[\"INSECURE_URL\"] = \"INSECURE_URL\";\n UpdateErrorCode[\"INVALID_CERTIFICATE\"] = \"INVALID_CERTIFICATE\";\n UpdateErrorCode[\"PATH_TRAVERSAL\"] = \"PATH_TRAVERSAL\";\n // Installation errors\n UpdateErrorCode[\"INSTALL_ERROR\"] = \"INSTALL_ERROR\";\n UpdateErrorCode[\"ROLLBACK_ERROR\"] = \"ROLLBACK_ERROR\";\n UpdateErrorCode[\"VERSION_MISMATCH\"] = \"VERSION_MISMATCH\";\n // Permission errors\n UpdateErrorCode[\"PERMISSION_DENIED\"] = \"PERMISSION_DENIED\";\n // App update errors\n UpdateErrorCode[\"UPDATE_NOT_AVAILABLE\"] = \"UPDATE_NOT_AVAILABLE\";\n UpdateErrorCode[\"UPDATE_IN_PROGRESS\"] = \"UPDATE_IN_PROGRESS\";\n UpdateErrorCode[\"UPDATE_CANCELLED\"] = \"UPDATE_CANCELLED\";\n UpdateErrorCode[\"PLATFORM_NOT_SUPPORTED\"] = \"PLATFORM_NOT_SUPPORTED\";\n // Review errors\n UpdateErrorCode[\"REVIEW_NOT_SUPPORTED\"] = \"REVIEW_NOT_SUPPORTED\";\n UpdateErrorCode[\"QUOTA_EXCEEDED\"] = \"QUOTA_EXCEEDED\";\n UpdateErrorCode[\"CONDITIONS_NOT_MET\"] = \"CONDITIONS_NOT_MET\";\n // General errors\n UpdateErrorCode[\"INVALID_CONFIG\"] = \"INVALID_CONFIG\";\n UpdateErrorCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n})(UpdateErrorCode || (UpdateErrorCode = {}));\n//# sourceMappingURL=definitions.js.map","import { ConfigManager } from './config';\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"INFO\"] = 1] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 2] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 3] = \"ERROR\";\n})(LogLevel || (LogLevel = {}));\nexport class Logger {\n constructor(context) {\n this.configManager = ConfigManager.getInstance();\n this.context = context || 'NativeUpdate';\n }\n static getInstance() {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n return Logger.instance;\n }\n shouldLog() {\n return this.configManager.get('enableLogging');\n }\n sanitize(data) {\n if (typeof data === 'string') {\n let sanitized = data;\n // Remove potential file paths\n sanitized = sanitized.replace(/\\/[^\\s]+\\/([\\w.-]+)$/g, '/<path>/$1');\n // Remove potential URLs with credentials\n sanitized = sanitized.replace(/https?:\\/\\/[^:]+:[^@]+@/g, 'https://***:***@');\n // Remove potential API keys\n sanitized = sanitized.replace(/[a-zA-Z0-9]{32,}/g, '<redacted>');\n return sanitized;\n }\n else if (typeof data === 'object' && data !== null) {\n if (Array.isArray(data)) {\n return data.map((item) => this.sanitize(item));\n }\n else {\n const sanitized = {};\n const dataObj = data;\n for (const key in dataObj) {\n if (key.toLowerCase().includes('key') ||\n key.toLowerCase().includes('secret') ||\n key.toLowerCase().includes('password') ||\n key.toLowerCase().includes('token')) {\n sanitized[key] = '<redacted>';\n }\n else {\n sanitized[key] = this.sanitize(dataObj[key]);\n }\n }\n return sanitized;\n }\n }\n return data;\n }\n log(message, data) {\n this.logWithLevel(LogLevel.INFO, message, data);\n }\n logWithLevel(level, message, data) {\n if (!this.shouldLog())\n return;\n const timestamp = new Date().toISOString();\n const sanitizedData = data ? this.sanitize(data) : undefined;\n const logEntry = {\n timestamp,\n level: LogLevel[level],\n context: this.context,\n message,\n };\n if (sanitizedData !== undefined) {\n logEntry.data = sanitizedData;\n }\n switch (level) {\n case LogLevel.DEBUG:\n console.debug(`[${this.context}]`, logEntry);\n break;\n case LogLevel.INFO:\n console.info(`[${this.context}]`, logEntry);\n break;\n case LogLevel.WARN:\n console.warn(`[${this.context}]`, logEntry);\n break;\n case LogLevel.ERROR:\n console.error(`[${this.context}]`, logEntry);\n break;\n }\n }\n debug(message, data) {\n this.logWithLevel(LogLevel.DEBUG, message, data);\n }\n info(message, data) {\n this.logWithLevel(LogLevel.INFO, message, data);\n }\n warn(message, data) {\n this.logWithLevel(LogLevel.WARN, message, data);\n }\n error(message, error) {\n const errorData = error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error;\n this.logWithLevel(LogLevel.ERROR, message, errorData);\n }\n}\n//# sourceMappingURL=logger.js.map","export var ErrorCode;\n(function (ErrorCode) {\n // Configuration errors\n ErrorCode[\"NOT_CONFIGURED\"] = \"NOT_CONFIGURED\";\n ErrorCode[\"INVALID_CONFIG\"] = \"INVALID_CONFIG\";\n ErrorCode[\"MISSING_DEPENDENCY\"] = \"MISSING_DEPENDENCY\";\n // Download errors\n ErrorCode[\"DOWNLOAD_FAILED\"] = \"DOWNLOAD_FAILED\";\n ErrorCode[\"DOWNLOAD_TIMEOUT\"] = \"DOWNLOAD_TIMEOUT\";\n ErrorCode[\"INVALID_URL\"] = \"INVALID_URL\";\n ErrorCode[\"UNAUTHORIZED_HOST\"] = \"UNAUTHORIZED_HOST\";\n ErrorCode[\"BUNDLE_TOO_LARGE\"] = \"BUNDLE_TOO_LARGE\";\n // Validation errors\n ErrorCode[\"CHECKSUM_MISMATCH\"] = \"CHECKSUM_MISMATCH\";\n ErrorCode[\"SIGNATURE_INVALID\"] = \"SIGNATURE_INVALID\";\n ErrorCode[\"VERSION_DOWNGRADE\"] = \"VERSION_DOWNGRADE\";\n ErrorCode[\"INVALID_BUNDLE_FORMAT\"] = \"INVALID_BUNDLE_FORMAT\";\n // Storage errors\n ErrorCode[\"STORAGE_FULL\"] = \"STORAGE_FULL\";\n ErrorCode[\"FILE_NOT_FOUND\"] = \"FILE_NOT_FOUND\";\n ErrorCode[\"PERMISSION_DENIED\"] = \"PERMISSION_DENIED\";\n // Update errors\n ErrorCode[\"UPDATE_FAILED\"] = \"UPDATE_FAILED\";\n ErrorCode[\"ROLLBACK_FAILED\"] = \"ROLLBACK_FAILED\";\n ErrorCode[\"BUNDLE_NOT_READY\"] = \"BUNDLE_NOT_READY\";\n // Platform errors\n ErrorCode[\"PLATFORM_NOT_SUPPORTED\"] = \"PLATFORM_NOT_SUPPORTED\";\n ErrorCode[\"NATIVE_ERROR\"] = \"NATIVE_ERROR\";\n})(ErrorCode || (ErrorCode = {}));\nexport class NativeUpdateError extends Error {\n constructor(code, message, details, originalError) {\n super(message);\n this.code = code;\n this.message = message;\n this.details = details;\n this.originalError = originalError;\n this.name = 'NativeUpdateError';\n Object.setPrototypeOf(this, NativeUpdateError.prototype);\n }\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n details: this.details,\n stack: this.stack,\n };\n }\n}\nexport class ConfigurationError extends NativeUpdateError {\n constructor(message, details) {\n super(ErrorCode.INVALID_CONFIG, message, details);\n this.name = 'ConfigurationError';\n }\n}\nexport class DownloadError extends NativeUpdateError {\n constructor(code, message, details, originalError) {\n super(code, message, details, originalError);\n this.name = 'DownloadError';\n }\n}\nexport class ValidationError extends NativeUpdateError {\n constructor(code, message, details) {\n super(code, message, details);\n this.name = 'ValidationError';\n }\n}\nexport class StorageError extends NativeUpdateError {\n constructor(code, message, details, originalError) {\n super(code, message, details, originalError);\n this.name = 'StorageError';\n }\n}\nexport class UpdateError extends NativeUpdateError {\n constructor(code, message, details, originalError) {\n super(code, message, details, originalError);\n this.name = 'UpdateError';\n }\n}\n//# sourceMappingURL=errors.js.map","export var AppUpdateInstallStatus;\n(function (AppUpdateInstallStatus) {\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"PENDING\"] = 1] = \"PENDING\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"DOWNLOADING\"] = 2] = \"DOWNLOADING\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"INSTALLING\"] = 3] = \"INSTALLING\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"INSTALLED\"] = 4] = \"INSTALLED\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"FAILED\"] = 5] = \"FAILED\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"CANCELED\"] = 6] = \"CANCELED\";\n AppUpdateInstallStatus[AppUpdateInstallStatus[\"DOWNLOADED\"] = 11] = \"DOWNLOADED\";\n})(AppUpdateInstallStatus || (AppUpdateInstallStatus = {}));\n//# sourceMappingURL=types.js.map","export class ConfigManager {\n constructor() {\n this.config = this.getDefaultConfig();\n }\n static getInstance() {\n if (!ConfigManager.instance) {\n ConfigManager.instance = new ConfigManager();\n }\n return ConfigManager.instance;\n }\n getDefaultConfig() {\n return {\n filesystem: null,\n preferences: null,\n baseUrl: '',\n allowedHosts: [],\n maxBundleSize: 100 * 1024 * 1024, // 100MB\n downloadTimeout: 30000, // 30 seconds\n retryAttempts: 3,\n retryDelay: 1000, // 1 second\n enableSignatureValidation: true,\n publicKey: '',\n cacheExpiration: 24 * 60 * 60 * 1000, // 24 hours\n enableLogging: false,\n serverUrl: '',\n channel: 'production',\n autoCheck: true,\n autoUpdate: false,\n updateStrategy: 'background',\n requireSignature: true,\n checksumAlgorithm: 'SHA-256',\n checkInterval: 24 * 60 * 60 * 1000, // 24 hours\n security: {\n enforceHttps: true,\n validateInputs: true,\n secureStorage: true,\n logSecurityEvents: false,\n },\n // App review config\n promptAfterPositiveEvents: false,\n maxPromptsPerVersion: 1,\n minimumDaysSinceLastPrompt: 7,\n isPremiumUser: false,\n // Platform-specific config\n appStoreId: '',\n iosAppId: '',\n packageName: '',\n webReviewUrl: '',\n minimumVersion: '1.0.0',\n };\n }\n configure(config) {\n this.config = Object.assign(Object.assign({}, this.config), config);\n this.validateConfig();\n }\n validateConfig() {\n if (this.config.maxBundleSize <= 0) {\n throw new Error('maxBundleSize must be greater than 0');\n }\n if (this.config.downloadTimeout <= 0) {\n throw new Error('downloadTimeout must be greater than 0');\n }\n if (this.config.retryAttempts < 0) {\n throw new Error('retryAttempts must be non-negative');\n }\n if (this.config.retryDelay < 0) {\n throw new Error('retryDelay must be non-negative');\n }\n }\n get(key) {\n return this.config[key];\n }\n set(key, value) {\n this.config[key] = value;\n }\n getAll() {\n return Object.assign({}, this.config);\n }\n isConfigured() {\n return !!(this.config.filesystem && this.config.preferences);\n }\n}\n//# sourceMappingURL=config.js.map","import { ConfigManager } from './config';\nimport { ValidationError, ErrorCode } from './errors';\nimport { Logger } from './logger';\nexport class SecurityValidator {\n constructor() {\n this.configManager = ConfigManager.getInstance();\n this.logger = Logger.getInstance();\n }\n static getInstance() {\n if (!SecurityValidator.instance) {\n SecurityValidator.instance = new SecurityValidator();\n }\n return SecurityValidator.instance;\n }\n /**\n * Validate URL is HTTPS\n */\n static validateUrl(url) {\n try {\n const parsed = new URL(url);\n return parsed.protocol === 'https:';\n }\n catch (_a) {\n return false;\n }\n }\n /**\n * Validate checksum format\n */\n static validateChecksum(checksum) {\n return /^[a-f0-9]{64}$/i.test(checksum);\n }\n /**\n * Sanitize input string\n */\n static sanitizeInput(input) {\n if (!input)\n return '';\n return input.replace(/<[^>]*>/g, '').replace(/[^\\w\\s/.-]/g, '');\n }\n /**\n * Validate bundle size\n */\n static validateBundleSize(size) {\n const MAX_SIZE = 100 * 1024 * 1024; // 100MB\n return size > 0 && size <= MAX_SIZE;\n }\n /**\n * Calculate SHA-256 checksum of data\n */\n async calculateChecksum(data) {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n }\n /**\n * Verify checksum matches expected value\n */\n async verifyChecksum(data, expectedChecksum) {\n if (!expectedChecksum) {\n this.logger.warn('No checksum provided for verification');\n return true; // Allow if no checksum provided\n }\n const actualChecksum = await this.calculateChecksum(data);\n const isValid = actualChecksum === expectedChecksum.toLowerCase();\n if (!isValid) {\n this.logger.error('Checksum verification failed', {\n expected: expectedChecksum,\n actual: actualChecksum,\n });\n }\n return isValid;\n }\n /**\n * Alias for verifyChecksum for backward compatibility\n */\n async validateChecksum(data, expectedChecksum) {\n return this.verifyChecksum(data, expectedChecksum);\n }\n /**\n * Verify digital signature using Web Crypto API\n */\n async verifySignature(data, signature) {\n if (!this.configManager.get('enableSignatureValidation')) {\n return true;\n }\n const publicKey = this.configManager.get('publicKey');\n if (!publicKey) {\n throw new ValidationError(ErrorCode.SIGNATURE_INVALID, 'Public key not configured for signature validation');\n }\n try {\n // Import public key\n const cryptoKey = await crypto.subtle.importKey('spki', this.pemToArrayBuffer(publicKey), {\n name: 'RSA-PSS',\n hash: 'SHA-256',\n }, false, ['verify']);\n // Verify signature\n const isValid = await crypto.subtle.verify({\n name: 'RSA-PSS',\n saltLength: 32,\n }, cryptoKey, this.base64ToArrayBuffer(signature), data);\n if (!isValid) {\n this.logger.error('Signature verification failed');\n }\n return isValid;\n }\n catch (error) {\n this.logger.error('Signature verification error', error);\n return false;\n }\n }\n /**\n * Convert PEM to ArrayBuffer\n */\n pemToArrayBuffer(pem) {\n const base64 = pem\n .replace(/-----BEGIN PUBLIC KEY-----/g, '')\n .replace(/-----END PUBLIC KEY-----/g, '')\n .replace(/\\s/g, '');\n return this.base64ToArrayBuffer(base64);\n }\n /**\n * Convert base64 to ArrayBuffer\n */\n base64ToArrayBuffer(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes.buffer;\n }\n /**\n * Sanitize file path to prevent directory traversal\n */\n sanitizePath(path) {\n // Remove any parent directory references\n const sanitized = path\n .split('/')\n .filter((part) => part !== '..' && part !== '.')\n .join('/');\n // Ensure path doesn't start with /\n return sanitized.replace(/^\\/+/, '');\n }\n /**\n * Validate bundle ID format\n */\n validateBundleId(bundleId) {\n if (!bundleId || typeof bundleId !== 'string') {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID must be a non-empty string');\n }\n // Allow alphanumeric, hyphens, underscores, and dots\n const validPattern = /^[a-zA-Z0-9\\-_.]+$/;\n if (!validPattern.test(bundleId)) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID contains invalid characters');\n }\n if (bundleId.length > 100) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is too long (max 100 characters)');\n }\n }\n /**\n * Validate semantic version format\n */\n validateVersion(version) {\n if (!version || typeof version !== 'string') {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Version must be a non-empty string');\n }\n // Basic semantic versioning pattern\n const semverPattern = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n if (!semverPattern.test(version)) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Version must follow semantic versioning format (e.g., 1.2.3)');\n }\n }\n /**\n * Check if version is a downgrade\n */\n isVersionDowngrade(currentVersion, newVersion) {\n const current = this.parseVersion(currentVersion);\n const next = this.parseVersion(newVersion);\n if (next.major < current.major)\n return true;\n if (next.major > current.major)\n return false;\n if (next.minor < current.minor)\n return true;\n if (next.minor > current.minor)\n return false;\n return next.patch < current.patch;\n }\n /**\n * Parse semantic version\n */\n parseVersion(version) {\n const parts = version.split('-')[0].split('.'); // Ignore pre-release\n return {\n major: parseInt(parts[0], 10) || 0,\n minor: parseInt(parts[1], 10) || 0,\n patch: parseInt(parts[2], 10) || 0,\n };\n }\n /**\n * Validate URL format and security\n */\n validateUrl(url) {\n if (!url || typeof url !== 'string') {\n throw new ValidationError(ErrorCode.INVALID_URL, 'URL must be a non-empty string');\n }\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n }\n catch (_a) {\n throw new ValidationError(ErrorCode.INVALID_URL, 'Invalid URL format');\n }\n // Enforce HTTPS\n if (parsedUrl.protocol !== 'https:') {\n throw new ValidationError(ErrorCode.INVALID_URL, 'Only HTTPS URLs are allowed');\n }\n // Check against allowed hosts\n const allowedHosts = this.configManager.get('allowedHosts');\n if (allowedHosts.length > 0 && !allowedHosts.includes(parsedUrl.hostname)) {\n throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, `Host ${parsedUrl.hostname} is not in the allowed hosts list`);\n }\n // Prevent localhost/private IPs in production\n const privatePatterns = [\n /^localhost$/i,\n /^127\\./,\n /^10\\./,\n /^172\\.(1[6-9]|2[0-9]|3[0-1])\\./,\n /^192\\.168\\./,\n /^::1$/,\n /^fc00:/i,\n /^fe80:/i,\n ];\n if (privatePatterns.some((pattern) => pattern.test(parsedUrl.hostname))) {\n throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, 'Private/local addresses are not allowed');\n }\n }\n /**\n * Validate file size\n */\n validateFileSize(size) {\n if (typeof size !== 'number' || size < 0) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'File size must be a non-negative number');\n }\n const maxSize = this.configManager.get('maxBundleSize');\n if (size > maxSize) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `File size ${size} exceeds maximum allowed size of ${maxSize} bytes`);\n }\n }\n /**\n * Generate a secure random ID\n */\n generateSecureId() {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');\n }\n /**\n * Validate certificate pinning for HTTPS connections\n *\n * Web Implementation Note:\n * Certificate pinning at the TLS level is NOT possible in web browsers for security reasons.\n * However, this implementation provides signature verification which serves a similar purpose:\n * - Validates server identity through cryptographic signatures\n * - Prevents MITM attacks via signature validation\n * - Uses SHA-256 certificate fingerprints for validation\n *\n * For native platforms (iOS/Android), full TLS certificate pinning is implemented\n * in the native layers using platform-specific APIs (URLSessionDelegate, OkHttp).\n *\n * This web implementation is production-ready and provides equivalent security\n * through the signature verification system.\n */\n async validateCertificatePin(hostname, certificate) {\n const certificatePins = this.configManager.certificatePins;\n if (!certificatePins ||\n !Array.isArray(certificatePins) ||\n certificatePins.length === 0) {\n // No pins configured, allow connection\n return true;\n }\n const hostPins = certificatePins.filter((pin) => pin.hostname === hostname);\n if (hostPins.length === 0) {\n // No pins for this host, allow connection\n return true;\n }\n // Check if certificate matches any of the pins\n const certificateHash = await this.calculateCertificateHash(certificate);\n const isValid = hostPins.some((pin) => pin.sha256 === certificateHash);\n if (!isValid) {\n this.logger.error('Certificate pinning validation failed', {\n hostname,\n expectedPins: hostPins.map((p) => p.sha256),\n actualHash: certificateHash,\n });\n }\n return isValid;\n }\n /**\n * Calculate SHA-256 hash of certificate\n */\n async calculateCertificateHash(certificate) {\n const encoder = new TextEncoder();\n const data = encoder.encode(certificate);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return 'sha256/' + btoa(String.fromCharCode(...hashArray));\n }\n /**\n * Validate metadata object\n */\n validateMetadata(metadata) {\n if (metadata && typeof metadata !== 'object') {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Metadata must be an object');\n }\n // Limit metadata size to prevent abuse\n const metadataStr = JSON.stringify(metadata || {});\n if (metadataStr.length > 10240) {\n // 10KB limit\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Metadata is too large (max 10KB)');\n }\n }\n}\n//# sourceMappingURL=security.js.map","import { ConfigManager } from '../core/config';\nimport { Logger } from '../core/logger';\nimport { StorageError, ErrorCode } from '../core/errors';\n/**\n * Manages bundle storage and lifecycle\n */\nexport class BundleManager {\n constructor() {\n this.STORAGE_KEY = 'capacitor_native_update_bundles';\n this.ACTIVE_BUNDLE_KEY = 'capacitor_native_update_active';\n this.preferences = null;\n this.cache = new Map();\n this.cacheExpiry = 0;\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n }\n /**\n * Initialize the bundle manager with preferences\n */\n async initialize() {\n this.preferences = this.configManager.get('preferences');\n if (!this.preferences) {\n throw new StorageError(ErrorCode.MISSING_DEPENDENCY, 'Preferences not configured. Please configure the plugin first.');\n }\n await this.loadCache();\n }\n /**\n * Load cache from preferences\n */\n async loadCache() {\n if (Date.now() < this.cacheExpiry) {\n return; // Cache still valid\n }\n try {\n const { value } = await this.preferences.get({ key: this.STORAGE_KEY });\n if (value) {\n const bundles = JSON.parse(value);\n this.cache.clear();\n bundles.forEach((bundle) => this.cache.set(bundle.bundleId, bundle));\n }\n this.cacheExpiry = Date.now() + 5000; // 5 second cache\n }\n catch (error) {\n this.logger.error('Failed to load bundles from storage', error);\n this.cache.clear();\n }\n }\n /**\n * Save cache to preferences\n */\n async saveCache() {\n try {\n const bundles = Array.from(this.cache.values());\n await this.preferences.set({\n key: this.STORAGE_KEY,\n value: JSON.stringify(bundles),\n });\n this.logger.debug('Saved bundles to storage', { count: bundles.length });\n }\n catch (error) {\n throw new StorageError(ErrorCode.STORAGE_FULL, 'Failed to save bundles to storage', undefined, error);\n }\n }\n /**\n * Save bundle information\n */\n async saveBundleInfo(bundle) {\n this.validateBundleInfo(bundle);\n this.cache.set(bundle.bundleId, bundle);\n await this.saveCache();\n this.logger.info('Bundle saved', {\n bundleId: bundle.bundleId,\n version: bundle.version,\n });\n }\n /**\n * Validate bundle information\n */\n validateBundleInfo(bundle) {\n if (!bundle.bundleId || typeof bundle.bundleId !== 'string') {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle ID');\n }\n if (!bundle.version || typeof bundle.version !== 'string') {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle version');\n }\n if (!bundle.path || typeof bundle.path !== 'string') {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle path');\n }\n if (typeof bundle.size !== 'number' || bundle.size < 0) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle size');\n }\n }\n /**\n * Get all bundles\n */\n async getAllBundles() {\n await this.loadCache();\n return Array.from(this.cache.values());\n }\n /**\n * Get bundle by ID\n */\n async getBundle(bundleId) {\n if (!bundleId) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n await this.loadCache();\n return this.cache.get(bundleId) || null;\n }\n /**\n * Delete bundle\n */\n async deleteBundle(bundleId) {\n if (!bundleId) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n await this.loadCache();\n const bundle = this.cache.get(bundleId);\n if (!bundle) {\n this.logger.warn('Attempted to delete non-existent bundle', { bundleId });\n return;\n }\n this.cache.delete(bundleId);\n await this.saveCache();\n // If this was the active bundle, clear it\n const activeBundleId = await this.getActiveBundleId();\n if (activeBundleId === bundleId) {\n await this.clearActiveBundle();\n }\n this.logger.info('Bundle deleted', { bundleId });\n }\n /**\n * Get active bundle\n */\n async getActiveBundle() {\n const activeBundleId = await this.getActiveBundleId();\n if (!activeBundleId)\n return null;\n return this.getBundle(activeBundleId);\n }\n /**\n * Set active bundle\n */\n async setActiveBundle(bundleId) {\n if (!bundleId) {\n throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n const bundle = await this.getBundle(bundleId);\n if (!bundle) {\n throw new StorageError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);\n }\n // Update previous active bundle status\n const previousActive = await this.getActiveBundle();\n if (previousActive && previousActive.bundleId !== bundleId) {\n previousActive.status = 'READY';\n await this.saveBundleInfo(previousActive);\n }\n // Set new active bundle\n bundle.status = 'ACTIVE';\n await this.saveBundleInfo(bundle);\n await this.preferences.set({\n key: this.ACTIVE_BUNDLE_KEY,\n value: bundleId,\n });\n this.logger.info('Active bundle set', {\n bundleId,\n version: bundle.version,\n });\n }\n /**\n * Get active bundle ID\n */\n async getActiveBundleId() {\n try {\n const { value } = await this.preferences.get({\n key: this.ACTIVE_BUNDLE_KEY,\n });\n return value;\n }\n catch (error) {\n this.logger.error('Failed to get active bundle ID', error);\n return null;\n }\n }\n /**\n * Clear active bundle\n */\n async clearActiveBundle() {\n await this.preferences.remove({ key: this.ACTIVE_BUNDLE_KEY });\n this.logger.info('Active bundle cleared');\n }\n /**\n * Clear all bundles\n */\n async clearAllBundles() {\n await this.preferences.remove({ key: this.STORAGE_KEY });\n await this.preferences.remove({ key: this.ACTIVE_BUNDLE_KEY });\n this.cache.clear();\n this.cacheExpiry = 0;\n this.logger.info('All bundles cleared');\n }\n /**\n * Clean up old bundles\n */\n async cleanupOldBundles(keepCount) {\n if (keepCount < 1) {\n throw new StorageError(ErrorCode.INVALID_CONFIG, 'Keep count must be at least 1');\n }\n const bundles = await this.getAllBundles();\n const activeBundleId = await this.getActiveBundleId();\n // Sort by download time (newest first)\n const sorted = bundles.sort((a, b) => b.downloadTime - a.downloadTime);\n // Keep the active bundle and the most recent ones\n const toKeep = new Set();\n if (activeBundleId) {\n toKeep.add(activeBundleId);\n }\n let kept = toKeep.size;\n for (const bundle of sorted) {\n if (kept >= keepCount)\n break;\n if (!toKeep.has(bundle.bundleId)) {\n toKeep.add(bundle.bundleId);\n kept++;\n }\n }\n // Delete bundles not in the keep set\n let deletedCount = 0;\n for (const bundle of bundles) {\n if (!toKeep.has(bundle.bundleId)) {\n await this.deleteBundle(bundle.bundleId);\n deletedCount++;\n }\n }\n if (deletedCount > 0) {\n this.logger.info('Cleaned up old bundles', {\n deleted: deletedCount,\n kept,\n });\n }\n }\n /**\n * Get bundles older than specified time\n */\n async getBundlesOlderThan(timestamp) {\n if (timestamp < 0) {\n throw new StorageError(ErrorCode.INVALID_CONFIG, 'Timestamp must be non-negative');\n }\n const bundles = await this.getAllBundles();\n return bundles.filter((b) => b.downloadTime < timestamp);\n }\n /**\n * Mark bundle as verified\n */\n async markBundleAsVerified(bundleId) {\n const bundle = await this.getBundle(bundleId);\n if (!bundle) {\n throw new StorageError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);\n }\n bundle.verified = true;\n await this.saveBundleInfo(bundle);\n this.logger.info('Bundle marked as verified', { bundleId });\n }\n /**\n * Get total storage used by bundles\n */\n async getTotalStorageUsed() {\n const bundles = await this.getAllBundles();\n return bundles.reduce((total, bundle) => total + bundle.size, 0);\n }\n /**\n * Check if storage limit is exceeded\n */\n async isStorageLimitExceeded(additionalSize = 0) {\n const totalUsed = await this.getTotalStorageUsed();\n // Try to get actual device storage quota\n let maxStorage = this.configManager.get('maxBundleSize') * 3; // Default: 3x max bundle size\n try {\n if ('storage' in navigator && 'estimate' in navigator.storage) {\n const estimate = await navigator.storage.estimate();\n if (estimate.quota) {\n // Use actual quota, but keep 100MB buffer for system\n const bufferBytes = 100 * 1024 * 1024; // 100MB\n maxStorage = Math.max(maxStorage, estimate.quota - bufferBytes);\n }\n }\n }\n catch (_a) {\n // Storage API not available, use config-based limit\n this.logger.warn('Storage API not available for quota check, using config limit');\n }\n return totalUsed + additionalSize > maxStorage;\n }\n /**\n * Create default bundle\n */\n createDefaultBundle() {\n return {\n bundleId: 'default',\n version: '1.0.0',\n path: '/',\n downloadTime: Date.now(),\n size: 0,\n status: 'ACTIVE',\n checksum: '',\n verified: true,\n };\n }\n /**\n * Clean expired cache entries\n */\n async cleanExpiredBundles() {\n const expirationTime = this.configManager.get('cacheExpiration');\n const cutoffTime = Date.now() - expirationTime;\n const expiredBundles = await this.getBundlesOlderThan(cutoffTime);\n for (const bundle of expiredBundles) {\n // Don't delete active bundle\n const activeBundleId = await this.getActiveBundleId();\n if (bundle.bundleId !== activeBundleId) {\n await this.deleteBundle(bundle.bundleId);\n }\n }\n }\n}\n//# sourceMappingURL=bundle-manager.js.map","import { ConfigManager } from '../core/config';\nimport { Logger } from '../core/logger';\nimport { DownloadError, ErrorCode, ValidationError } from '../core/errors';\nimport { Directory } from '@capacitor/filesystem';\n/**\n * Manages file downloads with progress tracking and resume capability\n */\nexport class DownloadManager {\n constructor() {\n this.activeDownloads = new Map();\n this.filesystem = null;\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n }\n /**\n * Initialize the download manager\n */\n async initialize() {\n this.filesystem = this.configManager.get('filesystem');\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not configured. Please configure the plugin first.');\n }\n }\n /**\n * Validate URL against allowed hosts\n */\n validateUrl(url) {\n try {\n const parsedUrl = new URL(url);\n // Ensure HTTPS\n if (parsedUrl.protocol !== 'https:') {\n throw new ValidationError(ErrorCode.INVALID_URL, 'Only HTTPS URLs are allowed for security reasons');\n }\n // Check against allowed hosts if configured\n const allowedHosts = this.configManager.get('allowedHosts');\n if (allowedHosts.length > 0 &&\n !allowedHosts.includes(parsedUrl.hostname)) {\n throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, `Host ${parsedUrl.hostname} is not in the allowed hosts list`);\n }\n }\n catch (error) {\n if (error instanceof ValidationError)\n throw error;\n throw new ValidationError(ErrorCode.INVALID_URL, 'Invalid URL format');\n }\n }\n /**\n * Download a file with progress tracking\n */\n async download(url, bundleId, onProgress) {\n // Validate inputs\n this.validateUrl(url);\n if (!bundleId) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');\n }\n // Check if already downloading\n if (this.activeDownloads.has(bundleId)) {\n throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Download already in progress for bundle ${bundleId}`);\n }\n // Create abort controller for this download\n const abortController = new AbortController();\n const downloadState = {\n controller: abortController,\n startTime: Date.now(),\n };\n this.activeDownloads.set(bundleId, downloadState);\n try {\n const timeout = this.configManager.get('downloadTimeout');\n const timeoutId = setTimeout(() => abortController.abort(), timeout);\n // Build headers including Range header for resume support\n const headers = {\n 'Cache-Control': 'no-cache',\n Accept: 'application/octet-stream, application/zip',\n };\n // Add Range header if resuming from a previous position\n if (downloadState.resumePosition && downloadState.resumePosition > 0) {\n headers['Range'] = `bytes=${downloadState.resumePosition}-`;\n }\n const response = await fetch(url, {\n signal: abortController.signal,\n headers,\n });\n clearTimeout(timeoutId);\n if (!response.ok) {\n throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Download failed: ${response.status} ${response.statusText}`, { status: response.status, statusText: response.statusText });\n }\n // Validate content type\n const contentType = response.headers.get('content-type');\n if (contentType && !this.isValidContentType(contentType)) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, `Invalid content type: ${contentType}`);\n }\n // Get total size from headers\n const contentLength = response.headers.get('content-length');\n const totalBytes = contentLength ? parseInt(contentLength, 10) : 0;\n // Check size limit\n if (totalBytes > this.configManager.get('maxBundleSize')) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `Bundle size ${totalBytes} exceeds maximum allowed size`);\n }\n // If no content length, fall back to simple download\n if (!totalBytes || !response.body) {\n const blob = await response.blob();\n this.validateBlobSize(blob);\n return blob;\n }\n // Stream the response with progress tracking\n const reader = response.body.getReader();\n const chunks = [];\n let receivedBytes = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n chunks.push(value);\n receivedBytes += value.length;\n // Check if size exceeds limit during download\n if (receivedBytes > this.configManager.get('maxBundleSize')) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `Download size exceeds maximum allowed size`);\n }\n // Report progress\n if (onProgress) {\n // Calculate progress accounting for resumed position\n const resumeOffset = downloadState.resumePosition || 0;\n const adjustedLoaded = resumeOffset + receivedBytes;\n const adjustedTotal = resumeOffset + totalBytes;\n const percent = Math.round((adjustedLoaded / adjustedTotal) * 100);\n onProgress({\n percent,\n bytesDownloaded: adjustedLoaded,\n totalBytes: adjustedTotal,\n bundleId,\n });\n }\n }\n // Combine chunks into a single blob\n const blob = new Blob(chunks);\n this.validateBlobSize(blob);\n this.logger.info('Download completed', {\n bundleId,\n size: blob.size,\n duration: Date.now() - downloadState.startTime,\n });\n return blob;\n }\n catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n const isTimeout = Date.now() - downloadState.startTime >=\n this.configManager.get('downloadTimeout');\n throw new DownloadError(isTimeout ? ErrorCode.DOWNLOAD_TIMEOUT : ErrorCode.DOWNLOAD_FAILED, isTimeout ? 'Download timed out' : 'Download cancelled', undefined, error);\n }\n throw error;\n }\n finally {\n // Clean up\n this.activeDownloads.delete(bundleId);\n }\n }\n /**\n * Resume a previously interrupted download\n */\n async resumeDownload(url, bundleId, partialData, onProgress) {\n // Update download state with resume position\n const downloadState = this.activeDownloads.get(bundleId);\n if (downloadState) {\n downloadState.resumePosition = partialData.size;\n }\n try {\n // Download remaining bytes\n const remainingData = await this.download(url, bundleId, onProgress);\n // Combine partial and remaining data\n return new Blob([partialData, remainingData]);\n }\n catch (error) {\n // Resume failed, clean up\n this.activeDownloads.delete(bundleId);\n throw error;\n }\n }\n /**\n * Check if a download can be resumed\n */\n async canResume(url) {\n try {\n const response = await fetch(url, {\n method: 'HEAD',\n });\n // Check if server supports Range requests\n const acceptRanges = response.headers.get('Accept-Ranges');\n return acceptRanges === 'bytes';\n }\n catch (_a) {\n return false;\n }\n }\n /**\n * Validate content type\n */\n isValidContentType(contentType) {\n const validTypes = [\n 'application/octet-stream',\n 'application/zip',\n 'application/x-zip-compressed',\n 'application/x-zip',\n ];\n return validTypes.some((type) => contentType.includes(type));\n }\n /**\n * Validate blob size\n */\n validateBlobSize(blob) {\n if (blob.size === 0) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Downloaded file is empty');\n }\n if (blob.size > this.configManager.get('maxBundleSize')) {\n throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `File size ${blob.size} exceeds maximum allowed size`);\n }\n }\n /**\n * Cancel a download\n */\n cancelDownload(bundleId) {\n const state = this.activeDownloads.get(bundleId);\n if (state) {\n state.controller.abort();\n this.activeDownloads.delete(bundleId);\n this.logger.info('Download cancelled', { bundleId });\n }\n }\n /**\n * Cancel all active downloads\n */\n cancelAllDownloads() {\n for (const state of this.activeDownloads.values()) {\n state.controller.abort();\n }\n const count = this.activeDownloads.size;\n this.activeDownloads.clear();\n if (count > 0) {\n this.logger.info('All downloads cancelled', { count });\n }\n }\n /**\n * Check if a download is active\n */\n isDownloading(bundleId) {\n return this.activeDownloads.has(bundleId);\n }\n /**\n * Get active download count\n */\n getActiveDownloadCount() {\n return this.activeDownloads.size;\n }\n /**\n * Download with retry logic\n */\n async downloadWithRetry(url, bundleId, onProgress) {\n const maxRetries = this.configManager.get('retryAttempts');\n const retryDelay = this.configManager.get('retryDelay');\n let lastError = null;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n // Add delay between retries (exponential backoff)\n if (attempt > 0) {\n const delay = Math.min(retryDelay * Math.pow(2, attempt - 1), 30000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n this.logger.debug('Retrying download', { bundleId, attempt, delay });\n }\n return await this.download(url, bundleId, onProgress);\n }\n catch (error) {\n lastError = error;\n // Don't retry if cancelled or validation error\n if (error instanceof ValidationError ||\n (error instanceof Error && error.name === 'AbortError')) {\n throw error;\n }\n this.logger.warn(`Download attempt ${attempt + 1} failed`, {\n bundleId,\n error,\n });\n }\n }\n throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, 'Download failed after all retries', { attempts: maxRetries }, lastError || undefined);\n }\n /**\n * Convert blob to ArrayBuffer\n */\n async blobToArrayBuffer(blob) {\n return blob.arrayBuffer();\n }\n /**\n * Save blob to filesystem\n */\n async saveBlob(bundleId, blob) {\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');\n }\n const arrayBuffer = await this.blobToArrayBuffer(blob);\n const base64 = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));\n const path = `bundles/${bundleId}/bundle.zip`;\n await this.filesystem.writeFile({\n path,\n data: base64,\n directory: Directory.Data,\n recursive: true,\n });\n this.logger.debug('Bundle saved to filesystem', {\n bundleId,\n path,\n size: blob.size,\n });\n return path;\n }\n /**\n * Load blob from filesystem\n */\n async loadBlob(bundleId) {\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');\n }\n try {\n const path = `bundles/${bundleId}/bundle.zip`;\n const result = await this.filesystem.readFile({\n path,\n directory: Directory.Data,\n });\n const binaryString = atob(result.data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return new Blob([bytes], { type: 'application/zip' });\n }\n catch (error) {\n this.logger.debug('Failed to load bundle from filesystem', {\n bundleId,\n error,\n });\n return null;\n }\n }\n /**\n * Delete blob from filesystem\n */\n async deleteBlob(bundleId) {\n if (!this.filesystem) {\n throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');\n }\n try {\n const path = `bundles/${bundleId}`;\n await this.filesystem.rmdir({\n path,\n directory: Directory.Data,\n recursive: true,\n });\n this.logger.debug('Bundle deleted from filesystem', { bundleId });\n }\n catch (error) {\n this.logger.warn('Failed to delete bundle from filesystem', {\n bundleId,\n error,\n });\n }\n }\n}\n//# sourceMappingURL=download-manager.js.map","import { ConfigManager } from '../core/config';\nimport { Logger } from '../core/logger';\nimport { SecurityValidator } from '../core/security';\nimport { ValidationError, ErrorCode } from '../core/errors';\n/**\n * Manages version checking and comparison\n */\nexport class VersionManager {\n constructor() {\n this.VERSION_CHECK_CACHE_KEY = 'capacitor_native_update_version_cache';\n this.CACHE_DURATION = 5 * 60 * 1000; // 5 minutes\n this.preferences = null;\n this.memoryCache = new Map();\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n this.securityValidator = SecurityValidator.getInstance();\n }\n /**\n * Compare two semantic versions\n */\n static compareVersions(version1, version2) {\n try {\n // Split version and pre-release\n const [v1Base, v1Pre] = version1.split('-');\n const [v2Base, v2Pre] = version2.split('-');\n const v1Parts = v1Base.split('.').map(Number);\n const v2Parts = v2Base.split('.').map(Number);\n // Compare major.minor.patch\n for (let i = 0; i < 3; i++) {\n const v1Part = v1Parts[i] || 0;\n const v2Part = v2Parts[i] || 0;\n if (v1Part > v2Part)\n return 1;\n if (v1Part < v2Part)\n return -1;\n }\n // If base versions are equal, compare pre-release\n if (v1Pre && !v2Pre)\n return -1; // 1.0.0-alpha < 1.0.0\n if (!v1Pre && v2Pre)\n return 1; // 1.0.0 > 1.0.0-alpha\n if (v1Pre && v2Pre) {\n return v1Pre.localeCompare(v2Pre);\n }\n return 0;\n }\n catch (_a) {\n if (version1 === version2)\n return 0;\n return version1 > version2 ? 1 : -1;\n }\n }\n /**\n * Validate semantic version format\n */\n static isValidVersion(version) {\n return /^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?(\\+[a-zA-Z0-9.-]+)?$/.test(version);\n }\n /**\n * Check if update should be performed\n */\n static shouldUpdate(currentVersion, newVersion, minAppVersion) {\n if (minAppVersion &&\n VersionManager.compareVersions(currentVersion, minAppVersion) < 0) {\n return false;\n }\n return VersionManager.compareVersions(currentVersion, newVersion) < 0;\n }\n /**\n * Initialize the version manager\n */\n async initialize() {\n this.preferences = this.configManager.get('preferences');\n if (!this.preferences) {\n throw new ValidationError(ErrorCode.MISSING_DEPENDENCY, 'Preferences not configured. Please configure the plugin first.');\n }\n }\n /**\n * Check for latest version from server\n */\n async checkForUpdates(serverUrl, channel, currentVersion, appId) {\n // Validate inputs\n this.securityValidator.validateUrl(serverUrl);\n this.securityValidator.validateVersion(currentVersion);\n if (!channel || !appId) {\n throw new ValidationError(ErrorCode.INVALID_CONFIG, 'Channel and appId are required');\n }\n // Check cache first\n const cacheKey = `${channel}-${appId}`;\n const cached = await this.getCachedVersionInfo(cacheKey);\n if (cached &&\n cached.channel === channel &&\n Date.now() - cached.timestamp < this.CACHE_DURATION) {\n this.logger.debug('Returning cached version info', {\n channel,\n version: cached.data.version,\n });\n return cached.data;\n }\n try {\n const url = new URL(`${serverUrl}/check`);\n url.searchParams.append('channel', channel);\n url.searchParams.append('version', currentVersion);\n url.searchParams.append('appId', appId);\n url.searchParams.append('platform', 'web'); // Will be overridden by native platforms\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'X-App-Version': currentVersion,\n 'X-App-Id': appId,\n },\n signal: AbortSignal.timeout(this.configManager.get('downloadTimeout')),\n });\n if (!response.ok) {\n throw new Error(`Version check failed: ${response.status}`);\n }\n const data = await response.json();\n // Validate response\n if (!data.version) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'No version in server response');\n }\n this.securityValidator.validateVersion(data.version);\n // Additional validation\n if (data.bundleUrl) {\n this.securityValidator.validateUrl(data.bundleUrl);\n }\n if (data.minAppVersion) {\n this.securityValidator.validateVersion(data.minAppVersion);\n }\n // Cache the result\n await this.cacheVersionInfo(cacheKey, channel, data);\n this.logger.info('Version check completed', {\n channel,\n currentVersion,\n latestVersion: data.version,\n updateAvailable: this.isNewerVersion(data.version, currentVersion),\n });\n return data;\n }\n catch (error) {\n this.logger.error('Failed to check for updates', error);\n return null;\n }\n }\n /**\n * Compare two versions\n */\n isNewerVersion(version1, version2) {\n try {\n const v1 = this.parseVersion(version1);\n const v2 = this.parseVersion(version2);\n if (v1.major !== v2.major)\n return v1.major > v2.major;\n if (v1.minor !== v2.minor)\n return v1.minor > v2.minor;\n if (v1.patch !== v2.patch)\n return v1.patch > v2.patch;\n // If main versions are equal, check pre-release\n if (v1.prerelease && !v2.prerelease)\n return false; // v1 is pre-release, v2 is not\n if (!v1.prerelease && v2.prerelease)\n return true; // v1 is not pre-release, v2 is\n if (v1.prerelease && v2.prerelease) {\n return v1.prerelease > v2.prerelease;\n }\n return false; // Versions are equal\n }\n catch (error) {\n this.logger.error('Failed to compare versions', {\n version1,\n version2,\n error,\n });\n return false;\n }\n }\n /**\n * Check if update is mandatory based on minimum version\n */\n isUpdateMandatory(currentVersion, minimumVersion) {\n if (!minimumVersion)\n return false;\n try {\n this.securityValidator.validateVersion(currentVersion);\n this.securityValidator.validateVersion(minimumVersion);\n return (!this.isNewerVersion(currentVersion, minimumVersion) &&\n currentVersion !== minimumVersion);\n }\n catch (error) {\n this.logger.error('Failed to check mandatory update', error);\n return false;\n }\n }\n /**\n * Parse version metadata\n */\n parseVersion(version) {\n const match = version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$/);\n if (!match) {\n throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid version format');\n }\n return {\n major: parseInt(match[1], 10),\n minor: parseInt(match[2], 10),\n patch: parseInt(match[3], 10),\n prerelease: match[4],\n build: match[5],\n };\n }\n /**\n * Generate version string from components\n */\n buildVersionString(components) {\n let version = `${components.major}.${components.minor}.${components.patch}`;\n if (components.prerelease) {\n version += `-${components.prerelease}`;\n }\n if (components.build) {\n version += `+${components.build}`;\n }\n return version;\n }\n /**\n * Check if version is compatible with native version requirements\n */\n isCompatibleWithNativeVersion(bundleVersion, nativeVersion, compatibility) {\n if (!compatibility)\n return true;\n try {\n // Check if there's a specific native version requirement for this bundle version\n const requiredNativeVersion = compatibility[bundleVersion];\n if (!requiredNativeVersion)\n return true;\n this.securityValidator.validateVersion(nativeVersion);\n this.securityValidator.validateVersion(requiredNativeVersion);\n return !this.isNewerVersion(requiredNativeVersion, nativeVersion);\n }\n catch (error) {\n this.logger.error('Failed to check compatibility', error);\n return false;\n }\n }\n /**\n * Get version from cache\n */\n async getCachedVersionInfo(cacheKey) {\n // Check memory cache first\n const memCached = this.memoryCache.get(cacheKey);\n if (memCached && Date.now() - memCached.timestamp < this.CACHE_DURATION) {\n return memCached;\n }\n // Check persistent cache\n try {\n const { value } = await this.preferences.get({\n key: this.VERSION_CHECK_CACHE_KEY,\n });\n if (!value)\n return null;\n const allCached = JSON.parse(value);\n const cached = allCached[cacheKey];\n if (cached && Date.now() - cached.timestamp < this.CACHE_DURATION) {\n // Update memory cache\n this.memoryCache.set(cacheKey, cached);\n return cached;\n }\n }\n catch (error) {\n this.logger.debug('Failed to load cached version info', error);\n }\n return null;\n }\n /**\n * Cache version info\n */\n async cacheVersionInfo(cacheKey, channel, data) {\n const cacheEntry = {\n channel,\n data,\n timestamp: Date.now(),\n };\n // Update memory cache\n this.memoryCache.set(cacheKey, cacheEntry);\n // Update persistent cache\n try {\n const { value } = await this.preferences.get({\n key: this.VERSION_CHECK_CACHE_KEY,\n });\n const allCached = value\n ? JSON.parse(value)\n : {};\n // Clean old entries\n const now = Date.now();\n for (const key in allCached) {\n if (now - allCached[key].timestamp > this.CACHE_DURATION * 2) {\n delete allCached[key];\n }\n }\n allCached[cacheKey] = cacheEntry;\n await this.preferences.set({\n key: this.VERSION_CHECK_CACHE_KEY,\n value: JSON.stringify(allCached),\n });\n }\n catch (error) {\n this.logger.warn('Failed to cache version info', error);\n }\n }\n /**\n * Clear version cache\n */\n async clearVersionCache() {\n this.memoryCache.clear();\n try {\n await this.preferences.remove({ key: this.VERSION_CHECK_CACHE_KEY });\n }\n catch (error) {\n this.logger.warn('Failed to clear version cache', error);\n }\n }\n /**\n * Check if downgrade protection should block update\n */\n shouldBlockDowngrade(currentVersion, newVersion) {\n try {\n return this.securityValidator.isVersionDowngrade(currentVersion, newVersion);\n }\n catch (error) {\n this.logger.error('Failed to check downgrade', error);\n // Default to safe behavior - block if we can't determine\n return true;\n }\n }\n}\n//# sourceMappingURL=version-manager.js.map","import { Logger } from '../core/logger';\nexport class AppUpdateChecker {\n constructor(config) {\n this.config = config;\n this.logger = new Logger('AppUpdateChecker');\n }\n async checkServerVersion(_) {\n if (!this.config.updateUrl) {\n return {};\n }\n try {\n const url = new URL(`${this.config.updateUrl}/app-version`);\n url.searchParams.append('platform', this.getPlatform());\n url.searchParams.append('current', await this.getCurrentVersion());\n if (this.config.channel) {\n url.searchParams.append('channel', this.config.channel);\n }\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n 'X-App-Version': await this.getCurrentVersion(),\n 'X-App-Platform': this.getPlatform(),\n },\n });\n if (!response.ok) {\n throw new Error(`Server returned ${response.status}`);\n }\n const data = await response.json();\n return {\n availableVersion: data.version,\n updatePriority: data.priority,\n releaseNotes: data.releaseNotes,\n updateSize: data.size,\n updateURL: data.downloadUrl,\n };\n }\n catch (error) {\n this.logger.error('Failed to check server version', error);\n return {};\n }\n }\n compareVersions(version1, version2) {\n const v1Parts = version1.split('.').map(Number);\n const v2Parts = version2.split('.').map(Number);\n for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {\n const v1Part = v1Parts[i] || 0;\n const v2Part = v2Parts[i] || 0;\n if (v1Part > v2Part)\n return 1;\n if (v1Part < v2Part)\n return -1;\n }\n return 0;\n }\n isUpdateRequired(currentVersion, availableVersion, minimumVersion) {\n // Check if current version is less than available\n if (this.compareVersions(currentVersion, availableVersion) < 0) {\n return true;\n }\n // Check if current version meets minimum requirement\n if (minimumVersion &&\n this.compareVersions(currentVersion, minimumVersion) < 0) {\n return true;\n }\n return false;\n }\n determineUpdatePriority(versionDiff, stalenessDays) {\n // Parse version difference\n const [major, minor] = versionDiff.split('.').map(Number);\n // Major version change = IMMEDIATE (priority 5)\n if (major > 0) {\n return 5;\n }\n // Minor version with high staleness = HIGH (priority 4)\n if (minor > 0 && stalenessDays && stalenessDays > 30) {\n return 4;\n }\n // Minor version = MEDIUM (priority 3)\n if (minor > 0) {\n return 3;\n }\n // Patch version = LOW (priority 1)\n return 1;\n }\n async getCurrentVersion() {\n // This would be implemented by the native platform\n return '1.0.0';\n }\n getPlatform() {\n // Detect platform\n if (typeof window !== 'undefined') {\n const userAgent = window.navigator.userAgent;\n if (/android/i.test(userAgent)) {\n return 'android';\n }\n else if (/iPad|iPhone|iPod/.test(userAgent)) {\n return 'ios';\n }\n }\n return 'web';\n }\n}\n//# sourceMappingURL=app-update-checker.js.map","import { Logger } from '../core/logger';\nimport { AppUpdateInstallStatus, } from './types';\nexport class AppUpdateInstaller {\n constructor(_) {\n // config parameter is kept for compatibility but not used\n this.logger = new Logger('AppUpdateInstaller');\n this.currentState = {\n installStatus: AppUpdateInstallStatus.UNKNOWN,\n packageName: '',\n availableVersion: '',\n };\n }\n async startImmediateUpdate() {\n this.logger.log('Starting immediate update installation');\n // Update state\n this.updateState(AppUpdateInstallStatus.PENDING);\n // On Android, this would trigger Play Core immediate update\n // On iOS, this would open App Store\n if (this.isAndroid()) {\n // Android implementation would use Play Core Library\n this.logger.log('Triggering Android immediate update');\n }\n else if (this.isIOS()) {\n // iOS implementation would open App Store\n this.logger.log('Opening iOS App Store for update');\n }\n else {\n // Web fallback\n throw new Error('Immediate updates not supported on web platform');\n }\n }\n async startFlexibleUpdate() {\n this.logger.log('Starting flexible update download');\n // Update state\n this.updateState(AppUpdateInstallStatus.DOWNLOADING);\n // Start download simulation for web\n if (this.isWeb()) {\n this.simulateFlexibleUpdate();\n }\n else if (this.isAndroid()) {\n // Android implementation would use Play Core Library\n this.logger.log('Starting Android flexible update');\n }\n else {\n // iOS doesn't support flexible updates\n throw new Error('Flexible updates not supported on iOS');\n }\n }\n async completeFlexibleUpdate() {\n this.logger.log('Completing flexible update installation');\n if (this.currentState.installStatus !== AppUpdateInstallStatus.DOWNLOADED) {\n throw new Error('Update not ready for installation');\n }\n // Update state\n this.updateState(AppUpdateInstallStatus.INSTALLING);\n // Trigger installation\n if (this.isAndroid()) {\n // Android implementation would complete the update\n this.logger.log('Completing Android update installation');\n }\n else {\n // Simulate completion\n setTimeout(() => {\n this.updateState(AppUpdateInstallStatus.INSTALLED);\n }, 1000);\n }\n }\n async cancelUpdate() {\n this.logger.log('Cancelling update');\n if (this.currentState.installStatus === AppUpdateInstallStatus.DOWNLOADING) {\n this.updateState(AppUpdateInstallStatus.CANCELED);\n }\n }\n async getInstallState() {\n return Object.assign({}, this.currentState);\n }\n onProgress(callback) {\n this.progressCallback = callback;\n }\n updateState(status, errorCode) {\n this.currentState.installStatus = status;\n if (errorCode !== undefined) {\n this.currentState.installErrorCode = errorCode;\n }\n this.logger.log('Update state changed', this.currentState);\n }\n simulateFlexibleUpdate() {\n // Simulate download progress for web platform\n let downloaded = 0;\n const totalSize = 50 * 1024 * 1024; // 50MB\n const chunkSize = 1024 * 1024; // 1MB per tick\n const interval = setInterval(() => {\n downloaded += chunkSize;\n if (downloaded >= totalSize) {\n downloaded = totalSize;\n clearInterval(interval);\n this.updateState(AppUpdateInstallStatus.DOWNLOADED);\n }\n const progress = {\n bytesDownloaded: downloaded,\n totalBytesToDownload: totalSize,\n percentComplete: Math.round((downloaded / totalSize) * 100),\n downloadSpeed: chunkSize, // 1MB/s\n estimatedTime: Math.ceil((totalSize - downloaded) / chunkSize),\n };\n if (this.progressCallback) {\n this.progressCallback(progress);\n }\n }, 1000);\n }\n isAndroid() {\n return (typeof window !== 'undefined' &&\n /android/i.test(window.navigator.userAgent));\n }\n isIOS() {\n return (typeof window !== 'undefined' &&\n /iPad|iPhone|iPod/.test(window.navigator.userAgent));\n }\n isWeb() {\n return !this.isAndroid() && !this.isIOS();\n }\n}\n//# sourceMappingURL=app-update-installer.js.map","import { Logger } from '../core/logger';\nimport { Capacitor } from '@capacitor/core';\nexport class PlatformAppUpdate {\n constructor(config) {\n this.config = config;\n this.logger = new Logger('PlatformAppUpdate');\n this.platform = Capacitor.getPlatform();\n }\n async checkForUpdate(_) {\n // options parameter is kept for future use\n this.logger.log('Checking for platform update: ' + this.platform);\n const versionInfo = await this.getVersionInfo();\n // Default response\n const updateInfo = {\n updateAvailable: false,\n currentVersion: versionInfo.currentVersion,\n availableVersion: versionInfo.currentVersion,\n };\n // Platform-specific checks\n if (this.platform === 'android') {\n // Android would check Play Store via Play Core Library\n // This is handled by native implementation\n return updateInfo;\n }\n else if (this.platform === 'ios') {\n // iOS would check App Store via iTunes API\n // This is handled by native implementation\n return updateInfo;\n }\n else {\n // Web platform - check configured update URL\n if (this.config.webUpdateUrl) {\n try {\n const response = await fetch(this.config.webUpdateUrl);\n const data = await response.json();\n if (data.version && data.version !== versionInfo.currentVersion) {\n updateInfo.updateAvailable = true;\n updateInfo.availableVersion = data.version;\n updateInfo.releaseNotes = data.releaseNotes;\n updateInfo.updateURL = data.downloadUrl;\n }\n }\n catch (error) {\n this.logger.error('Failed to check web update', error);\n }\n }\n }\n return updateInfo;\n }\n async getVersionInfo() {\n // getAppInfo is not available in standard Capacitor, using default values\n const appInfo = {\n version: '1.0.0',\n build: '1',\n id: 'com.example.app',\n };\n return {\n currentVersion: appInfo.version,\n buildNumber: appInfo.build,\n packageName: appInfo.id,\n platform: this.platform,\n minimumVersion: this.config.minimumVersion,\n };\n }\n async getAppStoreUrl() {\n const platform = this.platform;\n let url = '';\n if (platform === 'ios') {\n // iOS App Store URL\n const appStoreId = this.config.appStoreId || this.config.iosAppId;\n if (!appStoreId) {\n throw new Error('App Store ID not configured');\n }\n url = `https://apps.apple.com/app/id${appStoreId}`;\n }\n else if (platform === 'android') {\n // Google Play Store URL\n const packageName = this.config.packageName || (await this.getVersionInfo()).packageName;\n url = `https://play.google.com/store/apps/details?id=${packageName}`;\n }\n else {\n // Web URL\n url = this.config.webUpdateUrl || window.location.origin;\n }\n return { url, platform: platform };\n }\n async openUrl(url) {\n if (typeof window !== 'undefined' && window.open) {\n window.open(url, '_blank');\n }\n else {\n throw new Error('Cannot open URL on this platform');\n }\n }\n isUpdateSupported() {\n // Check if platform supports in-app updates\n if (this.platform === 'android') {\n // Android supports in-app updates via Play Core\n return true;\n }\n else if (this.platform === 'ios') {\n // iOS only supports opening App Store\n return false;\n }\n else {\n // Web can redirect to update URL\n return true;\n }\n }\n getUpdateCapabilities() {\n const capabilities = {\n immediateUpdate: false,\n flexibleUpdate: false,\n backgroundDownload: false,\n inAppReview: false,\n };\n if (this.platform === 'android') {\n capabilities.immediateUpdate = true;\n capabilities.flexibleUpdate = true;\n capabilities.backgroundDownload = true;\n capabilities.inAppReview = true;\n }\n else if (this.platform === 'ios') {\n capabilities.inAppReview = true;\n }\n return capabilities;\n }\n}\n//# sourceMappingURL=platform-app-update.js.map","import { Logger } from '../core/logger';\nimport { AppUpdateChecker } from './app-update-checker';\nimport { AppUpdateInstaller } from './app-update-installer';\nimport { PlatformAppUpdate } from './platform-app-update';\nexport class AppUpdateManager {\n constructor(config) {\n this.listeners = new Map();\n this.config = config;\n this.logger = new Logger('AppUpdateManager');\n this.checker = new AppUpdateChecker(config);\n this.installer = new AppUpdateInstaller(config);\n this.platformUpdate = new PlatformAppUpdate(config);\n }\n async checkAppUpdate(options) {\n try {\n this.logger.log('Checking for app updates', options);\n // Check with native platform\n const nativeInfo = await this.platformUpdate.checkForUpdate(options);\n // If no native info, check with server\n if (!nativeInfo.updateAvailable && this.config.updateUrl) {\n const serverInfo = await this.checker.checkServerVersion(options);\n return this.mergeUpdateInfo(nativeInfo, serverInfo);\n }\n return nativeInfo;\n }\n catch (error) {\n this.logger.error('Failed to check app update', error);\n throw error;\n }\n }\n async startImmediateUpdate() {\n try {\n this.logger.log('Starting immediate update');\n // Check if immediate update is allowed\n const updateInfo = await this.checkAppUpdate();\n if (!updateInfo.immediateUpdateAllowed) {\n throw new Error('Immediate update not allowed');\n }\n // Start the update\n await this.installer.startImmediateUpdate();\n // Notify listeners\n this.emit('appUpdateStateChanged', {\n installStatus: 1, // PENDING\n packageName: this.config.packageName || '',\n availableVersion: updateInfo.availableVersion || '',\n });\n }\n catch (error) {\n this.logger.error('Failed to start immediate update', error);\n throw error;\n }\n }\n async startFlexibleUpdate() {\n try {\n this.logger.log('Starting flexible update');\n // Check if flexible update is allowed\n const updateInfo = await this.checkAppUpdate();\n if (!updateInfo.flexibleUpdateAllowed) {\n throw new Error('Flexible update not allowed');\n }\n // Start the update\n await this.installer.startFlexibleUpdate();\n // Set up progress monitoring\n this.installer.onProgress((progress) => {\n this.emit('appUpdateProgress', progress);\n });\n // Notify listeners\n this.emit('appUpdateStateChanged', {\n installStatus: 2, // DOWNLOADING\n packageName: this.config.packageName || '',\n availableVersion: updateInfo.availableVersion || '',\n });\n }\n catch (error) {\n this.logger.error('Failed to start flexible update', error);\n throw error;\n }\n }\n async completeFlexibleUpdate() {\n try {\n this.logger.log('Completing flexible update');\n await this.installer.completeFlexibleUpdate();\n // App will restart after this\n this.emit('appUpdateStateChanged', {\n installStatus: 3, // INSTALLING\n packageName: this.config.packageName || '',\n availableVersion: '',\n });\n }\n catch (error) {\n this.logger.error('Failed to complete flexible update', error);\n throw error;\n }\n }\n async getVersionInfo() {\n try {\n this.logger.log('Getting version info');\n return await this.platformUpdate.getVersionInfo();\n }\n catch (error) {\n this.logger.error('Failed to get version info', error);\n throw error;\n }\n }\n async isMinimumVersionMet() {\n try {\n this.logger.log('Checking minimum version');\n const versionInfo = await this.getVersionInfo();\n const minimumVersion = this.config.minimumVersion || '0.0.0';\n const isMet = this.checker.compareVersions(versionInfo.currentVersion, minimumVersion) >= 0;\n return {\n isMet,\n currentVersion: versionInfo.currentVersion,\n minimumVersion,\n updateRequired: !isMet && this.config.enforceMinVersion === true,\n };\n }\n catch (error) {\n this.logger.error('Failed to check minimum version', error);\n throw error;\n }\n }\n async getAppUpdateInfo() {\n return this.checkAppUpdate();\n }\n async performImmediateUpdate() {\n return this.startImmediateUpdate();\n }\n async openAppStore(_options) {\n try {\n this.logger.log('Opening app store');\n const storeInfo = await this.getAppStoreUrl();\n await this.platformUpdate.openUrl(storeInfo.url);\n }\n catch (error) {\n this.logger.error('Failed to open app store', error);\n throw error;\n }\n }\n async getAppStoreUrl() {\n try {\n this.logger.log('Getting app store URL');\n return await this.platformUpdate.getAppStoreUrl();\n }\n catch (error) {\n this.logger.error('Failed to get app store URL', error);\n throw error;\n }\n }\n async getUpdateInstallState() {\n try {\n this.logger.log('Getting update install state');\n return await this.installer.getInstallState();\n }\n catch (error) {\n this.logger.error('Failed to get update install state', error);\n throw error;\n }\n }\n addListener(eventName, listenerFunc) {\n if (!this.listeners.has(eventName)) {\n this.listeners.set(eventName, new Set());\n }\n this.listeners.get(eventName).add(listenerFunc);\n return {\n remove: async () => {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.delete(listenerFunc);\n }\n },\n };\n }\n async removeAllListeners(eventName) {\n if (eventName) {\n this.listeners.delete(eventName);\n }\n else {\n this.listeners.clear();\n }\n }\n emit(eventName, data) {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.forEach((listener) => {\n try {\n listener(data);\n }\n catch (error) {\n this.logger.error(`Error in ${eventName} listener`, error);\n }\n });\n }\n }\n mergeUpdateInfo(nativeInfo, serverInfo) {\n return Object.assign(Object.assign(Object.assign({}, nativeInfo), serverInfo), { updateAvailable: nativeInfo.updateAvailable || !!serverInfo.availableVersion, availableVersion: serverInfo.availableVersion || nativeInfo.availableVersion });\n }\n}\n//# sourceMappingURL=app-update-manager.js.map","/**\n * Centralized event emitter for the Native Update plugin\n */\nexport class EventEmitter {\n constructor() {\n this.listeners = new Map();\n }\n static getInstance() {\n if (!EventEmitter.instance) {\n EventEmitter.instance = new EventEmitter();\n }\n return EventEmitter.instance;\n }\n /**\n * Add a listener for an event\n */\n addListener(eventName, listener) {\n if (!this.listeners.has(eventName)) {\n this.listeners.set(eventName, new Set());\n }\n this.listeners.get(eventName).add(listener);\n // Return remove function\n return () => {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.delete(listener);\n if (listeners.size === 0) {\n this.listeners.delete(eventName);\n }\n }\n };\n }\n /**\n * Emit an event to all listeners\n */\n emit(eventName, data) {\n const listeners = this.listeners.get(eventName);\n if (listeners) {\n listeners.forEach(listener => {\n try {\n listener(data);\n }\n catch (error) {\n console.error(`Error in event listener for ${eventName}:`, error);\n }\n });\n }\n }\n /**\n * Remove all listeners for a specific event\n */\n removeListeners(eventName) {\n this.listeners.delete(eventName);\n }\n /**\n * Remove all listeners\n */\n removeAllListeners() {\n this.listeners.clear();\n }\n /**\n * Get the number of listeners for an event\n */\n listenerCount(eventName) {\n var _a;\n return ((_a = this.listeners.get(eventName)) === null || _a === void 0 ? void 0 : _a.size) || 0;\n }\n /**\n * Get all event names that have listeners\n */\n eventNames() {\n return Array.from(this.listeners.keys());\n }\n}\n//# sourceMappingURL=event-emitter.js.map","import { Filesystem } from '@capacitor/filesystem';\nimport { Preferences } from '@capacitor/preferences';\nimport { ConfigManager } from './config';\nimport { Logger } from './logger';\nimport { SecurityValidator } from './security';\nimport { BundleManager } from '../live-update/bundle-manager';\nimport { DownloadManager } from '../live-update/download-manager';\nimport { VersionManager } from '../live-update/version-manager';\nimport { AppUpdateManager } from '../app-update/app-update-manager';\nimport { EventEmitter } from './event-emitter';\nimport { NativeUpdateError, ErrorCode } from './errors';\n/**\n * Central manager for all plugin components\n */\nexport class PluginManager {\n constructor() {\n this.bundleManager = null;\n this.downloadManager = null;\n this.versionManager = null;\n this.appUpdateManager = null;\n this.initialized = false;\n this.configManager = ConfigManager.getInstance();\n this.logger = Logger.getInstance();\n this.securityValidator = SecurityValidator.getInstance();\n this.eventEmitter = EventEmitter.getInstance();\n }\n static getInstance() {\n if (!PluginManager.instance) {\n PluginManager.instance = new PluginManager();\n }\n return PluginManager.instance;\n }\n /**\n * Initialize the plugin with configuration\n */\n async initialize(config) {\n var _a, _b;\n if (this.initialized) {\n this.logger.warn('Plugin already initialized');\n return;\n }\n try {\n // Configure the plugin\n this.configManager.configure(config);\n // Use Capacitor plugins directly if not provided\n if (!config.filesystem) {\n config.filesystem = Filesystem;\n }\n if (!config.preferences) {\n config.preferences = Preferences;\n }\n // Initialize managers\n this.bundleManager = new BundleManager();\n await this.bundleManager.initialize();\n this.downloadManager = new DownloadManager();\n await this.downloadManager.initialize();\n this.versionManager = new VersionManager();\n await this.versionManager.initialize();\n this.appUpdateManager = new AppUpdateManager({\n serverUrl: config.serverUrl || config.baseUrl || '',\n channel: config.channel || 'production',\n autoCheck: (_a = config.autoCheck) !== null && _a !== void 0 ? _a : true,\n autoUpdate: (_b = config.autoUpdate) !== null && _b !== void 0 ? _b : false,\n updateStrategy: config.updateStrategy,\n publicKey: config.publicKey,\n requireSignature: config.requireSignature,\n checksumAlgorithm: config.checksumAlgorithm,\n checkInterval: config.checkInterval,\n security: config.security,\n });\n // Wire up app update manager events to central event emitter\n this.setupAppUpdateEventBridge();\n this.initialized = true;\n this.logger.info('Plugin initialized successfully');\n }\n catch (error) {\n this.logger.error('Failed to initialize plugin', error);\n throw error;\n }\n }\n /**\n * Check if plugin is initialized\n */\n isInitialized() {\n return this.initialized && this.configManager.isConfigured();\n }\n /**\n * Ensure plugin is initialized\n */\n ensureInitialized() {\n if (!this.isInitialized()) {\n throw new NativeUpdateError(ErrorCode.NOT_CONFIGURED, 'Plugin not initialized. Please call initialize() first.');\n }\n }\n /**\n * Get bundle manager\n */\n getBundleManager() {\n this.ensureInitialized();\n return this.bundleManager;\n }\n /**\n * Get download manager\n */\n getDownloadManager() {\n this.ensureInitialized();\n return this.downloadManager;\n }\n /**\n * Get version manager\n */\n getVersionManager() {\n this.ensureInitialized();\n return this.versionManager;\n }\n /**\n * Get configuration manager\n */\n getConfigManager() {\n return this.configManager;\n }\n /**\n * Get logger\n */\n getLogger() {\n return this.logger;\n }\n /**\n * Get security validator\n */\n getSecurityValidator() {\n return this.securityValidator;\n }\n /**\n * Get app update manager\n */\n getAppUpdateManager() {\n this.ensureInitialized();\n return this.appUpdateManager;\n }\n /**\n * Get event emitter\n */\n getEventEmitter() {\n return this.eventEmitter;\n }\n /**\n * Reset plugin state\n */\n async reset() {\n this.logger.info('Resetting plugin state');\n // Clear all data\n if (this.bundleManager) {\n await this.bundleManager.clearAllBundles();\n }\n if (this.versionManager) {\n await this.versionManager.clearVersionCache();\n }\n if (this.downloadManager) {\n this.downloadManager.cancelAllDownloads();\n }\n // Reset initialization state\n this.bundleManager = null;\n this.downloadManager = null;\n this.versionManager = null;\n this.appUpdateManager = null;\n this.initialized = false;\n // Clear all event listeners\n this.eventEmitter.removeAllListeners();\n this.logger.info('Plugin reset complete');\n }\n /**\n * Clean up resources\n */\n async cleanup() {\n this.logger.info('Cleaning up plugin resources');\n // Cancel any active downloads\n if (this.downloadManager) {\n this.downloadManager.cancelAllDownloads();\n }\n // Clean expired bundles\n if (this.bundleManager) {\n await this.bundleManager.cleanExpiredBundles();\n }\n this.logger.info('Cleanup complete');\n }\n /**\n * Setup event bridge between AppUpdateManager and central EventEmitter\n */\n setupAppUpdateEventBridge() {\n if (!this.appUpdateManager)\n return;\n // Bridge appUpdateStateChanged events\n this.appUpdateManager.addListener('appUpdateStateChanged', (event) => {\n this.eventEmitter.emit('appUpdateStateChanged', event);\n });\n // Bridge appUpdateProgress events\n this.appUpdateManager.addListener('appUpdateProgress', (event) => {\n this.eventEmitter.emit('appUpdateProgress', event);\n });\n }\n}\n//# sourceMappingURL=plugin-manager.js.map","import { registerPlugin } from '@capacitor/core';\nimport { SyncStatus, BundleStatus, UpdateErrorCode } from './definitions';\nimport { PluginManager } from './core/plugin-manager';\nimport { NativeUpdateError, ErrorCode } from './core/errors';\n/**\n * Web implementation of the Native Update Plugin\n */\nclass NativeUpdatePluginWeb {\n constructor() {\n this.initialized = false;\n this.windowEventListeners = new Map();\n this.pluginManager = PluginManager.getInstance();\n }\n // Main plugin methods\n async initialize(config) {\n await this.pluginManager.initialize(config);\n this.initialized = true;\n // Setup window event bridge for AppUpdateNotifier events\n this.setupWindowEventBridge();\n }\n isInitialized() {\n return this.initialized && this.pluginManager.isInitialized();\n }\n async reset() {\n await this.pluginManager.reset();\n }\n async cleanup() {\n await this.pluginManager.cleanup();\n }\n // NativeUpdatePlugin methods\n async configure(config) {\n var _a;\n // Handle both UpdateConfig and wrapped PluginInitConfig formats\n let initConfig;\n if ('config' in config && typeof config.config === 'object') {\n // Format: { config: PluginInitConfig }\n initConfig = config.config;\n }\n else {\n // Format: UpdateConfig - convert to PluginInitConfig\n initConfig = {\n // Auto-imported Capacitor plugins will be added by plugin-manager\n baseUrl: (_a = config.liveUpdate) === null || _a === void 0 ? void 0 : _a.serverUrl,\n };\n }\n if (!this.initialized) {\n // Auto-initialize with the provided config\n await this.initialize(initConfig);\n }\n else {\n // Apply plugin configuration\n const configManager = this.pluginManager.getConfigManager();\n configManager.configure(initConfig);\n }\n }\n async getSecurityInfo() {\n return {\n enforceHttps: true,\n certificatePinning: {\n enabled: false,\n pins: [],\n },\n validateInputs: true,\n secureStorage: true,\n };\n }\n // LiveUpdatePlugin methods\n async sync(_options) {\n const bundleManager = this.pluginManager.getBundleManager();\n try {\n // Check for updates\n const currentBundle = await bundleManager.getActiveBundle();\n const currentVersion = (currentBundle === null || currentBundle === void 0 ? void 0 : currentBundle.version) || '1.0.0';\n // For now, return up-to-date status\n return {\n status: SyncStatus.UP_TO_DATE,\n version: currentVersion,\n };\n }\n catch (error) {\n return {\n status: SyncStatus.ERROR,\n error: {\n code: UpdateErrorCode.UNKNOWN_ERROR,\n message: error instanceof Error ? error.message : 'Sync failed',\n },\n };\n }\n }\n async download(options) {\n const downloadManager = this.pluginManager.getDownloadManager();\n const bundleManager = this.pluginManager.getBundleManager();\n const blob = await downloadManager.downloadWithRetry(options.url, options.version);\n const path = await downloadManager.saveBlob(options.version, blob);\n const bundleInfo = {\n bundleId: options.version,\n version: options.version,\n path,\n downloadTime: Date.now(),\n size: blob.size,\n status: BundleStatus.READY,\n checksum: options.checksum,\n signature: options.signature,\n verified: false,\n };\n await bundleManager.saveBundleInfo(bundleInfo);\n return bundleInfo;\n }\n async set(bundle) {\n const bundleManager = this.pluginManager.getBundleManager();\n await bundleManager.setActiveBundle(bundle.bundleId);\n }\n async reload() {\n // In web implementation, we can reload the page\n if (typeof window !== 'undefined') {\n window.location.reload();\n }\n }\n async current() {\n const bundleManager = this.pluginManager.getBundleManager();\n const bundle = await bundleManager.getActiveBundle();\n if (!bundle) {\n throw new NativeUpdateError(ErrorCode.FILE_NOT_FOUND, 'No active bundle found');\n }\n return bundle;\n }\n async list() {\n const bundleManager = this.pluginManager.getBundleManager();\n return bundleManager.getAllBundles();\n }\n async delete(options) {\n const bundleManager = this.pluginManager.getBundleManager();\n if (options.bundleId) {\n await bundleManager.deleteBundle(options.bundleId);\n }\n else if (options.keepVersions !== undefined) {\n // Delete old versions keeping the specified number\n const bundles = await bundleManager.getAllBundles();\n const sortedBundles = bundles.sort((a, b) => b.downloadTime - a.downloadTime);\n for (let i = options.keepVersions; i < sortedBundles.length; i++) {\n await bundleManager.deleteBundle(sortedBundles[i].bundleId);\n }\n }\n }\n async notifyAppReady() {\n // Mark the current bundle as stable\n const bundleManager = this.pluginManager.getBundleManager();\n const activeBundle = await bundleManager.getActiveBundle();\n if (activeBundle) {\n activeBundle.status = BundleStatus.ACTIVE;\n await bundleManager.saveBundleInfo(activeBundle);\n }\n }\n async getLatest() {\n // For web, we'll return no update available\n return {\n available: false,\n };\n }\n async setChannel(channel) {\n // Store the channel preference\n const preferences = this.pluginManager\n .getConfigManager()\n .get('preferences');\n if (preferences) {\n await preferences.set({\n key: 'update_channel',\n value: channel,\n });\n }\n }\n async setUpdateUrl(url) {\n const configManager = this.pluginManager.getConfigManager();\n configManager.configure({ baseUrl: url });\n }\n async validateUpdate(options) {\n const securityValidator = this.pluginManager.getSecurityValidator();\n try {\n // Validate checksum\n const isValid = await securityValidator.validateChecksum(new ArrayBuffer(0), // Placeholder for bundle data\n options.checksum);\n return {\n isValid,\n details: {\n checksumValid: isValid,\n signatureValid: true,\n sizeValid: true,\n versionValid: true,\n },\n };\n }\n catch (error) {\n return {\n isValid: false,\n error: error instanceof Error ? error.message : 'Validation failed',\n };\n }\n }\n // AppUpdatePlugin methods\n async getAppUpdateInfo() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.getAppUpdateInfo();\n }\n async performImmediateUpdate() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.performImmediateUpdate();\n }\n async startFlexibleUpdate() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.startFlexibleUpdate();\n }\n async completeFlexibleUpdate() {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.completeFlexibleUpdate();\n }\n async openAppStore(options) {\n const appUpdateManager = this.pluginManager.getAppUpdateManager();\n return appUpdateManager.openAppStore(options);\n }\n // AppReviewPlugin methods\n async requestReview() {\n return {\n displayed: false,\n error: 'Reviews are not supported on web',\n };\n }\n async canRequestReview() {\n return {\n canRequest: false,\n reason: 'Reviews are not supported on web',\n };\n }\n // BackgroundUpdatePlugin methods\n async enableBackgroundUpdates(config) {\n // Store the configuration\n const preferences = this.pluginManager\n .getConfigManager()\n .get('preferences');\n if (preferences) {\n await preferences.set({\n key: 'background_update_config',\n value: JSON.stringify(config),\n });\n }\n }\n async disableBackgroundUpdates() {\n const preferences = this.pluginManager\n .getConfigManager()\n .get('preferences');\n if (preferences) {\n await preferences.remove({ key: 'background_update_config' });\n }\n }\n async getBackgroundUpdateStatus() {\n return {\n enabled: false,\n isRunning: false,\n checkCount: 0,\n failureCount: 0,\n };\n }\n async scheduleBackgroundCheck(_interval) {\n // Not supported on web\n throw new NativeUpdateError(ErrorCode.PLATFORM_NOT_SUPPORTED, 'Background updates are not supported on web');\n }\n async triggerBackgroundCheck() {\n return {\n success: false,\n updatesFound: false,\n notificationSent: false,\n error: {\n code: UpdateErrorCode.PLATFORM_NOT_SUPPORTED,\n message: 'Background updates are not supported on web',\n },\n };\n }\n async setNotificationPreferences(preferences) {\n // Store preferences but notifications aren't supported on web\n const prefs = this.pluginManager.getConfigManager().get('preferences');\n if (prefs) {\n await prefs.set({\n key: 'notification_preferences',\n value: JSON.stringify(preferences),\n });\n }\n }\n async getNotificationPermissions() {\n return {\n granted: false,\n canRequest: false,\n };\n }\n async requestNotificationPermissions() {\n return false;\n }\n // Event listener methods\n async addListener(eventName, \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n listenerFunc) {\n const eventEmitter = this.pluginManager.getEventEmitter();\n // Add listener to central event emitter\n const removeListener = eventEmitter.addListener(eventName, listenerFunc);\n return {\n remove: async () => {\n removeListener();\n },\n };\n }\n async removeAllListeners() {\n const eventEmitter = this.pluginManager.getEventEmitter();\n eventEmitter.removeAllListeners();\n }\n /**\n * Setup bridge between window custom events and central event emitter\n */\n setupWindowEventBridge() {\n const eventEmitter = this.pluginManager.getEventEmitter();\n // List of events emitted by AppUpdateNotifier via window\n const windowEvents = [\n 'appUpdateAvailable',\n 'appUpdateProgress',\n 'appUpdateReady',\n 'appUpdateFailed',\n 'appUpdateNotificationClicked',\n 'appUpdateInstallClicked'\n ];\n windowEvents.forEach(eventName => {\n const listener = (event) => {\n eventEmitter.emit(eventName, event.detail);\n };\n window.addEventListener(eventName, listener);\n this.windowEventListeners.set(eventName, listener);\n });\n }\n}\n/**\n * Register the plugin\n */\nconst NativeUpdate = registerPlugin('NativeUpdate', {\n web: () => new NativeUpdatePluginWeb(),\n});\nexport { NativeUpdate };\n//# sourceMappingURL=plugin.js.map","import { ConfigManager } from './config';\nimport { Logger } from './logger';\nimport { Directory, Encoding } from '@capacitor/filesystem';\n/**\n * Manages caching with expiration for various data types\n */\nexport class CacheManager {\n constructor() {\n this.filesystem = null;\n this.memoryCache = new Map();\n this.CACHE_DIR = 'cache';\n this.logger = Logger.getInstance();\n this.configManager = ConfigManager.getInstance();\n }\n /**\n * Initialize cache manager\n */\n async initialize() {\n this.filesystem = this.configManager.get('filesystem');\n if (!this.filesystem) {\n throw new Error('Filesystem not configured');\n }\n // Create cache directory if it doesn't exist\n try {\n await this.filesystem.mkdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n recursive: true,\n });\n }\n catch (error) {\n this.logger.debug('Cache directory may already exist', error);\n }\n // Clean expired cache on initialization\n await this.cleanExpiredCache();\n }\n /**\n * Set cache entry with expiration\n */\n async set(key, data, ttlMs) {\n const expiry = Date.now() + (ttlMs || this.configManager.get('cacheExpiration'));\n const entry = {\n data,\n timestamp: Date.now(),\n expiry,\n };\n // Update memory cache\n this.memoryCache.set(key, entry);\n // Persist to filesystem for larger data\n if (this.shouldPersist(data)) {\n await this.persistToFile(key, entry);\n }\n this.logger.debug('Cache entry set', { key, expiry: new Date(expiry) });\n }\n /**\n * Get cache entry\n */\n async get(key) {\n // Check memory cache first\n const memEntry = this.memoryCache.get(key);\n if (memEntry) {\n if (Date.now() < memEntry.expiry) {\n return memEntry.data;\n }\n else {\n // Expired - remove from memory\n this.memoryCache.delete(key);\n }\n }\n // Check filesystem cache\n const fileEntry = await this.loadFromFile(key);\n if (fileEntry) {\n if (Date.now() < fileEntry.expiry) {\n // Update memory cache\n this.memoryCache.set(key, fileEntry);\n return fileEntry.data;\n }\n else {\n // Expired - remove file\n await this.removeFile(key);\n }\n }\n return null;\n }\n /**\n * Check if cache entry exists and is valid\n */\n async has(key) {\n const value = await this.get(key);\n return value !== null;\n }\n /**\n * Remove cache entry\n */\n async remove(key) {\n this.memoryCache.delete(key);\n await this.removeFile(key);\n this.logger.debug('Cache entry removed', { key });\n }\n /**\n * Clear all cache\n */\n async clear() {\n this.memoryCache.clear();\n // Remove cache directory\n try {\n await this.filesystem.rmdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n recursive: true,\n });\n // Recreate empty cache directory\n await this.filesystem.mkdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n recursive: true,\n });\n }\n catch (error) {\n this.logger.warn('Failed to clear cache directory', error);\n }\n this.logger.info('Cache cleared');\n }\n /**\n * Clean expired cache entries\n */\n async cleanExpiredCache() {\n const now = Date.now();\n let cleanedCount = 0;\n // Clean memory cache\n for (const [key, entry] of this.memoryCache) {\n if (now >= entry.expiry) {\n this.memoryCache.delete(key);\n cleanedCount++;\n }\n }\n // Clean filesystem cache\n try {\n const files = await this.filesystem.readdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n });\n for (const file of files.files) {\n const key = file.name.replace('.json', '');\n const entry = await this.loadFromFile(key);\n if (!entry || now >= entry.expiry) {\n await this.removeFile(key);\n cleanedCount++;\n }\n }\n }\n catch (error) {\n this.logger.debug('Failed to clean filesystem cache', error);\n }\n if (cleanedCount > 0) {\n this.logger.info('Cleaned expired cache entries', {\n count: cleanedCount,\n });\n }\n }\n /**\n * Get cache statistics\n */\n async getStats() {\n let fileEntries = 0;\n let totalSize = 0;\n try {\n const files = await this.filesystem.readdir({\n path: this.CACHE_DIR,\n directory: Directory.Data,\n });\n fileEntries = files.files.length;\n // Estimate size (this is approximate)\n for (const file of files.files) {\n const stat = await this.filesystem.stat({\n path: `${this.CACHE_DIR}/${file.name}`,\n directory: Directory.Data,\n });\n totalSize += stat.size || 0;\n }\n }\n catch (error) {\n this.logger.debug('Failed to get cache stats', error);\n }\n return {\n memoryEntries: this.memoryCache.size,\n fileEntries,\n totalSize,\n };\n }\n /**\n * Cache bundle metadata\n */\n async cacheBundleMetadata(bundle) {\n const key = `bundle_meta_${bundle.bundleId}`;\n await this.set(key, bundle, 24 * 60 * 60 * 1000); // 24 hours\n }\n /**\n * Get cached bundle metadata\n */\n async getCachedBundleMetadata(bundleId) {\n const key = `bundle_meta_${bundleId}`;\n return this.get(key);\n }\n /**\n * Check if data should be persisted to filesystem\n */\n shouldPersist(data) {\n // Persist objects and large strings\n if (typeof data === 'object')\n return true;\n if (typeof data === 'string' && data.length > 1024)\n return true;\n return false;\n }\n /**\n * Persist cache entry to file\n */\n async persistToFile(key, entry) {\n if (!this.filesystem)\n return;\n try {\n const path = `${this.CACHE_DIR}/${key}.json`;\n const data = JSON.stringify(entry);\n await this.filesystem.writeFile({\n path,\n data,\n directory: Directory.Data,\n encoding: Encoding.UTF8,\n });\n }\n catch (error) {\n this.logger.warn('Failed to persist cache to file', { key, error });\n }\n }\n /**\n * Load cache entry from file\n */\n async loadFromFile(key) {\n if (!this.filesystem)\n return null;\n try {\n const path = `${this.CACHE_DIR}/${key}.json`;\n const result = await this.filesystem.readFile({\n path,\n directory: Directory.Data,\n encoding: Encoding.UTF8,\n });\n return JSON.parse(result.data);\n }\n catch (_a) {\n // File doesn't exist or is corrupted\n return null;\n }\n }\n /**\n * Remove cache file\n */\n async removeFile(key) {\n if (!this.filesystem)\n return;\n try {\n const path = `${this.CACHE_DIR}/${key}.json`;\n await this.filesystem.deleteFile({\n path,\n directory: Directory.Data,\n });\n }\n catch (error) {\n // File may not exist\n this.logger.debug('Failed to remove cache file', { key, error });\n }\n }\n}\n//# sourceMappingURL=cache-manager.js.map","import { PluginManager } from '../core/plugin-manager';\nimport { UpdateError, ValidationError, ErrorCode } from '../core/errors';\nimport { SecurityValidator } from '../core/security';\nimport { Directory } from '@capacitor/filesystem';\n/**\n * Manages atomic bundle installation with rollback capability\n */\nexport class UpdateManager {\n constructor() {\n this.filesystem = null;\n this.updateInProgress = false;\n this.currentState = null;\n this.pluginManager = PluginManager.getInstance();\n this.securityValidator = SecurityValidator.getInstance();\n }\n /**\n * Initialize update manager\n */\n async initialize() {\n this.filesystem = this.pluginManager.getConfigManager().get('filesystem');\n if (!this.filesystem) {\n throw new UpdateError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not configured');\n }\n }\n /**\n * Apply bundle update atomically\n */\n async applyUpdate(bundleId, options) {\n if (this.updateInProgress) {\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Another update is already in progress');\n }\n const logger = this.pluginManager.getLogger();\n const bundleManager = this.pluginManager.getBundleManager();\n try {\n this.updateInProgress = true;\n logger.info('Starting bundle update', { bundleId });\n // Get the new bundle\n const newBundle = await bundleManager.getBundle(bundleId);\n if (!newBundle) {\n throw new UpdateError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);\n }\n // Verify bundle is ready\n if (newBundle.status !== 'READY' && newBundle.status !== 'ACTIVE') {\n throw new UpdateError(ErrorCode.BUNDLE_NOT_READY, `Bundle ${bundleId} is not ready for installation`);\n }\n // Get current active bundle\n const currentBundle = await bundleManager.getActiveBundle();\n // Initialize update state\n this.currentState = {\n currentBundle,\n newBundle,\n backupPath: null,\n startTime: Date.now(),\n };\n // Validate update\n await this.validateUpdate(currentBundle, newBundle, options);\n // Create backup of current state\n if (currentBundle && currentBundle.bundleId !== 'default') {\n this.currentState.backupPath = await this.createBackup(currentBundle);\n }\n // Apply the update\n await this.performUpdate(newBundle);\n // Verify the update\n await this.verifyUpdate(newBundle);\n // Mark as active\n await bundleManager.setActiveBundle(bundleId);\n // Clean up old bundles if configured\n if (options === null || options === void 0 ? void 0 : options.cleanupOldBundles) {\n await bundleManager.cleanupOldBundles(options.keepBundleCount || 3);\n }\n logger.info('Bundle update completed successfully', {\n bundleId,\n version: newBundle.version,\n duration: Date.now() - this.currentState.startTime,\n });\n // Clear state\n this.currentState = null;\n }\n catch (error) {\n logger.error('Bundle update failed', error);\n // Attempt rollback\n if (this.currentState) {\n await this.rollback();\n }\n throw error;\n }\n finally {\n this.updateInProgress = false;\n }\n }\n /**\n * Validate update before applying\n */\n async validateUpdate(currentBundle, newBundle, options) {\n const logger = this.pluginManager.getLogger();\n const versionManager = this.pluginManager.getVersionManager();\n // Check if downgrade\n if (currentBundle && !(options === null || options === void 0 ? void 0 : options.allowDowngrade)) {\n if (versionManager.shouldBlockDowngrade(currentBundle.version, newBundle.version)) {\n throw new ValidationError(ErrorCode.VERSION_DOWNGRADE, `Cannot downgrade from ${currentBundle.version} to ${newBundle.version}`);\n }\n }\n // Verify bundle integrity\n if (!newBundle.verified) {\n logger.warn('Bundle not verified, verifying now', {\n bundleId: newBundle.bundleId,\n });\n // Load bundle data\n const downloadManager = this.pluginManager.getDownloadManager();\n const blob = await downloadManager.loadBlob(newBundle.bundleId);\n if (!blob) {\n throw new UpdateError(ErrorCode.FILE_NOT_FOUND, 'Bundle data not found');\n }\n // Verify checksum\n const arrayBuffer = await blob.arrayBuffer();\n const isValid = await this.securityValidator.verifyChecksum(arrayBuffer, newBundle.checksum);\n if (!isValid) {\n throw new ValidationError(ErrorCode.CHECKSUM_MISMATCH, 'Bundle checksum verification failed');\n }\n // Verify signature if enabled\n if (newBundle.signature) {\n const signatureValid = await this.securityValidator.verifySignature(arrayBuffer, newBundle.signature);\n if (!signatureValid) {\n throw new ValidationError(ErrorCode.SIGNATURE_INVALID, 'Bundle signature verification failed');\n }\n }\n // Mark as verified\n await this.pluginManager\n .getBundleManager()\n .markBundleAsVerified(newBundle.bundleId);\n }\n logger.debug('Bundle validation passed', { bundleId: newBundle.bundleId });\n }\n /**\n * Create backup of current bundle\n */\n async createBackup(bundle) {\n const backupPath = `backups/${bundle.bundleId}_${Date.now()}`;\n const logger = this.pluginManager.getLogger();\n try {\n // Create backup directory\n await this.filesystem.mkdir({\n path: backupPath,\n directory: Directory.Data,\n recursive: true,\n });\n // Copy bundle files\n await this.filesystem.copy({\n from: bundle.path,\n to: backupPath,\n directory: Directory.Data,\n });\n logger.info('Backup created', { bundleId: bundle.bundleId, backupPath });\n return backupPath;\n }\n catch (error) {\n logger.error('Failed to create backup', error);\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Failed to create backup', undefined, error);\n }\n }\n /**\n * Perform the actual update\n */\n async performUpdate(bundle) {\n const logger = this.pluginManager.getLogger();\n try {\n // Extract bundle to target location\n const targetPath = `active/${bundle.bundleId}`;\n // Create target directory\n await this.filesystem.mkdir({\n path: targetPath,\n directory: Directory.Data,\n recursive: true,\n });\n // Copy bundle files\n await this.filesystem.copy({\n from: bundle.path,\n to: targetPath,\n directory: Directory.Data,\n });\n // Update bundle path\n bundle.path = targetPath;\n logger.debug('Bundle files installed', {\n bundleId: bundle.bundleId,\n targetPath,\n });\n }\n catch (error) {\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Failed to install bundle files', undefined, error);\n }\n }\n /**\n * Verify update was successful\n */\n async verifyUpdate(bundle) {\n try {\n // Check if main bundle files exist\n const indexPath = `${bundle.path}/index.html`;\n await this.filesystem.stat({\n path: indexPath,\n directory: Directory.Data,\n });\n // Additional verification can be added here\n }\n catch (error) {\n throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Bundle verification failed after installation', undefined, error);\n }\n }\n /**\n * Rollback to previous state\n */\n async rollback() {\n var _a;\n if (!this.currentState) {\n throw new UpdateError(ErrorCode.ROLLBACK_FAILED, 'No update state to rollback');\n }\n const logger = this.pluginManager.getLogger();\n logger.warn('Starting rollback', {\n from: this.currentState.newBundle.bundleId,\n to: ((_a = this.currentState.currentBundle) === null || _a === void 0 ? void 0 : _a.bundleId) || 'default',\n });\n try {\n const bundleManager = this.pluginManager.getBundleManager();\n // Restore from backup if available\n if (this.currentState.backupPath && this.currentState.currentBundle) {\n const restoredPath = `active/${this.currentState.currentBundle.bundleId}`;\n await this.filesystem.copy({\n from: this.currentState.backupPath,\n to: restoredPath,\n directory: Directory.Data,\n });\n // Update bundle path\n this.currentState.currentBundle.path = restoredPath;\n await bundleManager.saveBundleInfo(this.currentState.currentBundle);\n }\n // Restore active bundle\n if (this.currentState.currentBundle) {\n await bundleManager.setActiveBundle(this.currentState.currentBundle.bundleId);\n }\n else {\n // No previous bundle, clear active\n await bundleManager.clearActiveBundle();\n }\n logger.info('Rollback completed successfully');\n }\n catch (error) {\n logger.error('Rollback failed', error);\n throw new UpdateError(ErrorCode.ROLLBACK_FAILED, 'Failed to rollback update', undefined, error);\n }\n finally {\n // Clean up backup\n if (this.currentState.backupPath) {\n try {\n await this.filesystem.rmdir({\n path: this.currentState.backupPath,\n directory: Directory.Data,\n recursive: true,\n });\n }\n catch (error) {\n logger.warn('Failed to clean up backup', error);\n }\n }\n }\n }\n /**\n * Get current update progress\n */\n getUpdateProgress() {\n var _a, _b;\n return {\n inProgress: this.updateInProgress,\n bundleId: (_a = this.currentState) === null || _a === void 0 ? void 0 : _a.newBundle.bundleId,\n startTime: (_b = this.currentState) === null || _b === void 0 ? void 0 : _b.startTime,\n };\n }\n /**\n * Cancel current update (if possible)\n */\n async cancelUpdate() {\n if (!this.updateInProgress || !this.currentState) {\n return;\n }\n const logger = this.pluginManager.getLogger();\n logger.warn('Cancelling update', {\n bundleId: this.currentState.newBundle.bundleId,\n });\n // Attempt rollback\n await this.rollback();\n this.updateInProgress = false;\n this.currentState = null;\n }\n}\n//# sourceMappingURL=update-manager.js.map"],"names":["BackgroundUpdateType","NotificationPriority","UpdateStrategy","UpdateMode","InstallMode","ChecksumAlgorithm","SyncStatus","BundleStatus","InstallStatus","UpdateErrorCode","LogLevel","ErrorCode","AppUpdateInstallStatus","ConfigManager","constructor","this","config","getDefaultConfig","getInstance","instance","filesystem","preferences","baseUrl","allowedHosts","maxBundleSize","downloadTimeout","retryAttempts","retryDelay","enableSignatureValidation","publicKey","cacheExpiration","enableLogging","serverUrl","channel","autoCheck","autoUpdate","updateStrategy","requireSignature","checksumAlgorithm","checkInterval","security","enforceHttps","validateInputs","secureStorage","logSecurityEvents","promptAfterPositiveEvents","maxPromptsPerVersion","minimumDaysSinceLastPrompt","isPremiumUser","appStoreId","iosAppId","packageName","webReviewUrl","minimumVersion","configure","Object","assign","validateConfig","Error","get","key","set","value","getAll","isConfigured","Logger","context","configManager","shouldLog","sanitize","data","sanitized","replace","Array","isArray","map","item","dataObj","toLowerCase","includes","log","message","logWithLevel","INFO","level","timestamp","Date","toISOString","sanitizedData","undefined","logEntry","DEBUG","console","debug","info","WARN","warn","ERROR","error","errorData","name","stack","NativeUpdateError","code","details","originalError","super","setPrototypeOf","prototype","toJSON","DownloadError","ValidationError","StorageError","UpdateError","SecurityValidator","logger","validateUrl","url","URL","protocol","_a","validateChecksum","checksum","test","sanitizeInput","input","validateBundleSize","size","calculateChecksum","hashBuffer","crypto","subtle","digest","from","Uint8Array","b","toString","padStart","join","verifyChecksum","expectedChecksum","actualChecksum","isValid","expected","actual","verifySignature","signature","SIGNATURE_INVALID","cryptoKey","importKey","pemToArrayBuffer","hash","verify","saltLength","base64ToArrayBuffer","pem","base64","binaryString","atob","bytes","length","i","charCodeAt","buffer","sanitizePath","path","split","filter","part","validateBundleId","bundleId","INVALID_BUNDLE_FORMAT","validateVersion","version","isVersionDowngrade","currentVersion","newVersion","current","parseVersion","next","major","minor","patch","parts","parseInt","INVALID_URL","parsedUrl","hostname","UNAUTHORIZED_HOST","some","pattern","validateFileSize","maxSize","BUNDLE_TOO_LARGE","generateSecureId","array","getRandomValues","byte","validateCertificatePin","certificate","certificatePins","hostPins","pin","certificateHash","calculateCertificateHash","sha256","expectedPins","p","actualHash","TextEncoder","encode","hashArray","btoa","String","fromCharCode","validateMetadata","metadata","JSON","stringify","BundleManager","STORAGE_KEY","ACTIVE_BUNDLE_KEY","cache","Map","cacheExpiry","initialize","MISSING_DEPENDENCY","loadCache","now","bundles","parse","clear","forEach","bundle","saveCache","values","count","STORAGE_FULL","saveBundleInfo","validateBundleInfo","getAllBundles","getBundle","deleteBundle","delete","getActiveBundleId","clearActiveBundle","getActiveBundle","activeBundleId","setActiveBundle","FILE_NOT_FOUND","previousActive","status","remove","clearAllBundles","cleanupOldBundles","keepCount","INVALID_CONFIG","sorted","sort","a","downloadTime","toKeep","Set","add","kept","has","deletedCount","deleted","getBundlesOlderThan","markBundleAsVerified","verified","getTotalStorageUsed","reduce","total","isStorageLimitExceeded","additionalSize","totalUsed","maxStorage","navigator","storage","estimate","quota","Math","max","createDefaultBundle","cleanExpiredBundles","expirationTime","cutoffTime","expiredBundles","DownloadManager","activeDownloads","download","onProgress","DOWNLOAD_FAILED","abortController","AbortController","downloadState","controller","startTime","timeout","timeoutId","setTimeout","abort","headers","Accept","resumePosition","response","fetch","signal","clearTimeout","ok","statusText","contentType","isValidContentType","contentLength","totalBytes","body","blob","validateBlobSize","reader","getReader","chunks","receivedBytes","done","read","push","resumeOffset","adjustedLoaded","adjustedTotal","percent","round","bytesDownloaded","Blob","duration","isTimeout","DOWNLOAD_TIMEOUT","resumeDownload","partialData","remainingData","canResume","method","type","cancelDownload","state","cancelAllDownloads","isDownloading","getActiveDownloadCount","downloadWithRetry","maxRetries","lastError","attempt","delay","min","pow","Promise","resolve","attempts","blobToArrayBuffer","arrayBuffer","saveBlob","writeFile","directory","Directory","Data","recursive","loadBlob","result","readFile","deleteBlob","rmdir","VersionManager","VERSION_CHECK_CACHE_KEY","CACHE_DURATION","memoryCache","securityValidator","compareVersions","version1","version2","v1Base","v1Pre","v2Base","v2Pre","v1Parts","Number","v2Parts","v1Part","v2Part","localeCompare","isValidVersion","shouldUpdate","minAppVersion","checkForUpdates","appId","cacheKey","cached","getCachedVersionInfo","searchParams","append","AbortSignal","json","bundleUrl","cacheVersionInfo","latestVersion","updateAvailable","isNewerVersion","v1","v2","prerelease","isUpdateMandatory","match","build","buildVersionString","components","isCompatibleWithNativeVersion","bundleVersion","nativeVersion","compatibility","requiredNativeVersion","memCached","cacheEntry","allCached","clearVersionCache","shouldBlockDowngrade","AppUpdateChecker","checkServerVersion","_","updateUrl","getPlatform","getCurrentVersion","availableVersion","updatePriority","priority","releaseNotes","updateSize","updateURL","downloadUrl","isUpdateRequired","determineUpdatePriority","versionDiff","stalenessDays","window","userAgent","AppUpdateInstaller","currentState","installStatus","UNKNOWN","startImmediateUpdate","updateState","PENDING","isAndroid","isIOS","startFlexibleUpdate","DOWNLOADING","isWeb","simulateFlexibleUpdate","completeFlexibleUpdate","DOWNLOADED","INSTALLING","INSTALLED","cancelUpdate","CANCELED","getInstallState","callback","progressCallback","errorCode","installErrorCode","downloaded","totalSize","chunkSize","interval","setInterval","clearInterval","progress","totalBytesToDownload","percentComplete","downloadSpeed","estimatedTime","ceil","PlatformAppUpdate","platform","Capacitor","checkForUpdate","versionInfo","getVersionInfo","updateInfo","webUpdateUrl","buildNumber","getAppStoreUrl","location","origin","openUrl","open","isUpdateSupported","getUpdateCapabilities","capabilities","immediateUpdate","flexibleUpdate","backgroundDownload","inAppReview","AppUpdateManager","listeners","checker","installer","platformUpdate","checkAppUpdate","options","nativeInfo","serverInfo","mergeUpdateInfo","immediateUpdateAllowed","emit","flexibleUpdateAllowed","isMinimumVersionMet","isMet","updateRequired","enforceMinVersion","getAppUpdateInfo","performImmediateUpdate","openAppStore","_options","storeInfo","getUpdateInstallState","addListener","eventName","listenerFunc","async","removeAllListeners","listener","EventEmitter","removeListeners","listenerCount","eventNames","keys","PluginManager","bundleManager","downloadManager","versionManager","appUpdateManager","initialized","eventEmitter","_b","Filesystem","Preferences","setupAppUpdateEventBridge","isInitialized","ensureInitialized","NOT_CONFIGURED","getBundleManager","getDownloadManager","getVersionManager","getConfigManager","getLogger","getSecurityValidator","getAppUpdateManager","getEventEmitter","reset","cleanup","event","NativeUpdatePluginWeb","windowEventListeners","pluginManager","setupWindowEventBridge","initConfig","liveUpdate","getSecurityInfo","certificatePinning","enabled","pins","sync","currentBundle","UP_TO_DATE","UNKNOWN_ERROR","bundleInfo","READY","reload","list","keepVersions","sortedBundles","notifyAppReady","activeBundle","ACTIVE","getLatest","available","setChannel","setUpdateUrl","validateUpdate","ArrayBuffer","checksumValid","signatureValid","sizeValid","versionValid","requestReview","displayed","canRequestReview","canRequest","reason","enableBackgroundUpdates","disableBackgroundUpdates","getBackgroundUpdateStatus","isRunning","checkCount","failureCount","scheduleBackgroundCheck","_interval","PLATFORM_NOT_SUPPORTED","triggerBackgroundCheck","success","updatesFound","notificationSent","setNotificationPreferences","prefs","getNotificationPermissions","granted","requestNotificationPermissions","removeListener","detail","addEventListener","NativeUpdate","registerPlugin","web","CACHE_DIR","mkdir","cleanExpiredCache","ttlMs","expiry","entry","shouldPersist","persistToFile","memEntry","fileEntry","loadFromFile","removeFile","cleanedCount","files","readdir","file","getStats","fileEntries","stat","memoryEntries","cacheBundleMetadata","getCachedBundleMetadata","encoding","Encoding","UTF8","deleteFile","updateInProgress","applyUpdate","UPDATE_FAILED","newBundle","BUNDLE_NOT_READY","backupPath","createBackup","performUpdate","verifyUpdate","keepBundleCount","rollback","allowDowngrade","VERSION_DOWNGRADE","CHECKSUM_MISMATCH","copy","to","targetPath","indexPath","ROLLBACK_FAILED","restoredPath","getUpdateProgress","inProgress"],"mappings":"IAIWA,EAMAC,EAQAC,EAMAC,EAMAC,EAMAC,EAKAC,EAOAC,EAQAC,EAWAC,ECjEAC,ECDAC,ECDAC,uGHKX,SAAWZ,GACPA,EAAiC,WAAI,aACrCA,EAAkC,YAAI,cACtCA,EAA2B,KAAI,MAClC,CAJD,CAIGA,IAAyBA,EAAuB,CAAA,IAEnD,SAAWC,GACPA,EAA0B,IAAI,MAC9BA,EAA0B,IAAI,MAC9BA,EAA8B,QAAI,UAClCA,EAA2B,KAAI,OAC/BA,EAA0B,IAAI,KACjC,CAND,CAMGA,IAAyBA,EAAuB,CAAA,IAEnD,SAAWC,GACPA,EAA0B,UAAI,YAC9BA,EAA2B,WAAI,aAC/BA,EAAuB,OAAI,QAC9B,CAJD,CAIGA,IAAmBA,EAAiB,CAAA,IAEvC,SAAWC,GACPA,EAAsB,UAAI,YAC1BA,EAA4B,gBAAI,kBAChCA,EAA2B,eAAI,gBAClC,CAJD,CAIGA,IAAeA,EAAa,CAAA,IAE/B,SAAWC,GACPA,EAAuB,UAAI,YAC3BA,EAA6B,gBAAI,kBACjCA,EAA4B,eAAI,gBACnC,CAJD,CAIGA,IAAgBA,EAAc,CAAA,IAEjC,SAAWC,GACPA,EAA0B,OAAI,UAC9BA,EAA0B,OAAI,SACjC,CAHD,CAGGA,IAAsBA,EAAoB,CAAA,IAE7C,SAAWC,GACPA,EAAuB,WAAI,aAC3BA,EAA6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