function l(n){let e=new URL(n,window.skinRoot).href,t=S.get(e);return t||(t=b(e),S.set(e,t)),t}async function b(n){let e=await(await fetch(n)).text(),t=new CSSStyleSheet;return t.replaceSync(e.replaceAll('url("./','url("'+window.skinRoot)),t}var S=new Map;var c=(a=>(a.newResourceState="newResourceState",a.cacheDownloadFinished="cacheDownloadFinished",a.cacheDownloadSizeAlert="cacheDownloadSizeAlert",a.cacheDownloadProgress="cacheDownloadProgress",a.cachesCleared="cachesCleared",a.appSize="appSize",a.isCacheable="isCacheable",a.pwaState="pwaState",a.redirect="redirect",a))(c||{});var w=class extends EventTarget{constructor(e){super(),this.worker=e}init(){this.postMessage({type:"syncResourceState",url:window.location.href})}postMessage(e,t){let o=new MessageChannel;o.port1.onmessage=i=>{this.onMessage(i)},e.url=window.location.href,(t||this.worker).postMessage(e,[o.port2])}onMessage(e){e.data?.type in c&&this.dispatchEvent(new CustomEvent(e.data.type,{detail:e.data}))}},y=await navigator.serviceWorker.ready;window.swClient=new w(y.active);window.addEventListener("load",()=>r().init());function r(){return window.swClient}var h={online:"Ressource issue du serveur",loading:"Chargement",downloadingCaches:n=>`Téléchargement en cours : ${n}%`,synchronized:"Ressource hors-ligne à jour",newVersionAvailable:"Nouvelle version disponible",distantNotFound:"Ressource distante inaccessible (erreur 404)",unknownUpdateState:"État de mise à jour inconnu",download:"Télécharger",authenticate:"S\'authentifier",close:"Fermer"},f={newVersionAvailable:"Télécharger",notAuthenticatedRedirectedToLogin:"S\'authentifier",notAuthenticatedError:"Voir la page d\'erreur (nouvel onglet)",forbiddenAccessError:"Voir la page d\'erreur (nouvel onglet)",unknownState:"Ouvrir la ressource en ligne (nouvel onglet)"},v={online:"La ressource affichée est issue du serveur.",loading:"Chargement en cours...",downloadingCaches:"Téléchargement en cours...",noNetwork:"État de mise à jour inconnu : impossible de se connecter au serveur.",synchronized:"Ressource hors-ligne à jour : vous consultez la dernière version mise en ligne.",newVersionAvailable:"Une nouvelle version de la ressource est disponible. Voulez-vous la télécharger ?",distantNotFound:"Ressource distante inaccessible (erreur 404) : si vous supprimez l\'accès hors-ligne, vous ne pourrez plus consulter cette ressource.",notAuthenticatedRedirectedToLogin:"État de mise à jour inconnu : vous devez vous reconnecter au serveur pour déterminer si une mise à jour est disponible.",notAuthenticatedError:"État de mise à jour inconnu : vous n\'êtes pas connecté au serveur (erreur 401).",forbiddenAccessError:"État de mise à jour inconnu : vous n\'êtes pas autorisé par le serveur à consulter la ressource en ligne (erreur 403).",unknownState:"État de mise à jour inconnu : consultez la ressource en ligne pour déterminer si une mise à jour est disponible.",unexpectedError:"État de mise à jour inconnu : une erreur est survenue."},p=class extends HTMLElement{async connectedCallback(){this.noLabel=this.hasAttribute("noLabel")&&this.getAttribute("noLabel")!=="false",this.noOnlineStatus=this.hasAttribute("noOnlineStatus")&&this.getAttribute("noOnlineStatus")!=="false",this.swClient=r(),this.attachShadow({mode:"open"}),this.shadowRoot?.adoptedStyleSheets.push(await l("./pwa/components.css")),this.shadowRoot.innerHTML=`
			<div id="status">
				<span id="status-message"></span>
			</div>
			<div id="popup" hidden>
				<div id="popup-arrow"></div>
				<div id="popup-content"></div>
			</div>
		`,this.changeStatus("loading"),this.swClient.addEventListener("newResourceState",e=>{this.changeStatus(e.detail.text),this.updatePopupContent(e.detail.text)}),this.swClient.addEventListener("cacheDownloadProgress",e=>{this.updateProgress(e.detail.progress)}),this.swClient.addEventListener("cacheDownloadFinished",e=>{this.progress=null}),this.shadowRoot.querySelector("#status")?.addEventListener("click",()=>{let e=this.shadowRoot.querySelector("#popup");e.hasAttribute("hidden")?e.removeAttribute("hidden"):e.setAttribute("hidden","")}),this.swClient.init()}changeStatus(e,t){let o=this.shadowRoot?.querySelector("#status"),i=o.querySelector("#status-message");if(this.noOnlineStatus&&e==="online"?o.setAttribute("hidden",""):o.removeAttribute("hidden"),t){let d=t.value/t.total*100;d>100&&(d=100),this.noLabel||(i.textContent=h.downloadingCaches(d.toFixed(0))),o.title=v.downloadingCaches}else this.noLabel||(i.textContent=h[e]||h.unknownUpdateState),o.title=v[e];o.className=e}updateProgress(e){this.progress={total:e.total||this.progress.total,value:this.progress?.value?this.progress.value+e.value:e.value},this.changeStatus("downloadingCaches",this.progress)}updatePopupContent(e){let t=this.shadowRoot.querySelector("#popup-content");t.innerHTML=`
			<p>${v[e]}</p>
			<div id="popup-controls">
				<button id="popup-action" hidden></button>
				<button id="popup-close">${h.close}</button>
			</div>
		`;let o=t.querySelector("#popup-action");e==="newVersionAvailable"?(o.addEventListener("click",()=>{this.swClient.postMessage({type:"downloadAllCaches"}),this.shadowRoot?.querySelector("#popup")?.setAttribute("hidden","")}),o.innerHTML=f[e],o.removeAttribute("hidden")):(e==="notAuthenticatedRedirectedToLogin"||e==="notAuthenticatedError"||e==="forbiddenAccessError"||e==="unknownState")&&(o.addEventListener("click",()=>{this.shadowRoot?.querySelector("#popup")?.setAttribute("hidden",""),this.swClient.addEventListener("redirect",i=>{i.detail?.newTab?window.open(i.detail?.url,"_blank"):window.location.href=i.detail?.url},{once:!0}),this.swClient.postMessage({type:"authenticate",url:window.location.href})}),o.innerHTML=f[e],o.removeAttribute("hidden")),t.querySelector("#popup-close")?.addEventListener("click",()=>{this.shadowRoot?.querySelector("#popup")?.setAttribute("hidden","")})}};customElements.define("pwa-indicator",p);var s={downloadSizeAlertMb:n=>`Le poids des contenus à télécharger est de ${n}Mo.<br/>Confirmez-vous le téléchargement ?`,downloadSizeAlertGb:n=>`Le poids des contenus à télécharger est de ${n}Go.<br/>Confirmez-vous le téléchargement ?`,downloadSuccess:"La ressource a été téléchargée et peut maintenant être consultée hors-ligne.",downloadFailed:"Le téléchargement a échoué.",clearCachesAlert:"La ressource est actuellement accessible hors ligne",cachesCleared:"Accès hors-ligne supprimé. La ressource doit maintenant être consultée en ligne.",yes:"Oui",no:"Non",downloadCaches:"Télécharger la ressource pour consultation hors-ligne",clearCaches:"Supprimer l\'accès hors-ligne à la ressource",close:"Fermer"},C={downloadCaches:`
        <button id="btn-download-cache" title="${s.downloadCaches}"></button>
    `,clearCaches:`<button id="btn-clear-cache" title="${s.clearCaches}"></button>
    `},u=class extends HTMLElement{async connectedCallback(){this.attachShadow({mode:"open"}),this.shadowRoot?.adoptedStyleSheets.push(await l("./pwa/components.css")),this.shadowRoot.innerHTML=`
            <div id="cache-controls"></div>
            <dialog id="cache-dialog">
                <p id="cache-dialog-message"></p>
                <div id="cache-dialog-controls"></div>
            </dialog>
        `,this.swClient=r(),this.addEventListeners(),this.swClient.postMessage({type:"getIsCacheable"})}addEventListeners(){window.addEventListener("appinstalled",async()=>{this.toggleToHiddenState(),this.swClient.postMessage({type:"downloadAllCaches",usersFullConsent:!0})}),this.swClient.addEventListener("isCacheable",async e=>{e.detail?.cacheable?(this.swClient.postMessage({type:"getPWAState"}),this.swClient.addEventListener("pwaState",async t=>{let o=t.detail.pwaState;o.pwaInstalled?this.toggleToHiddenState():o.cachesDownloaded?this.toggleToOfflineState():this.toggleToOnlineState()},{once:!0})):this.toggleToHiddenState()},{once:!0}),this.swClient.addEventListener("cacheDownloadSizeAlert",e=>{this.showDownloadSizeAlert(e.detail?.appSize)}),this.swClient.addEventListener("cacheDownloadFinished",async e=>{e.detail?.success?(this.swClient.postMessage({type:"getPWAState"}),this.swClient.addEventListener("pwaState",async t=>{t.detail.pwaState.pwaInstalled||this.toggleToOfflineState(),this.showInformativeAlert(s.downloadSuccess)},{once:!0})):this.showInformativeAlert(s.downloadFailed)}),this.swClient.addEventListener("cachesCleared",async()=>{this.toggleToOnlineState(),this.showInformativeAlert(s.cachesCleared)})}toggleToOnlineState(){this.shadowRoot.querySelector("#cache-controls").innerHTML=C.downloadCaches,this.shadowRoot.querySelector("#btn-download-cache")?.addEventListener("click",()=>this.downloadCaches(!1))}toggleToOfflineState(){this.shadowRoot.querySelector("#cache-controls").innerHTML=C.clearCaches,this.shadowRoot.querySelector("#btn-clear-cache")?.addEventListener("click",()=>this.showClearCachesAlert())}toggleToHiddenState(){this.shadowRoot.querySelector("#cache-controls").replaceChildren()}downloadCaches(e){this.swClient.postMessage({type:"downloadAllCaches",usersFullConsent:e})}clearCaches(){this.swClient.postMessage({type:"clearAllCaches"})}showClearCachesAlert(){let e=this.shadowRoot.querySelector("#cache-dialog");e.querySelector("#cache-dialog-message").innerHTML=s.clearCachesAlert,e.querySelector("#cache-dialog-controls").innerHTML=`
            <button id="consent-yes">${s.clearCaches}</button>
            <button id="consent-no">${s.close}</button>
        `,e.querySelector("#consent-yes")?.addEventListener("click",()=>{this.clearCaches(),e.close()}),e.querySelector("#consent-no")?.addEventListener("click",()=>e.close()),e.showModal()}showDownloadSizeAlert(e){let t=this.shadowRoot.querySelector("#cache-dialog"),o;e>=1e9?o=s.downloadSizeAlertGb((e/1e9).toFixed(2)):o=s.downloadSizeAlertMb((e/1e6).toFixed(2)),t.querySelector("#cache-dialog-message").innerHTML=o,t.querySelector("#cache-dialog-controls").innerHTML=`
            <button id="consent-yes">${s.yes}</button>
            <button id="consent-no">${s.no}</button>
        `,t.querySelector("#consent-yes")?.addEventListener("click",()=>{this.downloadCaches(!0),t.close()}),t.querySelector("#consent-no")?.addEventListener("click",()=>t.close()),t.showModal()}showInformativeAlert(e){let t=this.shadowRoot.querySelector("#cache-dialog");t.querySelector("#cache-dialog-message").textContent=e,t.querySelector("#cache-dialog-controls").innerHTML=`
            <button id="close-dialog">${s.close}</button>
        `,t.querySelector("#close-dialog")?.addEventListener("click",()=>t.close()),t.showModal()}};customElements.define("pwa-cache-controller",u);var A={installApp:"Installer comme une application"},g=class extends HTMLElement{constructor(){super(...arguments);this.installPrompt=null}async connectedCallback(){this.attachShadow({mode:"open"}),this.shadowRoot?.adoptedStyleSheets.push(await l("./pwa/components.css")),this.shadowRoot.innerHTML=`
            <div id="install-controls"></div>
            <dialog id="install-dialog"></dialog>
        `,this.swClient=r(),this.addEventListeners()}addEventListeners(){window.addEventListener("beforeinstallprompt",async t=>{t.preventDefault(),this.installPrompt=t,this.swClient.postMessage({type:"beforeInstallPromptEvent"}),this.swClient.postMessage({type:"getIsCacheable"})}),window.addEventListener("appinstalled",async()=>{this.installPrompt=null,this.shadowRoot.querySelector("#install-controls")?.replaceChildren(),this.swClient.postMessage({type:"appInstalledEvent"})}),this.swClient.addEventListener("isCacheable",async t=>{this.swClient.postMessage({type:"getPWAState"});let o=t.detail?.cacheable;this.swClient.addEventListener("pwaState",async i=>{let d=i.detail.pwaState;o&&this.installPrompt&&!d.pwaInstalled&&navigator.onLine&&this.showInstallButton()},{once:!0})})}showInstallButton(){this.shadowRoot.querySelector("#install-controls").innerHTML=`
             <button id="btn-install-app" title="${A.installApp}"></button>
        `,this.shadowRoot.querySelector("#btn-install-app").addEventListener("click",async()=>{this.installPrompt&&(await this.installPrompt.prompt(),this.installPrompt.userChoice.then(o=>{o.outcome==="accepted"&&this.shadowRoot.querySelector("#btn-install-app")?.setAttribute("hidden","")}),this.installPrompt=null)})}};customElements.define("pwa-install-controller",g);export{u as PWACacheController,p as PWAIndicator,g as PWAInstallController};
