native-update-capacitor 5.0.0 → 5.0.1

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/dist/plugin.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! Native Update Plugin v5.0.0 | Native Update License (see LICENSE) */
2
- !function(e,t,a,i){var r,n,o,s,l,d,c,u,h,g,p,f;e.BackgroundUpdateType=void 0,(r=e.BackgroundUpdateType||(e.BackgroundUpdateType={})).APP_UPDATE="app_update",r.LIVE_UPDATE="live_update",r.BOTH="both",e.NotificationPriority=void 0,(n=e.NotificationPriority||(e.NotificationPriority={})).MIN="min",n.LOW="low",n.DEFAULT="default",n.HIGH="high",n.MAX="max",e.UpdateStrategy=void 0,(o=e.UpdateStrategy||(e.UpdateStrategy={})).IMMEDIATE="immediate",o.BACKGROUND="background",o.MANUAL="manual",e.UpdateMode=void 0,(s=e.UpdateMode||(e.UpdateMode={})).IMMEDIATE="immediate",s.ON_NEXT_RESTART="on_next_restart",s.ON_NEXT_RESUME="on_next_resume",e.InstallMode=void 0,(l=e.InstallMode||(e.InstallMode={})).IMMEDIATE="immediate",l.ON_NEXT_RESTART="on_next_restart",l.ON_NEXT_RESUME="on_next_resume",e.ChecksumAlgorithm=void 0,(d=e.ChecksumAlgorithm||(e.ChecksumAlgorithm={})).SHA256="SHA-256",d.SHA512="SHA-512",e.SyncStatus=void 0,(c=e.SyncStatus||(e.SyncStatus={})).UP_TO_DATE="UP_TO_DATE",c.UPDATE_AVAILABLE="UPDATE_AVAILABLE",c.UPDATE_INSTALLED="UPDATE_INSTALLED",c.ERROR="ERROR",e.BundleStatus=void 0,(u=e.BundleStatus||(e.BundleStatus={})).PENDING="PENDING",u.DOWNLOADING="DOWNLOADING",u.READY="READY",u.ACTIVE="ACTIVE",u.FAILED="FAILED",e.InstallStatus=void 0,(h=e.InstallStatus||(e.InstallStatus={})).UNKNOWN="UNKNOWN",h.PENDING="PENDING",h.DOWNLOADING="DOWNLOADING",h.DOWNLOADED="DOWNLOADED",h.INSTALLING="INSTALLING",h.INSTALLED="INSTALLED",h.FAILED="FAILED",h.CANCELED="CANCELED",e.UpdateErrorCode=void 0,(g=e.UpdateErrorCode||(e.UpdateErrorCode={})).NETWORK_ERROR="NETWORK_ERROR",g.SERVER_ERROR="SERVER_ERROR",g.TIMEOUT_ERROR="TIMEOUT_ERROR",g.DOWNLOAD_ERROR="DOWNLOAD_ERROR",g.STORAGE_ERROR="STORAGE_ERROR",g.SIZE_LIMIT_EXCEEDED="SIZE_LIMIT_EXCEEDED",g.VERIFICATION_ERROR="VERIFICATION_ERROR",g.CHECKSUM_ERROR="CHECKSUM_ERROR",g.SIGNATURE_ERROR="SIGNATURE_ERROR",g.INSECURE_URL="INSECURE_URL",g.INVALID_CERTIFICATE="INVALID_CERTIFICATE",g.PATH_TRAVERSAL="PATH_TRAVERSAL",g.INSTALL_ERROR="INSTALL_ERROR",g.ROLLBACK_ERROR="ROLLBACK_ERROR",g.VERSION_MISMATCH="VERSION_MISMATCH",g.PERMISSION_DENIED="PERMISSION_DENIED",g.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",g.UPDATE_IN_PROGRESS="UPDATE_IN_PROGRESS",g.UPDATE_CANCELLED="UPDATE_CANCELLED",g.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",g.REVIEW_NOT_SUPPORTED="REVIEW_NOT_SUPPORTED",g.QUOTA_EXCEEDED="QUOTA_EXCEEDED",g.CONDITIONS_NOT_MET="CONDITIONS_NOT_MET",g.INVALID_CONFIG="INVALID_CONFIG",g.NOT_CONFIGURED="NOT_CONFIGURED",g.UNKNOWN_ERROR="UNKNOWN_ERROR";class w{constructor(){this.config=this.getDefaultConfig()}static getInstance(){return w.instance||(w.instance=new w),w.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)}}e.LogLevel=void 0,(p=e.LogLevel||(e.LogLevel={}))[p.DEBUG=0]="DEBUG",p[p.INFO=1]="INFO",p[p.WARN=2]="WARN",p[p.ERROR=3]="ERROR";class m{constructor(e){this.configManager=w.getInstance(),this.context=e||"NativeUpdate"}static getInstance(){return m.instance||(m.instance=new m),m.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(t,a){this.logWithLevel(e.LogLevel.INFO,t,a)}logWithLevel(t,a,i){if(!this.shouldLog())return;const r=(new Date).toISOString(),n=i?this.sanitize(i):void 0,o={timestamp:r,level:e.LogLevel[t],context:this.context,message:a};switch(void 0!==n&&(o.data=n),t){case e.LogLevel.DEBUG:console.debug(`[${this.context}]`,o);break;case e.LogLevel.INFO:console.info(`[${this.context}]`,o);break;case e.LogLevel.WARN:console.warn(`[${this.context}]`,o);break;case e.LogLevel.ERROR:console.error(`[${this.context}]`,o)}}debug(t,a){this.logWithLevel(e.LogLevel.DEBUG,t,a)}info(t,a){this.logWithLevel(e.LogLevel.INFO,t,a)}warn(t,a){this.logWithLevel(e.LogLevel.WARN,t,a)}error(t,a){const i=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;this.logWithLevel(e.LogLevel.ERROR,t,i)}}e.ErrorCode=void 0,(f=e.ErrorCode||(e.ErrorCode={})).NOT_CONFIGURED="NOT_CONFIGURED",f.INVALID_CONFIG="INVALID_CONFIG",f.MISSING_DEPENDENCY="MISSING_DEPENDENCY",f.NETWORK_ERROR="NETWORK_ERROR",f.SERVER_ERROR="SERVER_ERROR",f.DOWNLOAD_FAILED="DOWNLOAD_FAILED",f.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",f.INVALID_URL="INVALID_URL",f.INSECURE_URL="INSECURE_URL",f.UNAUTHORIZED_HOST="UNAUTHORIZED_HOST",f.BUNDLE_TOO_LARGE="BUNDLE_TOO_LARGE",f.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",f.SIGNATURE_INVALID="SIGNATURE_INVALID",f.VERSION_DOWNGRADE="VERSION_DOWNGRADE",f.INVALID_BUNDLE_FORMAT="INVALID_BUNDLE_FORMAT",f.VALIDATION_ERROR="VALIDATION_ERROR",f.STORAGE_FULL="STORAGE_FULL",f.FILE_NOT_FOUND="FILE_NOT_FOUND",f.PERMISSION_DENIED="PERMISSION_DENIED",f.UPDATE_FAILED="UPDATE_FAILED",f.ROLLBACK_FAILED="ROLLBACK_FAILED",f.BUNDLE_NOT_READY="BUNDLE_NOT_READY",f.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",f.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",f.NATIVE_ERROR="NATIVE_ERROR";class v extends Error{constructor(e,t,a,i){super(t),this.code=e,this.message=t,this.details=a,this.originalError=i,this.name="NativeUpdateError",Object.setPrototypeOf(this,v.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,stack:this.stack}}}class y extends v{constructor(e,t,a,i){super(e,t,a,i),this.name="DownloadError"}}class E extends v{constructor(e,t,a){super(e,t,a),this.name="ValidationError"}}class I extends v{constructor(e,t,a,i){super(e,t,a,i),this.name="StorageError"}}class A extends v{constructor(e,t,a,i){super(e,t,a,i),this.name="UpdateError"}}class D{constructor(){this.configManager=w.getInstance(),this.logger=m.getInstance()}static getInstance(){return D.instance||(D.instance=new D),D.instance}static validateUrl(e){try{return"https:"===new URL(e).protocol}catch(e){return!1}}static validateDownloadUrl(t){if(!this.validateUrl(t))throw new E(e.ErrorCode.INSECURE_URL,`Refusing non-HTTPS URL: ${t}`)}static validateStoreUrl(t){let a;try{a=new URL(t)}catch(a){throw new E(e.ErrorCode.INSECURE_URL,`Invalid URL: ${t}`)}if(!["https:","market:","itms-apps:"].includes(a.protocol))throw new E(e.ErrorCode.INSECURE_URL,`Refusing URL scheme ${a.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(t,a){if(!a)throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Checksum is required but was not provided");const i=await this.calculateChecksum(t),r=i===a.toLowerCase();return r||this.logger.error("Checksum verification failed",{expected:a,actual:i}),r}async validateChecksum(e,t){return this.verifyChecksum(e,t)}async verifySignature(t,a){const i=this.configManager.get("enableSignatureValidation"),r=this.configManager.get("requireSignature"),n=this.configManager.get("publicKey");if(!a){if(i||r||n)throw new E(e.ErrorCode.SIGNATURE_INVALID,"Signature is required but was not provided");return!0}if(!n)throw new E(e.ErrorCode.SIGNATURE_INVALID,"Public key not configured for signature validation");try{const e=await crypto.subtle.importKey("spki",this.pemToArrayBuffer(n),{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]),i=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},e,this.base64ToArrayBuffer(a),t);return i||this.logger.error("Signature verification failed"),i}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(t){if(!t||"string"!=typeof t)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID must be a non-empty string");if(!/^[a-zA-Z0-9\-_.]+$/.test(t))throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID contains invalid characters");if(t.length>100)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is too long (max 100 characters)")}validateVersion(t){if(!t||"string"!=typeof t)throw new E(e.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(t))throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Version must follow semantic versioning format (e.g., 1.2.3)")}isVersionDowngrade(e,t){const a=this.parseVersion(e),i=this.parseVersion(t);return i.major<a.major||!(i.major>a.major)&&(i.minor<a.minor||!(i.minor>a.minor)&&i.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(t){if(!t||"string"!=typeof t)throw new E(e.ErrorCode.INVALID_URL,"URL must be a non-empty string");let a;try{a=new URL(t)}catch(t){throw new E(e.ErrorCode.INVALID_URL,"Invalid URL format")}if("https:"!==a.protocol)throw new E(e.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed");const i=this.configManager.get("allowedHosts");if(i.length>0&&!i.includes(a.hostname))throw new E(e.ErrorCode.UNAUTHORIZED_HOST,`Host ${a.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(a.hostname)))throw new E(e.ErrorCode.UNAUTHORIZED_HOST,"Private/local addresses are not allowed")}validateFileSize(t){if("number"!=typeof t||t<0)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"File size must be a non-negative number");const a=this.configManager.get("maxBundleSize");if(t>a)throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,`File size ${t} exceeds maximum allowed size of ${a} 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 i=a.filter(t=>t.hostname===e);if(0===i.length)return!0;const r=await this.calculateCertificateHash(t),n=i.some(e=>e.sha256===r);return n||this.logger.error("Certificate pinning validation failed",{hostname:e,expectedPins:i.map(e=>e.sha256),actualHash:r}),n}async calculateCertificateHash(e){const t=(new TextEncoder).encode(e),a=await crypto.subtle.digest("SHA-256",t),i=Array.from(new Uint8Array(a));return"sha256/"+btoa(String.fromCharCode(...i))}validateMetadata(t){if(t&&"object"!=typeof t)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata must be an object");if(JSON.stringify(t||{}).length>10240)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata is too large (max 10KB)")}}class b{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=m.getInstance(),this.configManager=w.getInstance()}setDownloadManager(e){this.downloadManager=e}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new I(e.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(t){throw new I(e.ErrorCode.STORAGE_FULL,"Failed to save bundles to storage",void 0,t)}}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(t){if(!t.bundleId||"string"!=typeof t.bundleId)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle ID");if(!t.version||"string"!=typeof t.version)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle version");if(!t.path||"string"!=typeof t.path)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle path");if("number"!=typeof t.size||t.size<0)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle size")}async getAllBundles(){return await this.loadCache(),Array.from(this.cache.values())}async getBundle(t){if(!t)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");return await this.loadCache(),this.cache.get(t)||null}async deleteBundle(t){if(!t)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(await this.loadCache(),this.cache.get(t)){if(this.cache.delete(t),await this.saveCache(),await this.getActiveBundleId()===t&&await this.clearActiveBundle(),this.downloadManager)try{await this.downloadManager.deleteBlob(t)}catch(e){this.logger.warn("Failed to delete bundle file",{bundleId:t,error:e})}this.logger.info("Bundle deleted",{bundleId:t})}else this.logger.warn("Attempted to delete non-existent bundle",{bundleId:t})}async getActiveBundle(){const e=await this.getActiveBundleId();return e?this.getBundle(e):null}async setActiveBundle(t){if(!t)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");const a=await this.getBundle(t);if(!a)throw new I(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${t} not found`);const i=await this.getActiveBundle();i&&i.bundleId!==t&&(i.status="READY",await this.saveBundleInfo(i)),a.status="ACTIVE",await this.saveBundleInfo(a),await this.preferences.set({key:this.ACTIVE_BUNDLE_KEY,value:t}),this.logger.info("Active bundle set",{bundleId:t,version:a.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(t){if(t<1)throw new I(e.ErrorCode.INVALID_CONFIG,"Keep count must be at least 1");const a=await this.getAllBundles(),i=await this.getActiveBundleId(),r=a.sort((e,t)=>t.downloadTime-e.downloadTime),n=new Set;i&&n.add(i);let o=n.size;for(const e of r){if(o>=t)break;n.has(e.bundleId)||(n.add(e.bundleId),o++)}let s=0;for(const e of a)n.has(e.bundleId)||(await this.deleteBundle(e.bundleId),s++);s>0&&this.logger.info("Cleaned up old bundles",{deleted:s,kept:o})}async getBundlesOlderThan(t){if(t<0)throw new I(e.ErrorCode.INVALID_CONFIG,"Timestamp must be non-negative");return(await this.getAllBundles()).filter(e=>e.downloadTime<t)}async markBundleAsVerified(t){const a=await this.getBundle(t);if(!a)throw new I(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${t} not found`);a.verified=!0,await this.saveBundleInfo(a),this.logger.info("Bundle marked as verified",{bundleId:t})}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 U{constructor(){this.activeDownloads=new Map,this.lastResponseMeta=new Map,this.filesystem=null,this.logger=m.getInstance(),this.configManager=w.getInstance()}async initialize(){if(this.filesystem=this.configManager.get("filesystem"),!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured. Please configure the plugin first.")}validateUrl(t){try{const a=new URL(t);if("https:"!==a.protocol)throw new E(e.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed for security reasons");const i=this.configManager.get("allowedHosts");if(i.length>0&&!i.includes(a.hostname))throw new E(e.ErrorCode.UNAUTHORIZED_HOST,`Host ${a.hostname} is not in the allowed hosts list`)}catch(t){if(t instanceof E)throw t;throw new E(e.ErrorCode.INVALID_URL,"Invalid URL format")}}async download(t,a,i){var r;const n="function"==typeof i?{onProgress:i}:null!=i?i:{},o=n.onProgress,s=null!==(r=n.resumePosition)&&void 0!==r?r:0;if(this.validateUrl(t),!a)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(this.activeDownloads.has(a))throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Download already in progress for bundle ${a}`);const l=new AbortController,d={controller:l,startTime:Date.now(),resumePosition:s>0?s:void 0};this.activeDownloads.set(a,d);try{const i=this.configManager.get("downloadTimeout"),r=setTimeout(()=>l.abort(),i),n={"Cache-Control":"no-cache",Accept:"application/octet-stream, application/zip"};s>0&&(n.Range=`bytes=${s}-`);const c=await fetch(t,{signal:l.signal,headers:n});if(clearTimeout(r),!c.ok)throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Download failed: ${c.status} ${c.statusText}`,{status:c.status,statusText:c.statusText});const u=s>0&&206===c.status;d.serverReturnedPartial=u,this.lastResponseMeta.set(a,{partial:u});const h=c.headers.get("content-type");if(h&&!this.isValidContentType(h))throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,`Invalid content type: ${h}`);const g=c.headers.get("content-length"),p=g?parseInt(g,10):0;if(p>this.configManager.get("maxBundleSize"))throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,`Bundle size ${p} exceeds maximum allowed size`);if(!p||!c.body){const e=await c.blob();return this.validateBlobSize(e),e}const f=c.body.getReader(),w=[];let m=0;for(;;){const{done:t,value:i}=await f.read();if(t)break;if(w.push(i),m+=i.length,m>this.configManager.get("maxBundleSize"))throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,"Download size exceeds maximum allowed size");if(o){const e=d.resumePosition||0,t=e+m,i=e+p;o({percent:Math.round(t/i*100),bytesDownloaded:t,totalBytes:i,bundleId:a})}}const v=new Blob(w);return this.validateBlobSize(v),this.logger.info("Download completed",{bundleId:a,size:v.size,duration:Date.now()-d.startTime}),v}catch(t){if(t instanceof Error&&"AbortError"===t.name){const a=Date.now()-d.startTime>=this.configManager.get("downloadTimeout");throw new y(a?e.ErrorCode.DOWNLOAD_TIMEOUT:e.ErrorCode.DOWNLOAD_FAILED,a?"Download timed out":"Download cancelled",void 0,t)}throw t}finally{this.activeDownloads.delete(a)}}async resumeDownload(e,t,a,i){const r=await this.download(e,t,{onProgress:i,resumePosition:a.size}),n=this.lastResponseMeta.get(t);return this.lastResponseMeta.delete(t),(null==n?void 0:n.partial)?new Blob([a,r]):(this.logger.info("Resume: server returned full response; discarding partial data",{bundleId:t,partialSize:a.size,responseSize:r.size}),r)}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(t){if(0===t.size)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Downloaded file is empty");if(t.size>this.configManager.get("maxBundleSize"))throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,`File size ${t.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(t,a,i){const r=this.configManager.get("retryAttempts"),n=this.configManager.get("retryDelay");let o=null;for(let e=0;e<r;e++)try{if(e>0){const t=n*Math.pow(2,e-1),i=.5*(Math.random()-.5)*t,r=Math.min(Math.max(t+i,100),3e4);await new Promise(e=>setTimeout(e,r)),this.logger.debug("Retrying download",{bundleId:a,attempt:e,delay:r})}return await this.download(t,a,i)}catch(t){if(o=t,t instanceof E||t instanceof Error&&"AbortError"===t.name)throw t;this.logger.warn(`Download attempt ${e+1} failed`,{bundleId:a,error:t})}throw new y(e.ErrorCode.DOWNLOAD_FAILED,"Download failed after all retries",{attempts:r},o||void 0)}async blobToArrayBuffer(e){return e.arrayBuffer()}async saveBlob(t,i){if(!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");const r=await this.blobToArrayBuffer(i),n=new Uint8Array(r);let o="";for(let e=0;e<n.length;e+=32768)o+=String.fromCharCode.apply(null,Array.from(n.subarray(e,e+32768)));const s=btoa(o),l=`bundles/${t}/bundle.zip`;return await this.filesystem.writeFile({path:l,data:s,directory:a.Directory.Data,recursive:!0}),this.logger.debug("Bundle saved to filesystem",{bundleId:t,path:l,size:i.size}),l}async loadBlob(t){if(!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const e=`bundles/${t}/bundle.zip`,i=await this.filesystem.readFile({path:e,directory:a.Directory.Data}),r=atob(i.data),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return new Blob([n],{type:"application/zip"})}catch(e){return this.logger.debug("Failed to load bundle from filesystem",{bundleId:t,error:e}),null}}async deleteBlob(t){if(!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const e=`bundles/${t}`;await this.filesystem.rmdir({path:e,directory:a.Directory.Data,recursive:!0}),this.logger.debug("Bundle deleted from filesystem",{bundleId:t})}catch(e){this.logger.warn("Failed to delete bundle from filesystem",{bundleId:t,error:e})}}}async function N(e,t){var a,i,r,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!==(i=u.signatureAlgorithm)&&void 0!==i?i:void 0,delta:null!==(r=u.delta)&&void 0!==r?r: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 C(e){const t=e.trim().replace(/^v/i,"").split("+")[0],a=t.indexOf("-"),i=-1===a?t:t.slice(0,a),r=-1===a?"":t.slice(a+1);return{core:i.split(".").map(e=>{const t=Number.parseInt(e,10);return Number.isFinite(t)?t:0}),pre:""===r?[]:r.split(".")}}const S=/^\d+$/,L=/^(.*?)(\d+)$/;function R(e,t){const a=S.test(e),i=S.test(t);if(a&&i)return Math.sign(Number(e)-Number(t));if(a)return-1;if(i)return 1;const r=L.exec(e),n=L.exec(t);return r&&n&&r[1]===n[1]?Math.sign(Number(r[2])-Number(n[2])):e===t?0:e<t?-1:1}function _(e,t){var a,i;const r=C(e),n=C(t),o=Math.max(r.core.length,n.core.length,3);for(let e=0;e<o;e++){const t=(null!==(a=r.core[e])&&void 0!==a?a:0)-(null!==(i=n.core[e])&&void 0!==i?i:0);if(0!==t)return Math.sign(t)}if(0===r.pre.length&&0===n.pre.length)return 0;if(0===r.pre.length)return 1;if(0===n.pre.length)return-1;const s=Math.max(r.pre.length,n.pre.length);for(let e=0;e<s;e++){const t=r.pre[e],a=n.pre[e];if(void 0===t)return-1;if(void 0===a)return 1;const i=R(t,a);if(0!==i)return i}return 0}class M{constructor(){this.VERSION_CHECK_CACHE_KEY="capacitor_native_update_version_cache",this.CACHE_DURATION=3e5,this.preferences=null,this.memoryCache=new Map,this.logger=m.getInstance(),this.configManager=w.getInstance(),this.securityValidator=D.getInstance()}static compareVersions(e,t){return _(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&&M.compareVersions(e,a)<0)&&M.compareVersions(e,t)<0}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new E(e.ErrorCode.MISSING_DEPENDENCY,"Preferences not configured. Please configure the plugin first.")}async checkForUpdates(t,a,i,r){var n;if(this.securityValidator.validateUrl(t),this.securityValidator.validateVersion(i),!a||!r)throw new E(e.ErrorCode.INVALID_CONFIG,"Channel and appId are required");const o=`${a}-${r}`,s=await this.getCachedVersionInfo(o);if(s&&s.channel===a&&Date.now()-s.timestamp<this.CACHE_DURATION)return this.logger.debug("Returning cached version info",{channel:a,version:s.data.version}),s.data;const l=this.configManager.get("apiKey");if(!l)return this.logger.warn("VersionManager.checkForUpdates: no apiKey configured — the Native Update backend requires X-API-Key"),null;try{const r=await N(t,{apiKey:l,channel:a,currentVersion:i,deviceId:"web-client",platform:"web",appVersion:i,signal:AbortSignal.timeout(this.configManager.get("downloadTimeout"))}),s={available:r.available,version:r.version,url:r.downloadUrl,mandatory:r.mandatory,notes:null!==(n=r.releaseNotes)&&void 0!==n?n:void 0,size:r.size,checksum:r.checksum};if(!s.available)return s;if(!s.version)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"No version in server response");return this.securityValidator.validateVersion(s.version),s.url&&this.securityValidator.validateUrl(s.url),r.minNativeVersion&&this.securityValidator.validateVersion(r.minNativeVersion),await this.cacheVersionInfo(o,a,s),this.logger.info("Version check completed",{channel:a,currentVersion:i,latestVersion:s.version,updateAvailable:this.isNewerVersion(s.version,i)}),s}catch(e){return this.logger.error("Failed to check for updates",e),null}}isNewerVersion(e,t){try{const a=this.parseVersion(e),i=this.parseVersion(t);return a.major!==i.major?a.major>i.major:a.minor!==i.minor?a.minor>i.minor:a.patch!==i.patch?a.patch>i.patch:!(a.prerelease&&!i.prerelease||(a.prerelease||!i.prerelease)&&(!a.prerelease||!i.prerelease||!(a.prerelease>i.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(t){const a=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/);if(!a)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid version format");return{major:parseInt(a[1],10),minor:parseInt(a[2],10),patch:parseInt(a[3],10),prerelease:a[4],build:a[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 i=a[e];return!i||(this.securityValidator.validateVersion(t),this.securityValidator.validateVersion(i),!this.isNewerVersion(i,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 i={channel:t,data:a,timestamp:Date.now()};this.memoryCache.set(e,i);try{const{value:t}=await this.preferences.get({key:this.VERSION_CHECK_CACHE_KEY}),a=t?JSON.parse(t):{},r=Date.now();for(const e in a)r-a[e].timestamp>2*this.CACHE_DURATION&&delete a[e];a[e]=i,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&&M.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 O{constructor(e){this.cachedAppInfo=null,this.CACHE_DURATION=6e4,this.config=e,this.logger=new m("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 i=await a.json();return{availableVersion:i.version,updatePriority:i.priority,releaseNotes:i.releaseNotes,updateSize:i.size,updateURL:i.downloadUrl}}catch(e){return this.logger.error("Failed to check server version",e),{}}}compareVersions(e,t){return _(e,t)}isUpdateRequired(e,t,a){return this.compareVersions(e,t)<0||!!(a&&this.compareVersions(e,a)<0)}determineUpdatePriority(e,t){const[a,i]=e.split(".").map(Number);return a>0?5:i>0&&t&&t>30?4:i>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 T;!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"}(T||(T={}));class B{constructor(e){this.flexibleUpdateInterval=null,this.logger=new m("AppUpdateInstaller"),this.currentState={installStatus:T.UNKNOWN,packageName:"",availableVersion:""}}async startImmediateUpdate(){if(this.logger.log("Starting immediate update installation"),this.updateState(T.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(T.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!==T.DOWNLOADED)throw new Error("Update not ready for installation");this.updateState(T.INSTALLING),this.isAndroid()?this.logger.log("Completing Android update installation"):setTimeout(()=>{this.updateState(T.INSTALLED)},1e3)}async cancelUpdate(){this.logger.log("Cancelling update"),this.flexibleUpdateInterval&&(clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=null),this.currentState.installStatus===T.DOWNLOADING&&this.updateState(T.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(T.DOWNLOADED));const i={bytesDownloaded:e,totalBytesToDownload:t,percentComplete:Math.round(e/t*100),downloadSpeed:a,estimatedTime:Math.ceil((t-e)/a)};this.progressCallback&&this.progressCallback(i)},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 V{constructor(e){this.config=e,this.logger=new m("PlatformAppUpdate"),this.platform=t.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{D.validateDownloadUrl(this.config.webUpdateUrl);const e=await fetch(this.config.webUpdateUrl),i=await e.json();i.version&&i.version!==t.currentVersion&&(a.updateAvailable=!0,a.availableVersion=i.version,a.releaseNotes=i.releaseNotes,i.downloadUrl&&(D.validateStoreUrl(i.downloadUrl),a.updateURL=i.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(D.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 k{constructor(e){this.listeners=new Map,this.config=e,this.logger=new m("AppUpdateManager"),this.checker=new O(e),this.installer=new B(e),this.platformUpdate=new V(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 F{constructor(){this.config=null,this.status={enabled:!1,isRunning:!1,checkCount:0,failureCount:0},this.deps={},this.logger=m.getInstance(),this.configManager=w.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 t;if(!(null===(t=this.config)||void 0===t?void 0:t.enabled))return{success:!1,updatesFound:!1,notificationSent:!1,error:{code:e.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(t){return this.status.failureCount++,this.status.isRunning=!1,this.status.lastError={code:e.UpdateErrorCode.UNKNOWN_ERROR,message:t instanceof Error?t.message:"Unknown error"},{success:!1,updatesFound:!1,notificationSent:!1,error:this.status.lastError}}}async checkForUpdates(){var t,a,i,r,n,o;const s=[];let l,d;((null===(t=this.config)||void 0===t?void 0:t.updateTypes.includes(e.BackgroundUpdateType.APP_UPDATE))||(null===(a=this.config)||void 0===a?void 0:a.updateTypes.includes(e.BackgroundUpdateType.BOTH)))&&s.push(this.checkAppUpdate()),((null===(i=this.config)||void 0===i?void 0:i.updateTypes.includes(e.BackgroundUpdateType.LIVE_UPDATE))||(null===(r=this.config)||void 0===r?void 0:r.updateTypes.includes(e.BackgroundUpdateType.BOTH)))&&s.push(this.checkLiveUpdate());const c=await Promise.allSettled(s);"fulfilled"===(null===(n=c[0])||void 0===n?void 0:n.status)&&(l=c[0].value),"fulfilled"===(null===(o=c[1])||void 0===o?void 0:o.status)&&(d=c[1].value);const u=(null==l?void 0:l.updateAvailable)||(null==d?void 0:d.available)||!1;let h=!1;return u&&(h=await this.sendNotification(l,d)),{success:!0,updatesFound:u,appUpdate:l,liveUpdate:d,notificationSent:h}}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(),i=e.version||e.latestVersion,r=i&&this.compareVersions(t,i)<0;return{updateAvailable:r,currentVersion:t,availableVersion:r?i: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",i=this.configManager.get("appId");if(e&&i){const r=await this.deps.versionManager.checkForUpdates(e,a,t,i);if(r)return r}}catch(e){this.logger.error("Failed to check live update via VersionManager",e)}const a=this.configManager.get("baseUrl")||this.configManager.get("serverUrl"),i=this.configManager.get("apiKey");if(a&&i)try{const r=this.configManager.get("channel")||"production",n=await N(a,{apiKey:i,channel:r,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 i=this.config.notificationPreferences;let r=i.title||"Update Available",n=i.description||"";if((null==e?void 0:e.updateAvailable)?(r="App Update Available",n=`Version ${e.availableVersion} is ready to install.`):(null==t?void 0:t.available)&&(r="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(r,{body:n}),!0}catch(e){this.logger.error("Failed to send notification",e)}return this.logger.info("Background update notification",{title:r,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 _(e,t)}}const P=new m("NativeUpdate.EventEmitter");class z{constructor(){this.listeners=new Map}static getInstance(){return z.instance||(z.instance=new z),z.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){P.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 x{constructor(){this.bundleManager=null,this.downloadManager=null,this.versionManager=null,this.appUpdateManager=null,this.backgroundScheduler=null,this.initialized=!1,this.configManager=w.getInstance(),this.logger=m.getInstance(),this.securityValidator=D.getInstance(),this.eventEmitter=z.getInstance()}static getInstance(){return x.instance||(x.instance=new x),x.instance}async initialize(e){var t,r;if(this.initialized)this.logger.warn("Plugin already initialized");else try{e.filesystem||(e.filesystem=a.Filesystem),e.preferences||(e.preferences=i.Preferences),this.configManager.configure(e),this.bundleManager=new b,await this.bundleManager.initialize(),this.downloadManager=new U,await this.downloadManager.initialize(),this.bundleManager.setDownloadManager(this.downloadManager),this.versionManager=new M,await this.versionManager.initialize(),this.appUpdateManager=new k({serverUrl:e.serverUrl||e.baseUrl||"",channel:e.channel||"production",autoCheck:null===(t=e.autoCheck)||void 0===t||t,autoUpdate:null!==(r=e.autoUpdate)&&void 0!==r&&r,updateStrategy:e.updateStrategy,publicKey:e.publicKey,requireSignature:e.requireSignature,checksumAlgorithm:e.checksumAlgorithm,checkInterval:e.checkInterval,security:e.security}),this.setupAppUpdateEventBridge(),this.backgroundScheduler=new F,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 v(e.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 G{constructor(){this.logger=m.getInstance(),this.configManager=w.getInstance()}async downloadWithDelta(t,a,i){var r;const n=Date.now();if(this.configManager.get("enableDeltaUpdates")&&(null===(r=t.delta)||void 0===r?void 0:r.available)&&t.delta.patchUrl&&a)try{this.logger.info("Attempting delta update",{patchSize:t.delta.patchSize,fullSize:t.size}),null==i||i(10);const r=await this.downloadPatch(t.delta.patchUrl);if(t.delta.patchChecksum&&!await this.verifyChecksum(r,t.delta.patchChecksum))throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Delta patch checksum mismatch");null==i||i(50);const o=await this.applyPatch(a,r,t.delta.targetChecksum||t.checksum);null==i||i(90);const s=await this.calculateChecksum(o);if(s!==(t.delta.targetChecksum||t.checksum))throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Delta patch result checksum mismatch");null==i||i(100);const l=Date.now()-n;return this.logger.info("Delta update successful",{downloadSize:r.byteLength,resultSize:o.byteLength,savings:`${Math.round(100*(1-r.byteLength/(t.size||o.byteLength)))}%`,duration:l}),{usedDelta:!0,bundleData:o,checksum:s,downloadSize:r.byteLength,duration:l}}catch(e){this.logger.warn("Delta update failed, falling back to full download",{error:e})}if(null==i||i(10),!t.bundleUrl)throw new y(e.ErrorCode.DOWNLOAD_FAILED,"No bundle URL provided");const o=await this.downloadFull(t.bundleUrl,i),s=Date.now()-n,l=await this.calculateChecksum(o);if(t.checksum&&l!==t.checksum)throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Full bundle checksum mismatch");return{usedDelta:!1,bundleData:o,checksum:l,downloadSize:o.byteLength,duration:s}}async downloadPatch(t){D.validateDownloadUrl(t);const a=await fetch(t);if(!a.ok)throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Failed to download delta patch: ${a.status}`);const i=this.configManager.get("maxBundleSize");if(Number(a.headers.get("content-length")||0)>i)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");const r=await a.arrayBuffer();if(r.byteLength>i)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");return r}async downloadFull(t,a){D.validateDownloadUrl(t);const i=await fetch(t);if(!i.ok)throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Failed to download bundle: ${i.status}`);const r=i.headers.get("content-length"),n=r?parseInt(r,10):0,o=this.configManager.get("maxBundleSize");if(n>o)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(n&&i.body){const t=i.body.getReader(),r=[];let s=0;for(;;){const{done:i,value:l}=await t.read();if(i)break;if(r.push(l),s+=l.length,s>o)throw await t.cancel(),new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(a){const e=Math.round(s/n*90)+10;a(Math.min(e,99))}}null==a||a(100);const l=new Uint8Array(s);let d=0;for(const e of r)l.set(e,d),d+=e.length;return l.buffer}const s=await i.arrayBuffer();if(s.byteLength>o)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");return null==a||a(100),s}async applyPatch(e,t,a){const i=(new TextDecoder).decode(t),r=JSON.parse(i);if("NUDELTA/1"!==r.format||r.targetChecksum!==a)throw new Error("Unsupported or inconsistent delta patch");const n=await this.calculateChecksum(e);if(r.baseChecksum!==n)throw new Error("NUDELTA base checksum mismatch");return this.applyNuDelta(e,r)}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 i=new Uint8Array(e),r=[];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>i.length)throw new Error("NUDELTA copy operation is out of bounds");a=i.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");r.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 r)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 H{constructor(){this.initialized=!1,this.windowEventListeners=new Map,this.pluginManager=x.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(t){let a;if("config"in t&&"object"==typeof t.config)a=t.config;else{const e=t.liveUpdate,i=t.appUpdate,r=t.appReview;a={appId:null==e?void 0:e.appId,baseUrl:null==e?void 0:e.serverUrl,serverUrl:null==e?void 0:e.serverUrl,apiKey:null==e?void 0:e.apiKey,channel:null==e?void 0:e.channel,autoCheck:null==e?void 0:e.autoUpdate,autoUpdate:null==e?void 0:e.autoUpdate,updateStrategy:null==e?void 0:e.updateStrategy,publicKey:null==e?void 0:e.publicKey,requireSignature:null==e?void 0:e.requireSignature,allowUnsignedDevelopmentUpdates:null==e?void 0:e.allowUnsignedDevelopmentUpdates,maxBundleSize:null==e?void 0:e.maxBundleSize,maxUncompressedBundleSize:null==e?void 0:e.maxUncompressedBundleSize,allowedHosts:null==e?void 0:e.allowedHosts,enableDeltaUpdates:null==e?void 0:e.enableDeltaUpdates,checksumAlgorithm:null==e?void 0:e.checksumAlgorithm,checkInterval:null==e?void 0:e.checkInterval,security:t.security,appStoreId:null==i?void 0:i.appStoreId,packageName:null==i?void 0:i.packageName,webReviewUrl:null==r?void 0:r.webReviewUrl}}if(this.initialized)throw new v(e.ErrorCode.INVALID_CONFIG,"Configuration is locked after initialization. Call reset() before configuring again.");await this.initialize(a)}async getSecurityInfo(){return{enforceHttps:!0,certificatePinning:{enabled:!1,pins:[]},validateInputs:!0,secureStorage:!0}}async sync(t){try{const a=await this.checkForUpdate();if(!a.available||!a.latestVersion||!a.url)return{status:e.SyncStatus.UP_TO_DATE,version:a.currentVersion};if("immediate"===(null==t?void 0:t.updateMode)||void 0===(null==t?void 0:t.updateMode)){const t=await this.downloadUpdate({url:a.url,version:a.latestVersion,checksum:a.checksum,signature:a.signature,signatureAlgorithm:a.signatureAlgorithm,delta:a.delta});return await this.applyUpdate(t.bundleId),{status:e.SyncStatus.UPDATE_INSTALLED,version:a.latestVersion,description:a.notes,mandatory:a.mandatory}}return{status:e.SyncStatus.UPDATE_AVAILABLE,version:a.latestVersion,description:a.notes,mandatory:a.mandatory}}catch(t){return{status:e.SyncStatus.ERROR,error:{code:e.UpdateErrorCode.UNKNOWN_ERROR,message:t instanceof Error?t.message:"Sync failed"}}}}async download(t){const a=this.pluginManager.getDownloadManager(),i=this.pluginManager.getBundleManager();let r;const n=await i.getActiveBundle();if(t.delta&&(null==n?void 0:n.version)===t.delta.fromVersion){const e=await a.loadBlob(n.bundleId),i=await(new G).downloadWithDelta({updateAvailable:!0,version:t.version,bundleUrl:t.url,checksum:t.checksum,size:void 0,delta:{available:!0,patchUrl:t.delta.patchUrl,patchSize:t.delta.patchSize,patchChecksum:t.delta.patchChecksum,targetChecksum:t.delta.targetChecksum}},e?await e.arrayBuffer():null);r=new Blob([i.bundleData],{type:"application/zip"})}else r=await a.downloadWithRetry(t.url,t.version);const o=await r.arrayBuffer();await this.validateBundleData(o,t.checksum,t.signature);const s=new Blob([o],{type:r.type}),l=await a.saveBlob(t.version,s),d={bundleId:t.version,version:t.version,path:l,downloadTime:Date.now(),size:s.size,status:e.BundleStatus.READY,checksum:t.checksum,signature:t.signature,signatureAlgorithm:t.signatureAlgorithm,verified:!0};return await i.saveBundleInfo(d),d}async set(t){const a=this.pluginManager.getBundleManager();if(!t.verified)throw new v(e.ErrorCode.SIGNATURE_INVALID,`Refusing to activate unverified bundle ${t.bundleId}`);await a.setActiveBundle(t.bundleId)}async reload(){"undefined"!=typeof window&&window.location.reload()}async current(){const t=this.pluginManager.getBundleManager(),a=await t.getActiveBundle();if(!a)throw new v(e.ErrorCode.FILE_NOT_FOUND,"No active bundle found");return a}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 i=e.keepVersions;i<a.length;i++)await t.deleteBundle(a[i].bundleId)}}async notifyAppReady(){const t=this.pluginManager.getBundleManager(),a=await t.getActiveBundle();a&&(a.status=e.BundleStatus.ACTIVE,await t.saveBundleInfo(a))}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 i=e.bundlePath.match(/bundles\/([^/]+)\/bundle\.zip$/),r=i?i[1]:e.bundlePath,n=await a.loadBlob(r);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 t,a,i;const r=this.pluginManager.getBundleManager(),n=this.pluginManager.getConfigManager();try{const o=await r.getActiveBundle(),s=(null==o?void 0:o.version)||"1.0.0",l=n.get("baseUrl");if(!l)return{available:!1,currentVersion:s};const d=n.get("apiKey");if(!d)throw new v(e.ErrorCode.INVALID_CONFIG,"apiKey is required when using Laravel backend");const c=n.get("channel")||"production",u=this.getDeviceInfo(s),h=await N(l,{apiKey:d,channel:c,currentVersion:s,deviceId:u.deviceId,platform:u.platform,appVersion:u.appVersion,identity:await this.resolveAppIdentity()});return h.available?{available:!0,currentVersion:s,latestVersion:h.version,url:h.downloadUrl,mandatory:h.mandatory,notes:null!==(t=h.releaseNotes)&&void 0!==t?t:void 0,size:h.size,checksum:h.checksum,signature:null!==(a=h.signature)&&void 0!==a?a:void 0,signatureAlgorithm:h.signature?"RSA-SHA256":void 0,delta:null!==(i=h.delta)&&void 0!==i?i:void 0}:h.held?{available:!1,currentVersion:s,latestVersion:h.version,held:!0,heldMessage:h.message}:{available:!1,currentVersion:s}}catch(t){throw new v(e.ErrorCode.NETWORK_ERROR,t instanceof Error?t.message:"Failed to check for updates")}}async downloadUpdate(t){const a=this.pluginManager.getDownloadManager(),i=this.pluginManager.getBundleManager(),r=this.pluginManager.getEventEmitter();let n;if(!((null==t?void 0:t.url)&&(null==t?void 0:t.version)||(n=await this.checkForUpdate(),n.available&&n.url)))throw new v(e.ErrorCode.UPDATE_NOT_AVAILABLE,"No update available to download");const o=(null==t?void 0:t.url)||(null==n?void 0:n.url)||"",s=(null==t?void 0:t.version)||(null==n?void 0:n.latestVersion)||"",l=(null==t?void 0:t.checksum)||(null==n?void 0:n.checksum)||"",d=(null==t?void 0:t.signature)||(null==n?void 0:n.signature)||"",c=(null==t?void 0:t.signatureAlgorithm)||(null==n?void 0:n.signatureAlgorithm),u=(null==t?void 0:t.delta)||(null==n?void 0:n.delta);if(!o||!s)throw new v(e.ErrorCode.INVALID_CONFIG,"URL and version are required for download");const h=await a.downloadWithRetry(o,s,e=>{r.emit("downloadProgress",e),(null==t?void 0:t.onProgress)&&t.onProgress(e)}),g=await h.arrayBuffer();await this.validateBundleData(g,l,d||void 0);const p=new Blob([g],{type:h.type}),f={bundleId:s,version:s,path:await a.saveBlob(s,p),downloadTime:Date.now(),size:p.size,status:e.BundleStatus.READY,checksum:l,signature:d||void 0,signatureAlgorithm:c,metadata:u?{delta:u}:void 0,verified:!0};return await i.saveBundleInfo(f),f}async applyUpdate(t){const a=this.pluginManager.getBundleManager();let i=t;if(!i){const t=(await a.getAllBundles()).filter(t=>t.status===e.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime);if(0===t.length)throw new v(e.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");i=t[0].bundleId}const r=await a.getBundle(i);if(!r)throw new v(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${i} 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 _(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(t,a,i){const r=this.pluginManager.getSecurityValidator(),n=this.pluginManager.getConfigManager();if(a&&!await r.verifyChecksum(t,a))throw new v(e.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");const o=n.get("requireSignature"),s=n.get("publicKey");if(o){if(!s)throw new v(e.ErrorCode.INVALID_CONFIG,"Signature verification required but publicKey is not configured");if(!i)throw new v(e.ErrorCode.SIGNATURE_INVALID,"Signature verification required but no signature provided");if(!await r.verifySignature(t,i))throw new v(e.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(t){throw new v(e.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 $=t.registerPlugin("NativeUpdate",{web:()=>new H}),K=new Proxy($,{get(t,a,i){if("isInitialized"===a)return async()=>{const e=await t.isInitialized();return"boolean"==typeof e?e:!!(e&&"object"==typeof e&&"initialized"in e&&e.initialized)};if("list"===a)return async()=>{const e=await t.list();return Array.isArray(e)?e:e&&"object"==typeof e&&"bundles"in e&&Array.isArray(e.bundles)?e.bundles:[]};if("setChannel"===a)return e=>t.setChannel({channel:e});if("setUpdateUrl"===a)return e=>t.setUpdateUrl({url:e});if("scheduleBackgroundCheck"===a)return e=>t.scheduleBackgroundCheck({interval:e});if("requestNotificationPermissions"===a)return async()=>{const e=await t.requestNotificationPermissions();return"boolean"==typeof e?e:!!(e&&"object"==typeof e&&"granted"in e&&e.granted)};if("checkForUpdate"===a)return async()=>{const[e,a]=await Promise.all([t.getLatest(),t.current()]);return{available:!0===e.available&&"string"==typeof e.version&&M.compareVersions(e.version,a.version)>0,latestVersion:e.version,currentVersion:a.version,url:e.url,mandatory:e.mandatory,notes:e.notes,size:e.size,checksum:e.checksum,signature:e.signature,signatureAlgorithm:e.signatureAlgorithm,delta:e.delta,held:!0===e.held||void 0,heldMessage:e.heldMessage}};if("downloadUpdate"===a)return async(a={})=>{var i,r,n,o,s,l;const d=a.url&&a.version&&a.checksum?void 0:await t.getLatest(),c=null!==(i=a.url)&&void 0!==i?i:null==d?void 0:d.url,u=null!==(r=a.version)&&void 0!==r?r:null==d?void 0:d.version,h=null!==(n=a.checksum)&&void 0!==n?n:null==d?void 0:d.checksum;if(!c||!u||!h)throw new v(e.ErrorCode.UPDATE_NOT_AVAILABLE,"No downloadable update is available");return t.download({url:c,version:u,checksum:h,signature:null!==(o=a.signature)&&void 0!==o?o:null==d?void 0:d.signature,signatureAlgorithm:null!==(s=a.signatureAlgorithm)&&void 0!==s?s:null==d?void 0:d.signatureAlgorithm,delta:null!==(l=a.delta)&&void 0!==l?l:null==d?void 0:d.delta})};if("applyUpdate"===a)return async a=>{const i=await K.list(),r=a?i.find(e=>e.bundleId===a):i.filter(t=>t.status===e.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime)[0];if(!r)throw new v(e.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");await t.set(r),await t.reload()};if("cancelDownload"===a)return e=>t.cancelDownload({bundleId:e});if("isDownloading"===a)return async e=>{const a=await t.isDownloading({bundleId:e});return"boolean"==typeof a?a:!!(a&&"object"==typeof a&&"isDownloading"in a&&a.isDownloading)};if("getActiveDownloadCount"===a)return async()=>{const e=await t.getActiveDownloadCount();return"number"==typeof e?e:e&&"object"==typeof e&&"count"in e&&"number"==typeof e.count?e.count:0};const r=Reflect.get(t,a,i);return"function"==typeof r?r.bind(t):r}});e.BundleManager=b,e.CacheManager=class{constructor(){this.filesystem=null,this.memoryCache=new Map,this.CACHE_DIR="cache",this.logger=m.getInstance(),this.configManager=w.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:a.Directory.Data,recursive:!0})}catch(e){this.logger.debug("Cache directory may already exist",e)}await this.cleanExpiredCache()}async set(e,t,a){const i=Date.now()+(a||this.configManager.get("cacheExpiration")),r={data:t,timestamp:Date.now(),expiry:i};this.memoryCache.set(e,r),this.shouldPersist(t)&&await this.persistToFile(e,r),this.logger.debug("Cache entry set",{key:e,expiry:new Date(i)})}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:a.Directory.Data,recursive:!0}),await this.filesystem.mkdir({path:this.CACHE_DIR,directory:a.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,i]of this.memoryCache)e>=i.expiry&&(this.memoryCache.delete(a),t++);try{const i=await this.filesystem.readdir({path:this.CACHE_DIR,directory:a.Directory.Data});for(const a of i.files){const i=a.name.replace(".json",""),r=await this.loadFromFile(i);(!r||e>=r.expiry)&&(await this.removeFile(i),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 i=await this.filesystem.readdir({path:this.CACHE_DIR,directory:a.Directory.Data});e=i.files.length;for(const e of i.files)t+=(await this.filesystem.stat({path:`${this.CACHE_DIR}/${e.name}`,directory:a.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 i=`${this.CACHE_DIR}/${e}.json`,r=JSON.stringify(t);await this.filesystem.writeFile({path:i,data:r,directory:a.Directory.Data,encoding:a.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`,i=await this.filesystem.readFile({path:t,directory:a.Directory.Data,encoding:a.Encoding.UTF8});return JSON.parse(i.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:a.Directory.Data})}catch(t){this.logger.debug("Failed to remove cache file",{key:e,error:t})}}},e.ConfigManager=w,e.ConfigurationError=class extends v{constructor(t,a){super(e.ErrorCode.INVALID_CONFIG,t,a),this.name="ConfigurationError"}},e.DownloadError=y,e.DownloadManager=U,e.Logger=m,e.NativeUpdate=K,e.NativeUpdateError=v,e.PluginManager=x,e.SecurityValidator=D,e.StorageError=I,e.UpdateErrorClass=A,e.UpdateManager=class{constructor(){this.filesystem=null,this.updateInProgress=!1,this.currentState=null,this.pluginManager=x.getInstance(),this.securityValidator=D.getInstance()}async initialize(){if(this.filesystem=this.pluginManager.getConfigManager().get("filesystem"),!this.filesystem)throw new A(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured")}async applyUpdate(t,a){var i;if(this.updateInProgress)throw new A(e.ErrorCode.UPDATE_FAILED,"Another update is already in progress");const r=this.pluginManager.getLogger(),n=this.pluginManager.getBundleManager();try{this.updateInProgress=!0,r.info("Starting bundle update",{bundleId:t});const o=await n.getBundle(t);if(!o)throw new A(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${t} not found`);if("READY"!==o.status&&"ACTIVE"!==o.status)throw new A(e.ErrorCode.BUNDLE_NOT_READY,`Bundle ${t} is not ready for installation`);const s=await n.getActiveBundle();this.currentState={currentBundle:s,newBundle:o,backupPath:null,startTime:Date.now()},await this.validateUpdate(s,o,a),s&&"default"!==s.bundleId&&(this.currentState.backupPath=await this.createBackup(s)),await this.performUpdate(o),await this.verifyUpdate(o),await n.setActiveBundle(t);const l=this.pluginManager.getVersionManager(),d=this.pluginManager.getConfigManager();if(await l.rememberAppliedVersion(d.get("channel"),o.version),!1!==(null==a?void 0:a.cleanupOldBundles)){const e=null!==(i=null==a?void 0:a.keepBundleCount)&&void 0!==i?i:3;await n.cleanupOldBundles(e)}r.info("Bundle update completed successfully",{bundleId:t,version:o.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(t,a,i){const r=this.pluginManager.getLogger(),n=this.pluginManager.getVersionManager(),o=this.pluginManager.getConfigManager();if(t&&n.shouldBlockDowngrade(t.version,a.version))throw new E(e.ErrorCode.VERSION_DOWNGRADE,`Cannot downgrade from ${t.version} to ${a.version}`);const s=o.get("channel"),l=await n.getMaxSeenVersion(s);if(l&&n.shouldBlockDowngrade(l,a.version))throw new E(e.ErrorCode.VERSION_DOWNGRADE,`Cannot apply ${a.version} - device has previously applied ${l} on channel ${s}`);if(!a.verified){r.warn("Bundle not verified, verifying now",{bundleId:a.bundleId});const t=this.pluginManager.getDownloadManager(),i=await t.loadBlob(a.bundleId);if(!i)throw new A(e.ErrorCode.FILE_NOT_FOUND,"Bundle data not found");const n=await i.arrayBuffer();if(!await this.securityValidator.verifyChecksum(n,a.checksum))throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");if(a.signature&&!await this.securityValidator.verifySignature(n,a.signature))throw new E(e.ErrorCode.SIGNATURE_INVALID,"Bundle signature verification failed");await this.pluginManager.getBundleManager().markBundleAsVerified(a.bundleId)}r.debug("Bundle validation passed",{bundleId:a.bundleId})}async createBackup(t){const i=`backups/${t.bundleId}_${Date.now()}`,r=this.pluginManager.getLogger();try{return await this.filesystem.mkdir({path:i,directory:a.Directory.Data,recursive:!0}),await this.filesystem.copy({from:t.path,to:i,directory:a.Directory.Data}),r.info("Backup created",{bundleId:t.bundleId,backupPath:i}),i}catch(t){throw r.error("Failed to create backup",t),new A(e.ErrorCode.UPDATE_FAILED,"Failed to create backup",void 0,t)}}async performUpdate(t){const i=this.pluginManager.getLogger();try{const e=`active/${t.bundleId}`;await this.filesystem.mkdir({path:e,directory:a.Directory.Data,recursive:!0}),await this.filesystem.copy({from:t.path,to:e,directory:a.Directory.Data}),t.path=e,i.debug("Bundle files installed",{bundleId:t.bundleId,targetPath:e})}catch(t){throw new A(e.ErrorCode.UPDATE_FAILED,"Failed to install bundle files",void 0,t)}}async verifyUpdate(t){try{const e=`${t.path}/index.html`;await this.filesystem.stat({path:e,directory:a.Directory.Data})}catch(t){throw new A(e.ErrorCode.UPDATE_FAILED,"Bundle verification failed after installation",void 0,t)}}async rollback(){var t;if(!this.currentState)throw new A(e.ErrorCode.ROLLBACK_FAILED,"No update state to rollback");const i=this.pluginManager.getLogger();i.warn("Starting rollback",{from:this.currentState.newBundle.bundleId,to:(null===(t=this.currentState.currentBundle)||void 0===t?void 0:t.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:a.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(),i.info("Rollback completed successfully")}catch(t){throw i.error("Rollback failed",t),new A(e.ErrorCode.ROLLBACK_FAILED,"Failed to rollback update",void 0,t)}finally{if(this.currentState.backupPath)try{await this.filesystem.rmdir({path:this.currentState.backupPath,directory:a.Directory.Data,recursive:!0})}catch(e){i.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)}},e.ValidationError=E,e.VersionManager=M,e.compareVersions=_}({},capacitorExports,capacitorFilesystem,capacitorPreferences);
1
+ /*! Native Update Plugin v5.0.1 | Native Update License (see LICENSE) */
2
+ !function(e,t,a,i){var r,n,o,s,l,d,c,u,h,g,p,f;e.BackgroundUpdateType=void 0,(r=e.BackgroundUpdateType||(e.BackgroundUpdateType={})).APP_UPDATE="app_update",r.LIVE_UPDATE="live_update",r.BOTH="both",e.NotificationPriority=void 0,(n=e.NotificationPriority||(e.NotificationPriority={})).MIN="min",n.LOW="low",n.DEFAULT="default",n.HIGH="high",n.MAX="max",e.UpdateStrategy=void 0,(o=e.UpdateStrategy||(e.UpdateStrategy={})).IMMEDIATE="immediate",o.BACKGROUND="background",o.MANUAL="manual",e.UpdateMode=void 0,(s=e.UpdateMode||(e.UpdateMode={})).IMMEDIATE="immediate",s.ON_NEXT_RESTART="on_next_restart",s.ON_NEXT_RESUME="on_next_resume",e.InstallMode=void 0,(l=e.InstallMode||(e.InstallMode={})).IMMEDIATE="immediate",l.ON_NEXT_RESTART="on_next_restart",l.ON_NEXT_RESUME="on_next_resume",e.ChecksumAlgorithm=void 0,(d=e.ChecksumAlgorithm||(e.ChecksumAlgorithm={})).SHA256="SHA-256",d.SHA512="SHA-512",e.SyncStatus=void 0,(c=e.SyncStatus||(e.SyncStatus={})).UP_TO_DATE="UP_TO_DATE",c.UPDATE_AVAILABLE="UPDATE_AVAILABLE",c.UPDATE_INSTALLED="UPDATE_INSTALLED",c.ERROR="ERROR",e.BundleStatus=void 0,(u=e.BundleStatus||(e.BundleStatus={})).PENDING="PENDING",u.DOWNLOADING="DOWNLOADING",u.READY="READY",u.ACTIVE="ACTIVE",u.FAILED="FAILED",e.InstallStatus=void 0,(h=e.InstallStatus||(e.InstallStatus={})).UNKNOWN="UNKNOWN",h.PENDING="PENDING",h.DOWNLOADING="DOWNLOADING",h.DOWNLOADED="DOWNLOADED",h.INSTALLING="INSTALLING",h.INSTALLED="INSTALLED",h.FAILED="FAILED",h.CANCELED="CANCELED",e.UpdateErrorCode=void 0,(g=e.UpdateErrorCode||(e.UpdateErrorCode={})).NETWORK_ERROR="NETWORK_ERROR",g.SERVER_ERROR="SERVER_ERROR",g.TIMEOUT_ERROR="TIMEOUT_ERROR",g.DOWNLOAD_ERROR="DOWNLOAD_ERROR",g.STORAGE_ERROR="STORAGE_ERROR",g.SIZE_LIMIT_EXCEEDED="SIZE_LIMIT_EXCEEDED",g.VERIFICATION_ERROR="VERIFICATION_ERROR",g.CHECKSUM_ERROR="CHECKSUM_ERROR",g.SIGNATURE_ERROR="SIGNATURE_ERROR",g.INSECURE_URL="INSECURE_URL",g.INVALID_CERTIFICATE="INVALID_CERTIFICATE",g.PATH_TRAVERSAL="PATH_TRAVERSAL",g.INSTALL_ERROR="INSTALL_ERROR",g.ROLLBACK_ERROR="ROLLBACK_ERROR",g.VERSION_MISMATCH="VERSION_MISMATCH",g.PERMISSION_DENIED="PERMISSION_DENIED",g.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",g.UPDATE_IN_PROGRESS="UPDATE_IN_PROGRESS",g.UPDATE_CANCELLED="UPDATE_CANCELLED",g.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",g.REVIEW_NOT_SUPPORTED="REVIEW_NOT_SUPPORTED",g.QUOTA_EXCEEDED="QUOTA_EXCEEDED",g.CONDITIONS_NOT_MET="CONDITIONS_NOT_MET",g.INVALID_CONFIG="INVALID_CONFIG",g.NOT_CONFIGURED="NOT_CONFIGURED",g.UNKNOWN_ERROR="UNKNOWN_ERROR";class w{constructor(){this.config=this.getDefaultConfig()}static getInstance(){return w.instance||(w.instance=new w),w.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)}}e.LogLevel=void 0,(p=e.LogLevel||(e.LogLevel={}))[p.DEBUG=0]="DEBUG",p[p.INFO=1]="INFO",p[p.WARN=2]="WARN",p[p.ERROR=3]="ERROR";class m{constructor(e){this.configManager=w.getInstance(),this.context=e||"NativeUpdate"}static getInstance(){return m.instance||(m.instance=new m),m.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(t,a){this.logWithLevel(e.LogLevel.INFO,t,a)}logWithLevel(t,a,i){if(!this.shouldLog())return;const r=(new Date).toISOString(),n=i?this.sanitize(i):void 0,o={timestamp:r,level:e.LogLevel[t],context:this.context,message:a};switch(void 0!==n&&(o.data=n),t){case e.LogLevel.DEBUG:console.debug(`[${this.context}]`,o);break;case e.LogLevel.INFO:console.info(`[${this.context}]`,o);break;case e.LogLevel.WARN:console.warn(`[${this.context}]`,o);break;case e.LogLevel.ERROR:console.error(`[${this.context}]`,o)}}debug(t,a){this.logWithLevel(e.LogLevel.DEBUG,t,a)}info(t,a){this.logWithLevel(e.LogLevel.INFO,t,a)}warn(t,a){this.logWithLevel(e.LogLevel.WARN,t,a)}error(t,a){const i=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;this.logWithLevel(e.LogLevel.ERROR,t,i)}}e.ErrorCode=void 0,(f=e.ErrorCode||(e.ErrorCode={})).NOT_CONFIGURED="NOT_CONFIGURED",f.INVALID_CONFIG="INVALID_CONFIG",f.MISSING_DEPENDENCY="MISSING_DEPENDENCY",f.NETWORK_ERROR="NETWORK_ERROR",f.SERVER_ERROR="SERVER_ERROR",f.DOWNLOAD_FAILED="DOWNLOAD_FAILED",f.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",f.INVALID_URL="INVALID_URL",f.INSECURE_URL="INSECURE_URL",f.UNAUTHORIZED_HOST="UNAUTHORIZED_HOST",f.BUNDLE_TOO_LARGE="BUNDLE_TOO_LARGE",f.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",f.SIGNATURE_INVALID="SIGNATURE_INVALID",f.VERSION_DOWNGRADE="VERSION_DOWNGRADE",f.INVALID_BUNDLE_FORMAT="INVALID_BUNDLE_FORMAT",f.VALIDATION_ERROR="VALIDATION_ERROR",f.STORAGE_FULL="STORAGE_FULL",f.FILE_NOT_FOUND="FILE_NOT_FOUND",f.PERMISSION_DENIED="PERMISSION_DENIED",f.UPDATE_FAILED="UPDATE_FAILED",f.ROLLBACK_FAILED="ROLLBACK_FAILED",f.BUNDLE_NOT_READY="BUNDLE_NOT_READY",f.UPDATE_NOT_AVAILABLE="UPDATE_NOT_AVAILABLE",f.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",f.NATIVE_ERROR="NATIVE_ERROR";class v extends Error{constructor(e,t,a,i){super(t),this.code=e,this.message=t,this.details=a,this.originalError=i,this.name="NativeUpdateError",Object.setPrototypeOf(this,v.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,stack:this.stack}}}class y extends v{constructor(e,t,a,i){super(e,t,a,i),this.name="DownloadError"}}class E extends v{constructor(e,t,a){super(e,t,a),this.name="ValidationError"}}class I extends v{constructor(e,t,a,i){super(e,t,a,i),this.name="StorageError"}}class A extends v{constructor(e,t,a,i){super(e,t,a,i),this.name="UpdateError"}}class D{constructor(){this.configManager=w.getInstance(),this.logger=m.getInstance()}static getInstance(){return D.instance||(D.instance=new D),D.instance}static validateUrl(e){try{return"https:"===new URL(e).protocol}catch(e){return!1}}static validateDownloadUrl(t){if(!this.validateUrl(t))throw new E(e.ErrorCode.INSECURE_URL,`Refusing non-HTTPS URL: ${t}`)}static validateStoreUrl(t){let a;try{a=new URL(t)}catch(a){throw new E(e.ErrorCode.INSECURE_URL,`Invalid URL: ${t}`)}if(!["https:","market:","itms-apps:"].includes(a.protocol))throw new E(e.ErrorCode.INSECURE_URL,`Refusing URL scheme ${a.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(t,a){if(!a)throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Checksum is required but was not provided");const i=await this.calculateChecksum(t),r=i===a.toLowerCase();return r||this.logger.error("Checksum verification failed",{expected:a,actual:i}),r}async validateChecksum(e,t){return this.verifyChecksum(e,t)}async verifySignature(t,a){const i=this.configManager.get("enableSignatureValidation"),r=this.configManager.get("requireSignature"),n=this.configManager.get("publicKey");if(!a){if(i||r||n)throw new E(e.ErrorCode.SIGNATURE_INVALID,"Signature is required but was not provided");return!0}if(!n)throw new E(e.ErrorCode.SIGNATURE_INVALID,"Public key not configured for signature validation");try{const e=await crypto.subtle.importKey("spki",this.pemToArrayBuffer(n),{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]),i=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},e,this.base64ToArrayBuffer(a),t);return i||this.logger.error("Signature verification failed"),i}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(t){if(!t||"string"!=typeof t)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID must be a non-empty string");if(!/^[a-zA-Z0-9\-_.]+$/.test(t))throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID contains invalid characters");if(t.length>100)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is too long (max 100 characters)")}validateVersion(t){if(!t||"string"!=typeof t)throw new E(e.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(t))throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Version must follow semantic versioning format (e.g., 1.2.3)")}isVersionDowngrade(e,t){const a=this.parseVersion(e),i=this.parseVersion(t);return i.major<a.major||!(i.major>a.major)&&(i.minor<a.minor||!(i.minor>a.minor)&&i.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(t){if(!t||"string"!=typeof t)throw new E(e.ErrorCode.INVALID_URL,"URL must be a non-empty string");let a;try{a=new URL(t)}catch(t){throw new E(e.ErrorCode.INVALID_URL,"Invalid URL format")}if("https:"!==a.protocol)throw new E(e.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed");const i=this.configManager.get("allowedHosts");if(i.length>0&&!i.includes(a.hostname))throw new E(e.ErrorCode.UNAUTHORIZED_HOST,`Host ${a.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(a.hostname)))throw new E(e.ErrorCode.UNAUTHORIZED_HOST,"Private/local addresses are not allowed")}validateFileSize(t){if("number"!=typeof t||t<0)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"File size must be a non-negative number");const a=this.configManager.get("maxBundleSize");if(t>a)throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,`File size ${t} exceeds maximum allowed size of ${a} 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 i=a.filter(t=>t.hostname===e);if(0===i.length)return!0;const r=await this.calculateCertificateHash(t),n=i.some(e=>e.sha256===r);return n||this.logger.error("Certificate pinning validation failed",{hostname:e,expectedPins:i.map(e=>e.sha256),actualHash:r}),n}async calculateCertificateHash(e){const t=(new TextEncoder).encode(e),a=await crypto.subtle.digest("SHA-256",t),i=Array.from(new Uint8Array(a));return"sha256/"+btoa(String.fromCharCode(...i))}validateMetadata(t){if(t&&"object"!=typeof t)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata must be an object");if(JSON.stringify(t||{}).length>10240)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Metadata is too large (max 10KB)")}}class b{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=m.getInstance(),this.configManager=w.getInstance()}setDownloadManager(e){this.downloadManager=e}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new I(e.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(t){throw new I(e.ErrorCode.STORAGE_FULL,"Failed to save bundles to storage",void 0,t)}}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(t){if(!t.bundleId||"string"!=typeof t.bundleId)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle ID");if(!t.version||"string"!=typeof t.version)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle version");if(!t.path||"string"!=typeof t.path)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle path");if("number"!=typeof t.size||t.size<0)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid bundle size")}async getAllBundles(){return await this.loadCache(),Array.from(this.cache.values())}async getBundle(t){if(!t)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");return await this.loadCache(),this.cache.get(t)||null}async deleteBundle(t){if(!t)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(await this.loadCache(),this.cache.get(t)){if(this.cache.delete(t),await this.saveCache(),await this.getActiveBundleId()===t&&await this.clearActiveBundle(),this.downloadManager)try{await this.downloadManager.deleteBlob(t)}catch(e){this.logger.warn("Failed to delete bundle file",{bundleId:t,error:e})}this.logger.info("Bundle deleted",{bundleId:t})}else this.logger.warn("Attempted to delete non-existent bundle",{bundleId:t})}async getActiveBundle(){const e=await this.getActiveBundleId();return e?this.getBundle(e):null}async setActiveBundle(t){if(!t)throw new I(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");const a=await this.getBundle(t);if(!a)throw new I(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${t} not found`);const i=await this.getActiveBundle();i&&i.bundleId!==t&&(i.status="READY",await this.saveBundleInfo(i)),a.status="ACTIVE",await this.saveBundleInfo(a),await this.preferences.set({key:this.ACTIVE_BUNDLE_KEY,value:t}),this.logger.info("Active bundle set",{bundleId:t,version:a.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(t){if(t<1)throw new I(e.ErrorCode.INVALID_CONFIG,"Keep count must be at least 1");const a=await this.getAllBundles(),i=await this.getActiveBundleId(),r=a.sort((e,t)=>t.downloadTime-e.downloadTime),n=new Set;i&&n.add(i);let o=n.size;for(const e of r){if(o>=t)break;n.has(e.bundleId)||(n.add(e.bundleId),o++)}let s=0;for(const e of a)n.has(e.bundleId)||(await this.deleteBundle(e.bundleId),s++);s>0&&this.logger.info("Cleaned up old bundles",{deleted:s,kept:o})}async getBundlesOlderThan(t){if(t<0)throw new I(e.ErrorCode.INVALID_CONFIG,"Timestamp must be non-negative");return(await this.getAllBundles()).filter(e=>e.downloadTime<t)}async markBundleAsVerified(t){const a=await this.getBundle(t);if(!a)throw new I(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${t} not found`);a.verified=!0,await this.saveBundleInfo(a),this.logger.info("Bundle marked as verified",{bundleId:t})}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 U{constructor(){this.activeDownloads=new Map,this.lastResponseMeta=new Map,this.filesystem=null,this.logger=m.getInstance(),this.configManager=w.getInstance()}async initialize(){if(this.filesystem=this.configManager.get("filesystem"),!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured. Please configure the plugin first.")}validateUrl(t){try{const a=new URL(t);if("https:"!==a.protocol)throw new E(e.ErrorCode.INVALID_URL,"Only HTTPS URLs are allowed for security reasons");const i=this.configManager.get("allowedHosts");if(i.length>0&&!i.includes(a.hostname))throw new E(e.ErrorCode.UNAUTHORIZED_HOST,`Host ${a.hostname} is not in the allowed hosts list`)}catch(t){if(t instanceof E)throw t;throw new E(e.ErrorCode.INVALID_URL,"Invalid URL format")}}async download(t,a,i){var r;const n="function"==typeof i?{onProgress:i}:null!=i?i:{},o=n.onProgress,s=null!==(r=n.resumePosition)&&void 0!==r?r:0;if(this.validateUrl(t),!a)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Bundle ID is required");if(this.activeDownloads.has(a))throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Download already in progress for bundle ${a}`);const l=new AbortController,d={controller:l,startTime:Date.now(),resumePosition:s>0?s:void 0};this.activeDownloads.set(a,d);try{const i=this.configManager.get("downloadTimeout"),r=setTimeout(()=>l.abort(),i),n={"Cache-Control":"no-cache",Accept:"application/octet-stream, application/zip"};s>0&&(n.Range=`bytes=${s}-`);const c=await fetch(t,{signal:l.signal,headers:n});if(clearTimeout(r),!c.ok)throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Download failed: ${c.status} ${c.statusText}`,{status:c.status,statusText:c.statusText});const u=s>0&&206===c.status;d.serverReturnedPartial=u,this.lastResponseMeta.set(a,{partial:u});const h=c.headers.get("content-type");if(h&&!this.isValidContentType(h))throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,`Invalid content type: ${h}`);const g=c.headers.get("content-length"),p=g?parseInt(g,10):0;if(p>this.configManager.get("maxBundleSize"))throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,`Bundle size ${p} exceeds maximum allowed size`);if(!p||!c.body){const e=await c.blob();return this.validateBlobSize(e),e}const f=c.body.getReader(),w=[];let m=0;for(;;){const{done:t,value:i}=await f.read();if(t)break;if(w.push(i),m+=i.length,m>this.configManager.get("maxBundleSize"))throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,"Download size exceeds maximum allowed size");if(o){const e=d.resumePosition||0,t=e+m,i=e+p;o({percent:Math.round(t/i*100),bytesDownloaded:t,totalBytes:i,bundleId:a})}}const v=new Blob(w);return this.validateBlobSize(v),this.logger.info("Download completed",{bundleId:a,size:v.size,duration:Date.now()-d.startTime}),v}catch(t){if(t instanceof Error&&"AbortError"===t.name){const a=Date.now()-d.startTime>=this.configManager.get("downloadTimeout");throw new y(a?e.ErrorCode.DOWNLOAD_TIMEOUT:e.ErrorCode.DOWNLOAD_FAILED,a?"Download timed out":"Download cancelled",void 0,t)}throw t}finally{this.activeDownloads.delete(a)}}async resumeDownload(e,t,a,i){const r=await this.download(e,t,{onProgress:i,resumePosition:a.size}),n=this.lastResponseMeta.get(t);return this.lastResponseMeta.delete(t),(null==n?void 0:n.partial)?new Blob([a,r]):(this.logger.info("Resume: server returned full response; discarding partial data",{bundleId:t,partialSize:a.size,responseSize:r.size}),r)}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(t){if(0===t.size)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Downloaded file is empty");if(t.size>this.configManager.get("maxBundleSize"))throw new E(e.ErrorCode.BUNDLE_TOO_LARGE,`File size ${t.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(t,a,i){const r=this.configManager.get("retryAttempts"),n=this.configManager.get("retryDelay");let o=null;for(let e=0;e<r;e++)try{if(e>0){const t=n*Math.pow(2,e-1),i=.5*(Math.random()-.5)*t,r=Math.min(Math.max(t+i,100),3e4);await new Promise(e=>setTimeout(e,r)),this.logger.debug("Retrying download",{bundleId:a,attempt:e,delay:r})}return await this.download(t,a,i)}catch(t){if(o=t,t instanceof E||t instanceof Error&&"AbortError"===t.name)throw t;this.logger.warn(`Download attempt ${e+1} failed`,{bundleId:a,error:t})}throw new y(e.ErrorCode.DOWNLOAD_FAILED,"Download failed after all retries",{attempts:r},o||void 0)}async blobToArrayBuffer(e){return e.arrayBuffer()}async saveBlob(t,i){if(!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");const r=await this.blobToArrayBuffer(i),n=new Uint8Array(r);let o="";for(let e=0;e<n.length;e+=32768)o+=String.fromCharCode.apply(null,Array.from(n.subarray(e,e+32768)));const s=btoa(o),l=`bundles/${t}/bundle.zip`;return await this.filesystem.writeFile({path:l,data:s,directory:a.Directory.Data,recursive:!0}),this.logger.debug("Bundle saved to filesystem",{bundleId:t,path:l,size:i.size}),l}async loadBlob(t){if(!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const e=`bundles/${t}/bundle.zip`,i=await this.filesystem.readFile({path:e,directory:a.Directory.Data}),r=atob(i.data),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return new Blob([n],{type:"application/zip"})}catch(e){return this.logger.debug("Failed to load bundle from filesystem",{bundleId:t,error:e}),null}}async deleteBlob(t){if(!this.filesystem)throw new y(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not initialized");try{const e=`bundles/${t}`;await this.filesystem.rmdir({path:e,directory:a.Directory.Data,recursive:!0}),this.logger.debug("Bundle deleted from filesystem",{bundleId:t})}catch(e){this.logger.warn("Failed to delete bundle from filesystem",{bundleId:t,error:e})}}}async function N(e,t){var a,i,r,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.1"};"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!==(i=u.signatureAlgorithm)&&void 0!==i?i:void 0,delta:null!==(r=u.delta)&&void 0!==r?r: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 C(e){const t=e.trim().replace(/^v/i,"").split("+")[0],a=t.indexOf("-"),i=-1===a?t:t.slice(0,a),r=-1===a?"":t.slice(a+1);return{core:i.split(".").map(e=>{const t=Number.parseInt(e,10);return Number.isFinite(t)?t:0}),pre:""===r?[]:r.split(".")}}const S=/^\d+$/,L=/^(.*?)(\d+)$/;function R(e,t){const a=S.test(e),i=S.test(t);if(a&&i)return Math.sign(Number(e)-Number(t));if(a)return-1;if(i)return 1;const r=L.exec(e),n=L.exec(t);return r&&n&&r[1]===n[1]?Math.sign(Number(r[2])-Number(n[2])):e===t?0:e<t?-1:1}function _(e,t){var a,i;const r=C(e),n=C(t),o=Math.max(r.core.length,n.core.length,3);for(let e=0;e<o;e++){const t=(null!==(a=r.core[e])&&void 0!==a?a:0)-(null!==(i=n.core[e])&&void 0!==i?i:0);if(0!==t)return Math.sign(t)}if(0===r.pre.length&&0===n.pre.length)return 0;if(0===r.pre.length)return 1;if(0===n.pre.length)return-1;const s=Math.max(r.pre.length,n.pre.length);for(let e=0;e<s;e++){const t=r.pre[e],a=n.pre[e];if(void 0===t)return-1;if(void 0===a)return 1;const i=R(t,a);if(0!==i)return i}return 0}class M{constructor(){this.VERSION_CHECK_CACHE_KEY="capacitor_native_update_version_cache",this.CACHE_DURATION=3e5,this.preferences=null,this.memoryCache=new Map,this.logger=m.getInstance(),this.configManager=w.getInstance(),this.securityValidator=D.getInstance()}static compareVersions(e,t){return _(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&&M.compareVersions(e,a)<0)&&M.compareVersions(e,t)<0}async initialize(){if(this.preferences=this.configManager.get("preferences"),!this.preferences)throw new E(e.ErrorCode.MISSING_DEPENDENCY,"Preferences not configured. Please configure the plugin first.")}async checkForUpdates(t,a,i,r){var n;if(this.securityValidator.validateUrl(t),this.securityValidator.validateVersion(i),!a||!r)throw new E(e.ErrorCode.INVALID_CONFIG,"Channel and appId are required");const o=`${a}-${r}`,s=await this.getCachedVersionInfo(o);if(s&&s.channel===a&&Date.now()-s.timestamp<this.CACHE_DURATION)return this.logger.debug("Returning cached version info",{channel:a,version:s.data.version}),s.data;const l=this.configManager.get("apiKey");if(!l)return this.logger.warn("VersionManager.checkForUpdates: no apiKey configured — the Native Update backend requires X-API-Key"),null;try{const r=await N(t,{apiKey:l,channel:a,currentVersion:i,deviceId:"web-client",platform:"web",appVersion:i,signal:AbortSignal.timeout(this.configManager.get("downloadTimeout"))}),s={available:r.available,version:r.version,url:r.downloadUrl,mandatory:r.mandatory,notes:null!==(n=r.releaseNotes)&&void 0!==n?n:void 0,size:r.size,checksum:r.checksum};if(!s.available)return s;if(!s.version)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"No version in server response");return this.securityValidator.validateVersion(s.version),s.url&&this.securityValidator.validateUrl(s.url),r.minNativeVersion&&this.securityValidator.validateVersion(r.minNativeVersion),await this.cacheVersionInfo(o,a,s),this.logger.info("Version check completed",{channel:a,currentVersion:i,latestVersion:s.version,updateAvailable:this.isNewerVersion(s.version,i)}),s}catch(e){return this.logger.error("Failed to check for updates",e),null}}isNewerVersion(e,t){try{const a=this.parseVersion(e),i=this.parseVersion(t);return a.major!==i.major?a.major>i.major:a.minor!==i.minor?a.minor>i.minor:a.patch!==i.patch?a.patch>i.patch:!(a.prerelease&&!i.prerelease||(a.prerelease||!i.prerelease)&&(!a.prerelease||!i.prerelease||!(a.prerelease>i.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(t){const a=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/);if(!a)throw new E(e.ErrorCode.INVALID_BUNDLE_FORMAT,"Invalid version format");return{major:parseInt(a[1],10),minor:parseInt(a[2],10),patch:parseInt(a[3],10),prerelease:a[4],build:a[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 i=a[e];return!i||(this.securityValidator.validateVersion(t),this.securityValidator.validateVersion(i),!this.isNewerVersion(i,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 i={channel:t,data:a,timestamp:Date.now()};this.memoryCache.set(e,i);try{const{value:t}=await this.preferences.get({key:this.VERSION_CHECK_CACHE_KEY}),a=t?JSON.parse(t):{},r=Date.now();for(const e in a)r-a[e].timestamp>2*this.CACHE_DURATION&&delete a[e];a[e]=i,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&&M.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 O{constructor(e){this.cachedAppInfo=null,this.CACHE_DURATION=6e4,this.config=e,this.logger=new m("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 i=await a.json();return{availableVersion:i.version,updatePriority:i.priority,releaseNotes:i.releaseNotes,updateSize:i.size,updateURL:i.downloadUrl}}catch(e){return this.logger.error("Failed to check server version",e),{}}}compareVersions(e,t){return _(e,t)}isUpdateRequired(e,t,a){return this.compareVersions(e,t)<0||!!(a&&this.compareVersions(e,a)<0)}determineUpdatePriority(e,t){const[a,i]=e.split(".").map(Number);return a>0?5:i>0&&t&&t>30?4:i>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 T;!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"}(T||(T={}));class B{constructor(e){this.flexibleUpdateInterval=null,this.logger=new m("AppUpdateInstaller"),this.currentState={installStatus:T.UNKNOWN,packageName:"",availableVersion:""}}async startImmediateUpdate(){if(this.logger.log("Starting immediate update installation"),this.updateState(T.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(T.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!==T.DOWNLOADED)throw new Error("Update not ready for installation");this.updateState(T.INSTALLING),this.isAndroid()?this.logger.log("Completing Android update installation"):setTimeout(()=>{this.updateState(T.INSTALLED)},1e3)}async cancelUpdate(){this.logger.log("Cancelling update"),this.flexibleUpdateInterval&&(clearInterval(this.flexibleUpdateInterval),this.flexibleUpdateInterval=null),this.currentState.installStatus===T.DOWNLOADING&&this.updateState(T.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(T.DOWNLOADED));const i={bytesDownloaded:e,totalBytesToDownload:t,percentComplete:Math.round(e/t*100),downloadSpeed:a,estimatedTime:Math.ceil((t-e)/a)};this.progressCallback&&this.progressCallback(i)},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 V{constructor(e){this.config=e,this.logger=new m("PlatformAppUpdate"),this.platform=t.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{D.validateDownloadUrl(this.config.webUpdateUrl);const e=await fetch(this.config.webUpdateUrl),i=await e.json();i.version&&i.version!==t.currentVersion&&(a.updateAvailable=!0,a.availableVersion=i.version,a.releaseNotes=i.releaseNotes,i.downloadUrl&&(D.validateStoreUrl(i.downloadUrl),a.updateURL=i.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(D.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 k{constructor(e){this.listeners=new Map,this.config=e,this.logger=new m("AppUpdateManager"),this.checker=new O(e),this.installer=new B(e),this.platformUpdate=new V(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 F{constructor(){this.config=null,this.status={enabled:!1,isRunning:!1,checkCount:0,failureCount:0},this.deps={},this.logger=m.getInstance(),this.configManager=w.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 t;if(!(null===(t=this.config)||void 0===t?void 0:t.enabled))return{success:!1,updatesFound:!1,notificationSent:!1,error:{code:e.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(t){return this.status.failureCount++,this.status.isRunning=!1,this.status.lastError={code:e.UpdateErrorCode.UNKNOWN_ERROR,message:t instanceof Error?t.message:"Unknown error"},{success:!1,updatesFound:!1,notificationSent:!1,error:this.status.lastError}}}async checkForUpdates(){var t,a,i,r,n,o;const s=[];let l,d;((null===(t=this.config)||void 0===t?void 0:t.updateTypes.includes(e.BackgroundUpdateType.APP_UPDATE))||(null===(a=this.config)||void 0===a?void 0:a.updateTypes.includes(e.BackgroundUpdateType.BOTH)))&&s.push(this.checkAppUpdate()),((null===(i=this.config)||void 0===i?void 0:i.updateTypes.includes(e.BackgroundUpdateType.LIVE_UPDATE))||(null===(r=this.config)||void 0===r?void 0:r.updateTypes.includes(e.BackgroundUpdateType.BOTH)))&&s.push(this.checkLiveUpdate());const c=await Promise.allSettled(s);"fulfilled"===(null===(n=c[0])||void 0===n?void 0:n.status)&&(l=c[0].value),"fulfilled"===(null===(o=c[1])||void 0===o?void 0:o.status)&&(d=c[1].value);const u=(null==l?void 0:l.updateAvailable)||(null==d?void 0:d.available)||!1;let h=!1;return u&&(h=await this.sendNotification(l,d)),{success:!0,updatesFound:u,appUpdate:l,liveUpdate:d,notificationSent:h}}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(),i=e.version||e.latestVersion,r=i&&this.compareVersions(t,i)<0;return{updateAvailable:r,currentVersion:t,availableVersion:r?i: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",i=this.configManager.get("appId");if(e&&i){const r=await this.deps.versionManager.checkForUpdates(e,a,t,i);if(r)return r}}catch(e){this.logger.error("Failed to check live update via VersionManager",e)}const a=this.configManager.get("baseUrl")||this.configManager.get("serverUrl"),i=this.configManager.get("apiKey");if(a&&i)try{const r=this.configManager.get("channel")||"production",n=await N(a,{apiKey:i,channel:r,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 i=this.config.notificationPreferences;let r=i.title||"Update Available",n=i.description||"";if((null==e?void 0:e.updateAvailable)?(r="App Update Available",n=`Version ${e.availableVersion} is ready to install.`):(null==t?void 0:t.available)&&(r="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(r,{body:n}),!0}catch(e){this.logger.error("Failed to send notification",e)}return this.logger.info("Background update notification",{title:r,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 _(e,t)}}const P=new m("NativeUpdate.EventEmitter");class z{constructor(){this.listeners=new Map}static getInstance(){return z.instance||(z.instance=new z),z.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){P.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 x{constructor(){this.bundleManager=null,this.downloadManager=null,this.versionManager=null,this.appUpdateManager=null,this.backgroundScheduler=null,this.initialized=!1,this.configManager=w.getInstance(),this.logger=m.getInstance(),this.securityValidator=D.getInstance(),this.eventEmitter=z.getInstance()}static getInstance(){return x.instance||(x.instance=new x),x.instance}async initialize(e){var t,r;if(this.initialized)this.logger.warn("Plugin already initialized");else try{e.filesystem||(e.filesystem=a.Filesystem),e.preferences||(e.preferences=i.Preferences),this.configManager.configure(e),this.bundleManager=new b,await this.bundleManager.initialize(),this.downloadManager=new U,await this.downloadManager.initialize(),this.bundleManager.setDownloadManager(this.downloadManager),this.versionManager=new M,await this.versionManager.initialize(),this.appUpdateManager=new k({serverUrl:e.serverUrl||e.baseUrl||"",channel:e.channel||"production",autoCheck:null===(t=e.autoCheck)||void 0===t||t,autoUpdate:null!==(r=e.autoUpdate)&&void 0!==r&&r,updateStrategy:e.updateStrategy,publicKey:e.publicKey,requireSignature:e.requireSignature,checksumAlgorithm:e.checksumAlgorithm,checkInterval:e.checkInterval,security:e.security}),this.setupAppUpdateEventBridge(),this.backgroundScheduler=new F,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 v(e.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 G{constructor(){this.logger=m.getInstance(),this.configManager=w.getInstance()}async downloadWithDelta(t,a,i){var r;const n=Date.now();if(this.configManager.get("enableDeltaUpdates")&&(null===(r=t.delta)||void 0===r?void 0:r.available)&&t.delta.patchUrl&&a)try{this.logger.info("Attempting delta update",{patchSize:t.delta.patchSize,fullSize:t.size}),null==i||i(10);const r=await this.downloadPatch(t.delta.patchUrl);if(t.delta.patchChecksum&&!await this.verifyChecksum(r,t.delta.patchChecksum))throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Delta patch checksum mismatch");null==i||i(50);const o=await this.applyPatch(a,r,t.delta.targetChecksum||t.checksum);null==i||i(90);const s=await this.calculateChecksum(o);if(s!==(t.delta.targetChecksum||t.checksum))throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Delta patch result checksum mismatch");null==i||i(100);const l=Date.now()-n;return this.logger.info("Delta update successful",{downloadSize:r.byteLength,resultSize:o.byteLength,savings:`${Math.round(100*(1-r.byteLength/(t.size||o.byteLength)))}%`,duration:l}),{usedDelta:!0,bundleData:o,checksum:s,downloadSize:r.byteLength,duration:l}}catch(e){this.logger.warn("Delta update failed, falling back to full download",{error:e})}if(null==i||i(10),!t.bundleUrl)throw new y(e.ErrorCode.DOWNLOAD_FAILED,"No bundle URL provided");const o=await this.downloadFull(t.bundleUrl,i),s=Date.now()-n,l=await this.calculateChecksum(o);if(t.checksum&&l!==t.checksum)throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Full bundle checksum mismatch");return{usedDelta:!1,bundleData:o,checksum:l,downloadSize:o.byteLength,duration:s}}async downloadPatch(t){D.validateDownloadUrl(t);const a=await fetch(t);if(!a.ok)throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Failed to download delta patch: ${a.status}`);const i=this.configManager.get("maxBundleSize");if(Number(a.headers.get("content-length")||0)>i)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");const r=await a.arrayBuffer();if(r.byteLength>i)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Delta patch exceeds the bundle size limit");return r}async downloadFull(t,a){D.validateDownloadUrl(t);const i=await fetch(t);if(!i.ok)throw new y(e.ErrorCode.DOWNLOAD_FAILED,`Failed to download bundle: ${i.status}`);const r=i.headers.get("content-length"),n=r?parseInt(r,10):0,o=this.configManager.get("maxBundleSize");if(n>o)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(n&&i.body){const t=i.body.getReader(),r=[];let s=0;for(;;){const{done:i,value:l}=await t.read();if(i)break;if(r.push(l),s+=l.length,s>o)throw await t.cancel(),new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");if(a){const e=Math.round(s/n*90)+10;a(Math.min(e,99))}}null==a||a(100);const l=new Uint8Array(s);let d=0;for(const e of r)l.set(e,d),d+=e.length;return l.buffer}const s=await i.arrayBuffer();if(s.byteLength>o)throw new y(e.ErrorCode.BUNDLE_TOO_LARGE,"Bundle exceeds the configured size limit");return null==a||a(100),s}async applyPatch(e,t,a){const i=(new TextDecoder).decode(t),r=JSON.parse(i);if("NUDELTA/1"!==r.format||r.targetChecksum!==a)throw new Error("Unsupported or inconsistent delta patch");const n=await this.calculateChecksum(e);if(r.baseChecksum!==n)throw new Error("NUDELTA base checksum mismatch");return this.applyNuDelta(e,r)}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 i=new Uint8Array(e),r=[];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>i.length)throw new Error("NUDELTA copy operation is out of bounds");a=i.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");r.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 r)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 H{constructor(){this.initialized=!1,this.windowEventListeners=new Map,this.pluginManager=x.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(t){let a;if("config"in t&&"object"==typeof t.config)a=t.config;else{const e=t.liveUpdate,i=t.appUpdate,r=t.appReview;a={appId:null==e?void 0:e.appId,baseUrl:null==e?void 0:e.serverUrl,serverUrl:null==e?void 0:e.serverUrl,apiKey:null==e?void 0:e.apiKey,channel:null==e?void 0:e.channel,autoCheck:null==e?void 0:e.autoUpdate,autoUpdate:null==e?void 0:e.autoUpdate,updateStrategy:null==e?void 0:e.updateStrategy,publicKey:null==e?void 0:e.publicKey,requireSignature:null==e?void 0:e.requireSignature,allowUnsignedDevelopmentUpdates:null==e?void 0:e.allowUnsignedDevelopmentUpdates,maxBundleSize:null==e?void 0:e.maxBundleSize,maxUncompressedBundleSize:null==e?void 0:e.maxUncompressedBundleSize,allowedHosts:null==e?void 0:e.allowedHosts,enableDeltaUpdates:null==e?void 0:e.enableDeltaUpdates,checksumAlgorithm:null==e?void 0:e.checksumAlgorithm,checkInterval:null==e?void 0:e.checkInterval,security:t.security,appStoreId:null==i?void 0:i.appStoreId,packageName:null==i?void 0:i.packageName,webReviewUrl:null==r?void 0:r.webReviewUrl}}if(this.initialized)throw new v(e.ErrorCode.INVALID_CONFIG,"Configuration is locked after initialization. Call reset() before configuring again.");await this.initialize(a)}async getSecurityInfo(){return{enforceHttps:!0,certificatePinning:{enabled:!1,pins:[]},validateInputs:!0,secureStorage:!0}}async sync(t){try{const a=await this.checkForUpdate();if(!a.available||!a.latestVersion||!a.url)return{status:e.SyncStatus.UP_TO_DATE,version:a.currentVersion};if("immediate"===(null==t?void 0:t.updateMode)||void 0===(null==t?void 0:t.updateMode)){const t=await this.downloadUpdate({url:a.url,version:a.latestVersion,checksum:a.checksum,signature:a.signature,signatureAlgorithm:a.signatureAlgorithm,delta:a.delta});return await this.applyUpdate(t.bundleId),{status:e.SyncStatus.UPDATE_INSTALLED,version:a.latestVersion,description:a.notes,mandatory:a.mandatory}}return{status:e.SyncStatus.UPDATE_AVAILABLE,version:a.latestVersion,description:a.notes,mandatory:a.mandatory}}catch(t){return{status:e.SyncStatus.ERROR,error:{code:e.UpdateErrorCode.UNKNOWN_ERROR,message:t instanceof Error?t.message:"Sync failed"}}}}async download(t){const a=this.pluginManager.getDownloadManager(),i=this.pluginManager.getBundleManager();let r;const n=await i.getActiveBundle();if(t.delta&&(null==n?void 0:n.version)===t.delta.fromVersion){const e=await a.loadBlob(n.bundleId),i=await(new G).downloadWithDelta({updateAvailable:!0,version:t.version,bundleUrl:t.url,checksum:t.checksum,size:void 0,delta:{available:!0,patchUrl:t.delta.patchUrl,patchSize:t.delta.patchSize,patchChecksum:t.delta.patchChecksum,targetChecksum:t.delta.targetChecksum}},e?await e.arrayBuffer():null);r=new Blob([i.bundleData],{type:"application/zip"})}else r=await a.downloadWithRetry(t.url,t.version);const o=await r.arrayBuffer();await this.validateBundleData(o,t.checksum,t.signature);const s=new Blob([o],{type:r.type}),l=await a.saveBlob(t.version,s),d={bundleId:t.version,version:t.version,path:l,downloadTime:Date.now(),size:s.size,status:e.BundleStatus.READY,checksum:t.checksum,signature:t.signature,signatureAlgorithm:t.signatureAlgorithm,verified:!0};return await i.saveBundleInfo(d),d}async set(t){const a=this.pluginManager.getBundleManager();if(!t.verified)throw new v(e.ErrorCode.SIGNATURE_INVALID,`Refusing to activate unverified bundle ${t.bundleId}`);await a.setActiveBundle(t.bundleId)}async reload(){"undefined"!=typeof window&&window.location.reload()}async current(){const t=this.pluginManager.getBundleManager(),a=await t.getActiveBundle();if(!a)throw new v(e.ErrorCode.FILE_NOT_FOUND,"No active bundle found");return a}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 i=e.keepVersions;i<a.length;i++)await t.deleteBundle(a[i].bundleId)}}async notifyAppReady(){const t=this.pluginManager.getBundleManager(),a=await t.getActiveBundle();a&&(a.status=e.BundleStatus.ACTIVE,await t.saveBundleInfo(a))}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 i=e.bundlePath.match(/bundles\/([^/]+)\/bundle\.zip$/),r=i?i[1]:e.bundlePath,n=await a.loadBlob(r);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 t,a,i;const r=this.pluginManager.getBundleManager(),n=this.pluginManager.getConfigManager();try{const o=await r.getActiveBundle(),s=(null==o?void 0:o.version)||"1.0.0",l=n.get("baseUrl");if(!l)return{available:!1,currentVersion:s};const d=n.get("apiKey");if(!d)throw new v(e.ErrorCode.INVALID_CONFIG,"apiKey is required when using Laravel backend");const c=n.get("channel")||"production",u=this.getDeviceInfo(s),h=await N(l,{apiKey:d,channel:c,currentVersion:s,deviceId:u.deviceId,platform:u.platform,appVersion:u.appVersion,identity:await this.resolveAppIdentity()});return h.available?{available:!0,currentVersion:s,latestVersion:h.version,url:h.downloadUrl,mandatory:h.mandatory,notes:null!==(t=h.releaseNotes)&&void 0!==t?t:void 0,size:h.size,checksum:h.checksum,signature:null!==(a=h.signature)&&void 0!==a?a:void 0,signatureAlgorithm:h.signature?"RSA-SHA256":void 0,delta:null!==(i=h.delta)&&void 0!==i?i:void 0}:h.held?{available:!1,currentVersion:s,latestVersion:h.version,held:!0,heldMessage:h.message}:{available:!1,currentVersion:s}}catch(t){throw new v(e.ErrorCode.NETWORK_ERROR,t instanceof Error?t.message:"Failed to check for updates")}}async downloadUpdate(t){const a=this.pluginManager.getDownloadManager(),i=this.pluginManager.getBundleManager(),r=this.pluginManager.getEventEmitter();let n;if(!((null==t?void 0:t.url)&&(null==t?void 0:t.version)||(n=await this.checkForUpdate(),n.available&&n.url)))throw new v(e.ErrorCode.UPDATE_NOT_AVAILABLE,"No update available to download");const o=(null==t?void 0:t.url)||(null==n?void 0:n.url)||"",s=(null==t?void 0:t.version)||(null==n?void 0:n.latestVersion)||"",l=(null==t?void 0:t.checksum)||(null==n?void 0:n.checksum)||"",d=(null==t?void 0:t.signature)||(null==n?void 0:n.signature)||"",c=(null==t?void 0:t.signatureAlgorithm)||(null==n?void 0:n.signatureAlgorithm),u=(null==t?void 0:t.delta)||(null==n?void 0:n.delta);if(!o||!s)throw new v(e.ErrorCode.INVALID_CONFIG,"URL and version are required for download");const h=await a.downloadWithRetry(o,s,e=>{r.emit("downloadProgress",e),(null==t?void 0:t.onProgress)&&t.onProgress(e)}),g=await h.arrayBuffer();await this.validateBundleData(g,l,d||void 0);const p=new Blob([g],{type:h.type}),f={bundleId:s,version:s,path:await a.saveBlob(s,p),downloadTime:Date.now(),size:p.size,status:e.BundleStatus.READY,checksum:l,signature:d||void 0,signatureAlgorithm:c,metadata:u?{delta:u}:void 0,verified:!0};return await i.saveBundleInfo(f),f}async applyUpdate(t){const a=this.pluginManager.getBundleManager();let i=t;if(!i){const t=(await a.getAllBundles()).filter(t=>t.status===e.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime);if(0===t.length)throw new v(e.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");i=t[0].bundleId}const r=await a.getBundle(i);if(!r)throw new v(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${i} 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 _(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(t,a,i){const r=this.pluginManager.getSecurityValidator(),n=this.pluginManager.getConfigManager();if(a&&!await r.verifyChecksum(t,a))throw new v(e.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");const o=n.get("requireSignature"),s=n.get("publicKey");if(o){if(!s)throw new v(e.ErrorCode.INVALID_CONFIG,"Signature verification required but publicKey is not configured");if(!i)throw new v(e.ErrorCode.SIGNATURE_INVALID,"Signature verification required but no signature provided");if(!await r.verifySignature(t,i))throw new v(e.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(t){throw new v(e.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 $=t.registerPlugin("NativeUpdate",{web:()=>new H}),K=new Proxy($,{get(t,a,i){if("isInitialized"===a)return async()=>{const e=await t.isInitialized();return"boolean"==typeof e?e:!!(e&&"object"==typeof e&&"initialized"in e&&e.initialized)};if("list"===a)return async()=>{const e=await t.list();return Array.isArray(e)?e:e&&"object"==typeof e&&"bundles"in e&&Array.isArray(e.bundles)?e.bundles:[]};if("setChannel"===a)return e=>t.setChannel({channel:e});if("setUpdateUrl"===a)return e=>t.setUpdateUrl({url:e});if("scheduleBackgroundCheck"===a)return e=>t.scheduleBackgroundCheck({interval:e});if("requestNotificationPermissions"===a)return async()=>{const e=await t.requestNotificationPermissions();return"boolean"==typeof e?e:!!(e&&"object"==typeof e&&"granted"in e&&e.granted)};if("checkForUpdate"===a)return async()=>{const[e,a]=await Promise.all([t.getLatest(),t.current()]);return{available:!0===e.available&&"string"==typeof e.version&&M.compareVersions(e.version,a.version)>0,latestVersion:e.version,currentVersion:a.version,url:e.url,mandatory:e.mandatory,notes:e.notes,size:e.size,checksum:e.checksum,signature:e.signature,signatureAlgorithm:e.signatureAlgorithm,delta:e.delta,held:!0===e.held||void 0,heldMessage:e.heldMessage}};if("downloadUpdate"===a)return async(a={})=>{var i,r,n,o,s,l;const d=a.url&&a.version&&a.checksum?void 0:await t.getLatest(),c=null!==(i=a.url)&&void 0!==i?i:null==d?void 0:d.url,u=null!==(r=a.version)&&void 0!==r?r:null==d?void 0:d.version,h=null!==(n=a.checksum)&&void 0!==n?n:null==d?void 0:d.checksum;if(!c||!u||!h)throw new v(e.ErrorCode.UPDATE_NOT_AVAILABLE,"No downloadable update is available");return t.download({url:c,version:u,checksum:h,signature:null!==(o=a.signature)&&void 0!==o?o:null==d?void 0:d.signature,signatureAlgorithm:null!==(s=a.signatureAlgorithm)&&void 0!==s?s:null==d?void 0:d.signatureAlgorithm,delta:null!==(l=a.delta)&&void 0!==l?l:null==d?void 0:d.delta})};if("applyUpdate"===a)return async a=>{const i=await K.list(),r=a?i.find(e=>e.bundleId===a):i.filter(t=>t.status===e.BundleStatus.READY).sort((e,t)=>t.downloadTime-e.downloadTime)[0];if(!r)throw new v(e.ErrorCode.FILE_NOT_FOUND,"No ready bundle found to apply");await t.set(r),await t.reload()};if("cancelDownload"===a)return e=>t.cancelDownload({bundleId:e});if("isDownloading"===a)return async e=>{const a=await t.isDownloading({bundleId:e});return"boolean"==typeof a?a:!!(a&&"object"==typeof a&&"isDownloading"in a&&a.isDownloading)};if("getActiveDownloadCount"===a)return async()=>{const e=await t.getActiveDownloadCount();return"number"==typeof e?e:e&&"object"==typeof e&&"count"in e&&"number"==typeof e.count?e.count:0};const r=Reflect.get(t,a,i);return"function"==typeof r?r.bind(t):r}});e.BundleManager=b,e.CacheManager=class{constructor(){this.filesystem=null,this.memoryCache=new Map,this.CACHE_DIR="cache",this.logger=m.getInstance(),this.configManager=w.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:a.Directory.Data,recursive:!0})}catch(e){this.logger.debug("Cache directory may already exist",e)}await this.cleanExpiredCache()}async set(e,t,a){const i=Date.now()+(a||this.configManager.get("cacheExpiration")),r={data:t,timestamp:Date.now(),expiry:i};this.memoryCache.set(e,r),this.shouldPersist(t)&&await this.persistToFile(e,r),this.logger.debug("Cache entry set",{key:e,expiry:new Date(i)})}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:a.Directory.Data,recursive:!0}),await this.filesystem.mkdir({path:this.CACHE_DIR,directory:a.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,i]of this.memoryCache)e>=i.expiry&&(this.memoryCache.delete(a),t++);try{const i=await this.filesystem.readdir({path:this.CACHE_DIR,directory:a.Directory.Data});for(const a of i.files){const i=a.name.replace(".json",""),r=await this.loadFromFile(i);(!r||e>=r.expiry)&&(await this.removeFile(i),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 i=await this.filesystem.readdir({path:this.CACHE_DIR,directory:a.Directory.Data});e=i.files.length;for(const e of i.files)t+=(await this.filesystem.stat({path:`${this.CACHE_DIR}/${e.name}`,directory:a.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 i=`${this.CACHE_DIR}/${e}.json`,r=JSON.stringify(t);await this.filesystem.writeFile({path:i,data:r,directory:a.Directory.Data,encoding:a.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`,i=await this.filesystem.readFile({path:t,directory:a.Directory.Data,encoding:a.Encoding.UTF8});return JSON.parse(i.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:a.Directory.Data})}catch(t){this.logger.debug("Failed to remove cache file",{key:e,error:t})}}},e.ConfigManager=w,e.ConfigurationError=class extends v{constructor(t,a){super(e.ErrorCode.INVALID_CONFIG,t,a),this.name="ConfigurationError"}},e.DownloadError=y,e.DownloadManager=U,e.Logger=m,e.NativeUpdate=K,e.NativeUpdateError=v,e.PluginManager=x,e.SecurityValidator=D,e.StorageError=I,e.UpdateErrorClass=A,e.UpdateManager=class{constructor(){this.filesystem=null,this.updateInProgress=!1,this.currentState=null,this.pluginManager=x.getInstance(),this.securityValidator=D.getInstance()}async initialize(){if(this.filesystem=this.pluginManager.getConfigManager().get("filesystem"),!this.filesystem)throw new A(e.ErrorCode.MISSING_DEPENDENCY,"Filesystem not configured")}async applyUpdate(t,a){var i;if(this.updateInProgress)throw new A(e.ErrorCode.UPDATE_FAILED,"Another update is already in progress");const r=this.pluginManager.getLogger(),n=this.pluginManager.getBundleManager();try{this.updateInProgress=!0,r.info("Starting bundle update",{bundleId:t});const o=await n.getBundle(t);if(!o)throw new A(e.ErrorCode.FILE_NOT_FOUND,`Bundle ${t} not found`);if("READY"!==o.status&&"ACTIVE"!==o.status)throw new A(e.ErrorCode.BUNDLE_NOT_READY,`Bundle ${t} is not ready for installation`);const s=await n.getActiveBundle();this.currentState={currentBundle:s,newBundle:o,backupPath:null,startTime:Date.now()},await this.validateUpdate(s,o,a),s&&"default"!==s.bundleId&&(this.currentState.backupPath=await this.createBackup(s)),await this.performUpdate(o),await this.verifyUpdate(o),await n.setActiveBundle(t);const l=this.pluginManager.getVersionManager(),d=this.pluginManager.getConfigManager();if(await l.rememberAppliedVersion(d.get("channel"),o.version),!1!==(null==a?void 0:a.cleanupOldBundles)){const e=null!==(i=null==a?void 0:a.keepBundleCount)&&void 0!==i?i:3;await n.cleanupOldBundles(e)}r.info("Bundle update completed successfully",{bundleId:t,version:o.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(t,a,i){const r=this.pluginManager.getLogger(),n=this.pluginManager.getVersionManager(),o=this.pluginManager.getConfigManager();if(t&&n.shouldBlockDowngrade(t.version,a.version))throw new E(e.ErrorCode.VERSION_DOWNGRADE,`Cannot downgrade from ${t.version} to ${a.version}`);const s=o.get("channel"),l=await n.getMaxSeenVersion(s);if(l&&n.shouldBlockDowngrade(l,a.version))throw new E(e.ErrorCode.VERSION_DOWNGRADE,`Cannot apply ${a.version} - device has previously applied ${l} on channel ${s}`);if(!a.verified){r.warn("Bundle not verified, verifying now",{bundleId:a.bundleId});const t=this.pluginManager.getDownloadManager(),i=await t.loadBlob(a.bundleId);if(!i)throw new A(e.ErrorCode.FILE_NOT_FOUND,"Bundle data not found");const n=await i.arrayBuffer();if(!await this.securityValidator.verifyChecksum(n,a.checksum))throw new E(e.ErrorCode.CHECKSUM_MISMATCH,"Bundle checksum verification failed");if(a.signature&&!await this.securityValidator.verifySignature(n,a.signature))throw new E(e.ErrorCode.SIGNATURE_INVALID,"Bundle signature verification failed");await this.pluginManager.getBundleManager().markBundleAsVerified(a.bundleId)}r.debug("Bundle validation passed",{bundleId:a.bundleId})}async createBackup(t){const i=`backups/${t.bundleId}_${Date.now()}`,r=this.pluginManager.getLogger();try{return await this.filesystem.mkdir({path:i,directory:a.Directory.Data,recursive:!0}),await this.filesystem.copy({from:t.path,to:i,directory:a.Directory.Data}),r.info("Backup created",{bundleId:t.bundleId,backupPath:i}),i}catch(t){throw r.error("Failed to create backup",t),new A(e.ErrorCode.UPDATE_FAILED,"Failed to create backup",void 0,t)}}async performUpdate(t){const i=this.pluginManager.getLogger();try{const e=`active/${t.bundleId}`;await this.filesystem.mkdir({path:e,directory:a.Directory.Data,recursive:!0}),await this.filesystem.copy({from:t.path,to:e,directory:a.Directory.Data}),t.path=e,i.debug("Bundle files installed",{bundleId:t.bundleId,targetPath:e})}catch(t){throw new A(e.ErrorCode.UPDATE_FAILED,"Failed to install bundle files",void 0,t)}}async verifyUpdate(t){try{const e=`${t.path}/index.html`;await this.filesystem.stat({path:e,directory:a.Directory.Data})}catch(t){throw new A(e.ErrorCode.UPDATE_FAILED,"Bundle verification failed after installation",void 0,t)}}async rollback(){var t;if(!this.currentState)throw new A(e.ErrorCode.ROLLBACK_FAILED,"No update state to rollback");const i=this.pluginManager.getLogger();i.warn("Starting rollback",{from:this.currentState.newBundle.bundleId,to:(null===(t=this.currentState.currentBundle)||void 0===t?void 0:t.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:a.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(),i.info("Rollback completed successfully")}catch(t){throw i.error("Rollback failed",t),new A(e.ErrorCode.ROLLBACK_FAILED,"Failed to rollback update",void 0,t)}finally{if(this.currentState.backupPath)try{await this.filesystem.rmdir({path:this.currentState.backupPath,directory:a.Directory.Data,recursive:!0})}catch(e){i.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)}},e.ValidationError=E,e.VersionManager=M,e.compareVersions=_}({},capacitorExports,capacitorFilesystem,capacitorPreferences);
package/docs/CHANGELOG.md CHANGED
@@ -5,14 +5,24 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [5.0.0] - Unreleased
8
+ Entries labelled “development draft” were never published to npm. Published release dates below follow the npm registry, including the corrected 1.0.6, 1.0.7 and 1.4.0 dates.
9
+
10
+ ## [5.0.1] - 2026-12-03
11
+
12
+ ### Fixed
13
+
14
+ - Android reads `plugins.NativeUpdate` from the packaged Capacitor configuration; a later `initialize()` call overrides matching fields. Incomplete native configuration waits for the JavaScript call.
15
+ - Flexible Play updates emit `appUpdateReady` after download and install only when the app calls `completeFlexibleUpdate()` after a user decision. The completion call checks that Play has a downloaded update and reports failures.
16
+ - Reference text now distinguishes emitted error codes from six reserved compatibility values and aligns the licence, package history and examples with the shipped source.
17
+
18
+ ## [5.0.0] - 2026-12-01
9
19
 
10
20
  ### Changed
11
21
 
12
22
  - Require Capacitor 9 peers and build against its current official plugins. The public JavaScript API, signed OTA format, CLI protocol and server contract are unchanged.
13
23
  - Move the Android plugin to AGP 9.4.1, Gradle 9.8.2, compile SDK 37 and min SDK 26. AGP supplies Kotlin; AndroidX Core now uses `androidx.core:core` 1.19.1. R8 consumer rules remain included.
14
24
  - Set the iOS plugin deployment target to 16 and constrain its CocoaPods Capacitor dependency to major 9.
15
- - Prepare the same plugin under `native-update-capacitor` at 5.0.0. See `docs/MIGRATION.md` for the host-app steps.
25
+ - Release the same plugin under `native-update-capacitor` at 5.0.0. See `docs/MIGRATION.md` for the host-app steps.
16
26
 
17
27
  ## [4.4.6] - 2026-11-21
18
28
 
@@ -735,7 +745,7 @@ No runtime behaviour changed for ESM consumers.
735
745
  `docs/tracking/production-readiness-audit-tracker.json`. The flow
736
746
  enters a 7-day cooldown; next allowed re-run 2026-05-18.
737
747
 
738
- ## [3.0.0] - 2026-05-04
748
+ ## 3.0.0 development draft (not published) — 2026-05-04
739
749
 
740
750
  ### Removed (BREAKING)
741
751
  - **Firestore backend.** `backendType: 'firestore'` and the
@@ -941,7 +951,7 @@ No runtime behaviour changed for ESM consumers.
941
951
  - Package updates: Capacitor 8.x, TypeScript 5.9.3, Vitest 4.0.18, ESLint 9.39.2
942
952
  - Node.js engine requirement: >=24.13.0
943
953
 
944
- ## [1.0.7] - 2025-01-15
954
+ ## [1.0.7] - 2025-08-15
945
955
 
946
956
  ### Fixed
947
957
  - **Critical Android Build Issues**:
@@ -955,7 +965,7 @@ No runtime behaviour changed for ESM consumers.
955
965
  - Updated package version to 1.0.7
956
966
  - Hardcoded critical dependency versions in Android build.gradle to prevent resolution issues
957
967
 
958
- ## [1.0.6] - 2025-01-15
968
+ ## [1.0.6] - 2025-08-15
959
969
 
960
970
  ### Fixed
961
971
  - **Android Build Issues**:
@@ -977,7 +987,7 @@ No runtime behaviour changed for ESM consumers.
977
987
  - playReviewVersion: 2.0.1
978
988
  - All dependencies now use proper version variables
979
989
 
980
- ## [1.4.0] - 2025-01-02
990
+ ## [1.4.0] - 2026-01-19
981
991
 
982
992
  ### Added
983
993
 
@@ -1008,7 +1018,7 @@ No runtime behaviour changed for ESM consumers.
1008
1018
  - Proper exclusion of test files in tsconfig
1009
1019
  - Removed console.log statements in favor of Logger
1010
1020
 
1011
- ## [0.0.2] - 2024-12-01
1021
+ ## 0.0.2 development draft (not published)
1012
1022
 
1013
1023
  ### Added
1014
1024
 
@@ -1032,7 +1042,7 @@ No runtime behaviour changed for ESM consumers.
1032
1042
  - Implemented checksum validation
1033
1043
  - Added certificate pinning support
1034
1044
 
1035
- ## [0.0.1] - 2024-01-08
1045
+ ## 0.0.1 development draft (not published)
1036
1046
 
1037
1047
  ### Added
1038
1048
 
@@ -1084,21 +1094,3 @@ No runtime behaviour changed for ESM consumers.
1084
1094
  - ESLint configuration needs update for v9 compatibility
1085
1095
  - Certificate pinning requires manual certificate configuration
1086
1096
  - Delta updates require server-side implementation
1087
-
1088
- ## Future Releases
1089
-
1090
- ### [0.1.0] - Planned
1091
-
1092
- - Add delta update server reference implementation
1093
- - Improve offline update handling
1094
- - Add update scheduling APIs
1095
- - Enhanced progress reporting with ETA
1096
- - Batch update support
1097
-
1098
- ### [0.2.0] - Planned
1099
-
1100
- - Machine learning for optimal update timing
1101
- - Peer-to-peer update distribution
1102
- - Advanced A/B testing framework
1103
- - Custom update UI components
1104
- - Differential compression algorithms
package/docs/MIGRATION.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Migration Guide
2
2
 
3
- ## Upgrading v4 → v5.0.0
3
+ ## Upgrading v4 → v5
4
4
 
5
- v5 targets Capacitor 9 across the JavaScript, Android and iOS plugin. Install `native-update@^5.0.0` or its identical `native-update-capacitor@^5.0.0` alias together with Capacitor 9 core and the Capacitor App, Device, Filesystem and Preferences plugins. Rebuild the native shell; a web-only update cannot replace Capacitor 8 native code. Node 24+, Java 21, Android min SDK 26/compile SDK 37 with AGP 9.4.1, and iOS 16+ are required. The host app follows the [Capacitor 9 app migration](https://capacitorjs.com/docs/updating/9-0), including Cordova-module cleanup, Gradle 9.8.2 and R8 release verification. The plugin's JS API, signed bundle format, rollback rules and server contract are unchanged.
5
+ v5 targets Capacitor 9 across the JavaScript, Android and iOS plugin. Install `native-update@^5.0.1` or its identical `native-update-capacitor@^5.0.1` alias together with Capacitor 9 core and the Capacitor App, Device, Filesystem and Preferences plugins. Rebuild the native shell; a web-only update cannot replace Capacitor 8 native code. Node 24+, Java 21, Android min SDK 26/compile SDK 37 with AGP 9.4.1, and iOS 16+ are required. The host app follows the [Capacitor 9 app migration](https://capacitorjs.com/docs/updating/9-0), including Cordova-module cleanup, Gradle 9.8.2 and R8 release verification. The plugin's JS API, signed bundle format, rollback rules and server contract are unchanged.
6
6
 
7
7
  For apps with Kotlin plugins, remove standalone Kotlin Gradle plugin declarations; AGP 9 provides Kotlin. For apps with no Cordova plugins, remove old unconditional Cordova module references before `cap sync`. Verify a debug launch and an R8-shrunk release build, plus an OTA apply and cold-start rollback on a test device. The iOS plugin now requires Capacitor 9 and iOS 16; validate it with Xcode 27 on a Mac.
8
8
 
@@ -25,6 +25,7 @@ GET {serverUrl}/v1/updates/check?channel={production|staging|development}
25
25
  | `X-App-Version` | when known | The native binary's version name. Used by `minNativeVersion`. |
26
26
  | `X-Client-Sdk` | yes, new SDKs | `capacitor` · `android` · `flutter` · `react-native` · `ios` |
27
27
  | `X-Sdk-Version` | yes, new SDKs | The SDK's own version, `[0-9A-Za-z.+-]{1,32}` |
28
+ | `Accept-Language` | when available | The device or browser language for translated server messages. The server falls back to English when a catalogue is unavailable. |
28
29
  | `X-Accept-Payload` | new SDKs | Comma-separated payload types the client can apply; Flutter adds `dart_aot` to receive code updates |
29
30
  | `X-Runtime-Key` | Flutter code updates | SHA-256 (lowercase hex) of the running `libflutter.so` |
30
31
  | `X-Android-Package` | Android | applicationId, for per-key client restrictions |
@@ -20,7 +20,7 @@ class LiveUpdatePlugin: @unchecked Sendable {
20
20
  // (crash-loop auto-rollback) defenses. Mirrors the Android constants
21
21
  // in LiveUpdatePlugin.kt so the two platforms stay in lockstep.
22
22
  /// This plugin's version, sent as X-Sdk-Version. Kept equal to package.json by tests/sdk-version.test.ts.
23
- static let sdkVersion = "5.0.0"
23
+ static let sdkVersion = "5.0.1"
24
24
  private static let activeBundleKey = "native_update_active_bundle"
25
25
  private static let previousBundleKey = "native_update_previous_active_bundle"
26
26
  private static let pendingBundleKey = "native_update_pending_verify_bundle"
@@ -516,6 +516,7 @@ class LiveUpdatePlugin: @unchecked Sendable {
516
516
  // SDK identity: the server offers this WebView only web bundles (docs/protocol/CLIENT-PROTOCOL.md).
517
517
  request.setValue("capacitor", forHTTPHeaderField: "X-Client-Sdk")
518
518
  request.setValue(LiveUpdatePlugin.sdkVersion, forHTTPHeaderField: "X-Sdk-Version")
519
+ request.setValue(Locale.current.identifier.replacingOccurrences(of: "_", with: "-"), forHTTPHeaderField: "Accept-Language")
519
520
  // App-identity header for API-key client restrictions (bundle id only;
520
521
  // team id is intentionally not sent by the plugin).
521
522
  if let bundleId = Bundle.main.bundleIdentifier {
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "native-update-capacitor",
3
- "version": "5.0.0",
3
+ "version": "5.0.1",
4
4
  "packageManager": "yarn@4.18.1",
5
5
  "engines": {
6
6
  "node": ">=24.16.0"
7
7
  },
8
- "description": "The Native Update Capacitor plugin under its framework name. Identical to native-update 5.0.0: signed OTA updates, in-app update and in-app review.",
8
+ "description": "The Native Update Capacitor plugin under its framework name. Identical to native-update 5.0.1: signed OTA updates, in-app update and in-app review.",
9
9
  "type": "module",
10
10
  "main": "dist/plugin.cjs",
11
11
  "module": "dist/esm/index.js",