native-update 5.0.0 → 5.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI-INTEGRATION-GUIDE.md +85 -76
- package/README.md +23 -15
- package/android/build.gradle +1 -1
- package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +13 -13
- package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +3 -1
- package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +79 -6
- package/cli/commands/bundle-create.js +4 -21
- package/cli/commands/flutter-patch.js +2 -11
- package/cli/commands/init.js +68 -87
- package/cli/commands/remote-shared.js +8 -13
- package/cli/commands/server-start.js +3 -3
- package/cli/index.js +6 -6
- package/cli/lib/archive-directory.js +54 -0
- package/cli/package.json +1 -1
- package/dist/esm/core/update-check.d.ts +2 -1
- package/dist/esm/core/update-check.js +5 -1
- package/dist/esm/definitions.d.ts +25 -6
- package/dist/esm/definitions.js +6 -0
- package/dist/esm/plugin.js +2 -0
- package/dist/esm/web.js +2 -0
- package/dist/plugin.cjs +1 -1
- package/dist/plugin.esm.js +1 -1
- package/dist/plugin.js +2 -2
- package/docs/CHANGELOG.md +24 -26
- package/docs/MIGRATION.md +2 -2
- package/docs/protocol/CLIENT-PROTOCOL.md +1 -0
- package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +2 -1
- package/package.json +5 -3
package/dist/plugin.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t,a,r,i,n,o,s,l,d,c,u,h=require("@capacitor/core"),p=require("@capacitor/filesystem"),g=require("@capacitor/preferences");exports.BackgroundUpdateType=void 0,(e=exports.BackgroundUpdateType||(exports.BackgroundUpdateType={})).APP_UPDATE="app_update",e.LIVE_UPDATE="live_update",e.BOTH="both",exports.NotificationPriority=void 0,(t=exports.NotificationPriority||(exports.NotificationPriority={})).MIN="min",t.LOW="low",t.DEFAULT="default",t.HIGH="high",t.MAX="max",exports.UpdateStrategy=void 0,(a=exports.UpdateStrategy||(exports.UpdateStrategy={})).IMMEDIATE="immediate",a.BACKGROUND="background",a.MANUAL="manual",exports.UpdateMode=void 0,(r=exports.UpdateMode||(exports.UpdateMode={})).IMMEDIATE="immediate",r.ON_NEXT_RESTART="on_next_restart",r.ON_NEXT_RESUME="on_next_resume",exports.InstallMode=void 0,(i=exports.InstallMode||(exports.InstallMode={})).IMMEDIATE="immediate",i.ON_NEXT_RESTART="on_next_restart",i.ON_NEXT_RESUME="on_next_resume",exports.ChecksumAlgorithm=void 0,(n=exports.ChecksumAlgorithm||(exports.ChecksumAlgorithm={})).SHA256="SHA-256",n.SHA512="SHA-512",exports.SyncStatus=void 0,(o=exports.SyncStatus||(exports.SyncStatus={})).UP_TO_DATE="UP_TO_DATE",o.UPDATE_AVAILABLE="UPDATE_AVAILABLE",o.UPDATE_INSTALLED="UPDATE_INSTALLED",o.ERROR="ERROR",exports.BundleStatus=void 0,(s=exports.BundleStatus||(exports.BundleStatus={})).PENDING="PENDING",s.DOWNLOADING="DOWNLOADING",s.READY="READY",s.ACTIVE="ACTIVE",s.FAILED="FAILED",exports.InstallStatus=void 0,(l=exports.InstallStatus||(exports.InstallStatus={})).UNKNOWN="UNKNOWN",l.PENDING="PENDING",l.DOWNLOADING="DOWNLOADING",l.DOWNLOADED="DOWNLOADED",l.INSTALLING="INSTALLING",l.INSTALLED="INSTALLED",l.FAILED="FAILED",l.CANCELED="CANCELED",exports.UpdateErrorCode=void 0,(d=exports.UpdateErrorCode||(exports.UpdateErrorCode={})).NETWORK_ERROR="NETWORK_ERROR",d.SERVER_ERROR="SERVER_ERROR",d.TIMEOUT_ERROR="TIMEOUT_ERROR",d.DOWNLOAD_ERROR="DOWNLOAD_ERROR",d.STORAGE_ERROR="STORAGE_ERROR",d.SIZE_LIMIT_EXCEEDED="SIZE_LIMIT_EXCEEDED",d.VERIFICATION_ERROR="VERIFICATION_ERROR",d.CHECKSUM_ERROR="CHECKSUM_ERROR",d.SIGNATURE_ERROR="SIGNATURE_ERROR",d.INSECURE_URL="INSECURE_URL",d.INVALID_CERTIFICATE="INVALID_CERTIFICATE",d.PATH_TRAVERSAL="PATH_TRAVERSAL",d.INSTALL_ERROR="INSTALL_ERROR",d.ROLLBACK_ERROR="ROLLBACK_ERROR",d.VERSION_MISMATCH="VERSION_MISMATCH",d.PERMISSION_DENIED="PERMISSION_DENIED",d.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",d.UPDATE_IN_PROGRESS="UPDATE_IN_PROGRESS",d.UPDATE_CANCELLED="UPDATE_CANCELLED",d.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",d.REVIEW_NOT_SUPPORTED="REVIEW_NOT_SUPPORTED",d.QUOTA_EXCEEDED="QUOTA_EXCEEDED",d.CONDITIONS_NOT_MET="CONDITIONS_NOT_MET",d.INVALID_CONFIG="INVALID_CONFIG",d.NOT_CONFIGURED="NOT_CONFIGURED",d.UNKNOWN_ERROR="UNKNOWN_ERROR";class f{constructor(){this.config=this.getDefaultConfig()}static getInstance(){return f.instance||(f.instance=new f),f.instance}getDefaultConfig(){return{filesystem:null,preferences:null,baseUrl:"",allowedHosts:[],maxBundleSize:104857600,maxUncompressedBundleSize:524288e3,downloadTimeout:3e4,retryAttempts:3,retryDelay:1e3,enableSignatureValidation:!0,publicKey:"",cacheExpiration:864e5,enableLogging:!1,serverUrl:"",channel:"production",appId:"",apiKey:"",autoCheck:!0,autoUpdate:!1,updateStrategy:"background",requireSignature:!0,checksumAlgorithm:"SHA-256",checkInterval:864e5,security:{enforceHttps:!0,validateInputs:!0,secureStorage:!0,logSecurityEvents:!1},allowUnsignedDevelopmentUpdates:!1,promptAfterPositiveEvents:!1,maxPromptsPerVersion:1,minimumDaysSinceLastPrompt:7,isPremiumUser:!1,appStoreId:"",iosAppId:"",packageName:"",webReviewUrl:"",minimumVersion:"1.0.0",enableDeltaUpdates:!0,enableStagedRollouts:!0}}configure(e){this.config=Object.assign(Object.assign({},this.config),e),this.validateConfig()}reset(){this.config=this.getDefaultConfig()}validateConfig(){if(this.config.baseUrl&&!this.config.baseUrl.startsWith("https://"))throw new Error("baseUrl must use HTTPS protocol for security");if(this.config.maxBundleSize<=0)throw new Error("maxBundleSize must be greater than 0");if(this.config.maxUncompressedBundleSize<=0)throw new Error("maxUncompressedBundleSize must be greater than 0");if(this.config.downloadTimeout<=0)throw new Error("downloadTimeout must be greater than 0");if(this.config.retryAttempts<0)throw new Error("retryAttempts must be non-negative");if(this.config.retryDelay<0)throw new Error("retryDelay must be non-negative");if(!1===this.config.security.enforceHttps)throw new Error("HTTPS enforcement cannot be disabled");if((this.config.serverUrl||this.config.apiKey)&&this.config.requireSignature&&!this.config.publicKey)throw new Error("publicKey is required when requireSignature is enabled");if(!this.config.requireSignature&&!this.config.allowUnsignedDevelopmentUpdates)throw new Error("Disabling signatures requires allowUnsignedDevelopmentUpdates for an explicit development-only setup")}get(e){return this.config[e]}set(e,t){this.config[e]=t}getAll(){return Object.assign({},this.config)}isConfigured(){return!(!this.config.filesystem||!this.config.preferences)}}exports.LogLevel=void 0,(c=exports.LogLevel||(exports.LogLevel={}))[c.DEBUG=0]="DEBUG",c[c.INFO=1]="INFO",c[c.WARN=2]="WARN",c[c.ERROR=3]="ERROR";class w{constructor(e){this.configManager=f.getInstance(),this.context=e||"NativeUpdate"}static getInstance(){return w.instance||(w.instance=new w),w.instance}shouldLog(){return this.configManager.get("enableLogging")}sanitize(e){if("string"==typeof e){let t=e;return t=t.replace(/\/[^\s]+\/([\w.-]+)$/g,"/<path>/$1"),t=t.replace(/https?:\/\/[^:]+:[^@]+@/g,"https://***:***@"),t=t.replace(/[a-zA-Z0-9]{32,}/g,"<redacted>"),t}if("object"==typeof e&&null!==e){if(Array.isArray(e))return e.map(e=>this.sanitize(e));{const t={},a=e;for(const e in a)t[e]=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("password")||e.toLowerCase().includes("token")?"<redacted>":this.sanitize(a[e]);return t}}return e}log(e,t){this.logWithLevel(exports.LogLevel.INFO,e,t)}logWithLevel(e,t,a){if(!this.shouldLog())return;const r=(new Date).toISOString(),i=a?this.sanitize(a):void 0,n={timestamp:r,level:exports.LogLevel[e],context:this.context,message:t};switch(void 0!==i&&(n.data=i),e){case exports.LogLevel.DEBUG:console.debug(`[${this.context}]`,n);break;case exports.LogLevel.INFO:console.info(`[${this.context}]`,n);break;case exports.LogLevel.WARN:console.warn(`[${this.context}]`,n);break;case exports.LogLevel.ERROR:console.error(`[${this.context}]`,n)}}debug(e,t){this.logWithLevel(exports.LogLevel.DEBUG,e,t)}info(e,t){this.logWithLevel(exports.LogLevel.INFO,e,t)}warn(e,t){this.logWithLevel(exports.LogLevel.WARN,e,t)}error(e,t){const a=t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t;this.logWithLevel(exports.LogLevel.ERROR,e,a)}}exports.ErrorCode=void 0,(u=exports.ErrorCode||(exports.ErrorCode={})).NOT_CONFIGURED="NOT_CONFIGURED",u.INVALID_CONFIG="INVALID_CONFIG",u.MISSING_DEPENDENCY="MISSING_DEPENDENCY",u.NETWORK_ERROR="NETWORK_ERROR",u.SERVER_ERROR="SERVER_ERROR",u.DOWNLOAD_FAILED="DOWNLOAD_FAILED",u.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",u.INVALID_URL="INVALID_URL",u.INSECURE_URL="INSECURE_URL",u.UNAUTHORIZED_HOST="UNAUTHORIZED_HOST",u.BUNDLE_TOO_LARGE="BUNDLE_TOO_LARGE",u.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",u.SIGNATURE_INVALID="SIGNATURE_INVALID",u.VERSION_DOWNGRADE="VERSION_DOWNGRADE",u.INVALID_BUNDLE_FORMAT="INVALID_BUNDLE_FORMAT",u.VALIDATION_ERROR="VALIDATION_ERROR",u.STORAGE_FULL="STORAGE_FULL",u.FILE_NOT_FOUND="FILE_NOT_FOUND",u.PERMISSION_DENIED="PERMISSION_DENIED",u.UPDATE_FAILED="UPDATE_FAILED",u.ROLLBACK_FAILED="ROLLBACK_FAILED",u.BUNDLE_NOT_READY="BUNDLE_NOT_READY",u.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",u.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",u.NATIVE_ERROR="NATIVE_ERROR";class m extends Error{constructor(e,t,a,r){super(t),this.code=e,this.message=t,this.details=a,this.originalError=r,this.name="NativeUpdateError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,stack:this.stack}}}class v extends m{constructor(e,t,a,r){super(e,t,a,r),this.name="DownloadError"}}class y extends m{constructor(e,t,a){super(e,t,a),this.name="ValidationError"}}class E extends m{constructor(e,t,a,r){super(e,t,a,r),this.name="StorageError"}}class I extends m{constructor(e,t,a,r){super(e,t,a,r),this.name="UpdateError"}}class A{constructor(){this.configManager=f.getInstance(),this.logger=w.getInstance()}static getInstance(){return A.instance||(A.instance=new A),A.instance}static validateUrl(e){try{return"https:"===new URL(e).protocol}catch(e){return!1}}static validateDownloadUrl(e){if(!this.validateUrl(e))throw new y(exports.ErrorCode.INSECURE_URL,`Refusing non-HTTPS URL: ${e}`)}static validateStoreUrl(e){let t;try{t=new URL(e)}catch(t){throw new y(exports.ErrorCode.INSECURE_URL,`Invalid URL: ${e}`)}if(!["https:","market:","itms-apps:"].includes(t.protocol))throw new y(exports.ErrorCode.INSECURE_URL,`Refusing URL scheme ${t.protocol}`)}static validateChecksum(e){return/^[a-f0-9]{64}$/i.test(e)}static sanitizeInput(e){return e?e.replace(/<[^>]*>/g,"").replace(/[^\w\s/.-]/g,""):""}static validateBundleSize(e){return e>0&&e<=104857600}async calculateChecksum(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async verifyChecksum(e,t){if(!t)throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Checksum is required but was not provided");const a=await this.calculateChecksum(e),r=a===t.toLowerCase();return r||this.logger.error("Checksum verification failed",{expected:t,actual:a}),r}async validateChecksum(e,t){return this.verifyChecksum(e,t)}async verifySignature(e,t){const a=this.configManager.get("enableSignatureValidation"),r=this.configManager.get("requireSignature"),i=this.configManager.get("publicKey");if(!t){if(a||r||i)throw new y(exports.ErrorCode.SIGNATURE_INVALID,"Signature is required but was not provided");return!0}if(!i)throw new y(exports.ErrorCode.SIGNATURE_INVALID,"Public key not configured for signature validation");try{const a=await crypto.subtle.importKey("spki",this.pemToArrayBuffer(i),{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]),r=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},a,this.base64ToArrayBuffer(t),e);return r||this.logger.error("Signature verification failed"),r}catch(e){return this.logger.error("Signature verification error",e),!1}}pemToArrayBuffer(e){const t=e.replace(/-----BEGIN PUBLIC KEY-----/g,"").replace(/-----END PUBLIC KEY-----/g,"").replace(/\s/g,"");return this.base64ToArrayBuffer(t)}base64ToArrayBuffer(e){const t=atob(e),a=new Uint8Array(t.length);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e);return a.buffer}sanitizePath(e){return e.split("/").filter(e=>".."!==e&&"."!==e).join("/").replace(/^\/+/,"")}validateBundleId(e){if(!e||"string"!=typeof e)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID must be a non-empty string");if(!/^[a-zA-Z0-9\-_.]+$/.test(e))throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID contains invalid characters");if(e.length>100)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is too long (max 100 characters)")}validateVersion(e){if(!e||"string"!=typeof e)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Version must be a non-empty string");if(!/^(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-]+)*))?$/.test(e))throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Version must follow semantic versioning format (e.g., 1.2.3)")}isVersionDowngrade(e,t){const a=this.parseVersion(e),r=this.parseVersion(t);return r.major<a.major||!(r.major>a.major)&&(r.minor<a.minor||!(r.minor>a.minor)&&r.patch<a.patch)}parseVersion(e){const t=e.split("-")[0].split(".");return{major:parseInt(t[0],10)||0,minor:parseInt(t[1],10)||0,patch:parseInt(t[2],10)||0}}validateUrl(e){if(!e||"string"!=typeof e)throw new y(exports.ErrorCode.INVALID_URL,"URL must be a non-empty string");let t;try{t=new URL(e)}catch(e){throw new y(exports.ErrorCode.INVALID_URL,"Invalid URL format")}if("https:"!==t.protocol)throw new y(exports.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed");const a=this.configManager.get("allowedHosts");if(a.length>0&&!a.includes(t.hostname))throw new y(exports.ErrorCode.UNAUTHORIZED_HOST,`Host ${t.hostname} is not in the allowed hosts list`);if([/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[0-1])\./,/^192\.168\./,/^::1$/,/^fc00:/i,/^fe80:/i].some(e=>e.test(t.hostname)))throw new y(exports.ErrorCode.UNAUTHORIZED_HOST,"Private/local addresses are not allowed")}validateFileSize(e){if("number"!=typeof e||e<0)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"File size must be a non-negative number");const t=this.configManager.get("maxBundleSize");if(e>t)throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,`File size ${e} exceeds maximum allowed size of ${t} bytes`)}generateSecureId(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}async validateCertificatePin(e,t){const a=this.configManager.certificatePins;if(!a||!Array.isArray(a)||0===a.length)return!0;const r=a.filter(t=>t.hostname===e);if(0===r.length)return!0;const i=await this.calculateCertificateHash(t),n=r.some(e=>e.sha256===i);return n||this.logger.error("Certificate pinning validation failed",{hostname:e,expectedPins:r.map(e=>e.sha256),actualHash:i}),n}async calculateCertificateHash(e){const t=(new TextEncoder).encode(e),a=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(a));return"sha256/"+btoa(String.fromCharCode(...r))}validateMetadata(e){if(e&&"object"!=typeof e)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata must be an object");if(JSON.stringify(e||{}).length>10240)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata is too large (max 10KB)")}}class D{constructor(){this.STORAGE_KEY="capacitor_native_update_bundles",this.ACTIVE_BUNDLE_KEY="capacitor_native_update_active",this.preferences=null,this.cache=new Map,this.cacheExpiry=0,this.downloadManager=null,this.logger=w.getInstance(),this.configManager=f.getInstance()}setDownloadManager(e){this.downloadManager=e}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new E(exports.ErrorCode.MISSING_DEPENDENCY,"Preferences not configured. Please configure the plugin first.");await this.loadCache()}async loadCache(){if(!(Date.now()<this.cacheExpiry))try{const{value:e}=await this.preferences.get({key:this.STORAGE_KEY});if(e){const t=JSON.parse(e);this.cache.clear(),t.forEach(e=>this.cache.set(e.bundleId,e))}this.cacheExpiry=Date.now()+5e3}catch(e){this.logger.error("Failed to load bundles from storage",e),this.cache.clear()}}async saveCache(){try{const e=Array.from(this.cache.values());await this.preferences.set({key:this.STORAGE_KEY,value:JSON.stringify(e)}),this.logger.debug("Saved bundles to storage",{count:e.length})}catch(e){throw new E(exports.ErrorCode.STORAGE_FULL,"Failed to save bundles to storage",void 0,e)}}async saveBundleInfo(e){this.validateBundleInfo(e),this.cache.set(e.bundleId,e),await this.saveCache(),this.logger.info("Bundle saved",{bundleId:e.bundleId,version:e.version})}validateBundleInfo(e){if(!e.bundleId||"string"!=typeof e.bundleId)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle ID");if(!e.version||"string"!=typeof e.version)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle version");if(!e.path||"string"!=typeof e.path)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle path");if("number"!=typeof e.size||e.size<0)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle size")}async getAllBundles(){return await this.loadCache(),Array.from(this.cache.values())}async getBundle(e){if(!e)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");return await this.loadCache(),this.cache.get(e)||null}async deleteBundle(e){if(!e)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(await this.loadCache(),this.cache.get(e)){if(this.cache.delete(e),await this.saveCache(),await this.getActiveBundleId()===e&&await this.clearActiveBundle(),this.downloadManager)try{await this.downloadManager.deleteBlob(e)}catch(t){this.logger.warn("Failed to delete bundle file",{bundleId:e,error:t})}this.logger.info("Bundle deleted",{bundleId:e})}else this.logger.warn("Attempted to delete non-existent bundle",{bundleId:e})}async getActiveBundle(){const e=await this.getActiveBundleId();return e?this.getBundle(e):null}async setActiveBundle(e){if(!e)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");const t=await this.getBundle(e);if(!t)throw new E(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${e} not found`);const a=await this.getActiveBundle();a&&a.bundleId!==e&&(a.status="READY",await this.saveBundleInfo(a)),t.status="ACTIVE",await this.saveBundleInfo(t),await this.preferences.set({key:this.ACTIVE_BUNDLE_KEY,value:e}),this.logger.info("Active bundle set",{bundleId:e,version:t.version})}async getActiveBundleId(){try{const{value:e}=await this.preferences.get({key:this.ACTIVE_BUNDLE_KEY});return e}catch(e){return this.logger.error("Failed to get active bundle ID",e),null}}async clearActiveBundle(){await this.preferences.remove({key:this.ACTIVE_BUNDLE_KEY}),this.logger.info("Active bundle cleared")}async clearAllBundles(){await this.preferences.remove({key:this.STORAGE_KEY}),await this.preferences.remove({key:this.ACTIVE_BUNDLE_KEY}),this.cache.clear(),this.cacheExpiry=0,this.logger.info("All bundles cleared")}async cleanupOldBundles(e){if(e<1)throw new E(exports.ErrorCode.INVALID_CONFIG,"Keep count must be at least 1");const t=await this.getAllBundles(),a=await this.getActiveBundleId(),r=t.sort((e,t)=>t.downloadTime-e.downloadTime),i=new Set;a&&i.add(a);let n=i.size;for(const t of r){if(n>=e)break;i.has(t.bundleId)||(i.add(t.bundleId),n++)}let o=0;for(const e of t)i.has(e.bundleId)||(await this.deleteBundle(e.bundleId),o++);o>0&&this.logger.info("Cleaned up old bundles",{deleted:o,kept:n})}async getBundlesOlderThan(e){if(e<0)throw new E(exports.ErrorCode.INVALID_CONFIG,"Timestamp must be non-negative");return(await this.getAllBundles()).filter(t=>t.downloadTime<e)}async markBundleAsVerified(e){const t=await this.getBundle(e);if(!t)throw new E(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${e} not found`);t.verified=!0,await this.saveBundleInfo(t),this.logger.info("Bundle marked as verified",{bundleId:e})}async getTotalStorageUsed(){return(await this.getAllBundles()).reduce((e,t)=>e+t.size,0)}async isStorageLimitExceeded(e=0){const t=await this.getTotalStorageUsed();let a=3*this.configManager.get("maxBundleSize");try{if("storage"in navigator&&"estimate"in navigator.storage){const e=await navigator.storage.estimate();e.quota&&(a=Math.max(a,e.quota-104857600))}}catch(e){this.logger.warn("Storage API not available for quota check, using config limit")}return t+e>a}createDefaultBundle(){return{bundleId:"default",version:"1.0.0",path:"/",downloadTime:Date.now(),size:0,status:"ACTIVE",checksum:"",verified:!0}}async cleanExpiredBundles(){const e=this.configManager.get("cacheExpiration"),t=Date.now()-e,a=await this.getBundlesOlderThan(t);for(const e of a){const t=await this.getActiveBundleId();e.bundleId!==t&&await this.deleteBundle(e.bundleId)}}}class b{constructor(){this.activeDownloads=new Map,this.lastResponseMeta=new Map,this.filesystem=null,this.logger=w.getInstance(),this.configManager=f.getInstance()}async initialize(){if(this.filesystem=this.configManager.get("filesystem"),!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured. Please configure the plugin first.")}validateUrl(e){try{const t=new URL(e);if("https:"!==t.protocol)throw new y(exports.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed for security reasons");const a=this.configManager.get("allowedHosts");if(a.length>0&&!a.includes(t.hostname))throw new y(exports.ErrorCode.UNAUTHORIZED_HOST,`Host ${t.hostname} is not in the allowed hosts list`)}catch(e){if(e instanceof y)throw e;throw new y(exports.ErrorCode.INVALID_URL,"Invalid URL format")}}async download(e,t,a){var r;const i="function"==typeof a?{onProgress:a}:null!=a?a:{},n=i.onProgress,o=null!==(r=i.resumePosition)&&void 0!==r?r:0;if(this.validateUrl(e),!t)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(this.activeDownloads.has(t))throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Download already in progress for bundle ${t}`);const s=new AbortController,l={controller:s,startTime:Date.now(),resumePosition:o>0?o:void 0};this.activeDownloads.set(t,l);try{const a=this.configManager.get("downloadTimeout"),r=setTimeout(()=>s.abort(),a),i={"Cache-Control":"no-cache",Accept:"application/octet-stream, application/zip"};o>0&&(i.Range=`bytes=${o}-`);const d=await fetch(e,{signal:s.signal,headers:i});if(clearTimeout(r),!d.ok)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Download failed: ${d.status} ${d.statusText}`,{status:d.status,statusText:d.statusText});const c=o>0&&206===d.status;l.serverReturnedPartial=c,this.lastResponseMeta.set(t,{partial:c});const u=d.headers.get("content-type");if(u&&!this.isValidContentType(u))throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,`Invalid content type: ${u}`);const h=d.headers.get("content-length"),p=h?parseInt(h,10):0;if(p>this.configManager.get("maxBundleSize"))throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,`Bundle size ${p} exceeds maximum allowed size`);if(!p||!d.body){const e=await d.blob();return this.validateBlobSize(e),e}const g=d.body.getReader(),f=[];let w=0;for(;;){const{done:e,value:a}=await g.read();if(e)break;if(f.push(a),w+=a.length,w>this.configManager.get("maxBundleSize"))throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,"Download size exceeds maximum allowed size");if(n){const e=l.resumePosition||0,a=e+w,r=e+p;n({percent:Math.round(a/r*100),bytesDownloaded:a,totalBytes:r,bundleId:t})}}const m=new Blob(f);return this.validateBlobSize(m),this.logger.info("Download completed",{bundleId:t,size:m.size,duration:Date.now()-l.startTime}),m}catch(e){if(e instanceof Error&&"AbortError"===e.name){const t=Date.now()-l.startTime>=this.configManager.get("downloadTimeout");throw new v(t?exports.ErrorCode.DOWNLOAD_TIMEOUT:exports.ErrorCode.DOWNLOAD_FAILED,t?"Download timed out":"Download cancelled",void 0,e)}throw e}finally{this.activeDownloads.delete(t)}}async resumeDownload(e,t,a,r){const i=await this.download(e,t,{onProgress:r,resumePosition:a.size}),n=this.lastResponseMeta.get(t);return this.lastResponseMeta.delete(t),(null==n?void 0:n.partial)?new Blob([a,i]):(this.logger.info("Resume: server returned full response; discarding partial data",{bundleId:t,partialSize:a.size,responseSize:i.size}),i)}async canResume(e){try{return"bytes"===(await fetch(e,{method:"HEAD"})).headers.get("Accept-Ranges")}catch(e){return!1}}isValidContentType(e){return["application/octet-stream","application/zip","application/x-zip-compressed","application/x-zip"].some(t=>e.includes(t))}validateBlobSize(e){if(0===e.size)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Downloaded file is empty");if(e.size>this.configManager.get("maxBundleSize"))throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,`File size ${e.size} exceeds maximum allowed size`)}cancelDownload(e){const t=this.activeDownloads.get(e);t&&(t.controller.abort(),this.activeDownloads.delete(e),this.logger.info("Download cancelled",{bundleId:e}))}cancelAllDownloads(){for(const e of this.activeDownloads.values())e.controller.abort();const e=this.activeDownloads.size;this.activeDownloads.clear(),e>0&&this.logger.info("All downloads cancelled",{count:e})}isDownloading(e){return this.activeDownloads.has(e)}getActiveDownloadCount(){return this.activeDownloads.size}async downloadWithRetry(e,t,a){const r=this.configManager.get("retryAttempts"),i=this.configManager.get("retryDelay");let n=null;for(let o=0;o<r;o++)try{if(o>0){const e=i*Math.pow(2,o-1),a=.5*(Math.random()-.5)*e,r=Math.min(Math.max(e+a,100),3e4);await new Promise(e=>setTimeout(e,r)),this.logger.debug("Retrying download",{bundleId:t,attempt:o,delay:r})}return await this.download(e,t,a)}catch(e){if(n=e,e instanceof y||e instanceof Error&&"AbortError"===e.name)throw e;this.logger.warn(`Download attempt ${o+1} failed`,{bundleId:t,error:e})}throw new v(exports.ErrorCode.DOWNLOAD_FAILED,"Download failed after all retries",{attempts:r},n||void 0)}async blobToArrayBuffer(e){return e.arrayBuffer()}async saveBlob(e,t){if(!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");const a=await this.blobToArrayBuffer(t),r=new Uint8Array(a);let i="";for(let e=0;e<r.length;e+=32768)i+=String.fromCharCode.apply(null,Array.from(r.subarray(e,e+32768)));const n=btoa(i),o=`bundles/${e}/bundle.zip`;return await this.filesystem.writeFile({path:o,data:n,directory:p.Directory.Data,recursive:!0}),this.logger.debug("Bundle saved to filesystem",{bundleId:e,path:o,size:t.size}),o}async loadBlob(e){if(!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const t=`bundles/${e}/bundle.zip`,a=await this.filesystem.readFile({path:t,directory:p.Directory.Data}),r=atob(a.data),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return new Blob([i],{type:"application/zip"})}catch(t){return this.logger.debug("Failed to load bundle from filesystem",{bundleId:e,error:t}),null}}async deleteBlob(e){if(!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const t=`bundles/${e}`;await this.filesystem.rmdir({path:t,directory:p.Directory.Data,recursive:!0}),this.logger.debug("Bundle deleted from filesystem",{bundleId:e})}catch(t){this.logger.warn("Failed to delete bundle from filesystem",{bundleId:e,error:t})}}}async function U(e,t){var a,r,i,n,o;const s=`${e.replace(/\/$/,"")}/v1/updates/check?channel=${encodeURIComponent(t.channel)}`,l={"Content-Type":"application/json","X-API-Key":t.apiKey,"X-Device-ID":t.deviceId,"X-Current-Version":t.currentVersion,"X-Platform":t.platform,"X-Client-Sdk":"capacitor","X-Sdk-Version":"5.0.0"};t.appVersion&&(l["X-App-Version"]=t.appVersion);const d=t.identity;"android"===(null==d?void 0:d.platform)?(d.packageName&&(l["X-Android-Package"]=d.packageName),d.certSha256&&(l["X-Android-Cert-Sha256"]=d.certSha256),d.certSha1&&(l["X-Android-Cert-Sha1"]=d.certSha1)):"ios"===(null==d?void 0:d.platform)&&(d.bundleId&&(l["X-Ios-Bundle-Id"]=d.bundleId),d.teamId&&(l["X-Ios-Team-Id"]=d.teamId));const c=await fetch(s,{method:"GET",headers:l,signal:t.signal});if(!c.ok)return{available:!1};const u=await c.json();return{available:Boolean(u.available),version:u.version,bundleId:u.bundleId,downloadUrl:u.downloadUrl,checksum:u.checksum,signature:null!==(a=u.signature)&&void 0!==a?a:void 0,signatureAlgorithm:null!==(r=u.signatureAlgorithm)&&void 0!==r?r:void 0,delta:null!==(i=u.delta)&&void 0!==i?i:void 0,size:u.size,mandatory:u.mandatory,releaseNotes:null!==(n=u.releaseNotes)&&void 0!==n?n:void 0,minNativeVersion:null!==(o=u.minNativeVersion)&&void 0!==o?o:void 0,expiresAt:u.expiresAt,payloadType:u.payloadType,message:u.message,held:!0===u.held||void 0,code:u.code}}function N(e){const t=e.trim().replace(/^v/i,"").split("+")[0],a=t.indexOf("-"),r=-1===a?t:t.slice(0,a),i=-1===a?"":t.slice(a+1);return{core:r.split(".").map(e=>{const t=Number.parseInt(e,10);return Number.isFinite(t)?t:0}),pre:""===i?[]:i.split(".")}}const C=/^\d+$/,S=/^(.*?)(\d+)$/;function L(e,t){const a=C.test(e),r=C.test(t);if(a&&r)return Math.sign(Number(e)-Number(t));if(a)return-1;if(r)return 1;const i=S.exec(e),n=S.exec(t);return i&&n&&i[1]===n[1]?Math.sign(Number(i[2])-Number(n[2])):e===t?0:e<t?-1:1}function R(e,t){var a,r;const i=N(e),n=N(t),o=Math.max(i.core.length,n.core.length,3);for(let e=0;e<o;e++){const t=(null!==(a=i.core[e])&&void 0!==a?a:0)-(null!==(r=n.core[e])&&void 0!==r?r:0);if(0!==t)return Math.sign(t)}if(0===i.pre.length&&0===n.pre.length)return 0;if(0===i.pre.length)return 1;if(0===n.pre.length)return-1;const s=Math.max(i.pre.length,n.pre.length);for(let e=0;e<s;e++){const t=i.pre[e],a=n.pre[e];if(void 0===t)return-1;if(void 0===a)return 1;const r=L(t,a);if(0!==r)return r}return 0}class _{constructor(){this.VERSION_CHECK_CACHE_KEY="capacitor_native_update_version_cache",this.CACHE_DURATION=3e5,this.preferences=null,this.memoryCache=new Map,this.logger=w.getInstance(),this.configManager=f.getInstance(),this.securityValidator=A.getInstance()}static compareVersions(e,t){return R(e,t)}static isValidVersion(e){return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(e)}static shouldUpdate(e,t,a){return!(a&&_.compareVersions(e,a)<0)&&_.compareVersions(e,t)<0}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new y(exports.ErrorCode.MISSING_DEPENDENCY,"Preferences not configured. Please configure the plugin first.")}async checkForUpdates(e,t,a,r){var i;if(this.securityValidator.validateUrl(e),this.securityValidator.validateVersion(a),!t||!r)throw new y(exports.ErrorCode.INVALID_CONFIG,"Channel and appId are required");const n=`${t}-${r}`,o=await this.getCachedVersionInfo(n);if(o&&o.channel===t&&Date.now()-o.timestamp<this.CACHE_DURATION)return this.logger.debug("Returning cached version info",{channel:t,version:o.data.version}),o.data;const s=this.configManager.get("apiKey");if(!s)return this.logger.warn("VersionManager.checkForUpdates: no apiKey configured — the Native Update backend requires X-API-Key"),null;try{const r=await U(e,{apiKey:s,channel:t,currentVersion:a,deviceId:"web-client",platform:"web",appVersion:a,signal:AbortSignal.timeout(this.configManager.get("downloadTimeout"))}),o={available:r.available,version:r.version,url:r.downloadUrl,mandatory:r.mandatory,notes:null!==(i=r.releaseNotes)&&void 0!==i?i:void 0,size:r.size,checksum:r.checksum};if(!o.available)return o;if(!o.version)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"No version in server response");return this.securityValidator.validateVersion(o.version),o.url&&this.securityValidator.validateUrl(o.url),r.minNativeVersion&&this.securityValidator.validateVersion(r.minNativeVersion),await this.cacheVersionInfo(n,t,o),this.logger.info("Version check completed",{channel:t,currentVersion:a,latestVersion:o.version,updateAvailable:this.isNewerVersion(o.version,a)}),o}catch(e){return this.logger.error("Failed to check for updates",e),null}}isNewerVersion(e,t){try{const a=this.parseVersion(e),r=this.parseVersion(t);return a.major!==r.major?a.major>r.major:a.minor!==r.minor?a.minor>r.minor:a.patch!==r.patch?a.patch>r.patch:!(a.prerelease&&!r.prerelease||(a.prerelease||!r.prerelease)&&(!a.prerelease||!r.prerelease||!(a.prerelease>r.prerelease)))}catch(a){return this.logger.error("Failed to compare versions",{version1:e,version2:t,error:a}),!1}}isUpdateMandatory(e,t){if(!t)return!1;try{return this.securityValidator.validateVersion(e),this.securityValidator.validateVersion(t),!this.isNewerVersion(e,t)&&e!==t}catch(e){return this.logger.error("Failed to check mandatory update",e),!1}}parseVersion(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/);if(!t)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid version format");return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),prerelease:t[4],build:t[5]}}buildVersionString(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease&&(t+=`-${e.prerelease}`),e.build&&(t+=`+${e.build}`),t}isCompatibleWithNativeVersion(e,t,a){if(!a)return!0;try{const r=a[e];return!r||(this.securityValidator.validateVersion(t),this.securityValidator.validateVersion(r),!this.isNewerVersion(r,t))}catch(e){return this.logger.error("Failed to check compatibility",e),!1}}async getCachedVersionInfo(e){const t=this.memoryCache.get(e);if(t&&Date.now()-t.timestamp<this.CACHE_DURATION)return t;try{const{value:t}=await this.preferences.get({key:this.VERSION_CHECK_CACHE_KEY});if(!t)return null;const a=JSON.parse(t)[e];if(a&&Date.now()-a.timestamp<this.CACHE_DURATION)return this.memoryCache.set(e,a),a}catch(e){this.logger.debug("Failed to load cached version info",e)}return null}async cacheVersionInfo(e,t,a){const r={channel:t,data:a,timestamp:Date.now()};this.memoryCache.set(e,r);try{const{value:t}=await this.preferences.get({key:this.VERSION_CHECK_CACHE_KEY}),a=t?JSON.parse(t):{},i=Date.now();for(const e in a)i-a[e].timestamp>2*this.CACHE_DURATION&&delete a[e];a[e]=r,await this.preferences.set({key:this.VERSION_CHECK_CACHE_KEY,value:JSON.stringify(a)})}catch(e){this.logger.warn("Failed to cache version info",e)}}async clearVersionCache(){this.memoryCache.clear();try{await this.preferences.remove({key:this.VERSION_CHECK_CACHE_KEY})}catch(e){this.logger.warn("Failed to clear version cache",e)}}shouldBlockDowngrade(e,t){try{return this.securityValidator.isVersionDowngrade(e,t)}catch(e){return this.logger.error("Failed to check downgrade",e),!0}}maxVersionKey(e){return`nu_max_version_${e}`}async getMaxSeenVersion(e){if(!this.preferences)return null;try{const{value:t}=await this.preferences.get({key:this.maxVersionKey(e)});return null!=t?t:null}catch(e){return this.logger.warn("Failed to read max-seen version",e),null}}async rememberAppliedVersion(e,t){if(!this.preferences)return;const a=await this.getMaxSeenVersion(e);if(!(a&&_.compareVersions(a,t)>=0))try{await this.preferences.set({key:this.maxVersionKey(e),value:t})}catch(e){this.logger.warn("Failed to persist max-seen version",e)}}}class M{constructor(e){this.cachedAppInfo=null,this.CACHE_DURATION=6e4,this.config=e,this.logger=new w("AppUpdateChecker")}async checkServerVersion(e){if(!this.config.updateUrl)return{};try{const e=await this.getCurrentVersion(),t=new URL(`${this.config.updateUrl}/app-version`);t.searchParams.append("platform",this.getPlatform()),t.searchParams.append("current",e),this.config.channel&&t.searchParams.append("channel",this.config.channel);const a=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json","X-App-Version":e,"X-App-Platform":this.getPlatform()}});if(!a.ok)throw new Error(`Server returned ${a.status}`);const r=await a.json();return{availableVersion:r.version,updatePriority:r.priority,releaseNotes:r.releaseNotes,updateSize:r.size,updateURL:r.downloadUrl}}catch(e){return this.logger.error("Failed to check server version",e),{}}}compareVersions(e,t){return R(e,t)}isUpdateRequired(e,t,a){return this.compareVersions(e,t)<0||!!(a&&this.compareVersions(e,a)<0)}determineUpdatePriority(e,t){const[a,r]=e.split(".").map(Number);return a>0?5:r>0&&t&&t>30?4:r>0?3:1}async getCurrentVersion(){if(this.cachedAppInfo&&Date.now()-this.cachedAppInfo.timestamp<this.CACHE_DURATION)return this.cachedAppInfo.version;try{const{App:e}=await(import("@capacitor/app")),t=await e.getInfo();return this.cachedAppInfo={version:t.version,build:t.build,name:t.name,id:t.id,timestamp:Date.now()},this.logger.debug("Got app info from Capacitor",{version:t.version,build:t.build}),t.version}catch(e){this.logger.debug("Failed to get app info from Capacitor, using fallback",e);const t=this.config.appVersion;if("string"==typeof t)return t;if("undefined"!=typeof window){const e=window;if("string"==typeof e.APP_VERSION)return e.APP_VERSION}return"1.0.0"}}async getCurrentBuild(){if(this.cachedAppInfo&&Date.now()-this.cachedAppInfo.timestamp<this.CACHE_DURATION)return this.cachedAppInfo.build;try{const{App:e}=await(import("@capacitor/app")),t=await e.getInfo();return this.cachedAppInfo={version:t.version,build:t.build,name:t.name,id:t.id,timestamp:Date.now()},t.build}catch(e){return"1"}}async getAppInfo(){if(this.cachedAppInfo&&Date.now()-this.cachedAppInfo.timestamp<this.CACHE_DURATION)return this.cachedAppInfo;try{const{App:e}=await(import("@capacitor/app")),t=await e.getInfo();return this.cachedAppInfo={version:t.version,build:t.build,name:t.name,id:t.id,timestamp:Date.now()},this.cachedAppInfo}catch(e){return{version:"1.0.0",build:"1",name:"App",id:"com.app",timestamp:Date.now()}}}clearCache(){this.cachedAppInfo=null}getPlatform(){if("undefined"!=typeof window){const e=window.navigator.userAgent;if(/android/i.test(e))return"android";if(/iPad|iPhone|iPod/.test(e))return"ios"}return"web"}}var O;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.PENDING=1]="PENDING",e[e.DOWNLOADING=2]="DOWNLOADING",e[e.INSTALLING=3]="INSTALLING",e[e.INSTALLED=4]="INSTALLED",e[e.FAILED=5]="FAILED",e[e.CANCELED=6]="CANCELED",e[e.DOWNLOADED=11]="DOWNLOADED"}(O||(O={}));class T{constructor(e){this.flexibleUpdateInterval=null,this.logger=new w("AppUpdateInstaller"),this.currentState={installStatus:O.UNKNOWN,packageName:"",availableVersion:""}}async startImmediateUpdate(){if(this.logger.log("Starting immediate update installation"),this.updateState(O.PENDING),this.isAndroid())this.logger.log("Triggering Android immediate update");else{if(!this.isIOS())throw new Error("Immediate updates not supported on web platform");this.logger.log("Opening iOS App Store for update")}}async startFlexibleUpdate(){if(this.logger.log("Starting flexible update download"),this.updateState(O.DOWNLOADING),this.isWeb())this.simulateFlexibleUpdate();else{if(!this.isAndroid())throw new Error("Flexible updates not supported on iOS");this.logger.log("Starting Android flexible update")}}async completeFlexibleUpdate(){if(this.logger.log("Completing flexible update installation"),this.currentState.installStatus!==O.DOWNLOADED)throw new Error("Update not ready for installation");this.updateState(O.INSTALLING),this.isAndroid()?this.logger.log("Completing Android update installation"):setTimeout(()=>{this.updateState(O.INSTALLED)},1e3)}async cancelUpdate(){this.logger.log("Cancelling update"),this.flexibleUpdateInterval&&(clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=null),this.currentState.installStatus===O.DOWNLOADING&&this.updateState(O.CANCELED)}async getInstallState(){return Object.assign({},this.currentState)}onProgress(e){this.progressCallback=e}updateState(e,t){this.currentState.installStatus=e,void 0!==t&&(this.currentState.installErrorCode=t),this.logger.log("Update state changed",this.currentState)}simulateFlexibleUpdate(){let e=0;const t=52428800,a=1048576;this.flexibleUpdateInterval&&clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=setInterval(()=>{e+=a,e>=t&&(e=t,this.flexibleUpdateInterval&&(clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=null),this.updateState(O.DOWNLOADED));const r={bytesDownloaded:e,totalBytesToDownload:t,percentComplete:Math.round(e/t*100),downloadSpeed:a,estimatedTime:Math.ceil((t-e)/a)};this.progressCallback&&this.progressCallback(r)},1e3)}isAndroid(){return"undefined"!=typeof window&&/android/i.test(window.navigator.userAgent)}isIOS(){return"undefined"!=typeof window&&/iPad|iPhone|iPod/.test(window.navigator.userAgent)}isWeb(){return!this.isAndroid()&&!this.isIOS()}}class x{constructor(e){this.config=e,this.logger=new w("PlatformAppUpdate"),this.platform=h.Capacitor.getPlatform()}async checkForUpdate(e){this.logger.log("Checking for platform update: "+this.platform);const t=await this.getVersionInfo(),a={updateAvailable:!1,currentVersion:t.currentVersion,availableVersion:t.currentVersion};if("android"===this.platform)return a;if("ios"===this.platform)return a;if(this.config.webUpdateUrl)try{A.validateDownloadUrl(this.config.webUpdateUrl);const e=await fetch(this.config.webUpdateUrl),r=await e.json();r.version&&r.version!==t.currentVersion&&(a.updateAvailable=!0,a.availableVersion=r.version,a.releaseNotes=r.releaseNotes,r.downloadUrl&&(A.validateStoreUrl(r.downloadUrl),a.updateURL=r.downloadUrl))}catch(e){this.logger.error("Failed to check web update",e)}return a}async getVersionInfo(){return{currentVersion:"1.0.0",buildNumber:"1",packageName:"com.example.app",platform:this.platform,minimumVersion:this.config.minimumVersion}}async getAppStoreUrl(){const e=this.platform;let t="";if("ios"===e){const e=this.config.appStoreId||this.config.iosAppId;if(!e)throw new Error("App Store ID not configured");t=`https://apps.apple.com/app/id${e}`}else t="android"===e?`https://play.google.com/store/apps/details?id=${this.config.packageName||(await this.getVersionInfo()).packageName}`:this.config.webUpdateUrl||window.location.origin;return{url:t,platform:e}}async openUrl(e){if(A.validateStoreUrl(e),"undefined"==typeof window||!window.open)throw new Error("Cannot open URL on this platform");window.open(e,"_blank","noopener,noreferrer")}isUpdateSupported(){return"android"===this.platform||"ios"!==this.platform}getUpdateCapabilities(){const e={immediateUpdate:!1,flexibleUpdate:!1,backgroundDownload:!1,inAppReview:!1};return"android"===this.platform?(e.immediateUpdate=!0,e.flexibleUpdate=!0,e.backgroundDownload=!0,e.inAppReview=!0):"ios"===this.platform&&(e.inAppReview=!0),e}}class B{constructor(e){this.listeners=new Map,this.config=e,this.logger=new w("AppUpdateManager"),this.checker=new M(e),this.installer=new T(e),this.platformUpdate=new x(e)}async checkAppUpdate(e){try{this.logger.log("Checking for app updates",e);const t=await this.platformUpdate.checkForUpdate(e);if(!t.updateAvailable&&this.config.updateUrl){const a=await this.checker.checkServerVersion(e);return this.mergeUpdateInfo(t,a)}return t}catch(e){throw this.logger.error("Failed to check app update",e),e}}async startImmediateUpdate(){try{this.logger.log("Starting immediate update");const e=await this.checkAppUpdate();if(!e.immediateUpdateAllowed)throw new Error("Immediate update not allowed");await this.installer.startImmediateUpdate(),this.emit("appUpdateStateChanged",{installStatus:1,packageName:this.config.packageName||"",availableVersion:e.availableVersion||""})}catch(e){throw this.logger.error("Failed to start immediate update",e),e}}async startFlexibleUpdate(){try{this.logger.log("Starting flexible update");const e=await this.checkAppUpdate();if(!e.flexibleUpdateAllowed)throw new Error("Flexible update not allowed");await this.installer.startFlexibleUpdate(),this.installer.onProgress(e=>{this.emit("appUpdateProgress",e)}),this.emit("appUpdateStateChanged",{installStatus:2,packageName:this.config.packageName||"",availableVersion:e.availableVersion||""})}catch(e){throw this.logger.error("Failed to start flexible update",e),e}}async completeFlexibleUpdate(){try{this.logger.log("Completing flexible update"),await this.installer.completeFlexibleUpdate(),this.emit("appUpdateStateChanged",{installStatus:3,packageName:this.config.packageName||"",availableVersion:""})}catch(e){throw this.logger.error("Failed to complete flexible update",e),e}}async getVersionInfo(){try{return this.logger.log("Getting version info"),await this.platformUpdate.getVersionInfo()}catch(e){throw this.logger.error("Failed to get version info",e),e}}async isMinimumVersionMet(){try{this.logger.log("Checking minimum version");const e=await this.getVersionInfo(),t=this.config.minimumVersion||"0.0.0",a=this.checker.compareVersions(e.currentVersion,t)>=0;return{isMet:a,currentVersion:e.currentVersion,minimumVersion:t,updateRequired:!a&&!0===this.config.enforceMinVersion}}catch(e){throw this.logger.error("Failed to check minimum version",e),e}}async getAppUpdateInfo(){return this.checkAppUpdate()}async performImmediateUpdate(){return this.startImmediateUpdate()}async openAppStore(e){try{this.logger.log("Opening app store");const e=await this.getAppStoreUrl();await this.platformUpdate.openUrl(e.url)}catch(e){throw this.logger.error("Failed to open app store",e),e}}async getAppStoreUrl(){try{return this.logger.log("Getting app store URL"),await this.platformUpdate.getAppStoreUrl()}catch(e){throw this.logger.error("Failed to get app store URL",e),e}}async getUpdateInstallState(){try{return this.logger.log("Getting update install state"),await this.installer.getInstallState()}catch(e){throw this.logger.error("Failed to get update install state",e),e}}addListener(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),{remove:async()=>{const a=this.listeners.get(e);a&&a.delete(t)}}}async removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}emit(e,t){const a=this.listeners.get(e);a&&a.forEach(a=>{try{a(t)}catch(t){this.logger.error(`Error in ${e} listener`,t)}})}mergeUpdateInfo(e,t){return Object.assign(Object.assign(Object.assign({},e),t),{updateAvailable:e.updateAvailable||!!t.availableVersion,availableVersion:t.availableVersion||e.availableVersion})}}class V{constructor(){this.config=null,this.status={enabled:!1,isRunning:!1,checkCount:0,failureCount:0},this.deps={},this.logger=w.getInstance(),this.configManager=f.getInstance()}setDependencies(e){this.deps=e}configure(e){this.config=e,this.status.enabled=e.enabled}getStatus(){return Object.assign({},this.status)}async performCheck(){var e;if(!(null===(e=this.config)||void 0===e?void 0:e.enabled))return{success:!1,updatesFound:!1,notificationSent:!1,error:{code:exports.UpdateErrorCode.INVALID_CONFIG,message:"Background updates not enabled"}};this.status.isRunning=!0,this.status.checkCount++;try{const e=await this.checkForUpdates();return this.status.lastCheckTime=Date.now(),this.status.isRunning=!1,this.status.lastError=void 0,e}catch(e){return this.status.failureCount++,this.status.isRunning=!1,this.status.lastError={code:exports.UpdateErrorCode.UNKNOWN_ERROR,message:e instanceof Error?e.message:"Unknown error"},{success:!1,updatesFound:!1,notificationSent:!1,error:this.status.lastError}}}async checkForUpdates(){var e,t,a,r,i,n;const o=[];let s,l;((null===(e=this.config)||void 0===e?void 0:e.updateTypes.includes(exports.BackgroundUpdateType.APP_UPDATE))||(null===(t=this.config)||void 0===t?void 0:t.updateTypes.includes(exports.BackgroundUpdateType.BOTH)))&&o.push(this.checkAppUpdate()),((null===(a=this.config)||void 0===a?void 0:a.updateTypes.includes(exports.BackgroundUpdateType.LIVE_UPDATE))||(null===(r=this.config)||void 0===r?void 0:r.updateTypes.includes(exports.BackgroundUpdateType.BOTH)))&&o.push(this.checkLiveUpdate());const d=await Promise.allSettled(o);"fulfilled"===(null===(i=d[0])||void 0===i?void 0:i.status)&&(s=d[0].value),"fulfilled"===(null===(n=d[1])||void 0===n?void 0:n.status)&&(l=d[1].value);const c=(null==s?void 0:s.updateAvailable)||(null==l?void 0:l.available)||!1;let u=!1;return c&&(u=await this.sendNotification(s,l)),{success:!0,updatesFound:c,appUpdate:s,liveUpdate:l,notificationSent:u}}async checkAppUpdate(){if(this.deps.appUpdateManager)try{return await this.deps.appUpdateManager.getAppUpdateInfo()}catch(e){this.logger.error("Failed to check app update via manager",e)}const e=this.configManager.get("baseUrl")||this.configManager.get("serverUrl");if(e)try{const t=await this.getCurrentAppVersion(),a=await fetch(`${e}/app-version`,{method:"GET",headers:{"Content-Type":"application/json","X-Current-Version":t,"X-Platform":this.getPlatform()}});if(a.ok){const e=await a.json(),r=e.version||e.latestVersion,i=r&&this.compareVersions(t,r)<0;return{updateAvailable:i,currentVersion:t,availableVersion:i?r:void 0,updatePriority:e.priority}}}catch(e){this.logger.error("Failed to check app update via server",e)}return{updateAvailable:!1,currentVersion:await this.getCurrentAppVersion()}}async checkLiveUpdate(){var e;let t="1.0.0";if(this.deps.bundleManager)try{const e=await this.deps.bundleManager.getActiveBundle();e&&(t=e.version)}catch(e){}if(this.deps.versionManager)try{const e=this.configManager.get("serverUrl"),a=this.configManager.get("channel")||"production",r=this.configManager.get("appId");if(e&&r){const i=await this.deps.versionManager.checkForUpdates(e,a,t,r);if(i)return i}}catch(e){this.logger.error("Failed to check live update via VersionManager",e)}const a=this.configManager.get("baseUrl")||this.configManager.get("serverUrl"),r=this.configManager.get("apiKey");if(a&&r)try{const i=this.configManager.get("channel")||"production",n=await U(a,{apiKey:r,channel:i,currentVersion:t,deviceId:"web-client",platform:this.getPlatform(),appVersion:t});return{available:n.available,version:n.version,url:n.available?n.downloadUrl:void 0,notes:null!==(e=n.releaseNotes)&&void 0!==e?e:void 0,size:n.size,checksum:n.checksum}}catch(e){this.logger.error("Failed to check live update via server",e)}return{available:!1}}async sendNotification(e,t){var a;if(!(null===(a=this.config)||void 0===a?void 0:a.notificationPreferences))return!1;const r=this.config.notificationPreferences;let i=r.title||"Update Available",n=r.description||"";if((null==e?void 0:e.updateAvailable)?(i="App Update Available",n=`Version ${e.availableVersion} is ready to install.`):(null==t?void 0:t.available)&&(i="New Update Available",n=`Version ${t.version} is ready to download. ${t.notes||""}`),"undefined"!=typeof window&&"Notification"in window)try{if("granted"===Notification.permission)return new Notification(i,{body:n}),!0}catch(e){this.logger.error("Failed to send notification",e)}return this.logger.info("Background update notification",{title:i,body:n}),!1}async getCurrentAppVersion(){try{const{App:e}=await(import("@capacitor/app"));return(await e.getInfo()).version}catch(e){return"1.0.0"}}getPlatform(){if("undefined"!=typeof window){const e=window.navigator.userAgent;if(/android/i.test(e))return"android";if(/iPad|iPhone|iPod/.test(e))return"ios"}return"web"}calculateNextCheckTime(){var e;return Date.now()+((null===(e=this.config)||void 0===e?void 0:e.checkInterval)||864e5)}shouldRespectBatteryOptimization(){var e,t;return null===(t=null===(e=this.config)||void 0===e?void 0:e.respectBatteryOptimization)||void 0===t||t}isNetworkConditionMet(){return"undefined"==typeof navigator||!("onLine"in navigator)||navigator.onLine}isBatteryLevelSufficient(){return!0}compareVersions(e,t){return R(e,t)}}const k=new w("NativeUpdate.EventEmitter");class F{constructor(){this.listeners=new Map}static getInstance(){return F.instance||(F.instance=new F),F.instance}addListener(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const a=this.listeners.get(e);a&&(a.delete(t),0===a.size&&this.listeners.delete(e))}}emit(e,t){const a=this.listeners.get(e);a&&a.forEach(a=>{try{a(t)}catch(t){k.error(`Error in event listener for ${e}`,t)}})}removeListeners(e){this.listeners.delete(e)}removeAllListeners(){this.listeners.clear()}listenerCount(e){var t;return(null===(t=this.listeners.get(e))||void 0===t?void 0:t.size)||0}eventNames(){return Array.from(this.listeners.keys())}}class P{constructor(){this.bundleManager=null,this.downloadManager=null,this.versionManager=null,this.appUpdateManager=null,this.backgroundScheduler=null,this.initialized=!1,this.configManager=f.getInstance(),this.logger=w.getInstance(),this.securityValidator=A.getInstance(),this.eventEmitter=F.getInstance()}static getInstance(){return P.instance||(P.instance=new P),P.instance}async initialize(e){var t,a;if(this.initialized)this.logger.warn("Plugin already initialized");else try{e.filesystem||(e.filesystem=p.Filesystem),e.preferences||(e.preferences=g.Preferences),this.configManager.configure(e),this.bundleManager=new D,await this.bundleManager.initialize(),this.downloadManager=new b,await this.downloadManager.initialize(),this.bundleManager.setDownloadManager(this.downloadManager),this.versionManager=new _,await this.versionManager.initialize(),this.appUpdateManager=new B({serverUrl:e.serverUrl||e.baseUrl||"",channel:e.channel||"production",autoCheck:null===(t=e.autoCheck)||void 0===t||t,autoUpdate:null!==(a=e.autoUpdate)&&void 0!==a&&a,updateStrategy:e.updateStrategy,publicKey:e.publicKey,requireSignature:e.requireSignature,checksumAlgorithm:e.checksumAlgorithm,checkInterval:e.checkInterval,security:e.security}),this.setupAppUpdateEventBridge(),this.backgroundScheduler=new V,this.backgroundScheduler.setDependencies({appUpdateManager:this.appUpdateManager,versionManager:this.versionManager,bundleManager:this.bundleManager}),this.initialized=!0,this.logger.info("Plugin initialized successfully")}catch(e){throw this.logger.error("Failed to initialize plugin",e),e}}isInitialized(){return this.initialized&&this.configManager.isConfigured()}ensureInitialized(){if(!this.isInitialized())throw new m(exports.ErrorCode.NOT_CONFIGURED,"Plugin not initialized. Please call initialize() first.")}getBundleManager(){return this.ensureInitialized(),this.bundleManager}getDownloadManager(){return this.ensureInitialized(),this.downloadManager}getVersionManager(){return this.ensureInitialized(),this.versionManager}getConfigManager(){return this.configManager}getLogger(){return this.logger}getSecurityValidator(){return this.securityValidator}getAppUpdateManager(){return this.ensureInitialized(),this.appUpdateManager}getEventEmitter(){return this.eventEmitter}getBackgroundScheduler(){return this.ensureInitialized(),this.backgroundScheduler}async reset(){this.logger.info("Resetting plugin state"),this.bundleManager&&await this.bundleManager.clearAllBundles(),this.versionManager&&await this.versionManager.clearVersionCache(),this.downloadManager&&this.downloadManager.cancelAllDownloads(),this.bundleManager=null,this.downloadManager=null,this.versionManager=null,this.appUpdateManager=null,this.backgroundScheduler=null,this.initialized=!1,this.configManager.reset(),this.eventEmitter.removeAllListeners(),this.logger.info("Plugin reset complete")}async cleanup(){this.logger.info("Cleaning up plugin resources"),this.downloadManager&&this.downloadManager.cancelAllDownloads(),this.bundleManager&&await this.bundleManager.cleanExpiredBundles(),this.logger.info("Cleanup complete")}setupAppUpdateEventBridge(){this.appUpdateManager&&(this.appUpdateManager.addListener("appUpdateStateChanged",e=>{this.eventEmitter.emit("appUpdateStateChanged",e)}),this.appUpdateManager.addListener("appUpdateProgress",e=>{this.eventEmitter.emit("appUpdateProgress",e)}))}}class z{constructor(){this.logger=w.getInstance(),this.configManager=f.getInstance()}async downloadWithDelta(e,t,a){var r;const i=Date.now();if(this.configManager.get("enableDeltaUpdates")&&(null===(r=e.delta)||void 0===r?void 0:r.available)&&e.delta.patchUrl&&t)try{this.logger.info("Attempting delta update",{patchSize:e.delta.patchSize,fullSize:e.size}),null==a||a(10);const r=await this.downloadPatch(e.delta.patchUrl);if(e.delta.patchChecksum&&!await this.verifyChecksum(r,e.delta.patchChecksum))throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Delta patch checksum mismatch");null==a||a(50);const n=await this.applyPatch(t,r,e.delta.targetChecksum||e.checksum);null==a||a(90);const o=await this.calculateChecksum(n);if(o!==(e.delta.targetChecksum||e.checksum))throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Delta patch result checksum mismatch");null==a||a(100);const s=Date.now()-i;return this.logger.info("Delta update successful",{downloadSize:r.byteLength,resultSize:n.byteLength,savings:`${Math.round(100*(1-r.byteLength/(e.size||n.byteLength)))}%`,duration:s}),{usedDelta:!0,bundleData:n,checksum:o,downloadSize:r.byteLength,duration:s}}catch(e){this.logger.warn("Delta update failed, falling back to full download",{error:e})}if(null==a||a(10),!e.bundleUrl)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,"No bundle URL provided");const n=await this.downloadFull(e.bundleUrl,a),o=Date.now()-i,s=await this.calculateChecksum(n);if(e.checksum&&s!==e.checksum)throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Full bundle checksum mismatch");return{usedDelta:!1,bundleData:n,checksum:s,downloadSize:n.byteLength,duration:o}}async downloadPatch(e){A.validateDownloadUrl(e);const t=await fetch(e);if(!t.ok)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Failed to download delta patch: ${t.status}`);const a=this.configManager.get("maxBundleSize");if(Number(t.headers.get("content-length")||0)>a)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");const r=await t.arrayBuffer();if(r.byteLength>a)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");return r}async downloadFull(e,t){A.validateDownloadUrl(e);const a=await fetch(e);if(!a.ok)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Failed to download bundle: ${a.status}`);const r=a.headers.get("content-length"),i=r?parseInt(r,10):0,n=this.configManager.get("maxBundleSize");if(i>n)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(i&&a.body){const e=a.body.getReader(),r=[];let o=0;for(;;){const{done:a,value:s}=await e.read();if(a)break;if(r.push(s),o+=s.length,o>n)throw await e.cancel(),new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(t){const e=Math.round(o/i*90)+10;t(Math.min(e,99))}}null==t||t(100);const s=new Uint8Array(o);let l=0;for(const e of r)s.set(e,l),l+=e.length;return s.buffer}const o=await a.arrayBuffer();if(o.byteLength>n)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");return null==t||t(100),o}async applyPatch(e,t,a){const r=(new TextDecoder).decode(t),i=JSON.parse(r);if("NUDELTA/1"!==i.format||i.targetChecksum!==a)throw new Error("Unsupported or inconsistent delta patch");const n=await this.calculateChecksum(e);if(i.baseChecksum!==n)throw new Error("NUDELTA base checksum mismatch");return this.applyNuDelta(e,i)}applyNuDelta(e,t){const a=this.configManager.get("maxBundleSize");if(!Number.isSafeInteger(t.targetSize)||t.targetSize<=0||t.targetSize>a)throw new Error("NUDELTA target size is invalid");if(!Array.isArray(t.operations)||0===t.operations.length||t.operations.length>1e5)throw new Error("NUDELTA operation count is invalid");const r=new Uint8Array(e),i=[];let n=0;for(const e of t.operations){let a;if("copy"===e.op){if(!Number.isSafeInteger(e.offset)||!Number.isSafeInteger(e.length)||e.offset<0||e.length<=0||e.offset+e.length>r.length)throw new Error("NUDELTA copy operation is out of bounds");a=r.slice(e.offset,e.offset+e.length)}else{if("literal"!==e.op||"string"!=typeof e.data)throw new Error("NUDELTA operation is invalid");{if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e.data))throw new Error("NUDELTA literal is not valid base64");const t=atob(e.data);a=Uint8Array.from(t,e=>e.charCodeAt(0))}}if(n+=a.length,n>t.targetSize)throw new Error("NUDELTA output exceeds declared size");i.push(a)}if(n!==t.targetSize)throw new Error("NUDELTA output size mismatch");const o=new Uint8Array(n);let s=0;for(const e of i)o.set(e,s),s+=e.length;return o.buffer}async calculateChecksum(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async verifyChecksum(e,t){return(await this.calculateChecksum(e)).toLowerCase()===t.toLowerCase()}isDeltaEnabled(){return this.configManager.get("enableDeltaUpdates")}}class G{constructor(){this.initialized=!1,this.windowEventListeners=new Map,this.pluginManager=P.getInstance()}async initialize(e){await this.pluginManager.initialize(e),this.initialized=!0,this.setupWindowEventBridge()}async isInitialized(){return this.initialized&&this.pluginManager.isInitialized()}async reset(){await this.pluginManager.reset(),this.initialized=!1}async cleanup(){await this.pluginManager.cleanup()}async configure(e){let t;if("config"in e&&"object"==typeof e.config)t=e.config;else{const a=e.liveUpdate,r=e.appUpdate,i=e.appReview;t={appId:null==a?void 0:a.appId,baseUrl:null==a?void 0:a.serverUrl,serverUrl:null==a?void 0:a.serverUrl,apiKey:null==a?void 0:a.apiKey,channel:null==a?void 0:a.channel,autoCheck:null==a?void 0:a.autoUpdate,autoUpdate:null==a?void 0:a.autoUpdate,updateStrategy:null==a?void 0:a.updateStrategy,publicKey:null==a?void 0:a.publicKey,requireSignature:null==a?void 0:a.requireSignature,allowUnsignedDevelopmentUpdates:null==a?void 0:a.allowUnsignedDevelopmentUpdates,maxBundleSize:null==a?void 0:a.maxBundleSize,maxUncompressedBundleSize:null==a?void 0:a.maxUncompressedBundleSize,allowedHosts:null==a?void 0:a.allowedHosts,enableDeltaUpdates:null==a?void 0:a.enableDeltaUpdates,checksumAlgorithm:null==a?void 0:a.checksumAlgorithm,checkInterval:null==a?void 0:a.checkInterval,security:e.security,appStoreId:null==r?void 0:r.appStoreId,packageName:null==r?void 0:r.packageName,webReviewUrl:null==i?void 0:i.webReviewUrl}}if(this.initialized)throw new m(exports.ErrorCode.INVALID_CONFIG,"Configuration is locked after initialization. Call reset() before configuring again.");await this.initialize(t)}async getSecurityInfo(){return{enforceHttps:!0,certificatePinning:{enabled:!1,pins:[]},validateInputs:!0,secureStorage:!0}}async sync(e){try{const t=await this.checkForUpdate();if(!t.available||!t.latestVersion||!t.url)return{status:exports.SyncStatus.UP_TO_DATE,version:t.currentVersion};if("immediate"===(null==e?void 0:e.updateMode)||void 0===(null==e?void 0:e.updateMode)){const e=await this.downloadUpdate({url:t.url,version:t.latestVersion,checksum:t.checksum,signature:t.signature,signatureAlgorithm:t.signatureAlgorithm,delta:t.delta});return await this.applyUpdate(e.bundleId),{status:exports.SyncStatus.UPDATE_INSTALLED,version:t.latestVersion,description:t.notes,mandatory:t.mandatory}}return{status:exports.SyncStatus.UPDATE_AVAILABLE,version:t.latestVersion,description:t.notes,mandatory:t.mandatory}}catch(e){return{status:exports.SyncStatus.ERROR,error:{code:exports.UpdateErrorCode.UNKNOWN_ERROR,message:e instanceof Error?e.message:"Sync failed"}}}}async download(e){const t=this.pluginManager.getDownloadManager(),a=this.pluginManager.getBundleManager();let r;const i=await a.getActiveBundle();if(e.delta&&(null==i?void 0:i.version)===e.delta.fromVersion){const a=await t.loadBlob(i.bundleId),n=await(new z).downloadWithDelta({updateAvailable:!0,version:e.version,bundleUrl:e.url,checksum:e.checksum,size:void 0,delta:{available:!0,patchUrl:e.delta.patchUrl,patchSize:e.delta.patchSize,patchChecksum:e.delta.patchChecksum,targetChecksum:e.delta.targetChecksum}},a?await a.arrayBuffer():null);r=new Blob([n.bundleData],{type:"application/zip"})}else r=await t.downloadWithRetry(e.url,e.version);const n=await r.arrayBuffer();await this.validateBundleData(n,e.checksum,e.signature);const o=new Blob([n],{type:r.type}),s=await t.saveBlob(e.version,o),l={bundleId:e.version,version:e.version,path:s,downloadTime:Date.now(),size:o.size,status:exports.BundleStatus.READY,checksum:e.checksum,signature:e.signature,signatureAlgorithm:e.signatureAlgorithm,verified:!0};return await a.saveBundleInfo(l),l}async set(e){const t=this.pluginManager.getBundleManager();if(!e.verified)throw new m(exports.ErrorCode.SIGNATURE_INVALID,`Refusing to activate unverified bundle ${e.bundleId}`);await t.setActiveBundle(e.bundleId)}async reload(){"undefined"!=typeof window&&window.location.reload()}async current(){const e=this.pluginManager.getBundleManager(),t=await e.getActiveBundle();if(!t)throw new m(exports.ErrorCode.FILE_NOT_FOUND,"No active bundle found");return t}async list(){return this.pluginManager.getBundleManager().getAllBundles()}async delete(e){const t=this.pluginManager.getBundleManager();if(e.bundleId)await t.deleteBundle(e.bundleId);else if(void 0!==e.keepVersions){const a=(await t.getAllBundles()).sort((e,t)=>t.downloadTime-e.downloadTime);for(let r=e.keepVersions;r<a.length;r++)await t.deleteBundle(a[r].bundleId)}}async notifyAppReady(){const e=this.pluginManager.getBundleManager(),t=await e.getActiveBundle();t&&(t.status=exports.BundleStatus.ACTIVE,await e.saveBundleInfo(t))}async getLatest(){const e=await this.checkForUpdate();return e.available?{available:!0,version:e.latestVersion,url:e.url,mandatory:e.mandatory,notes:e.notes,size:e.size,checksum:e.checksum,signature:e.signature,signatureAlgorithm:e.signatureAlgorithm,delta:e.delta}:e.held?{available:!1,held:!0,version:e.latestVersion,heldMessage:e.heldMessage}:{available:!1}}async setChannel(e){const t="string"==typeof e?e:e.channel,a=this.pluginManager.getConfigManager().get("preferences");a&&await a.set({key:"update_channel",value:t})}async setUpdateUrl(e){this.pluginManager.getLogger().warn("setUpdateUrl() is deprecated and ignored. Update URL is locked after initialize(). Call reset(), then initialize() with an updated serverUrl to switch servers.")}async validateUpdate(e){const t=this.pluginManager.getSecurityValidator(),a=this.pluginManager.getDownloadManager();try{const r=e.bundlePath.match(/bundles\/([^/]+)\/bundle\.zip$/),i=r?r[1]:e.bundlePath,n=await a.loadBlob(i);if(!n)return{isValid:!1,error:`Bundle not found at ${e.bundlePath}`};const o=await n.arrayBuffer(),s=await t.verifyChecksum(o,e.checksum);let l=!0;e.signature&&(l=await t.verifySignature(o,e.signature));const d=!e.maxSize||o.byteLength<=e.maxSize;return{isValid:s&&l&&d,details:{checksumValid:s,signatureValid:l,sizeValid:d,versionValid:!0}}}catch(e){return{isValid:!1,error:e instanceof Error?e.message:"Validation failed"}}}async getAppIdentity(){return{platform:"web"}}async resolveAppIdentity(){if(this.appIdentity)return this.appIdentity;try{this.appIdentity=await this.getAppIdentity()}catch(e){this.appIdentity={platform:"web"}}return this.appIdentity}async checkForUpdate(){var e,t,a;const r=this.pluginManager.getBundleManager(),i=this.pluginManager.getConfigManager();try{const n=await r.getActiveBundle(),o=(null==n?void 0:n.version)||"1.0.0",s=i.get("baseUrl");if(!s)return{available:!1,currentVersion:o};const l=i.get("apiKey");if(!l)throw new m(exports.ErrorCode.INVALID_CONFIG,"apiKey is required when using Laravel backend");const d=i.get("channel")||"production",c=this.getDeviceInfo(o),u=await U(s,{apiKey:l,channel:d,currentVersion:o,deviceId:c.deviceId,platform:c.platform,appVersion:c.appVersion,identity:await this.resolveAppIdentity()});return u.available?{available:!0,currentVersion:o,latestVersion:u.version,url:u.downloadUrl,mandatory:u.mandatory,notes:null!==(e=u.releaseNotes)&&void 0!==e?e:void 0,size:u.size,checksum:u.checksum,signature:null!==(t=u.signature)&&void 0!==t?t:void 0,signatureAlgorithm:u.signature?"RSA-SHA256":void 0,delta:null!==(a=u.delta)&&void 0!==a?a:void 0}:u.held?{available:!1,currentVersion:o,latestVersion:u.version,held:!0,heldMessage:u.message}:{available:!1,currentVersion:o}}catch(e){throw new m(exports.ErrorCode.NETWORK_ERROR,e instanceof Error?e.message:"Failed to check for updates")}}async downloadUpdate(e){const t=this.pluginManager.getDownloadManager(),a=this.pluginManager.getBundleManager(),r=this.pluginManager.getEventEmitter();let i;if(!((null==e?void 0:e.url)&&(null==e?void 0:e.version)||(i=await this.checkForUpdate(),i.available&&i.url)))throw new m(exports.ErrorCode.UPDATE_NOT_AVAILABLE,"No update available to download");const n=(null==e?void 0:e.url)||(null==i?void 0:i.url)||"",o=(null==e?void 0:e.version)||(null==i?void 0:i.latestVersion)||"",s=(null==e?void 0:e.checksum)||(null==i?void 0:i.checksum)||"",l=(null==e?void 0:e.signature)||(null==i?void 0:i.signature)||"",d=(null==e?void 0:e.signatureAlgorithm)||(null==i?void 0:i.signatureAlgorithm),c=(null==e?void 0:e.delta)||(null==i?void 0:i.delta);if(!n||!o)throw new m(exports.ErrorCode.INVALID_CONFIG,"URL and version are required for download");const u=await t.downloadWithRetry(n,o,t=>{r.emit("downloadProgress",t),(null==e?void 0:e.onProgress)&&e.onProgress(t)}),h=await u.arrayBuffer();await this.validateBundleData(h,s,l||void 0);const p=new Blob([h],{type:u.type}),g={bundleId:o,version:o,path:await t.saveBlob(o,p),downloadTime:Date.now(),size:p.size,status:exports.BundleStatus.READY,checksum:s,signature:l||void 0,signatureAlgorithm:d,metadata:c?{delta:c}:void 0,verified:!0};return await a.saveBundleInfo(g),g}async applyUpdate(e){const t=this.pluginManager.getBundleManager();let a=e;if(!a){const e=(await t.getAllBundles()).filter(e=>e.status===exports.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime);if(0===e.length)throw new m(exports.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");a=e[0].bundleId}const r=await t.getBundle(a);if(!r)throw new m(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${a} not found`);await this.set(r),await this.reload()}async cancelDownload(e){this.pluginManager.getDownloadManager().cancelDownload("string"==typeof e?e:e.bundleId)}async cancelAllDownloads(){this.pluginManager.getDownloadManager().cancelAllDownloads()}async isDownloading(e){return this.pluginManager.getDownloadManager().isDownloading("string"==typeof e?e:e.bundleId)}async getActiveDownloadCount(){return this.pluginManager.getDownloadManager().getActiveDownloadCount()}compareVersions(e,t){return R(e,t)}getDeviceInfo(e){return{deviceId:"web-client",platform:"web",appVersion:e,bundleVersion:e,osVersion:"undefined"!=typeof navigator?navigator.userAgent:"unknown",locale:"undefined"!=typeof navigator?navigator.language:"en-US"}}async validateBundleData(e,t,a){const r=this.pluginManager.getSecurityValidator(),i=this.pluginManager.getConfigManager();if(t&&!await r.verifyChecksum(e,t))throw new m(exports.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");const n=i.get("requireSignature"),o=i.get("publicKey");if(n){if(!o)throw new m(exports.ErrorCode.INVALID_CONFIG,"Signature verification required but publicKey is not configured");if(!a)throw new m(exports.ErrorCode.SIGNATURE_INVALID,"Signature verification required but no signature provided");if(!await r.verifySignature(e,a))throw new m(exports.ErrorCode.SIGNATURE_INVALID,"Bundle signature verification failed")}return!0}async getAppUpdateInfo(){return this.pluginManager.getAppUpdateManager().getAppUpdateInfo()}async performImmediateUpdate(){return this.pluginManager.getAppUpdateManager().performImmediateUpdate()}async startFlexibleUpdate(){return this.pluginManager.getAppUpdateManager().startFlexibleUpdate()}async completeFlexibleUpdate(){return this.pluginManager.getAppUpdateManager().completeFlexibleUpdate()}async openAppStore(e){return this.pluginManager.getAppUpdateManager().openAppStore(e)}async requestReview(){return{displayed:!1,error:"Reviews are not supported on web"}}async canRequestReview(){return{canRequest:!1,reason:"Reviews are not supported on web"}}async enableBackgroundUpdates(e){this.pluginManager.getBackgroundScheduler().configure(e);const t=this.pluginManager.getConfigManager().get("preferences");t&&await t.set({key:"background_update_config",value:JSON.stringify(e)})}async disableBackgroundUpdates(){this.pluginManager.getBackgroundScheduler().configure({enabled:!1,checkInterval:0,updateTypes:[]});const e=this.pluginManager.getConfigManager().get("preferences");e&&await e.remove({key:"background_update_config"})}async getBackgroundUpdateStatus(){return this.pluginManager.getBackgroundScheduler().getStatus()}async scheduleBackgroundCheck(e){throw new m(exports.ErrorCode.PLATFORM_NOT_SUPPORTED,"Background updates are not supported on web")}async triggerBackgroundCheck(){return this.pluginManager.getBackgroundScheduler().performCheck()}async setNotificationPreferences(e){const t=this.pluginManager.getConfigManager().get("preferences");t&&await t.set({key:"notification_preferences",value:JSON.stringify(e)})}async getNotificationPermissions(){return{granted:!1,canRequest:!1}}async requestNotificationPermissions(){return!1}async addListener(e,t){const a=this.pluginManager.getEventEmitter().addListener(e,t);return{remove:async()=>{a()}}}async removeAllListeners(){this.pluginManager.getEventEmitter().removeAllListeners()}setupWindowEventBridge(){const e=this.pluginManager.getEventEmitter();["appUpdateAvailable","appUpdateProgress","appUpdateReady","appUpdateFailed","appUpdateNotificationClicked","appUpdateInstallClicked"].forEach(t=>{const a=a=>{e.emit(t,a.detail)};window.addEventListener(t,a),this.windowEventListeners.set(t,a)})}}const H=h.registerPlugin("NativeUpdate",{web:()=>new G}),$=new Proxy(H,{get(e,t,a){if("isInitialized"===t)return async()=>{const t=await e.isInitialized();return"boolean"==typeof t?t:!!(t&&"object"==typeof t&&"initialized"in t&&t.initialized)};if("list"===t)return async()=>{const t=await e.list();return Array.isArray(t)?t:t&&"object"==typeof t&&"bundles"in t&&Array.isArray(t.bundles)?t.bundles:[]};if("setChannel"===t)return t=>e.setChannel({channel:t});if("setUpdateUrl"===t)return t=>e.setUpdateUrl({url:t});if("scheduleBackgroundCheck"===t)return t=>e.scheduleBackgroundCheck({interval:t});if("requestNotificationPermissions"===t)return async()=>{const t=await e.requestNotificationPermissions();return"boolean"==typeof t?t:!!(t&&"object"==typeof t&&"granted"in t&&t.granted)};if("checkForUpdate"===t)return async()=>{const[t,a]=await Promise.all([e.getLatest(),e.current()]);return{available:!0===t.available&&"string"==typeof t.version&&_.compareVersions(t.version,a.version)>0,latestVersion:t.version,currentVersion:a.version,url:t.url,mandatory:t.mandatory,notes:t.notes,size:t.size,checksum:t.checksum,signature:t.signature,signatureAlgorithm:t.signatureAlgorithm,delta:t.delta,held:!0===t.held||void 0,heldMessage:t.heldMessage}};if("downloadUpdate"===t)return async(t={})=>{var a,r,i,n,o,s;const l=t.url&&t.version&&t.checksum?void 0:await e.getLatest(),d=null!==(a=t.url)&&void 0!==a?a:null==l?void 0:l.url,c=null!==(r=t.version)&&void 0!==r?r:null==l?void 0:l.version,u=null!==(i=t.checksum)&&void 0!==i?i:null==l?void 0:l.checksum;if(!d||!c||!u)throw new m(exports.ErrorCode.UPDATE_NOT_AVAILABLE,"No downloadable update is available");return e.download({url:d,version:c,checksum:u,signature:null!==(n=t.signature)&&void 0!==n?n:null==l?void 0:l.signature,signatureAlgorithm:null!==(o=t.signatureAlgorithm)&&void 0!==o?o:null==l?void 0:l.signatureAlgorithm,delta:null!==(s=t.delta)&&void 0!==s?s:null==l?void 0:l.delta})};if("applyUpdate"===t)return async t=>{const a=await $.list(),r=t?a.find(e=>e.bundleId===t):a.filter(e=>e.status===exports.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime)[0];if(!r)throw new m(exports.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");await e.set(r),await e.reload()};if("cancelDownload"===t)return t=>e.cancelDownload({bundleId:t});if("isDownloading"===t)return async t=>{const a=await e.isDownloading({bundleId:t});return"boolean"==typeof a?a:!!(a&&"object"==typeof a&&"isDownloading"in a&&a.isDownloading)};if("getActiveDownloadCount"===t)return async()=>{const t=await e.getActiveDownloadCount();return"number"==typeof t?t:t&&"object"==typeof t&&"count"in t&&"number"==typeof t.count?t.count:0};const r=Reflect.get(e,t,a);return"function"==typeof r?r.bind(e):r}});exports.BundleManager=D,exports.CacheManager=class{constructor(){this.filesystem=null,this.memoryCache=new Map,this.CACHE_DIR="cache",this.logger=w.getInstance(),this.configManager=f.getInstance()}async initialize(){if(this.filesystem=this.configManager.get("filesystem"),!this.filesystem)throw new Error("Filesystem not configured");try{await this.filesystem.mkdir({path:this.CACHE_DIR,directory:p.Directory.Data,recursive:!0})}catch(e){this.logger.debug("Cache directory may already exist",e)}await this.cleanExpiredCache()}async set(e,t,a){const r=Date.now()+(a||this.configManager.get("cacheExpiration")),i={data:t,timestamp:Date.now(),expiry:r};this.memoryCache.set(e,i),this.shouldPersist(t)&&await this.persistToFile(e,i),this.logger.debug("Cache entry set",{key:e,expiry:new Date(r)})}async get(e){const t=this.memoryCache.get(e);if(t){if(Date.now()<t.expiry)return t.data;this.memoryCache.delete(e)}const a=await this.loadFromFile(e);if(a){if(Date.now()<a.expiry)return this.memoryCache.set(e,a),a.data;await this.removeFile(e)}return null}async has(e){return null!==await this.get(e)}async remove(e){this.memoryCache.delete(e),await this.removeFile(e),this.logger.debug("Cache entry removed",{key:e})}async clear(){this.memoryCache.clear();try{await this.filesystem.rmdir({path:this.CACHE_DIR,directory:p.Directory.Data,recursive:!0}),await this.filesystem.mkdir({path:this.CACHE_DIR,directory:p.Directory.Data,recursive:!0})}catch(e){this.logger.warn("Failed to clear cache directory",e)}this.logger.info("Cache cleared")}async cleanExpiredCache(){const e=Date.now();let t=0;for(const[a,r]of this.memoryCache)e>=r.expiry&&(this.memoryCache.delete(a),t++);try{const a=await this.filesystem.readdir({path:this.CACHE_DIR,directory:p.Directory.Data});for(const r of a.files){const a=r.name.replace(".json",""),i=await this.loadFromFile(a);(!i||e>=i.expiry)&&(await this.removeFile(a),t++)}}catch(e){this.logger.debug("Failed to clean filesystem cache",e)}t>0&&this.logger.info("Cleaned expired cache entries",{count:t})}async getStats(){let e=0,t=0;try{const a=await this.filesystem.readdir({path:this.CACHE_DIR,directory:p.Directory.Data});e=a.files.length;for(const e of a.files)t+=(await this.filesystem.stat({path:`${this.CACHE_DIR}/${e.name}`,directory:p.Directory.Data})).size||0}catch(e){this.logger.debug("Failed to get cache stats",e)}return{memoryEntries:this.memoryCache.size,fileEntries:e,totalSize:t}}async cacheBundleMetadata(e){const t=`bundle_meta_${e.bundleId}`;await this.set(t,e,864e5)}async getCachedBundleMetadata(e){return this.get(`bundle_meta_${e}`)}shouldPersist(e){return"object"==typeof e||"string"==typeof e&&e.length>1024}async persistToFile(e,t){if(this.filesystem)try{const a=`${this.CACHE_DIR}/${e}.json`,r=JSON.stringify(t);await this.filesystem.writeFile({path:a,data:r,directory:p.Directory.Data,encoding:p.Encoding.UTF8})}catch(t){this.logger.warn("Failed to persist cache to file",{key:e,error:t})}}async loadFromFile(e){if(!this.filesystem)return null;try{const t=`${this.CACHE_DIR}/${e}.json`,a=await this.filesystem.readFile({path:t,directory:p.Directory.Data,encoding:p.Encoding.UTF8});return JSON.parse(a.data)}catch(e){return null}}async removeFile(e){if(this.filesystem)try{const t=`${this.CACHE_DIR}/${e}.json`;await this.filesystem.deleteFile({path:t,directory:p.Directory.Data})}catch(t){this.logger.debug("Failed to remove cache file",{key:e,error:t})}}},exports.ConfigManager=f,exports.ConfigurationError=class extends m{constructor(e,t){super(exports.ErrorCode.INVALID_CONFIG,e,t),this.name="ConfigurationError"}},exports.DownloadError=v,exports.DownloadManager=b,exports.Logger=w,exports.NativeUpdate=$,exports.NativeUpdateError=m,exports.PluginManager=P,exports.SecurityValidator=A,exports.StorageError=E,exports.UpdateErrorClass=I,exports.UpdateManager=class{constructor(){this.filesystem=null,this.updateInProgress=!1,this.currentState=null,this.pluginManager=P.getInstance(),this.securityValidator=A.getInstance()}async initialize(){if(this.filesystem=this.pluginManager.getConfigManager().get("filesystem"),!this.filesystem)throw new I(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured")}async applyUpdate(e,t){var a;if(this.updateInProgress)throw new I(exports.ErrorCode.UPDATE_FAILED,"Another update is already in progress");const r=this.pluginManager.getLogger(),i=this.pluginManager.getBundleManager();try{this.updateInProgress=!0,r.info("Starting bundle update",{bundleId:e});const n=await i.getBundle(e);if(!n)throw new I(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${e} not found`);if("READY"!==n.status&&"ACTIVE"!==n.status)throw new I(exports.ErrorCode.BUNDLE_NOT_READY,`Bundle ${e} is not ready for installation`);const o=await i.getActiveBundle();this.currentState={currentBundle:o,newBundle:n,backupPath:null,startTime:Date.now()},await this.validateUpdate(o,n,t),o&&"default"!==o.bundleId&&(this.currentState.backupPath=await this.createBackup(o)),await this.performUpdate(n),await this.verifyUpdate(n),await i.setActiveBundle(e);const s=this.pluginManager.getVersionManager(),l=this.pluginManager.getConfigManager();if(await s.rememberAppliedVersion(l.get("channel"),n.version),!1!==(null==t?void 0:t.cleanupOldBundles)){const e=null!==(a=null==t?void 0:t.keepBundleCount)&&void 0!==a?a:3;await i.cleanupOldBundles(e)}r.info("Bundle update completed successfully",{bundleId:e,version:n.version,duration:Date.now()-this.currentState.startTime}),this.currentState=null}catch(e){throw r.error("Bundle update failed",e),this.currentState&&await this.rollback(),e}finally{this.updateInProgress=!1}}async validateUpdate(e,t,a){const r=this.pluginManager.getLogger(),i=this.pluginManager.getVersionManager(),n=this.pluginManager.getConfigManager();if(e&&i.shouldBlockDowngrade(e.version,t.version))throw new y(exports.ErrorCode.VERSION_DOWNGRADE,`Cannot downgrade from ${e.version} to ${t.version}`);const o=n.get("channel"),s=await i.getMaxSeenVersion(o);if(s&&i.shouldBlockDowngrade(s,t.version))throw new y(exports.ErrorCode.VERSION_DOWNGRADE,`Cannot apply ${t.version} - device has previously applied ${s} on channel ${o}`);if(!t.verified){r.warn("Bundle not verified, verifying now",{bundleId:t.bundleId});const e=this.pluginManager.getDownloadManager(),a=await e.loadBlob(t.bundleId);if(!a)throw new I(exports.ErrorCode.FILE_NOT_FOUND,"Bundle data not found");const i=await a.arrayBuffer();if(!await this.securityValidator.verifyChecksum(i,t.checksum))throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");if(t.signature&&!await this.securityValidator.verifySignature(i,t.signature))throw new y(exports.ErrorCode.SIGNATURE_INVALID,"Bundle signature verification failed");await this.pluginManager.getBundleManager().markBundleAsVerified(t.bundleId)}r.debug("Bundle validation passed",{bundleId:t.bundleId})}async createBackup(e){const t=`backups/${e.bundleId}_${Date.now()}`,a=this.pluginManager.getLogger();try{return await this.filesystem.mkdir({path:t,directory:p.Directory.Data,recursive:!0}),await this.filesystem.copy({from:e.path,to:t,directory:p.Directory.Data}),a.info("Backup created",{bundleId:e.bundleId,backupPath:t}),t}catch(e){throw a.error("Failed to create backup",e),new I(exports.ErrorCode.UPDATE_FAILED,"Failed to create backup",void 0,e)}}async performUpdate(e){const t=this.pluginManager.getLogger();try{const a=`active/${e.bundleId}`;await this.filesystem.mkdir({path:a,directory:p.Directory.Data,recursive:!0}),await this.filesystem.copy({from:e.path,to:a,directory:p.Directory.Data}),e.path=a,t.debug("Bundle files installed",{bundleId:e.bundleId,targetPath:a})}catch(e){throw new I(exports.ErrorCode.UPDATE_FAILED,"Failed to install bundle files",void 0,e)}}async verifyUpdate(e){try{const t=`${e.path}/index.html`;await this.filesystem.stat({path:t,directory:p.Directory.Data})}catch(e){throw new I(exports.ErrorCode.UPDATE_FAILED,"Bundle verification failed after installation",void 0,e)}}async rollback(){var e;if(!this.currentState)throw new I(exports.ErrorCode.ROLLBACK_FAILED,"No update state to rollback");const t=this.pluginManager.getLogger();t.warn("Starting rollback",{from:this.currentState.newBundle.bundleId,to:(null===(e=this.currentState.currentBundle)||void 0===e?void 0:e.bundleId)||"default"});try{const e=this.pluginManager.getBundleManager();if(this.currentState.backupPath&&this.currentState.currentBundle){const t=`active/${this.currentState.currentBundle.bundleId}`;await this.filesystem.copy({from:this.currentState.backupPath,to:t,directory:p.Directory.Data}),this.currentState.currentBundle.path=t,await e.saveBundleInfo(this.currentState.currentBundle)}this.currentState.currentBundle?await e.setActiveBundle(this.currentState.currentBundle.bundleId):await e.clearActiveBundle(),t.info("Rollback completed successfully")}catch(e){throw t.error("Rollback failed",e),new I(exports.ErrorCode.ROLLBACK_FAILED,"Failed to rollback update",void 0,e)}finally{if(this.currentState.backupPath)try{await this.filesystem.rmdir({path:this.currentState.backupPath,directory:p.Directory.Data,recursive:!0})}catch(e){t.warn("Failed to clean up backup",e)}}}getUpdateProgress(){var e,t;return{inProgress:this.updateInProgress,bundleId:null===(e=this.currentState)||void 0===e?void 0:e.newBundle.bundleId,startTime:null===(t=this.currentState)||void 0===t?void 0:t.startTime}}async cancelUpdate(){this.updateInProgress&&this.currentState&&(this.pluginManager.getLogger().warn("Cancelling update",{bundleId:this.currentState.newBundle.bundleId}),await this.rollback(),this.updateInProgress=!1,this.currentState=null)}},exports.ValidationError=y,exports.VersionManager=_,exports.compareVersions=R;
|
|
1
|
+
var e,t,a,r,i,n,o,s,l,d,c,u,h=require("@capacitor/core"),p=require("@capacitor/filesystem"),g=require("@capacitor/preferences");exports.BackgroundUpdateType=void 0,(e=exports.BackgroundUpdateType||(exports.BackgroundUpdateType={})).APP_UPDATE="app_update",e.LIVE_UPDATE="live_update",e.BOTH="both",exports.NotificationPriority=void 0,(t=exports.NotificationPriority||(exports.NotificationPriority={})).MIN="min",t.LOW="low",t.DEFAULT="default",t.HIGH="high",t.MAX="max",exports.UpdateStrategy=void 0,(a=exports.UpdateStrategy||(exports.UpdateStrategy={})).IMMEDIATE="immediate",a.BACKGROUND="background",a.MANUAL="manual",exports.UpdateMode=void 0,(r=exports.UpdateMode||(exports.UpdateMode={})).IMMEDIATE="immediate",r.ON_NEXT_RESTART="on_next_restart",r.ON_NEXT_RESUME="on_next_resume",exports.InstallMode=void 0,(i=exports.InstallMode||(exports.InstallMode={})).IMMEDIATE="immediate",i.ON_NEXT_RESTART="on_next_restart",i.ON_NEXT_RESUME="on_next_resume",exports.ChecksumAlgorithm=void 0,(n=exports.ChecksumAlgorithm||(exports.ChecksumAlgorithm={})).SHA256="SHA-256",n.SHA512="SHA-512",exports.SyncStatus=void 0,(o=exports.SyncStatus||(exports.SyncStatus={})).UP_TO_DATE="UP_TO_DATE",o.UPDATE_AVAILABLE="UPDATE_AVAILABLE",o.UPDATE_INSTALLED="UPDATE_INSTALLED",o.ERROR="ERROR",exports.BundleStatus=void 0,(s=exports.BundleStatus||(exports.BundleStatus={})).PENDING="PENDING",s.DOWNLOADING="DOWNLOADING",s.READY="READY",s.ACTIVE="ACTIVE",s.FAILED="FAILED",exports.InstallStatus=void 0,(l=exports.InstallStatus||(exports.InstallStatus={})).UNKNOWN="UNKNOWN",l.PENDING="PENDING",l.DOWNLOADING="DOWNLOADING",l.DOWNLOADED="DOWNLOADED",l.INSTALLING="INSTALLING",l.INSTALLED="INSTALLED",l.FAILED="FAILED",l.CANCELED="CANCELED",exports.UpdateErrorCode=void 0,(d=exports.UpdateErrorCode||(exports.UpdateErrorCode={})).NETWORK_ERROR="NETWORK_ERROR",d.SERVER_ERROR="SERVER_ERROR",d.TIMEOUT_ERROR="TIMEOUT_ERROR",d.DOWNLOAD_ERROR="DOWNLOAD_ERROR",d.STORAGE_ERROR="STORAGE_ERROR",d.SIZE_LIMIT_EXCEEDED="SIZE_LIMIT_EXCEEDED",d.VERIFICATION_ERROR="VERIFICATION_ERROR",d.CHECKSUM_ERROR="CHECKSUM_ERROR",d.SIGNATURE_ERROR="SIGNATURE_ERROR",d.INSECURE_URL="INSECURE_URL",d.INVALID_CERTIFICATE="INVALID_CERTIFICATE",d.PATH_TRAVERSAL="PATH_TRAVERSAL",d.INSTALL_ERROR="INSTALL_ERROR",d.ROLLBACK_ERROR="ROLLBACK_ERROR",d.VERSION_MISMATCH="VERSION_MISMATCH",d.PERMISSION_DENIED="PERMISSION_DENIED",d.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",d.UPDATE_IN_PROGRESS="UPDATE_IN_PROGRESS",d.UPDATE_CANCELLED="UPDATE_CANCELLED",d.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",d.REVIEW_NOT_SUPPORTED="REVIEW_NOT_SUPPORTED",d.QUOTA_EXCEEDED="QUOTA_EXCEEDED",d.CONDITIONS_NOT_MET="CONDITIONS_NOT_MET",d.INVALID_CONFIG="INVALID_CONFIG",d.NOT_CONFIGURED="NOT_CONFIGURED",d.UNKNOWN_ERROR="UNKNOWN_ERROR";class f{constructor(){this.config=this.getDefaultConfig()}static getInstance(){return f.instance||(f.instance=new f),f.instance}getDefaultConfig(){return{filesystem:null,preferences:null,baseUrl:"",allowedHosts:[],maxBundleSize:104857600,maxUncompressedBundleSize:524288e3,downloadTimeout:3e4,retryAttempts:3,retryDelay:1e3,enableSignatureValidation:!0,publicKey:"",cacheExpiration:864e5,enableLogging:!1,serverUrl:"",channel:"production",appId:"",apiKey:"",autoCheck:!0,autoUpdate:!1,updateStrategy:"background",requireSignature:!0,checksumAlgorithm:"SHA-256",checkInterval:864e5,security:{enforceHttps:!0,validateInputs:!0,secureStorage:!0,logSecurityEvents:!1},allowUnsignedDevelopmentUpdates:!1,promptAfterPositiveEvents:!1,maxPromptsPerVersion:1,minimumDaysSinceLastPrompt:7,isPremiumUser:!1,appStoreId:"",iosAppId:"",packageName:"",webReviewUrl:"",minimumVersion:"1.0.0",enableDeltaUpdates:!0,enableStagedRollouts:!0}}configure(e){this.config=Object.assign(Object.assign({},this.config),e),this.validateConfig()}reset(){this.config=this.getDefaultConfig()}validateConfig(){if(this.config.baseUrl&&!this.config.baseUrl.startsWith("https://"))throw new Error("baseUrl must use HTTPS protocol for security");if(this.config.maxBundleSize<=0)throw new Error("maxBundleSize must be greater than 0");if(this.config.maxUncompressedBundleSize<=0)throw new Error("maxUncompressedBundleSize must be greater than 0");if(this.config.downloadTimeout<=0)throw new Error("downloadTimeout must be greater than 0");if(this.config.retryAttempts<0)throw new Error("retryAttempts must be non-negative");if(this.config.retryDelay<0)throw new Error("retryDelay must be non-negative");if(!1===this.config.security.enforceHttps)throw new Error("HTTPS enforcement cannot be disabled");if((this.config.serverUrl||this.config.apiKey)&&this.config.requireSignature&&!this.config.publicKey)throw new Error("publicKey is required when requireSignature is enabled");if(!this.config.requireSignature&&!this.config.allowUnsignedDevelopmentUpdates)throw new Error("Disabling signatures requires allowUnsignedDevelopmentUpdates for an explicit development-only setup")}get(e){return this.config[e]}set(e,t){this.config[e]=t}getAll(){return Object.assign({},this.config)}isConfigured(){return!(!this.config.filesystem||!this.config.preferences)}}exports.LogLevel=void 0,(c=exports.LogLevel||(exports.LogLevel={}))[c.DEBUG=0]="DEBUG",c[c.INFO=1]="INFO",c[c.WARN=2]="WARN",c[c.ERROR=3]="ERROR";class w{constructor(e){this.configManager=f.getInstance(),this.context=e||"NativeUpdate"}static getInstance(){return w.instance||(w.instance=new w),w.instance}shouldLog(){return this.configManager.get("enableLogging")}sanitize(e){if("string"==typeof e){let t=e;return t=t.replace(/\/[^\s]+\/([\w.-]+)$/g,"/<path>/$1"),t=t.replace(/https?:\/\/[^:]+:[^@]+@/g,"https://***:***@"),t=t.replace(/[a-zA-Z0-9]{32,}/g,"<redacted>"),t}if("object"==typeof e&&null!==e){if(Array.isArray(e))return e.map(e=>this.sanitize(e));{const t={},a=e;for(const e in a)t[e]=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("password")||e.toLowerCase().includes("token")?"<redacted>":this.sanitize(a[e]);return t}}return e}log(e,t){this.logWithLevel(exports.LogLevel.INFO,e,t)}logWithLevel(e,t,a){if(!this.shouldLog())return;const r=(new Date).toISOString(),i=a?this.sanitize(a):void 0,n={timestamp:r,level:exports.LogLevel[e],context:this.context,message:t};switch(void 0!==i&&(n.data=i),e){case exports.LogLevel.DEBUG:console.debug(`[${this.context}]`,n);break;case exports.LogLevel.INFO:console.info(`[${this.context}]`,n);break;case exports.LogLevel.WARN:console.warn(`[${this.context}]`,n);break;case exports.LogLevel.ERROR:console.error(`[${this.context}]`,n)}}debug(e,t){this.logWithLevel(exports.LogLevel.DEBUG,e,t)}info(e,t){this.logWithLevel(exports.LogLevel.INFO,e,t)}warn(e,t){this.logWithLevel(exports.LogLevel.WARN,e,t)}error(e,t){const a=t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t;this.logWithLevel(exports.LogLevel.ERROR,e,a)}}exports.ErrorCode=void 0,(u=exports.ErrorCode||(exports.ErrorCode={})).NOT_CONFIGURED="NOT_CONFIGURED",u.INVALID_CONFIG="INVALID_CONFIG",u.MISSING_DEPENDENCY="MISSING_DEPENDENCY",u.NETWORK_ERROR="NETWORK_ERROR",u.SERVER_ERROR="SERVER_ERROR",u.DOWNLOAD_FAILED="DOWNLOAD_FAILED",u.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",u.INVALID_URL="INVALID_URL",u.INSECURE_URL="INSECURE_URL",u.UNAUTHORIZED_HOST="UNAUTHORIZED_HOST",u.BUNDLE_TOO_LARGE="BUNDLE_TOO_LARGE",u.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",u.SIGNATURE_INVALID="SIGNATURE_INVALID",u.VERSION_DOWNGRADE="VERSION_DOWNGRADE",u.INVALID_BUNDLE_FORMAT="INVALID_BUNDLE_FORMAT",u.VALIDATION_ERROR="VALIDATION_ERROR",u.STORAGE_FULL="STORAGE_FULL",u.FILE_NOT_FOUND="FILE_NOT_FOUND",u.PERMISSION_DENIED="PERMISSION_DENIED",u.UPDATE_FAILED="UPDATE_FAILED",u.ROLLBACK_FAILED="ROLLBACK_FAILED",u.BUNDLE_NOT_READY="BUNDLE_NOT_READY",u.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",u.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",u.NATIVE_ERROR="NATIVE_ERROR";class m extends Error{constructor(e,t,a,r){super(t),this.code=e,this.message=t,this.details=a,this.originalError=r,this.name="NativeUpdateError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,stack:this.stack}}}class v extends m{constructor(e,t,a,r){super(e,t,a,r),this.name="DownloadError"}}class y extends m{constructor(e,t,a){super(e,t,a),this.name="ValidationError"}}class E extends m{constructor(e,t,a,r){super(e,t,a,r),this.name="StorageError"}}class I extends m{constructor(e,t,a,r){super(e,t,a,r),this.name="UpdateError"}}class A{constructor(){this.configManager=f.getInstance(),this.logger=w.getInstance()}static getInstance(){return A.instance||(A.instance=new A),A.instance}static validateUrl(e){try{return"https:"===new URL(e).protocol}catch(e){return!1}}static validateDownloadUrl(e){if(!this.validateUrl(e))throw new y(exports.ErrorCode.INSECURE_URL,`Refusing non-HTTPS URL: ${e}`)}static validateStoreUrl(e){let t;try{t=new URL(e)}catch(t){throw new y(exports.ErrorCode.INSECURE_URL,`Invalid URL: ${e}`)}if(!["https:","market:","itms-apps:"].includes(t.protocol))throw new y(exports.ErrorCode.INSECURE_URL,`Refusing URL scheme ${t.protocol}`)}static validateChecksum(e){return/^[a-f0-9]{64}$/i.test(e)}static sanitizeInput(e){return e?e.replace(/<[^>]*>/g,"").replace(/[^\w\s/.-]/g,""):""}static validateBundleSize(e){return e>0&&e<=104857600}async calculateChecksum(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async verifyChecksum(e,t){if(!t)throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Checksum is required but was not provided");const a=await this.calculateChecksum(e),r=a===t.toLowerCase();return r||this.logger.error("Checksum verification failed",{expected:t,actual:a}),r}async validateChecksum(e,t){return this.verifyChecksum(e,t)}async verifySignature(e,t){const a=this.configManager.get("enableSignatureValidation"),r=this.configManager.get("requireSignature"),i=this.configManager.get("publicKey");if(!t){if(a||r||i)throw new y(exports.ErrorCode.SIGNATURE_INVALID,"Signature is required but was not provided");return!0}if(!i)throw new y(exports.ErrorCode.SIGNATURE_INVALID,"Public key not configured for signature validation");try{const a=await crypto.subtle.importKey("spki",this.pemToArrayBuffer(i),{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]),r=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},a,this.base64ToArrayBuffer(t),e);return r||this.logger.error("Signature verification failed"),r}catch(e){return this.logger.error("Signature verification error",e),!1}}pemToArrayBuffer(e){const t=e.replace(/-----BEGIN PUBLIC KEY-----/g,"").replace(/-----END PUBLIC KEY-----/g,"").replace(/\s/g,"");return this.base64ToArrayBuffer(t)}base64ToArrayBuffer(e){const t=atob(e),a=new Uint8Array(t.length);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e);return a.buffer}sanitizePath(e){return e.split("/").filter(e=>".."!==e&&"."!==e).join("/").replace(/^\/+/,"")}validateBundleId(e){if(!e||"string"!=typeof e)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID must be a non-empty string");if(!/^[a-zA-Z0-9\-_.]+$/.test(e))throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID contains invalid characters");if(e.length>100)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is too long (max 100 characters)")}validateVersion(e){if(!e||"string"!=typeof e)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Version must be a non-empty string");if(!/^(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-]+)*))?$/.test(e))throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Version must follow semantic versioning format (e.g., 1.2.3)")}isVersionDowngrade(e,t){const a=this.parseVersion(e),r=this.parseVersion(t);return r.major<a.major||!(r.major>a.major)&&(r.minor<a.minor||!(r.minor>a.minor)&&r.patch<a.patch)}parseVersion(e){const t=e.split("-")[0].split(".");return{major:parseInt(t[0],10)||0,minor:parseInt(t[1],10)||0,patch:parseInt(t[2],10)||0}}validateUrl(e){if(!e||"string"!=typeof e)throw new y(exports.ErrorCode.INVALID_URL,"URL must be a non-empty string");let t;try{t=new URL(e)}catch(e){throw new y(exports.ErrorCode.INVALID_URL,"Invalid URL format")}if("https:"!==t.protocol)throw new y(exports.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed");const a=this.configManager.get("allowedHosts");if(a.length>0&&!a.includes(t.hostname))throw new y(exports.ErrorCode.UNAUTHORIZED_HOST,`Host ${t.hostname} is not in the allowed hosts list`);if([/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[0-1])\./,/^192\.168\./,/^::1$/,/^fc00:/i,/^fe80:/i].some(e=>e.test(t.hostname)))throw new y(exports.ErrorCode.UNAUTHORIZED_HOST,"Private/local addresses are not allowed")}validateFileSize(e){if("number"!=typeof e||e<0)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"File size must be a non-negative number");const t=this.configManager.get("maxBundleSize");if(e>t)throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,`File size ${e} exceeds maximum allowed size of ${t} bytes`)}generateSecureId(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}async validateCertificatePin(e,t){const a=this.configManager.certificatePins;if(!a||!Array.isArray(a)||0===a.length)return!0;const r=a.filter(t=>t.hostname===e);if(0===r.length)return!0;const i=await this.calculateCertificateHash(t),n=r.some(e=>e.sha256===i);return n||this.logger.error("Certificate pinning validation failed",{hostname:e,expectedPins:r.map(e=>e.sha256),actualHash:i}),n}async calculateCertificateHash(e){const t=(new TextEncoder).encode(e),a=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(a));return"sha256/"+btoa(String.fromCharCode(...r))}validateMetadata(e){if(e&&"object"!=typeof e)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata must be an object");if(JSON.stringify(e||{}).length>10240)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata is too large (max 10KB)")}}class D{constructor(){this.STORAGE_KEY="capacitor_native_update_bundles",this.ACTIVE_BUNDLE_KEY="capacitor_native_update_active",this.preferences=null,this.cache=new Map,this.cacheExpiry=0,this.downloadManager=null,this.logger=w.getInstance(),this.configManager=f.getInstance()}setDownloadManager(e){this.downloadManager=e}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new E(exports.ErrorCode.MISSING_DEPENDENCY,"Preferences not configured. Please configure the plugin first.");await this.loadCache()}async loadCache(){if(!(Date.now()<this.cacheExpiry))try{const{value:e}=await this.preferences.get({key:this.STORAGE_KEY});if(e){const t=JSON.parse(e);this.cache.clear(),t.forEach(e=>this.cache.set(e.bundleId,e))}this.cacheExpiry=Date.now()+5e3}catch(e){this.logger.error("Failed to load bundles from storage",e),this.cache.clear()}}async saveCache(){try{const e=Array.from(this.cache.values());await this.preferences.set({key:this.STORAGE_KEY,value:JSON.stringify(e)}),this.logger.debug("Saved bundles to storage",{count:e.length})}catch(e){throw new E(exports.ErrorCode.STORAGE_FULL,"Failed to save bundles to storage",void 0,e)}}async saveBundleInfo(e){this.validateBundleInfo(e),this.cache.set(e.bundleId,e),await this.saveCache(),this.logger.info("Bundle saved",{bundleId:e.bundleId,version:e.version})}validateBundleInfo(e){if(!e.bundleId||"string"!=typeof e.bundleId)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle ID");if(!e.version||"string"!=typeof e.version)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle version");if(!e.path||"string"!=typeof e.path)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle path");if("number"!=typeof e.size||e.size<0)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle size")}async getAllBundles(){return await this.loadCache(),Array.from(this.cache.values())}async getBundle(e){if(!e)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");return await this.loadCache(),this.cache.get(e)||null}async deleteBundle(e){if(!e)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(await this.loadCache(),this.cache.get(e)){if(this.cache.delete(e),await this.saveCache(),await this.getActiveBundleId()===e&&await this.clearActiveBundle(),this.downloadManager)try{await this.downloadManager.deleteBlob(e)}catch(t){this.logger.warn("Failed to delete bundle file",{bundleId:e,error:t})}this.logger.info("Bundle deleted",{bundleId:e})}else this.logger.warn("Attempted to delete non-existent bundle",{bundleId:e})}async getActiveBundle(){const e=await this.getActiveBundleId();return e?this.getBundle(e):null}async setActiveBundle(e){if(!e)throw new E(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");const t=await this.getBundle(e);if(!t)throw new E(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${e} not found`);const a=await this.getActiveBundle();a&&a.bundleId!==e&&(a.status="READY",await this.saveBundleInfo(a)),t.status="ACTIVE",await this.saveBundleInfo(t),await this.preferences.set({key:this.ACTIVE_BUNDLE_KEY,value:e}),this.logger.info("Active bundle set",{bundleId:e,version:t.version})}async getActiveBundleId(){try{const{value:e}=await this.preferences.get({key:this.ACTIVE_BUNDLE_KEY});return e}catch(e){return this.logger.error("Failed to get active bundle ID",e),null}}async clearActiveBundle(){await this.preferences.remove({key:this.ACTIVE_BUNDLE_KEY}),this.logger.info("Active bundle cleared")}async clearAllBundles(){await this.preferences.remove({key:this.STORAGE_KEY}),await this.preferences.remove({key:this.ACTIVE_BUNDLE_KEY}),this.cache.clear(),this.cacheExpiry=0,this.logger.info("All bundles cleared")}async cleanupOldBundles(e){if(e<1)throw new E(exports.ErrorCode.INVALID_CONFIG,"Keep count must be at least 1");const t=await this.getAllBundles(),a=await this.getActiveBundleId(),r=t.sort((e,t)=>t.downloadTime-e.downloadTime),i=new Set;a&&i.add(a);let n=i.size;for(const t of r){if(n>=e)break;i.has(t.bundleId)||(i.add(t.bundleId),n++)}let o=0;for(const e of t)i.has(e.bundleId)||(await this.deleteBundle(e.bundleId),o++);o>0&&this.logger.info("Cleaned up old bundles",{deleted:o,kept:n})}async getBundlesOlderThan(e){if(e<0)throw new E(exports.ErrorCode.INVALID_CONFIG,"Timestamp must be non-negative");return(await this.getAllBundles()).filter(t=>t.downloadTime<e)}async markBundleAsVerified(e){const t=await this.getBundle(e);if(!t)throw new E(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${e} not found`);t.verified=!0,await this.saveBundleInfo(t),this.logger.info("Bundle marked as verified",{bundleId:e})}async getTotalStorageUsed(){return(await this.getAllBundles()).reduce((e,t)=>e+t.size,0)}async isStorageLimitExceeded(e=0){const t=await this.getTotalStorageUsed();let a=3*this.configManager.get("maxBundleSize");try{if("storage"in navigator&&"estimate"in navigator.storage){const e=await navigator.storage.estimate();e.quota&&(a=Math.max(a,e.quota-104857600))}}catch(e){this.logger.warn("Storage API not available for quota check, using config limit")}return t+e>a}createDefaultBundle(){return{bundleId:"default",version:"1.0.0",path:"/",downloadTime:Date.now(),size:0,status:"ACTIVE",checksum:"",verified:!0}}async cleanExpiredBundles(){const e=this.configManager.get("cacheExpiration"),t=Date.now()-e,a=await this.getBundlesOlderThan(t);for(const e of a){const t=await this.getActiveBundleId();e.bundleId!==t&&await this.deleteBundle(e.bundleId)}}}class b{constructor(){this.activeDownloads=new Map,this.lastResponseMeta=new Map,this.filesystem=null,this.logger=w.getInstance(),this.configManager=f.getInstance()}async initialize(){if(this.filesystem=this.configManager.get("filesystem"),!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured. Please configure the plugin first.")}validateUrl(e){try{const t=new URL(e);if("https:"!==t.protocol)throw new y(exports.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed for security reasons");const a=this.configManager.get("allowedHosts");if(a.length>0&&!a.includes(t.hostname))throw new y(exports.ErrorCode.UNAUTHORIZED_HOST,`Host ${t.hostname} is not in the allowed hosts list`)}catch(e){if(e instanceof y)throw e;throw new y(exports.ErrorCode.INVALID_URL,"Invalid URL format")}}async download(e,t,a){var r;const i="function"==typeof a?{onProgress:a}:null!=a?a:{},n=i.onProgress,o=null!==(r=i.resumePosition)&&void 0!==r?r:0;if(this.validateUrl(e),!t)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(this.activeDownloads.has(t))throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Download already in progress for bundle ${t}`);const s=new AbortController,l={controller:s,startTime:Date.now(),resumePosition:o>0?o:void 0};this.activeDownloads.set(t,l);try{const a=this.configManager.get("downloadTimeout"),r=setTimeout(()=>s.abort(),a),i={"Cache-Control":"no-cache",Accept:"application/octet-stream, application/zip"};o>0&&(i.Range=`bytes=${o}-`);const d=await fetch(e,{signal:s.signal,headers:i});if(clearTimeout(r),!d.ok)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Download failed: ${d.status} ${d.statusText}`,{status:d.status,statusText:d.statusText});const c=o>0&&206===d.status;l.serverReturnedPartial=c,this.lastResponseMeta.set(t,{partial:c});const u=d.headers.get("content-type");if(u&&!this.isValidContentType(u))throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,`Invalid content type: ${u}`);const h=d.headers.get("content-length"),p=h?parseInt(h,10):0;if(p>this.configManager.get("maxBundleSize"))throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,`Bundle size ${p} exceeds maximum allowed size`);if(!p||!d.body){const e=await d.blob();return this.validateBlobSize(e),e}const g=d.body.getReader(),f=[];let w=0;for(;;){const{done:e,value:a}=await g.read();if(e)break;if(f.push(a),w+=a.length,w>this.configManager.get("maxBundleSize"))throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,"Download size exceeds maximum allowed size");if(n){const e=l.resumePosition||0,a=e+w,r=e+p;n({percent:Math.round(a/r*100),bytesDownloaded:a,totalBytes:r,bundleId:t})}}const m=new Blob(f);return this.validateBlobSize(m),this.logger.info("Download completed",{bundleId:t,size:m.size,duration:Date.now()-l.startTime}),m}catch(e){if(e instanceof Error&&"AbortError"===e.name){const t=Date.now()-l.startTime>=this.configManager.get("downloadTimeout");throw new v(t?exports.ErrorCode.DOWNLOAD_TIMEOUT:exports.ErrorCode.DOWNLOAD_FAILED,t?"Download timed out":"Download cancelled",void 0,e)}throw e}finally{this.activeDownloads.delete(t)}}async resumeDownload(e,t,a,r){const i=await this.download(e,t,{onProgress:r,resumePosition:a.size}),n=this.lastResponseMeta.get(t);return this.lastResponseMeta.delete(t),(null==n?void 0:n.partial)?new Blob([a,i]):(this.logger.info("Resume: server returned full response; discarding partial data",{bundleId:t,partialSize:a.size,responseSize:i.size}),i)}async canResume(e){try{return"bytes"===(await fetch(e,{method:"HEAD"})).headers.get("Accept-Ranges")}catch(e){return!1}}isValidContentType(e){return["application/octet-stream","application/zip","application/x-zip-compressed","application/x-zip"].some(t=>e.includes(t))}validateBlobSize(e){if(0===e.size)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Downloaded file is empty");if(e.size>this.configManager.get("maxBundleSize"))throw new y(exports.ErrorCode.BUNDLE_TOO_LARGE,`File size ${e.size} exceeds maximum allowed size`)}cancelDownload(e){const t=this.activeDownloads.get(e);t&&(t.controller.abort(),this.activeDownloads.delete(e),this.logger.info("Download cancelled",{bundleId:e}))}cancelAllDownloads(){for(const e of this.activeDownloads.values())e.controller.abort();const e=this.activeDownloads.size;this.activeDownloads.clear(),e>0&&this.logger.info("All downloads cancelled",{count:e})}isDownloading(e){return this.activeDownloads.has(e)}getActiveDownloadCount(){return this.activeDownloads.size}async downloadWithRetry(e,t,a){const r=this.configManager.get("retryAttempts"),i=this.configManager.get("retryDelay");let n=null;for(let o=0;o<r;o++)try{if(o>0){const e=i*Math.pow(2,o-1),a=.5*(Math.random()-.5)*e,r=Math.min(Math.max(e+a,100),3e4);await new Promise(e=>setTimeout(e,r)),this.logger.debug("Retrying download",{bundleId:t,attempt:o,delay:r})}return await this.download(e,t,a)}catch(e){if(n=e,e instanceof y||e instanceof Error&&"AbortError"===e.name)throw e;this.logger.warn(`Download attempt ${o+1} failed`,{bundleId:t,error:e})}throw new v(exports.ErrorCode.DOWNLOAD_FAILED,"Download failed after all retries",{attempts:r},n||void 0)}async blobToArrayBuffer(e){return e.arrayBuffer()}async saveBlob(e,t){if(!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");const a=await this.blobToArrayBuffer(t),r=new Uint8Array(a);let i="";for(let e=0;e<r.length;e+=32768)i+=String.fromCharCode.apply(null,Array.from(r.subarray(e,e+32768)));const n=btoa(i),o=`bundles/${e}/bundle.zip`;return await this.filesystem.writeFile({path:o,data:n,directory:p.Directory.Data,recursive:!0}),this.logger.debug("Bundle saved to filesystem",{bundleId:e,path:o,size:t.size}),o}async loadBlob(e){if(!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const t=`bundles/${e}/bundle.zip`,a=await this.filesystem.readFile({path:t,directory:p.Directory.Data}),r=atob(a.data),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return new Blob([i],{type:"application/zip"})}catch(t){return this.logger.debug("Failed to load bundle from filesystem",{bundleId:e,error:t}),null}}async deleteBlob(e){if(!this.filesystem)throw new v(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const t=`bundles/${e}`;await this.filesystem.rmdir({path:t,directory:p.Directory.Data,recursive:!0}),this.logger.debug("Bundle deleted from filesystem",{bundleId:e})}catch(t){this.logger.warn("Failed to delete bundle from filesystem",{bundleId:e,error:t})}}}async function U(e,t){var a,r,i,n,o;const s=`${e.replace(/\/$/,"")}/v1/updates/check?channel=${encodeURIComponent(t.channel)}`,l={"Content-Type":"application/json","X-API-Key":t.apiKey,"X-Device-ID":t.deviceId,"X-Current-Version":t.currentVersion,"X-Platform":t.platform,"X-Client-Sdk":"capacitor","X-Sdk-Version":"5.0.2"};"undefined"!=typeof navigator&&navigator.language&&(l["Accept-Language"]=navigator.language),t.appVersion&&(l["X-App-Version"]=t.appVersion);const d=t.identity;"android"===(null==d?void 0:d.platform)?(d.packageName&&(l["X-Android-Package"]=d.packageName),d.certSha256&&(l["X-Android-Cert-Sha256"]=d.certSha256),d.certSha1&&(l["X-Android-Cert-Sha1"]=d.certSha1)):"ios"===(null==d?void 0:d.platform)&&(d.bundleId&&(l["X-Ios-Bundle-Id"]=d.bundleId),d.teamId&&(l["X-Ios-Team-Id"]=d.teamId));const c=await fetch(s,{method:"GET",headers:l,signal:t.signal});if(!c.ok)return{available:!1};const u=await c.json();return{available:Boolean(u.available),version:u.version,bundleId:u.bundleId,downloadUrl:u.downloadUrl,checksum:u.checksum,signature:null!==(a=u.signature)&&void 0!==a?a:void 0,signatureAlgorithm:null!==(r=u.signatureAlgorithm)&&void 0!==r?r:void 0,delta:null!==(i=u.delta)&&void 0!==i?i:void 0,size:u.size,mandatory:u.mandatory,releaseNotes:null!==(n=u.releaseNotes)&&void 0!==n?n:void 0,minNativeVersion:null!==(o=u.minNativeVersion)&&void 0!==o?o:void 0,expiresAt:u.expiresAt,payloadType:u.payloadType,message:u.message,held:!0===u.held||void 0,code:u.code}}function N(e){const t=e.trim().replace(/^v/i,"").split("+")[0],a=t.indexOf("-"),r=-1===a?t:t.slice(0,a),i=-1===a?"":t.slice(a+1);return{core:r.split(".").map(e=>{const t=Number.parseInt(e,10);return Number.isFinite(t)?t:0}),pre:""===i?[]:i.split(".")}}const C=/^\d+$/,S=/^(.*?)(\d+)$/;function L(e,t){const a=C.test(e),r=C.test(t);if(a&&r)return Math.sign(Number(e)-Number(t));if(a)return-1;if(r)return 1;const i=S.exec(e),n=S.exec(t);return i&&n&&i[1]===n[1]?Math.sign(Number(i[2])-Number(n[2])):e===t?0:e<t?-1:1}function R(e,t){var a,r;const i=N(e),n=N(t),o=Math.max(i.core.length,n.core.length,3);for(let e=0;e<o;e++){const t=(null!==(a=i.core[e])&&void 0!==a?a:0)-(null!==(r=n.core[e])&&void 0!==r?r:0);if(0!==t)return Math.sign(t)}if(0===i.pre.length&&0===n.pre.length)return 0;if(0===i.pre.length)return 1;if(0===n.pre.length)return-1;const s=Math.max(i.pre.length,n.pre.length);for(let e=0;e<s;e++){const t=i.pre[e],a=n.pre[e];if(void 0===t)return-1;if(void 0===a)return 1;const r=L(t,a);if(0!==r)return r}return 0}class _{constructor(){this.VERSION_CHECK_CACHE_KEY="capacitor_native_update_version_cache",this.CACHE_DURATION=3e5,this.preferences=null,this.memoryCache=new Map,this.logger=w.getInstance(),this.configManager=f.getInstance(),this.securityValidator=A.getInstance()}static compareVersions(e,t){return R(e,t)}static isValidVersion(e){return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(e)}static shouldUpdate(e,t,a){return!(a&&_.compareVersions(e,a)<0)&&_.compareVersions(e,t)<0}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new y(exports.ErrorCode.MISSING_DEPENDENCY,"Preferences not configured. Please configure the plugin first.")}async checkForUpdates(e,t,a,r){var i;if(this.securityValidator.validateUrl(e),this.securityValidator.validateVersion(a),!t||!r)throw new y(exports.ErrorCode.INVALID_CONFIG,"Channel and appId are required");const n=`${t}-${r}`,o=await this.getCachedVersionInfo(n);if(o&&o.channel===t&&Date.now()-o.timestamp<this.CACHE_DURATION)return this.logger.debug("Returning cached version info",{channel:t,version:o.data.version}),o.data;const s=this.configManager.get("apiKey");if(!s)return this.logger.warn("VersionManager.checkForUpdates: no apiKey configured — the Native Update backend requires X-API-Key"),null;try{const r=await U(e,{apiKey:s,channel:t,currentVersion:a,deviceId:"web-client",platform:"web",appVersion:a,signal:AbortSignal.timeout(this.configManager.get("downloadTimeout"))}),o={available:r.available,version:r.version,url:r.downloadUrl,mandatory:r.mandatory,notes:null!==(i=r.releaseNotes)&&void 0!==i?i:void 0,size:r.size,checksum:r.checksum};if(!o.available)return o;if(!o.version)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"No version in server response");return this.securityValidator.validateVersion(o.version),o.url&&this.securityValidator.validateUrl(o.url),r.minNativeVersion&&this.securityValidator.validateVersion(r.minNativeVersion),await this.cacheVersionInfo(n,t,o),this.logger.info("Version check completed",{channel:t,currentVersion:a,latestVersion:o.version,updateAvailable:this.isNewerVersion(o.version,a)}),o}catch(e){return this.logger.error("Failed to check for updates",e),null}}isNewerVersion(e,t){try{const a=this.parseVersion(e),r=this.parseVersion(t);return a.major!==r.major?a.major>r.major:a.minor!==r.minor?a.minor>r.minor:a.patch!==r.patch?a.patch>r.patch:!(a.prerelease&&!r.prerelease||(a.prerelease||!r.prerelease)&&(!a.prerelease||!r.prerelease||!(a.prerelease>r.prerelease)))}catch(a){return this.logger.error("Failed to compare versions",{version1:e,version2:t,error:a}),!1}}isUpdateMandatory(e,t){if(!t)return!1;try{return this.securityValidator.validateVersion(e),this.securityValidator.validateVersion(t),!this.isNewerVersion(e,t)&&e!==t}catch(e){return this.logger.error("Failed to check mandatory update",e),!1}}parseVersion(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/);if(!t)throw new y(exports.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid version format");return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),prerelease:t[4],build:t[5]}}buildVersionString(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease&&(t+=`-${e.prerelease}`),e.build&&(t+=`+${e.build}`),t}isCompatibleWithNativeVersion(e,t,a){if(!a)return!0;try{const r=a[e];return!r||(this.securityValidator.validateVersion(t),this.securityValidator.validateVersion(r),!this.isNewerVersion(r,t))}catch(e){return this.logger.error("Failed to check compatibility",e),!1}}async getCachedVersionInfo(e){const t=this.memoryCache.get(e);if(t&&Date.now()-t.timestamp<this.CACHE_DURATION)return t;try{const{value:t}=await this.preferences.get({key:this.VERSION_CHECK_CACHE_KEY});if(!t)return null;const a=JSON.parse(t)[e];if(a&&Date.now()-a.timestamp<this.CACHE_DURATION)return this.memoryCache.set(e,a),a}catch(e){this.logger.debug("Failed to load cached version info",e)}return null}async cacheVersionInfo(e,t,a){const r={channel:t,data:a,timestamp:Date.now()};this.memoryCache.set(e,r);try{const{value:t}=await this.preferences.get({key:this.VERSION_CHECK_CACHE_KEY}),a=t?JSON.parse(t):{},i=Date.now();for(const e in a)i-a[e].timestamp>2*this.CACHE_DURATION&&delete a[e];a[e]=r,await this.preferences.set({key:this.VERSION_CHECK_CACHE_KEY,value:JSON.stringify(a)})}catch(e){this.logger.warn("Failed to cache version info",e)}}async clearVersionCache(){this.memoryCache.clear();try{await this.preferences.remove({key:this.VERSION_CHECK_CACHE_KEY})}catch(e){this.logger.warn("Failed to clear version cache",e)}}shouldBlockDowngrade(e,t){try{return this.securityValidator.isVersionDowngrade(e,t)}catch(e){return this.logger.error("Failed to check downgrade",e),!0}}maxVersionKey(e){return`nu_max_version_${e}`}async getMaxSeenVersion(e){if(!this.preferences)return null;try{const{value:t}=await this.preferences.get({key:this.maxVersionKey(e)});return null!=t?t:null}catch(e){return this.logger.warn("Failed to read max-seen version",e),null}}async rememberAppliedVersion(e,t){if(!this.preferences)return;const a=await this.getMaxSeenVersion(e);if(!(a&&_.compareVersions(a,t)>=0))try{await this.preferences.set({key:this.maxVersionKey(e),value:t})}catch(e){this.logger.warn("Failed to persist max-seen version",e)}}}class M{constructor(e){this.cachedAppInfo=null,this.CACHE_DURATION=6e4,this.config=e,this.logger=new w("AppUpdateChecker")}async checkServerVersion(e){if(!this.config.updateUrl)return{};try{const e=await this.getCurrentVersion(),t=new URL(`${this.config.updateUrl}/app-version`);t.searchParams.append("platform",this.getPlatform()),t.searchParams.append("current",e),this.config.channel&&t.searchParams.append("channel",this.config.channel);const a=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json","X-App-Version":e,"X-App-Platform":this.getPlatform()}});if(!a.ok)throw new Error(`Server returned ${a.status}`);const r=await a.json();return{availableVersion:r.version,updatePriority:r.priority,releaseNotes:r.releaseNotes,updateSize:r.size,updateURL:r.downloadUrl}}catch(e){return this.logger.error("Failed to check server version",e),{}}}compareVersions(e,t){return R(e,t)}isUpdateRequired(e,t,a){return this.compareVersions(e,t)<0||!!(a&&this.compareVersions(e,a)<0)}determineUpdatePriority(e,t){const[a,r]=e.split(".").map(Number);return a>0?5:r>0&&t&&t>30?4:r>0?3:1}async getCurrentVersion(){if(this.cachedAppInfo&&Date.now()-this.cachedAppInfo.timestamp<this.CACHE_DURATION)return this.cachedAppInfo.version;try{const{App:e}=await(import("@capacitor/app")),t=await e.getInfo();return this.cachedAppInfo={version:t.version,build:t.build,name:t.name,id:t.id,timestamp:Date.now()},this.logger.debug("Got app info from Capacitor",{version:t.version,build:t.build}),t.version}catch(e){this.logger.debug("Failed to get app info from Capacitor, using fallback",e);const t=this.config.appVersion;if("string"==typeof t)return t;if("undefined"!=typeof window){const e=window;if("string"==typeof e.APP_VERSION)return e.APP_VERSION}return"1.0.0"}}async getCurrentBuild(){if(this.cachedAppInfo&&Date.now()-this.cachedAppInfo.timestamp<this.CACHE_DURATION)return this.cachedAppInfo.build;try{const{App:e}=await(import("@capacitor/app")),t=await e.getInfo();return this.cachedAppInfo={version:t.version,build:t.build,name:t.name,id:t.id,timestamp:Date.now()},t.build}catch(e){return"1"}}async getAppInfo(){if(this.cachedAppInfo&&Date.now()-this.cachedAppInfo.timestamp<this.CACHE_DURATION)return this.cachedAppInfo;try{const{App:e}=await(import("@capacitor/app")),t=await e.getInfo();return this.cachedAppInfo={version:t.version,build:t.build,name:t.name,id:t.id,timestamp:Date.now()},this.cachedAppInfo}catch(e){return{version:"1.0.0",build:"1",name:"App",id:"com.app",timestamp:Date.now()}}}clearCache(){this.cachedAppInfo=null}getPlatform(){if("undefined"!=typeof window){const e=window.navigator.userAgent;if(/android/i.test(e))return"android";if(/iPad|iPhone|iPod/.test(e))return"ios"}return"web"}}var O;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.PENDING=1]="PENDING",e[e.DOWNLOADING=2]="DOWNLOADING",e[e.INSTALLING=3]="INSTALLING",e[e.INSTALLED=4]="INSTALLED",e[e.FAILED=5]="FAILED",e[e.CANCELED=6]="CANCELED",e[e.DOWNLOADED=11]="DOWNLOADED"}(O||(O={}));class T{constructor(e){this.flexibleUpdateInterval=null,this.logger=new w("AppUpdateInstaller"),this.currentState={installStatus:O.UNKNOWN,packageName:"",availableVersion:""}}async startImmediateUpdate(){if(this.logger.log("Starting immediate update installation"),this.updateState(O.PENDING),this.isAndroid())this.logger.log("Triggering Android immediate update");else{if(!this.isIOS())throw new Error("Immediate updates not supported on web platform");this.logger.log("Opening iOS App Store for update")}}async startFlexibleUpdate(){if(this.logger.log("Starting flexible update download"),this.updateState(O.DOWNLOADING),this.isWeb())this.simulateFlexibleUpdate();else{if(!this.isAndroid())throw new Error("Flexible updates not supported on iOS");this.logger.log("Starting Android flexible update")}}async completeFlexibleUpdate(){if(this.logger.log("Completing flexible update installation"),this.currentState.installStatus!==O.DOWNLOADED)throw new Error("Update not ready for installation");this.updateState(O.INSTALLING),this.isAndroid()?this.logger.log("Completing Android update installation"):setTimeout(()=>{this.updateState(O.INSTALLED)},1e3)}async cancelUpdate(){this.logger.log("Cancelling update"),this.flexibleUpdateInterval&&(clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=null),this.currentState.installStatus===O.DOWNLOADING&&this.updateState(O.CANCELED)}async getInstallState(){return Object.assign({},this.currentState)}onProgress(e){this.progressCallback=e}updateState(e,t){this.currentState.installStatus=e,void 0!==t&&(this.currentState.installErrorCode=t),this.logger.log("Update state changed",this.currentState)}simulateFlexibleUpdate(){let e=0;const t=52428800,a=1048576;this.flexibleUpdateInterval&&clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=setInterval(()=>{e+=a,e>=t&&(e=t,this.flexibleUpdateInterval&&(clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=null),this.updateState(O.DOWNLOADED));const r={bytesDownloaded:e,totalBytesToDownload:t,percentComplete:Math.round(e/t*100),downloadSpeed:a,estimatedTime:Math.ceil((t-e)/a)};this.progressCallback&&this.progressCallback(r)},1e3)}isAndroid(){return"undefined"!=typeof window&&/android/i.test(window.navigator.userAgent)}isIOS(){return"undefined"!=typeof window&&/iPad|iPhone|iPod/.test(window.navigator.userAgent)}isWeb(){return!this.isAndroid()&&!this.isIOS()}}class x{constructor(e){this.config=e,this.logger=new w("PlatformAppUpdate"),this.platform=h.Capacitor.getPlatform()}async checkForUpdate(e){this.logger.log("Checking for platform update: "+this.platform);const t=await this.getVersionInfo(),a={updateAvailable:!1,currentVersion:t.currentVersion,availableVersion:t.currentVersion};if("android"===this.platform)return a;if("ios"===this.platform)return a;if(this.config.webUpdateUrl)try{A.validateDownloadUrl(this.config.webUpdateUrl);const e=await fetch(this.config.webUpdateUrl),r=await e.json();r.version&&r.version!==t.currentVersion&&(a.updateAvailable=!0,a.availableVersion=r.version,a.releaseNotes=r.releaseNotes,r.downloadUrl&&(A.validateStoreUrl(r.downloadUrl),a.updateURL=r.downloadUrl))}catch(e){this.logger.error("Failed to check web update",e)}return a}async getVersionInfo(){return{currentVersion:"1.0.0",buildNumber:"1",packageName:"com.example.app",platform:this.platform,minimumVersion:this.config.minimumVersion}}async getAppStoreUrl(){const e=this.platform;let t="";if("ios"===e){const e=this.config.appStoreId||this.config.iosAppId;if(!e)throw new Error("App Store ID not configured");t=`https://apps.apple.com/app/id${e}`}else t="android"===e?`https://play.google.com/store/apps/details?id=${this.config.packageName||(await this.getVersionInfo()).packageName}`:this.config.webUpdateUrl||window.location.origin;return{url:t,platform:e}}async openUrl(e){if(A.validateStoreUrl(e),"undefined"==typeof window||!window.open)throw new Error("Cannot open URL on this platform");window.open(e,"_blank","noopener,noreferrer")}isUpdateSupported(){return"android"===this.platform||"ios"!==this.platform}getUpdateCapabilities(){const e={immediateUpdate:!1,flexibleUpdate:!1,backgroundDownload:!1,inAppReview:!1};return"android"===this.platform?(e.immediateUpdate=!0,e.flexibleUpdate=!0,e.backgroundDownload=!0,e.inAppReview=!0):"ios"===this.platform&&(e.inAppReview=!0),e}}class B{constructor(e){this.listeners=new Map,this.config=e,this.logger=new w("AppUpdateManager"),this.checker=new M(e),this.installer=new T(e),this.platformUpdate=new x(e)}async checkAppUpdate(e){try{this.logger.log("Checking for app updates",e);const t=await this.platformUpdate.checkForUpdate(e);if(!t.updateAvailable&&this.config.updateUrl){const a=await this.checker.checkServerVersion(e);return this.mergeUpdateInfo(t,a)}return t}catch(e){throw this.logger.error("Failed to check app update",e),e}}async startImmediateUpdate(){try{this.logger.log("Starting immediate update");const e=await this.checkAppUpdate();if(!e.immediateUpdateAllowed)throw new Error("Immediate update not allowed");await this.installer.startImmediateUpdate(),this.emit("appUpdateStateChanged",{installStatus:1,packageName:this.config.packageName||"",availableVersion:e.availableVersion||""})}catch(e){throw this.logger.error("Failed to start immediate update",e),e}}async startFlexibleUpdate(){try{this.logger.log("Starting flexible update");const e=await this.checkAppUpdate();if(!e.flexibleUpdateAllowed)throw new Error("Flexible update not allowed");await this.installer.startFlexibleUpdate(),this.installer.onProgress(e=>{this.emit("appUpdateProgress",e)}),this.emit("appUpdateStateChanged",{installStatus:2,packageName:this.config.packageName||"",availableVersion:e.availableVersion||""})}catch(e){throw this.logger.error("Failed to start flexible update",e),e}}async completeFlexibleUpdate(){try{this.logger.log("Completing flexible update"),await this.installer.completeFlexibleUpdate(),this.emit("appUpdateStateChanged",{installStatus:3,packageName:this.config.packageName||"",availableVersion:""})}catch(e){throw this.logger.error("Failed to complete flexible update",e),e}}async getVersionInfo(){try{return this.logger.log("Getting version info"),await this.platformUpdate.getVersionInfo()}catch(e){throw this.logger.error("Failed to get version info",e),e}}async isMinimumVersionMet(){try{this.logger.log("Checking minimum version");const e=await this.getVersionInfo(),t=this.config.minimumVersion||"0.0.0",a=this.checker.compareVersions(e.currentVersion,t)>=0;return{isMet:a,currentVersion:e.currentVersion,minimumVersion:t,updateRequired:!a&&!0===this.config.enforceMinVersion}}catch(e){throw this.logger.error("Failed to check minimum version",e),e}}async getAppUpdateInfo(){return this.checkAppUpdate()}async performImmediateUpdate(){return this.startImmediateUpdate()}async openAppStore(e){try{this.logger.log("Opening app store");const e=await this.getAppStoreUrl();await this.platformUpdate.openUrl(e.url)}catch(e){throw this.logger.error("Failed to open app store",e),e}}async getAppStoreUrl(){try{return this.logger.log("Getting app store URL"),await this.platformUpdate.getAppStoreUrl()}catch(e){throw this.logger.error("Failed to get app store URL",e),e}}async getUpdateInstallState(){try{return this.logger.log("Getting update install state"),await this.installer.getInstallState()}catch(e){throw this.logger.error("Failed to get update install state",e),e}}addListener(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),{remove:async()=>{const a=this.listeners.get(e);a&&a.delete(t)}}}async removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}emit(e,t){const a=this.listeners.get(e);a&&a.forEach(a=>{try{a(t)}catch(t){this.logger.error(`Error in ${e} listener`,t)}})}mergeUpdateInfo(e,t){return Object.assign(Object.assign(Object.assign({},e),t),{updateAvailable:e.updateAvailable||!!t.availableVersion,availableVersion:t.availableVersion||e.availableVersion})}}class V{constructor(){this.config=null,this.status={enabled:!1,isRunning:!1,checkCount:0,failureCount:0},this.deps={},this.logger=w.getInstance(),this.configManager=f.getInstance()}setDependencies(e){this.deps=e}configure(e){this.config=e,this.status.enabled=e.enabled}getStatus(){return Object.assign({},this.status)}async performCheck(){var e;if(!(null===(e=this.config)||void 0===e?void 0:e.enabled))return{success:!1,updatesFound:!1,notificationSent:!1,error:{code:exports.UpdateErrorCode.INVALID_CONFIG,message:"Background updates not enabled"}};this.status.isRunning=!0,this.status.checkCount++;try{const e=await this.checkForUpdates();return this.status.lastCheckTime=Date.now(),this.status.isRunning=!1,this.status.lastError=void 0,e}catch(e){return this.status.failureCount++,this.status.isRunning=!1,this.status.lastError={code:exports.UpdateErrorCode.UNKNOWN_ERROR,message:e instanceof Error?e.message:"Unknown error"},{success:!1,updatesFound:!1,notificationSent:!1,error:this.status.lastError}}}async checkForUpdates(){var e,t,a,r,i,n;const o=[];let s,l;((null===(e=this.config)||void 0===e?void 0:e.updateTypes.includes(exports.BackgroundUpdateType.APP_UPDATE))||(null===(t=this.config)||void 0===t?void 0:t.updateTypes.includes(exports.BackgroundUpdateType.BOTH)))&&o.push(this.checkAppUpdate()),((null===(a=this.config)||void 0===a?void 0:a.updateTypes.includes(exports.BackgroundUpdateType.LIVE_UPDATE))||(null===(r=this.config)||void 0===r?void 0:r.updateTypes.includes(exports.BackgroundUpdateType.BOTH)))&&o.push(this.checkLiveUpdate());const d=await Promise.allSettled(o);"fulfilled"===(null===(i=d[0])||void 0===i?void 0:i.status)&&(s=d[0].value),"fulfilled"===(null===(n=d[1])||void 0===n?void 0:n.status)&&(l=d[1].value);const c=(null==s?void 0:s.updateAvailable)||(null==l?void 0:l.available)||!1;let u=!1;return c&&(u=await this.sendNotification(s,l)),{success:!0,updatesFound:c,appUpdate:s,liveUpdate:l,notificationSent:u}}async checkAppUpdate(){if(this.deps.appUpdateManager)try{return await this.deps.appUpdateManager.getAppUpdateInfo()}catch(e){this.logger.error("Failed to check app update via manager",e)}const e=this.configManager.get("baseUrl")||this.configManager.get("serverUrl");if(e)try{const t=await this.getCurrentAppVersion(),a=await fetch(`${e}/app-version`,{method:"GET",headers:{"Content-Type":"application/json","X-Current-Version":t,"X-Platform":this.getPlatform()}});if(a.ok){const e=await a.json(),r=e.version||e.latestVersion,i=r&&this.compareVersions(t,r)<0;return{updateAvailable:i,currentVersion:t,availableVersion:i?r:void 0,updatePriority:e.priority}}}catch(e){this.logger.error("Failed to check app update via server",e)}return{updateAvailable:!1,currentVersion:await this.getCurrentAppVersion()}}async checkLiveUpdate(){var e;let t="1.0.0";if(this.deps.bundleManager)try{const e=await this.deps.bundleManager.getActiveBundle();e&&(t=e.version)}catch(e){}if(this.deps.versionManager)try{const e=this.configManager.get("serverUrl"),a=this.configManager.get("channel")||"production",r=this.configManager.get("appId");if(e&&r){const i=await this.deps.versionManager.checkForUpdates(e,a,t,r);if(i)return i}}catch(e){this.logger.error("Failed to check live update via VersionManager",e)}const a=this.configManager.get("baseUrl")||this.configManager.get("serverUrl"),r=this.configManager.get("apiKey");if(a&&r)try{const i=this.configManager.get("channel")||"production",n=await U(a,{apiKey:r,channel:i,currentVersion:t,deviceId:"web-client",platform:this.getPlatform(),appVersion:t});return{available:n.available,version:n.version,url:n.available?n.downloadUrl:void 0,notes:null!==(e=n.releaseNotes)&&void 0!==e?e:void 0,size:n.size,checksum:n.checksum}}catch(e){this.logger.error("Failed to check live update via server",e)}return{available:!1}}async sendNotification(e,t){var a;if(!(null===(a=this.config)||void 0===a?void 0:a.notificationPreferences))return!1;const r=this.config.notificationPreferences;let i=r.title||"Update Available",n=r.description||"";if((null==e?void 0:e.updateAvailable)?(i="App Update Available",n=`Version ${e.availableVersion} is ready to install.`):(null==t?void 0:t.available)&&(i="New Update Available",n=`Version ${t.version} is ready to download. ${t.notes||""}`),"undefined"!=typeof window&&"Notification"in window)try{if("granted"===Notification.permission)return new Notification(i,{body:n}),!0}catch(e){this.logger.error("Failed to send notification",e)}return this.logger.info("Background update notification",{title:i,body:n}),!1}async getCurrentAppVersion(){try{const{App:e}=await(import("@capacitor/app"));return(await e.getInfo()).version}catch(e){return"1.0.0"}}getPlatform(){if("undefined"!=typeof window){const e=window.navigator.userAgent;if(/android/i.test(e))return"android";if(/iPad|iPhone|iPod/.test(e))return"ios"}return"web"}calculateNextCheckTime(){var e;return Date.now()+((null===(e=this.config)||void 0===e?void 0:e.checkInterval)||864e5)}shouldRespectBatteryOptimization(){var e,t;return null===(t=null===(e=this.config)||void 0===e?void 0:e.respectBatteryOptimization)||void 0===t||t}isNetworkConditionMet(){return"undefined"==typeof navigator||!("onLine"in navigator)||navigator.onLine}isBatteryLevelSufficient(){return!0}compareVersions(e,t){return R(e,t)}}const k=new w("NativeUpdate.EventEmitter");class F{constructor(){this.listeners=new Map}static getInstance(){return F.instance||(F.instance=new F),F.instance}addListener(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const a=this.listeners.get(e);a&&(a.delete(t),0===a.size&&this.listeners.delete(e))}}emit(e,t){const a=this.listeners.get(e);a&&a.forEach(a=>{try{a(t)}catch(t){k.error(`Error in event listener for ${e}`,t)}})}removeListeners(e){this.listeners.delete(e)}removeAllListeners(){this.listeners.clear()}listenerCount(e){var t;return(null===(t=this.listeners.get(e))||void 0===t?void 0:t.size)||0}eventNames(){return Array.from(this.listeners.keys())}}class P{constructor(){this.bundleManager=null,this.downloadManager=null,this.versionManager=null,this.appUpdateManager=null,this.backgroundScheduler=null,this.initialized=!1,this.configManager=f.getInstance(),this.logger=w.getInstance(),this.securityValidator=A.getInstance(),this.eventEmitter=F.getInstance()}static getInstance(){return P.instance||(P.instance=new P),P.instance}async initialize(e){var t,a;if(this.initialized)this.logger.warn("Plugin already initialized");else try{e.filesystem||(e.filesystem=p.Filesystem),e.preferences||(e.preferences=g.Preferences),this.configManager.configure(e),this.bundleManager=new D,await this.bundleManager.initialize(),this.downloadManager=new b,await this.downloadManager.initialize(),this.bundleManager.setDownloadManager(this.downloadManager),this.versionManager=new _,await this.versionManager.initialize(),this.appUpdateManager=new B({serverUrl:e.serverUrl||e.baseUrl||"",channel:e.channel||"production",autoCheck:null===(t=e.autoCheck)||void 0===t||t,autoUpdate:null!==(a=e.autoUpdate)&&void 0!==a&&a,updateStrategy:e.updateStrategy,publicKey:e.publicKey,requireSignature:e.requireSignature,checksumAlgorithm:e.checksumAlgorithm,checkInterval:e.checkInterval,security:e.security}),this.setupAppUpdateEventBridge(),this.backgroundScheduler=new V,this.backgroundScheduler.setDependencies({appUpdateManager:this.appUpdateManager,versionManager:this.versionManager,bundleManager:this.bundleManager}),this.initialized=!0,this.logger.info("Plugin initialized successfully")}catch(e){throw this.logger.error("Failed to initialize plugin",e),e}}isInitialized(){return this.initialized&&this.configManager.isConfigured()}ensureInitialized(){if(!this.isInitialized())throw new m(exports.ErrorCode.NOT_CONFIGURED,"Plugin not initialized. Please call initialize() first.")}getBundleManager(){return this.ensureInitialized(),this.bundleManager}getDownloadManager(){return this.ensureInitialized(),this.downloadManager}getVersionManager(){return this.ensureInitialized(),this.versionManager}getConfigManager(){return this.configManager}getLogger(){return this.logger}getSecurityValidator(){return this.securityValidator}getAppUpdateManager(){return this.ensureInitialized(),this.appUpdateManager}getEventEmitter(){return this.eventEmitter}getBackgroundScheduler(){return this.ensureInitialized(),this.backgroundScheduler}async reset(){this.logger.info("Resetting plugin state"),this.bundleManager&&await this.bundleManager.clearAllBundles(),this.versionManager&&await this.versionManager.clearVersionCache(),this.downloadManager&&this.downloadManager.cancelAllDownloads(),this.bundleManager=null,this.downloadManager=null,this.versionManager=null,this.appUpdateManager=null,this.backgroundScheduler=null,this.initialized=!1,this.configManager.reset(),this.eventEmitter.removeAllListeners(),this.logger.info("Plugin reset complete")}async cleanup(){this.logger.info("Cleaning up plugin resources"),this.downloadManager&&this.downloadManager.cancelAllDownloads(),this.bundleManager&&await this.bundleManager.cleanExpiredBundles(),this.logger.info("Cleanup complete")}setupAppUpdateEventBridge(){this.appUpdateManager&&(this.appUpdateManager.addListener("appUpdateStateChanged",e=>{this.eventEmitter.emit("appUpdateStateChanged",e)}),this.appUpdateManager.addListener("appUpdateProgress",e=>{this.eventEmitter.emit("appUpdateProgress",e)}))}}class z{constructor(){this.logger=w.getInstance(),this.configManager=f.getInstance()}async downloadWithDelta(e,t,a){var r;const i=Date.now();if(this.configManager.get("enableDeltaUpdates")&&(null===(r=e.delta)||void 0===r?void 0:r.available)&&e.delta.patchUrl&&t)try{this.logger.info("Attempting delta update",{patchSize:e.delta.patchSize,fullSize:e.size}),null==a||a(10);const r=await this.downloadPatch(e.delta.patchUrl);if(e.delta.patchChecksum&&!await this.verifyChecksum(r,e.delta.patchChecksum))throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Delta patch checksum mismatch");null==a||a(50);const n=await this.applyPatch(t,r,e.delta.targetChecksum||e.checksum);null==a||a(90);const o=await this.calculateChecksum(n);if(o!==(e.delta.targetChecksum||e.checksum))throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Delta patch result checksum mismatch");null==a||a(100);const s=Date.now()-i;return this.logger.info("Delta update successful",{downloadSize:r.byteLength,resultSize:n.byteLength,savings:`${Math.round(100*(1-r.byteLength/(e.size||n.byteLength)))}%`,duration:s}),{usedDelta:!0,bundleData:n,checksum:o,downloadSize:r.byteLength,duration:s}}catch(e){this.logger.warn("Delta update failed, falling back to full download",{error:e})}if(null==a||a(10),!e.bundleUrl)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,"No bundle URL provided");const n=await this.downloadFull(e.bundleUrl,a),o=Date.now()-i,s=await this.calculateChecksum(n);if(e.checksum&&s!==e.checksum)throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Full bundle checksum mismatch");return{usedDelta:!1,bundleData:n,checksum:s,downloadSize:n.byteLength,duration:o}}async downloadPatch(e){A.validateDownloadUrl(e);const t=await fetch(e);if(!t.ok)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Failed to download delta patch: ${t.status}`);const a=this.configManager.get("maxBundleSize");if(Number(t.headers.get("content-length")||0)>a)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");const r=await t.arrayBuffer();if(r.byteLength>a)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");return r}async downloadFull(e,t){A.validateDownloadUrl(e);const a=await fetch(e);if(!a.ok)throw new v(exports.ErrorCode.DOWNLOAD_FAILED,`Failed to download bundle: ${a.status}`);const r=a.headers.get("content-length"),i=r?parseInt(r,10):0,n=this.configManager.get("maxBundleSize");if(i>n)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(i&&a.body){const e=a.body.getReader(),r=[];let o=0;for(;;){const{done:a,value:s}=await e.read();if(a)break;if(r.push(s),o+=s.length,o>n)throw await e.cancel(),new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(t){const e=Math.round(o/i*90)+10;t(Math.min(e,99))}}null==t||t(100);const s=new Uint8Array(o);let l=0;for(const e of r)s.set(e,l),l+=e.length;return s.buffer}const o=await a.arrayBuffer();if(o.byteLength>n)throw new v(exports.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");return null==t||t(100),o}async applyPatch(e,t,a){const r=(new TextDecoder).decode(t),i=JSON.parse(r);if("NUDELTA/1"!==i.format||i.targetChecksum!==a)throw new Error("Unsupported or inconsistent delta patch");const n=await this.calculateChecksum(e);if(i.baseChecksum!==n)throw new Error("NUDELTA base checksum mismatch");return this.applyNuDelta(e,i)}applyNuDelta(e,t){const a=this.configManager.get("maxBundleSize");if(!Number.isSafeInteger(t.targetSize)||t.targetSize<=0||t.targetSize>a)throw new Error("NUDELTA target size is invalid");if(!Array.isArray(t.operations)||0===t.operations.length||t.operations.length>1e5)throw new Error("NUDELTA operation count is invalid");const r=new Uint8Array(e),i=[];let n=0;for(const e of t.operations){let a;if("copy"===e.op){if(!Number.isSafeInteger(e.offset)||!Number.isSafeInteger(e.length)||e.offset<0||e.length<=0||e.offset+e.length>r.length)throw new Error("NUDELTA copy operation is out of bounds");a=r.slice(e.offset,e.offset+e.length)}else{if("literal"!==e.op||"string"!=typeof e.data)throw new Error("NUDELTA operation is invalid");{if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e.data))throw new Error("NUDELTA literal is not valid base64");const t=atob(e.data);a=Uint8Array.from(t,e=>e.charCodeAt(0))}}if(n+=a.length,n>t.targetSize)throw new Error("NUDELTA output exceeds declared size");i.push(a)}if(n!==t.targetSize)throw new Error("NUDELTA output size mismatch");const o=new Uint8Array(n);let s=0;for(const e of i)o.set(e,s),s+=e.length;return o.buffer}async calculateChecksum(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async verifyChecksum(e,t){return(await this.calculateChecksum(e)).toLowerCase()===t.toLowerCase()}isDeltaEnabled(){return this.configManager.get("enableDeltaUpdates")}}class G{constructor(){this.initialized=!1,this.windowEventListeners=new Map,this.pluginManager=P.getInstance()}async initialize(e){await this.pluginManager.initialize(e),this.initialized=!0,this.setupWindowEventBridge()}async isInitialized(){return this.initialized&&this.pluginManager.isInitialized()}async reset(){await this.pluginManager.reset(),this.initialized=!1}async cleanup(){await this.pluginManager.cleanup()}async configure(e){let t;if("config"in e&&"object"==typeof e.config)t=e.config;else{const a=e.liveUpdate,r=e.appUpdate,i=e.appReview;t={appId:null==a?void 0:a.appId,baseUrl:null==a?void 0:a.serverUrl,serverUrl:null==a?void 0:a.serverUrl,apiKey:null==a?void 0:a.apiKey,channel:null==a?void 0:a.channel,autoCheck:null==a?void 0:a.autoUpdate,autoUpdate:null==a?void 0:a.autoUpdate,updateStrategy:null==a?void 0:a.updateStrategy,publicKey:null==a?void 0:a.publicKey,requireSignature:null==a?void 0:a.requireSignature,allowUnsignedDevelopmentUpdates:null==a?void 0:a.allowUnsignedDevelopmentUpdates,maxBundleSize:null==a?void 0:a.maxBundleSize,maxUncompressedBundleSize:null==a?void 0:a.maxUncompressedBundleSize,allowedHosts:null==a?void 0:a.allowedHosts,enableDeltaUpdates:null==a?void 0:a.enableDeltaUpdates,checksumAlgorithm:null==a?void 0:a.checksumAlgorithm,checkInterval:null==a?void 0:a.checkInterval,security:e.security,appStoreId:null==r?void 0:r.appStoreId,packageName:null==r?void 0:r.packageName,webReviewUrl:null==i?void 0:i.webReviewUrl}}if(this.initialized)throw new m(exports.ErrorCode.INVALID_CONFIG,"Configuration is locked after initialization. Call reset() before configuring again.");await this.initialize(t)}async getSecurityInfo(){return{enforceHttps:!0,certificatePinning:{enabled:!1,pins:[]},validateInputs:!0,secureStorage:!0}}async sync(e){try{const t=await this.checkForUpdate();if(!t.available||!t.latestVersion||!t.url)return{status:exports.SyncStatus.UP_TO_DATE,version:t.currentVersion};if("immediate"===(null==e?void 0:e.updateMode)||void 0===(null==e?void 0:e.updateMode)){const e=await this.downloadUpdate({url:t.url,version:t.latestVersion,checksum:t.checksum,signature:t.signature,signatureAlgorithm:t.signatureAlgorithm,delta:t.delta});return await this.applyUpdate(e.bundleId),{status:exports.SyncStatus.UPDATE_INSTALLED,version:t.latestVersion,description:t.notes,mandatory:t.mandatory}}return{status:exports.SyncStatus.UPDATE_AVAILABLE,version:t.latestVersion,description:t.notes,mandatory:t.mandatory}}catch(e){return{status:exports.SyncStatus.ERROR,error:{code:exports.UpdateErrorCode.UNKNOWN_ERROR,message:e instanceof Error?e.message:"Sync failed"}}}}async download(e){const t=this.pluginManager.getDownloadManager(),a=this.pluginManager.getBundleManager();let r;const i=await a.getActiveBundle();if(e.delta&&(null==i?void 0:i.version)===e.delta.fromVersion){const a=await t.loadBlob(i.bundleId),n=await(new z).downloadWithDelta({updateAvailable:!0,version:e.version,bundleUrl:e.url,checksum:e.checksum,size:void 0,delta:{available:!0,patchUrl:e.delta.patchUrl,patchSize:e.delta.patchSize,patchChecksum:e.delta.patchChecksum,targetChecksum:e.delta.targetChecksum}},a?await a.arrayBuffer():null);r=new Blob([n.bundleData],{type:"application/zip"})}else r=await t.downloadWithRetry(e.url,e.version);const n=await r.arrayBuffer();await this.validateBundleData(n,e.checksum,e.signature);const o=new Blob([n],{type:r.type}),s=await t.saveBlob(e.version,o),l={bundleId:e.version,version:e.version,path:s,downloadTime:Date.now(),size:o.size,status:exports.BundleStatus.READY,checksum:e.checksum,signature:e.signature,signatureAlgorithm:e.signatureAlgorithm,verified:!0};return await a.saveBundleInfo(l),l}async set(e){const t=this.pluginManager.getBundleManager();if(!e.verified)throw new m(exports.ErrorCode.SIGNATURE_INVALID,`Refusing to activate unverified bundle ${e.bundleId}`);await t.setActiveBundle(e.bundleId)}async reload(){"undefined"!=typeof window&&window.location.reload()}async current(){const e=this.pluginManager.getBundleManager(),t=await e.getActiveBundle();if(!t)throw new m(exports.ErrorCode.FILE_NOT_FOUND,"No active bundle found");return t}async list(){return this.pluginManager.getBundleManager().getAllBundles()}async delete(e){const t=this.pluginManager.getBundleManager();if(e.bundleId)await t.deleteBundle(e.bundleId);else if(void 0!==e.keepVersions){const a=(await t.getAllBundles()).sort((e,t)=>t.downloadTime-e.downloadTime);for(let r=e.keepVersions;r<a.length;r++)await t.deleteBundle(a[r].bundleId)}}async notifyAppReady(){const e=this.pluginManager.getBundleManager(),t=await e.getActiveBundle();t&&(t.status=exports.BundleStatus.ACTIVE,await e.saveBundleInfo(t))}async getLatest(){const e=await this.checkForUpdate();return e.available?{available:!0,version:e.latestVersion,url:e.url,mandatory:e.mandatory,notes:e.notes,size:e.size,checksum:e.checksum,signature:e.signature,signatureAlgorithm:e.signatureAlgorithm,delta:e.delta}:e.held?{available:!1,held:!0,version:e.latestVersion,heldMessage:e.heldMessage}:{available:!1}}async setChannel(e){const t="string"==typeof e?e:e.channel,a=this.pluginManager.getConfigManager().get("preferences");a&&await a.set({key:"update_channel",value:t})}async setUpdateUrl(e){this.pluginManager.getLogger().warn("setUpdateUrl() is deprecated and ignored. Update URL is locked after initialize(). Call reset(), then initialize() with an updated serverUrl to switch servers.")}async validateUpdate(e){const t=this.pluginManager.getSecurityValidator(),a=this.pluginManager.getDownloadManager();try{const r=e.bundlePath.match(/bundles\/([^/]+)\/bundle\.zip$/),i=r?r[1]:e.bundlePath,n=await a.loadBlob(i);if(!n)return{isValid:!1,error:`Bundle not found at ${e.bundlePath}`};const o=await n.arrayBuffer(),s=await t.verifyChecksum(o,e.checksum);let l=!0;e.signature&&(l=await t.verifySignature(o,e.signature));const d=!e.maxSize||o.byteLength<=e.maxSize;return{isValid:s&&l&&d,details:{checksumValid:s,signatureValid:l,sizeValid:d,versionValid:!0}}}catch(e){return{isValid:!1,error:e instanceof Error?e.message:"Validation failed"}}}async getAppIdentity(){return{platform:"web"}}async resolveAppIdentity(){if(this.appIdentity)return this.appIdentity;try{this.appIdentity=await this.getAppIdentity()}catch(e){this.appIdentity={platform:"web"}}return this.appIdentity}async checkForUpdate(){var e,t,a;const r=this.pluginManager.getBundleManager(),i=this.pluginManager.getConfigManager();try{const n=await r.getActiveBundle(),o=(null==n?void 0:n.version)||"1.0.0",s=i.get("baseUrl");if(!s)return{available:!1,currentVersion:o};const l=i.get("apiKey");if(!l)throw new m(exports.ErrorCode.INVALID_CONFIG,"apiKey is required when using Laravel backend");const d=i.get("channel")||"production",c=this.getDeviceInfo(o),u=await U(s,{apiKey:l,channel:d,currentVersion:o,deviceId:c.deviceId,platform:c.platform,appVersion:c.appVersion,identity:await this.resolveAppIdentity()});return u.available?{available:!0,currentVersion:o,latestVersion:u.version,url:u.downloadUrl,mandatory:u.mandatory,notes:null!==(e=u.releaseNotes)&&void 0!==e?e:void 0,size:u.size,checksum:u.checksum,signature:null!==(t=u.signature)&&void 0!==t?t:void 0,signatureAlgorithm:u.signature?"RSA-SHA256":void 0,delta:null!==(a=u.delta)&&void 0!==a?a:void 0}:u.held?{available:!1,currentVersion:o,latestVersion:u.version,held:!0,heldMessage:u.message}:{available:!1,currentVersion:o}}catch(e){throw new m(exports.ErrorCode.NETWORK_ERROR,e instanceof Error?e.message:"Failed to check for updates")}}async downloadUpdate(e){const t=this.pluginManager.getDownloadManager(),a=this.pluginManager.getBundleManager(),r=this.pluginManager.getEventEmitter();let i;if(!((null==e?void 0:e.url)&&(null==e?void 0:e.version)||(i=await this.checkForUpdate(),i.available&&i.url)))throw new m(exports.ErrorCode.UPDATE_NOT_AVAILABLE,"No update available to download");const n=(null==e?void 0:e.url)||(null==i?void 0:i.url)||"",o=(null==e?void 0:e.version)||(null==i?void 0:i.latestVersion)||"",s=(null==e?void 0:e.checksum)||(null==i?void 0:i.checksum)||"",l=(null==e?void 0:e.signature)||(null==i?void 0:i.signature)||"",d=(null==e?void 0:e.signatureAlgorithm)||(null==i?void 0:i.signatureAlgorithm),c=(null==e?void 0:e.delta)||(null==i?void 0:i.delta);if(!n||!o)throw new m(exports.ErrorCode.INVALID_CONFIG,"URL and version are required for download");const u=await t.downloadWithRetry(n,o,t=>{r.emit("downloadProgress",t),(null==e?void 0:e.onProgress)&&e.onProgress(t)}),h=await u.arrayBuffer();await this.validateBundleData(h,s,l||void 0);const p=new Blob([h],{type:u.type}),g={bundleId:o,version:o,path:await t.saveBlob(o,p),downloadTime:Date.now(),size:p.size,status:exports.BundleStatus.READY,checksum:s,signature:l||void 0,signatureAlgorithm:d,metadata:c?{delta:c}:void 0,verified:!0};return await a.saveBundleInfo(g),g}async applyUpdate(e){const t=this.pluginManager.getBundleManager();let a=e;if(!a){const e=(await t.getAllBundles()).filter(e=>e.status===exports.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime);if(0===e.length)throw new m(exports.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");a=e[0].bundleId}const r=await t.getBundle(a);if(!r)throw new m(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${a} not found`);await this.set(r),await this.reload()}async cancelDownload(e){this.pluginManager.getDownloadManager().cancelDownload("string"==typeof e?e:e.bundleId)}async cancelAllDownloads(){this.pluginManager.getDownloadManager().cancelAllDownloads()}async isDownloading(e){return this.pluginManager.getDownloadManager().isDownloading("string"==typeof e?e:e.bundleId)}async getActiveDownloadCount(){return this.pluginManager.getDownloadManager().getActiveDownloadCount()}compareVersions(e,t){return R(e,t)}getDeviceInfo(e){return{deviceId:"web-client",platform:"web",appVersion:e,bundleVersion:e,osVersion:"undefined"!=typeof navigator?navigator.userAgent:"unknown",locale:"undefined"!=typeof navigator?navigator.language:"en-US"}}async validateBundleData(e,t,a){const r=this.pluginManager.getSecurityValidator(),i=this.pluginManager.getConfigManager();if(t&&!await r.verifyChecksum(e,t))throw new m(exports.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");const n=i.get("requireSignature"),o=i.get("publicKey");if(n){if(!o)throw new m(exports.ErrorCode.INVALID_CONFIG,"Signature verification required but publicKey is not configured");if(!a)throw new m(exports.ErrorCode.SIGNATURE_INVALID,"Signature verification required but no signature provided");if(!await r.verifySignature(e,a))throw new m(exports.ErrorCode.SIGNATURE_INVALID,"Bundle signature verification failed")}return!0}async getAppUpdateInfo(){return this.pluginManager.getAppUpdateManager().getAppUpdateInfo()}async performImmediateUpdate(){return this.pluginManager.getAppUpdateManager().performImmediateUpdate()}async startFlexibleUpdate(){return this.pluginManager.getAppUpdateManager().startFlexibleUpdate()}async completeFlexibleUpdate(){return this.pluginManager.getAppUpdateManager().completeFlexibleUpdate()}async openAppStore(e){return this.pluginManager.getAppUpdateManager().openAppStore(e)}async requestReview(){return{shown:!1,displayed:!1,error:"Reviews are not supported on web"}}async canRequestReview(){return{allowed:!1,canRequest:!1,reason:"Reviews are not supported on web"}}async enableBackgroundUpdates(e){this.pluginManager.getBackgroundScheduler().configure(e);const t=this.pluginManager.getConfigManager().get("preferences");t&&await t.set({key:"background_update_config",value:JSON.stringify(e)})}async disableBackgroundUpdates(){this.pluginManager.getBackgroundScheduler().configure({enabled:!1,checkInterval:0,updateTypes:[]});const e=this.pluginManager.getConfigManager().get("preferences");e&&await e.remove({key:"background_update_config"})}async getBackgroundUpdateStatus(){return this.pluginManager.getBackgroundScheduler().getStatus()}async scheduleBackgroundCheck(e){throw new m(exports.ErrorCode.PLATFORM_NOT_SUPPORTED,"Background updates are not supported on web")}async triggerBackgroundCheck(){return this.pluginManager.getBackgroundScheduler().performCheck()}async setNotificationPreferences(e){const t=this.pluginManager.getConfigManager().get("preferences");t&&await t.set({key:"notification_preferences",value:JSON.stringify(e)})}async getNotificationPermissions(){return{granted:!1,canRequest:!1}}async requestNotificationPermissions(){return!1}async addListener(e,t){const a=this.pluginManager.getEventEmitter().addListener(e,t);return{remove:async()=>{a()}}}async removeAllListeners(){this.pluginManager.getEventEmitter().removeAllListeners()}setupWindowEventBridge(){const e=this.pluginManager.getEventEmitter();["appUpdateAvailable","appUpdateProgress","appUpdateReady","appUpdateFailed","appUpdateNotificationClicked","appUpdateInstallClicked"].forEach(t=>{const a=a=>{e.emit(t,a.detail)};window.addEventListener(t,a),this.windowEventListeners.set(t,a)})}}const H=h.registerPlugin("NativeUpdate",{web:()=>new G}),$=new Proxy(H,{get(e,t,a){if("isInitialized"===t)return async()=>{const t=await e.isInitialized();return"boolean"==typeof t?t:!!(t&&"object"==typeof t&&"initialized"in t&&t.initialized)};if("list"===t)return async()=>{const t=await e.list();return Array.isArray(t)?t:t&&"object"==typeof t&&"bundles"in t&&Array.isArray(t.bundles)?t.bundles:[]};if("setChannel"===t)return t=>e.setChannel({channel:t});if("setUpdateUrl"===t)return t=>e.setUpdateUrl({url:t});if("scheduleBackgroundCheck"===t)return t=>e.scheduleBackgroundCheck({interval:t});if("requestNotificationPermissions"===t)return async()=>{const t=await e.requestNotificationPermissions();return"boolean"==typeof t?t:!!(t&&"object"==typeof t&&"granted"in t&&t.granted)};if("checkForUpdate"===t)return async()=>{const[t,a]=await Promise.all([e.getLatest(),e.current()]);return{available:!0===t.available&&"string"==typeof t.version&&_.compareVersions(t.version,a.version)>0,latestVersion:t.version,currentVersion:a.version,url:t.url,mandatory:t.mandatory,notes:t.notes,size:t.size,checksum:t.checksum,signature:t.signature,signatureAlgorithm:t.signatureAlgorithm,delta:t.delta,held:!0===t.held||void 0,heldMessage:t.heldMessage}};if("downloadUpdate"===t)return async(t={})=>{var a,r,i,n,o,s;const l=t.url&&t.version&&t.checksum?void 0:await e.getLatest(),d=null!==(a=t.url)&&void 0!==a?a:null==l?void 0:l.url,c=null!==(r=t.version)&&void 0!==r?r:null==l?void 0:l.version,u=null!==(i=t.checksum)&&void 0!==i?i:null==l?void 0:l.checksum;if(!d||!c||!u)throw new m(exports.ErrorCode.UPDATE_NOT_AVAILABLE,"No downloadable update is available");return e.download({url:d,version:c,checksum:u,signature:null!==(n=t.signature)&&void 0!==n?n:null==l?void 0:l.signature,signatureAlgorithm:null!==(o=t.signatureAlgorithm)&&void 0!==o?o:null==l?void 0:l.signatureAlgorithm,delta:null!==(s=t.delta)&&void 0!==s?s:null==l?void 0:l.delta})};if("applyUpdate"===t)return async t=>{const a=await $.list(),r=t?a.find(e=>e.bundleId===t):a.filter(e=>e.status===exports.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime)[0];if(!r)throw new m(exports.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");await e.set(r),await e.reload()};if("cancelDownload"===t)return t=>e.cancelDownload({bundleId:t});if("isDownloading"===t)return async t=>{const a=await e.isDownloading({bundleId:t});return"boolean"==typeof a?a:!!(a&&"object"==typeof a&&"isDownloading"in a&&a.isDownloading)};if("getActiveDownloadCount"===t)return async()=>{const t=await e.getActiveDownloadCount();return"number"==typeof t?t:t&&"object"==typeof t&&"count"in t&&"number"==typeof t.count?t.count:0};const r=Reflect.get(e,t,a);return"function"==typeof r?r.bind(e):r}});exports.BundleManager=D,exports.CacheManager=class{constructor(){this.filesystem=null,this.memoryCache=new Map,this.CACHE_DIR="cache",this.logger=w.getInstance(),this.configManager=f.getInstance()}async initialize(){if(this.filesystem=this.configManager.get("filesystem"),!this.filesystem)throw new Error("Filesystem not configured");try{await this.filesystem.mkdir({path:this.CACHE_DIR,directory:p.Directory.Data,recursive:!0})}catch(e){this.logger.debug("Cache directory may already exist",e)}await this.cleanExpiredCache()}async set(e,t,a){const r=Date.now()+(a||this.configManager.get("cacheExpiration")),i={data:t,timestamp:Date.now(),expiry:r};this.memoryCache.set(e,i),this.shouldPersist(t)&&await this.persistToFile(e,i),this.logger.debug("Cache entry set",{key:e,expiry:new Date(r)})}async get(e){const t=this.memoryCache.get(e);if(t){if(Date.now()<t.expiry)return t.data;this.memoryCache.delete(e)}const a=await this.loadFromFile(e);if(a){if(Date.now()<a.expiry)return this.memoryCache.set(e,a),a.data;await this.removeFile(e)}return null}async has(e){return null!==await this.get(e)}async remove(e){this.memoryCache.delete(e),await this.removeFile(e),this.logger.debug("Cache entry removed",{key:e})}async clear(){this.memoryCache.clear();try{await this.filesystem.rmdir({path:this.CACHE_DIR,directory:p.Directory.Data,recursive:!0}),await this.filesystem.mkdir({path:this.CACHE_DIR,directory:p.Directory.Data,recursive:!0})}catch(e){this.logger.warn("Failed to clear cache directory",e)}this.logger.info("Cache cleared")}async cleanExpiredCache(){const e=Date.now();let t=0;for(const[a,r]of this.memoryCache)e>=r.expiry&&(this.memoryCache.delete(a),t++);try{const a=await this.filesystem.readdir({path:this.CACHE_DIR,directory:p.Directory.Data});for(const r of a.files){const a=r.name.replace(".json",""),i=await this.loadFromFile(a);(!i||e>=i.expiry)&&(await this.removeFile(a),t++)}}catch(e){this.logger.debug("Failed to clean filesystem cache",e)}t>0&&this.logger.info("Cleaned expired cache entries",{count:t})}async getStats(){let e=0,t=0;try{const a=await this.filesystem.readdir({path:this.CACHE_DIR,directory:p.Directory.Data});e=a.files.length;for(const e of a.files)t+=(await this.filesystem.stat({path:`${this.CACHE_DIR}/${e.name}`,directory:p.Directory.Data})).size||0}catch(e){this.logger.debug("Failed to get cache stats",e)}return{memoryEntries:this.memoryCache.size,fileEntries:e,totalSize:t}}async cacheBundleMetadata(e){const t=`bundle_meta_${e.bundleId}`;await this.set(t,e,864e5)}async getCachedBundleMetadata(e){return this.get(`bundle_meta_${e}`)}shouldPersist(e){return"object"==typeof e||"string"==typeof e&&e.length>1024}async persistToFile(e,t){if(this.filesystem)try{const a=`${this.CACHE_DIR}/${e}.json`,r=JSON.stringify(t);await this.filesystem.writeFile({path:a,data:r,directory:p.Directory.Data,encoding:p.Encoding.UTF8})}catch(t){this.logger.warn("Failed to persist cache to file",{key:e,error:t})}}async loadFromFile(e){if(!this.filesystem)return null;try{const t=`${this.CACHE_DIR}/${e}.json`,a=await this.filesystem.readFile({path:t,directory:p.Directory.Data,encoding:p.Encoding.UTF8});return JSON.parse(a.data)}catch(e){return null}}async removeFile(e){if(this.filesystem)try{const t=`${this.CACHE_DIR}/${e}.json`;await this.filesystem.deleteFile({path:t,directory:p.Directory.Data})}catch(t){this.logger.debug("Failed to remove cache file",{key:e,error:t})}}},exports.ConfigManager=f,exports.ConfigurationError=class extends m{constructor(e,t){super(exports.ErrorCode.INVALID_CONFIG,e,t),this.name="ConfigurationError"}},exports.DownloadError=v,exports.DownloadManager=b,exports.Logger=w,exports.NativeUpdate=$,exports.NativeUpdateError=m,exports.PluginManager=P,exports.SecurityValidator=A,exports.StorageError=E,exports.UpdateErrorClass=I,exports.UpdateManager=class{constructor(){this.filesystem=null,this.updateInProgress=!1,this.currentState=null,this.pluginManager=P.getInstance(),this.securityValidator=A.getInstance()}async initialize(){if(this.filesystem=this.pluginManager.getConfigManager().get("filesystem"),!this.filesystem)throw new I(exports.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured")}async applyUpdate(e,t){var a;if(this.updateInProgress)throw new I(exports.ErrorCode.UPDATE_FAILED,"Another update is already in progress");const r=this.pluginManager.getLogger(),i=this.pluginManager.getBundleManager();try{this.updateInProgress=!0,r.info("Starting bundle update",{bundleId:e});const n=await i.getBundle(e);if(!n)throw new I(exports.ErrorCode.FILE_NOT_FOUND,`Bundle ${e} not found`);if("READY"!==n.status&&"ACTIVE"!==n.status)throw new I(exports.ErrorCode.BUNDLE_NOT_READY,`Bundle ${e} is not ready for installation`);const o=await i.getActiveBundle();this.currentState={currentBundle:o,newBundle:n,backupPath:null,startTime:Date.now()},await this.validateUpdate(o,n,t),o&&"default"!==o.bundleId&&(this.currentState.backupPath=await this.createBackup(o)),await this.performUpdate(n),await this.verifyUpdate(n),await i.setActiveBundle(e);const s=this.pluginManager.getVersionManager(),l=this.pluginManager.getConfigManager();if(await s.rememberAppliedVersion(l.get("channel"),n.version),!1!==(null==t?void 0:t.cleanupOldBundles)){const e=null!==(a=null==t?void 0:t.keepBundleCount)&&void 0!==a?a:3;await i.cleanupOldBundles(e)}r.info("Bundle update completed successfully",{bundleId:e,version:n.version,duration:Date.now()-this.currentState.startTime}),this.currentState=null}catch(e){throw r.error("Bundle update failed",e),this.currentState&&await this.rollback(),e}finally{this.updateInProgress=!1}}async validateUpdate(e,t,a){const r=this.pluginManager.getLogger(),i=this.pluginManager.getVersionManager(),n=this.pluginManager.getConfigManager();if(e&&i.shouldBlockDowngrade(e.version,t.version))throw new y(exports.ErrorCode.VERSION_DOWNGRADE,`Cannot downgrade from ${e.version} to ${t.version}`);const o=n.get("channel"),s=await i.getMaxSeenVersion(o);if(s&&i.shouldBlockDowngrade(s,t.version))throw new y(exports.ErrorCode.VERSION_DOWNGRADE,`Cannot apply ${t.version} - device has previously applied ${s} on channel ${o}`);if(!t.verified){r.warn("Bundle not verified, verifying now",{bundleId:t.bundleId});const e=this.pluginManager.getDownloadManager(),a=await e.loadBlob(t.bundleId);if(!a)throw new I(exports.ErrorCode.FILE_NOT_FOUND,"Bundle data not found");const i=await a.arrayBuffer();if(!await this.securityValidator.verifyChecksum(i,t.checksum))throw new y(exports.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");if(t.signature&&!await this.securityValidator.verifySignature(i,t.signature))throw new y(exports.ErrorCode.SIGNATURE_INVALID,"Bundle signature verification failed");await this.pluginManager.getBundleManager().markBundleAsVerified(t.bundleId)}r.debug("Bundle validation passed",{bundleId:t.bundleId})}async createBackup(e){const t=`backups/${e.bundleId}_${Date.now()}`,a=this.pluginManager.getLogger();try{return await this.filesystem.mkdir({path:t,directory:p.Directory.Data,recursive:!0}),await this.filesystem.copy({from:e.path,to:t,directory:p.Directory.Data}),a.info("Backup created",{bundleId:e.bundleId,backupPath:t}),t}catch(e){throw a.error("Failed to create backup",e),new I(exports.ErrorCode.UPDATE_FAILED,"Failed to create backup",void 0,e)}}async performUpdate(e){const t=this.pluginManager.getLogger();try{const a=`active/${e.bundleId}`;await this.filesystem.mkdir({path:a,directory:p.Directory.Data,recursive:!0}),await this.filesystem.copy({from:e.path,to:a,directory:p.Directory.Data}),e.path=a,t.debug("Bundle files installed",{bundleId:e.bundleId,targetPath:a})}catch(e){throw new I(exports.ErrorCode.UPDATE_FAILED,"Failed to install bundle files",void 0,e)}}async verifyUpdate(e){try{const t=`${e.path}/index.html`;await this.filesystem.stat({path:t,directory:p.Directory.Data})}catch(e){throw new I(exports.ErrorCode.UPDATE_FAILED,"Bundle verification failed after installation",void 0,e)}}async rollback(){var e;if(!this.currentState)throw new I(exports.ErrorCode.ROLLBACK_FAILED,"No update state to rollback");const t=this.pluginManager.getLogger();t.warn("Starting rollback",{from:this.currentState.newBundle.bundleId,to:(null===(e=this.currentState.currentBundle)||void 0===e?void 0:e.bundleId)||"default"});try{const e=this.pluginManager.getBundleManager();if(this.currentState.backupPath&&this.currentState.currentBundle){const t=`active/${this.currentState.currentBundle.bundleId}`;await this.filesystem.copy({from:this.currentState.backupPath,to:t,directory:p.Directory.Data}),this.currentState.currentBundle.path=t,await e.saveBundleInfo(this.currentState.currentBundle)}this.currentState.currentBundle?await e.setActiveBundle(this.currentState.currentBundle.bundleId):await e.clearActiveBundle(),t.info("Rollback completed successfully")}catch(e){throw t.error("Rollback failed",e),new I(exports.ErrorCode.ROLLBACK_FAILED,"Failed to rollback update",void 0,e)}finally{if(this.currentState.backupPath)try{await this.filesystem.rmdir({path:this.currentState.backupPath,directory:p.Directory.Data,recursive:!0})}catch(e){t.warn("Failed to clean up backup",e)}}}getUpdateProgress(){var e,t;return{inProgress:this.updateInProgress,bundleId:null===(e=this.currentState)||void 0===e?void 0:e.newBundle.bundleId,startTime:null===(t=this.currentState)||void 0===t?void 0:t.startTime}}async cancelUpdate(){this.updateInProgress&&this.currentState&&(this.pluginManager.getLogger().warn("Cancelling update",{bundleId:this.currentState.newBundle.bundleId}),await this.rollback(),this.updateInProgress=!1,this.currentState=null)}},exports.ValidationError=y,exports.VersionManager=_,exports.compareVersions=R;
|