/* PWA v0.2-alpha3-front */


/* Source wp-base-config: */
!function(){"use strict";try{self["workbox:sw:4.0.0-beta.2"]&&_()}catch(t){}const t="https://storage.googleapis.com/workbox-cdn/releases/4.0.0-beta.2",e={backgroundSync:"background-sync",broadcastUpdate:"broadcast-cache-update",cacheableResponse:"cacheable-response",core:"core",expiration:"cache-expiration",googleAnalytics:"offline-ga",navigationPreload:"navigation-preload",precaching:"precaching",rangeRequests:"range-requests",routing:"routing",strategies:"strategies",streams:"streams"};self.workbox=new class{constructor(){return this.v={},this.t={debug:"localhost"===self.location.hostname,modulePathPrefix:null,modulePathCb:null},this.e=this.t.debug?"dev":"prod",this.s=!1,new Proxy(this,{get(t,s){if(t[s])return t[s];const o=e[s];return o&&t.loadModule(`workbox-${o}`),t[s]}})}setConfig(t={}){if(this.s)throw new Error("Config must be set before accessing workbox.* modules");Object.assign(this.t,t),this.e=this.t.debug?"dev":"prod"}loadModule(t){const e=this.o(t);try{importScripts(e),this.s=!0}catch(s){throw console.error(`Unable to import module '${t}' from '${e}'.`),s}}o(e){if(this.t.modulePathCb)return this.t.modulePathCb(e,this.t.debug);let s=[t];const o=`${e}.${this.e}.js`,r=this.t.modulePathPrefix;return r&&""===(s=r.split("/"))[s.length-1]&&s.splice(s.length-1,1),s.push(o),s.join("/")}}}();


workbox.setConfig( {
    "debug": false,
    "modulePathPrefix": "https://techjourney.net/plugins/pwa/wp-includes/js/workbox/"
} );
workbox.core.setCacheNameDetails( {
    "prefix": "wp-/",
    "precache": "precache-front",
    "suffix": "v1"
} );
workbox.core.skipWaiting();
workbox.navigationPreload.disable();
/* global workbox */

/**
 * Handle registering caching strategies.
 */

if ( ! self.wp ) {
	self.wp = {};
}

wp.serviceWorker = workbox;

// Skip the waiting phase for the Service Worker.
self.addEventListener( 'message', function ( event ) {
	if ( 'skipWaiting' === event.data.action ) {
		self.skipWaiting();
	}
} );


/* Source wp-precaching-routes: */


// IIFE is used for lexical scoping instead of just a braces block due to bug in Safari.
( () => {
	wp.serviceWorker.precaching.precache( [
    {
        "url": "https://techjourney.net/?wp_error_template=offline",
        "revision": "0.2-alpha3;Avada=5.9;tj=;user=0;options=f99b33725d8d8bdbab774bbca65fa96c;nav=c26dc0f669f2db6a1656f4e3f24ad82f;deps=f3059399a711eaf14721fd141a3c0a92;00811ad48302206ce5095a18c788e573"
    },
    {
        "url": "https://techjourney.net/?wp_error_template=500",
        "revision": "0.2-alpha3;Avada=5.9;tj=;user=0;options=f99b33725d8d8bdbab774bbca65fa96c;nav=c26dc0f669f2db6a1656f4e3f24ad82f;deps=f3059399a711eaf14721fd141a3c0a92;aab940b32831c27e0a4cc0bd2119108b"
    }
] );

	// @todo Should not these parameters be specific to each entry as opposed to all entries?
	// @todo Should not the strategy be tied to each entry as well?
	// @todo Use networkFirst instead of cacheFirst when WP_DEBUG.
	wp.serviceWorker.precaching.addRoute( {
		ignoreUrlParametersMatching: [
			/^utm_/,
			/^wp-mce-/,
			/^ver$/
		]
		// @todo Add urlManipulation which allows for the list of ignoreUrlParametersMatching to be supplied with each entry.
	} );
} )();


/* Source wp-offline-commenting: */


// IIFE is used for lexical scoping instead of just a braces block due to bug with const in Safari.
( () => {
	const queue = new wp.serviceWorker.backgroundSync.Queue( 'wpPendingComments' );
	const errorMessages = {
    "default": "Please check your internet connection, and try again.",
    "error": "Something prevented the page from being rendered. Please try again.",
    "comment": "Your comment will be submitted once you are back online!"
};

	const commentHandler = ( { event } ) => {

		const clone = event.request.clone();
		return fetch( event.request )
			.then( ( response ) => {
				if ( response.status < 500 ) {
					return response;
				}

				// @todo This is duplicated with code in service-worker-navigation-routing.js.
				return response.text().then( function( errorText ) {
					return caches.match( wp.serviceWorker.precaching.getCacheKeyForURL( "https://techjourney.net/?wp_error_template=500" ) ).then( function( errorResponse ) {

						if ( ! errorResponse ) {
							return response;
						}

						return errorResponse.text().then( function( text ) {
							let init = {
								status: errorResponse.status,
								statusText: errorResponse.statusText,
								headers: errorResponse.headers
							};

							let body = text.replace( /<!--WP_SERVICE_WORKER_ERROR_MESSAGE-->/, errorMessages.error );
							body = body.replace(
								/(<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_BEGIN-->)((?:.|\n)+?)(<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_END-->)/,
								( details ) => {
									if ( ! errorText ) {
										return ''; // Remove the details from the document entirely.
									}
									const src = 'data:text/html;base64,' + btoa( errorText ); // The errorText encoded as a text/html data URL.
									const srcdoc = errorText
										.replace( /&/g, '&amp;' )
										.replace( /'/g, '&#39;' )
										.replace( /"/g, '&quot;' )
										.replace( /</g, '&lt;' )
										.replace( />/g, '&gt;' );
									const iframe = `<iframe style="width:100%" src="${src}"  srcdoc="${srcdoc}"></iframe>`;
									details = details.replace( '{{{error_details_iframe}}}', iframe );
									// The following are in case the user wants to include the <iframe> in the template.
									details = details.replace( '{{{iframe_src}}}', src );
									details = details.replace( '{{{iframe_srcdoc}}}', srcdoc );

									// Replace the comments.
									details = details.replace( '<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_BEGIN-->', '' );
									details = details.replace( '<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_END-->', '' );
									return details;
								}
							);

							return new Response( body, init );
						} );
					} );
				} );
			} )
			.catch( () => {
				const bodyPromise = clone.blob();
				bodyPromise.then(
					function( body ) {
						const request = event.request;
						const req = new Request( request.url, {
							method: request.method,
							headers: request.headers,
							mode: 'same-origin',
							credentials: request.credentials,
							referrer: request.referrer,
							redirect: 'manual',
							body: body
						} );

						// Add request to queue.
						queue.pushRequest( {
							request: req 
						} );
					}
				);

				// @todo This is duplicated with code in service-worker-navigation-routing.js.
				return caches.match( wp.serviceWorker.precaching.getCacheKeyForURL( "https://techjourney.net/?wp_error_template=offline" ) ).then( function( response ) {

					return response.text().then( function( text ) {
						let init = {
							status: response.status,
							statusText: response.statusText,
							headers: response.headers
						};

						const body = text.replace( /<!--WP_SERVICE_WORKER_ERROR_MESSAGE-->/, errorMessages.comment );

						return new Response( body, init );
					} );
				} );
			} );
	};

	wp.serviceWorker.routing.registerRoute(
		/\/wp-comments-post\.php$/,
		commentHandler,
		'POST'
	);
} )();


/* Source wp-navigation-routing: */


// IIFE is used for lexical scoping instead of just a braces block due to bug with const in Safari.
( () => {
	const isStreamingResponses = false && wp.serviceWorker.streams.isSupported();
	const errorMessages = {
    "default": "Please check your internet connection, and try again.",
    "error": "Something prevented the page from being rendered. Please try again.",
    "comment": "Your comment will be submitted once you are back online!"
};
	const navigationRouteEntry = {
    "url": null,
    "revision": "0.2-alpha3;Avada=5.9;tj=;user=0;options=f99b33725d8d8bdbab774bbca65fa96c;nav=c26dc0f669f2db6a1656f4e3f24ad82f;deps=f3059399a711eaf14721fd141a3c0a92"
};

	/**
	 * Handle navigation request.
	 *
	 * @param event Event.
	 * @return {Promise<Response>} Response.
	 */
	async function handleNavigationRequest( { event } ) {
		let responsePreloaded = false;

		const canStreamResponse = () => {
			return isStreamingResponses && ! responsePreloaded;
		};

		const handleResponse = ( response ) => {
			if ( response.status < 500 ) {
				if ( response.redirected && canStreamResponse() ) {
					const redirectedUrl = new URL( response.url );
					redirectedUrl.searchParams.delete( "wp_stream_fragment" );
					const script = `
						<script id="wp-stream-fragment-replace-state">
						history.replaceState( {}, '', ${ JSON.stringify( redirectedUrl.toString() ) } );
						document.getElementById( 'wp-stream-fragment-replace-state' ).remove();
						</script>
					`;
					return response.text().then( ( body ) => {
						return new Response( script + body );
					} );
				} else {
					return response;
				}
			}

			if ( canStreamResponse() ) {
				return caches.match( wp.serviceWorker.precaching.getCacheKeyForURL( "https://techjourney.net/?wp_error_template=500&wp_stream_fragment=body" ) );
			}

			const originalResponse = response.clone();
			return response.text().then( function( responseBody ) {

				// Prevent serving custom error template if WordPress is already responding with a valid error page (e.g. via wp_die()).
				if ( -1 !== responseBody.indexOf( '</html>' ) ) {
					return originalResponse;
				}

				return caches.match( wp.serviceWorker.precaching.getCacheKeyForURL( "https://techjourney.net/?wp_error_template=500" ) ).then( function( errorResponse ) {

					if ( ! errorResponse ) {
						return response;
					}

					return errorResponse.text().then( function( text ) {
						let init = {
							status: errorResponse.status,
							statusText: errorResponse.statusText,
							headers: errorResponse.headers
						};

						let body = text.replace( /<!--WP_SERVICE_WORKER_ERROR_MESSAGE-->/, errorMessages.error );
						body = body.replace(
							/(<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_BEGIN-->)((?:.|\n)+?)(<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_END-->)/,
							( details ) => {
								if ( ! responseBody ) {
									return ''; // Remove the details from the document entirely.
								}
								const src = 'data:text/html;base64,' + btoa( responseBody ); // The errorText encoded as a text/html data URL.
								const srcdoc = responseBody
									.replace( /&/g, '&amp;' )
									.replace( /'/g, '&#39;' )
									.replace( /"/g, '&quot;' )
									.replace( /</g, '&lt;' )
									.replace( />/g, '&gt;' );
								const iframe = `<iframe style="width:100%" src="${src}" data-srcdoc="${srcdoc}"></iframe>`;
								details = details.replace( '{{{error_details_iframe}}}', iframe );
								// The following are in case the user wants to include the <iframe> in the template.
								details = details.replace( '{{{iframe_src}}}', src );
								details = details.replace( '{{{iframe_srcdoc}}}', srcdoc );

								// Replace the comments.
								details = details.replace( '<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_BEGIN-->', '' );
								details = details.replace( '<!--WP_SERVICE_WORKER_ERROR_TEMPLATE_END-->', '' );
								return details;
							}
						);

						return new Response( body, init );
					} );
				} );
			} );
		};

		const sendOfflineResponse = () => {
			if ( canStreamResponse() ) {
				return caches.match( wp.serviceWorker.precaching.getCacheKeyForURL( "https://techjourney.net/?wp_error_template=offline&wp_stream_fragment=body" ) );
			}

			return caches.match( wp.serviceWorker.precaching.getCacheKeyForURL( "https://techjourney.net/?wp_error_template=offline" ) ).then( function( response ) {
				return response.text().then( function( text ) {
					let init = {
						status: response.status,
						statusText: response.statusText,
						headers: response.headers
					};

					const body = text.replace( /<!--WP_SERVICE_WORKER_ERROR_MESSAGE-->/, errorMessages.default );

					return new Response( body, init );
				} );
			} );
		};

		/*
		 * If navigation preload is enabled, use the preload request instead of doing another fetch.
		 * This prevents requests from being duplicated. See <https://github.com/xwp/pwa-wp/issues/67>.
		 */
		if ( event.preloadResponse ) {
			try {
				const response = await event.preloadResponse;
				if ( response ) {
					responsePreloaded = true;
					return handleResponse( response );
				}
			} catch ( error ) {
				responsePreloaded = true;
				return sendOfflineResponse();
			}
		}

		const navigationCacheStrategy = new wp.serviceWorker.strategies[ "NetworkOnly" ]( ( function() {const strategyArgs = {};strategyArgs.plugins = [];return strategyArgs;} )() );

		if ( canStreamResponse() ) {
			const streamHeaderFragmentURL = null;
			const precacheStrategy = new wp.serviceWorker.strategies.cacheFirst({
				cacheName: wp.serviceWorker.core.cacheNames.precache,
			});

			const url = new URL( event.request.url );
			url.searchParams.append( "wp_stream_fragment", 'body' );
			const init = {
				mode: 'same-origin'
			};
			const copiedProps = [
				'method',
				'headers',
				'credentials',
				'cache',
				'redirect',
				'referrer',
				'integrity',
			];
			for ( const initProp of copiedProps ) {
				init[ initProp ] = event.request[ initProp ];
			}
			const request = new Request( url.toString(), init );
			const stream = wp.serviceWorker.streams.concatenateToResponse([
				precacheStrategy.makeRequest({ request: streamHeaderFragmentURL }),
				navigationCacheStrategy.makeRequest( { request } )
					.then( handleResponse )
					.catch( sendOfflineResponse ),
			]);

			return stream.response;
		} else {
			return navigationCacheStrategy.makeRequest( { request: event.request } )
				.then( handleResponse )
				.catch( sendOfflineResponse );
		}
	}

	const blacklist = [
    "^\\/wp\\-admin($|\\?.*|/.*)",
    "[^\\?]*.\\.php($|\\?.*)",
    ".*\\?(.*&)?(wp_stream_fragment|wp_service_worker)=",
    "[^\\?]*\\/feed\\/(\\w+\\/)?$",
    "\\?(.+&)*wp_customize=",
    "\\?(.+&)*customize_changeset_uuid=",
    "^\\/wp\\-json\\/.*"
].map( ( pattern ) => new RegExp( pattern ) );
	if ( navigationRouteEntry && navigationRouteEntry.url ) {
		wp.serviceWorker.routing.registerNavigationRoute(
			navigationRouteEntry.url,
			{ blacklist }
		);

		class FetchNavigationRoute extends wp.serviceWorker.routing.Route {
			/**
			 * If both `blacklist` and `whitelist` are provided, the `blacklist` will
			 * take precedence and the request will not match this route.
			 *
			 * @inheritDoc
			 */
			constructor(handler, {
				whitelist = [/./],
				blacklist = []
			} = {}) {
				super(options => this._match(options), handler);
				this._whitelist = whitelist;
				this._blacklist = blacklist;
			}

			/**
			 * Routes match handler.
			 *
			 * @param {Object} options
			 * @param {URL} options.url
			 * @param {Request} options.request
			 * @return {boolean}
			 *
			 * @private
			 */
			_match({ url, request }) {
				// This replaces checking for navigate in NavigationRoute, which looks for 'navigate' instead.
				if ( request.mode !== 'same-origin' ) {
					return false;
				}

				const pathnameAndSearch = url.pathname + url.search;
				for (const regExp of this._blacklist) {
					if (regExp.test(pathnameAndSearch)) {
						return false;
					}
				}

				return this._whitelist.some(regExp => regExp.test(pathnameAndSearch));
			}
		}

		wp.serviceWorker.routing.registerRoute(
			new FetchNavigationRoute(
				handleNavigationRequest,
				{ blacklist }
			)
		);
	} else {
		wp.serviceWorker.routing.registerRoute( new wp.serviceWorker.routing.NavigationRoute(
			handleNavigationRequest,
			{ blacklist }
		) );
	}
} )();

// Add fallback network-only navigation route to ensure preloadResponse is used if available.
wp.serviceWorker.routing.registerRoute( new wp.serviceWorker.routing.NavigationRoute(
	new wp.serviceWorker.strategies.NetworkOnly(),
	{
		whitelist: [
    "^\\/wp\\-admin($|\\?.*|/.*)",
    "[^\\?]*.\\.php($|\\?.*)",
    ".*\\?(.*&)?(wp_stream_fragment|wp_service_worker)=",
    "[^\\?]*\\/feed\\/(\\w+\\/)?$",
    "\\?(.+&)*wp_customize=",
    "\\?(.+&)*customize_changeset_uuid=",
    "^\\/wp\\-json\\/.*"
].map( ( pattern ) => new RegExp( pattern ) )
	}
) );


/* Source wp-caching-routes: */
wp.serviceWorker.routing.registerRoute( new RegExp( "^https\\:\\/\\/.*\\.(?:png|gif|jpg|jpeg|svg|webp)(\\?.*)?$" ), new wp.serviceWorker.strategies[ "CacheFirst" ]( ( function() {const strategyArgs = {
    "cacheName": "fusion_all_images"
};strategyArgs.plugins = [new wp.serviceWorker[ "expiration" ].Plugin( {
    "maxEntries": 60,
    "maxAgeSeconds": 2592000,
    "purgeOnQuotaError": true
} )];return strategyArgs;} )() ) );wp.serviceWorker.routing.registerRoute( new RegExp( "(^https\\:\\/\\/.*(?:googleapis|gstatic)\\.com\\/.*)|(^https\\:\\/\\/.*\\.(?:woff|woff2|ttf|eot)(\\?.*)?$)" ), new wp.serviceWorker.strategies[ "CacheFirst" ]( ( function() {const strategyArgs = {
    "cacheName": "fusion_all_fonts"
};strategyArgs.plugins = [new wp.serviceWorker[ "expiration" ].Plugin( {
    "maxEntries": 60,
    "maxAgeSeconds": 2592000,
    "purgeOnQuotaError": true
} )];return strategyArgs;} )() ) );wp.serviceWorker.routing.registerRoute( new RegExp( "^https\\:\\/\\/.*\\.(?:js)(\\?.*)?$" ), new wp.serviceWorker.strategies[ "CacheFirst" ]( ( function() {const strategyArgs = {
    "cacheName": "fusion_all_scripts"
};strategyArgs.plugins = [new wp.serviceWorker[ "expiration" ].Plugin( {
    "maxEntries": 60,
    "maxAgeSeconds": 2592000,
    "purgeOnQuotaError": true
} )];return strategyArgs;} )() ) );wp.serviceWorker.routing.registerRoute( new RegExp( "^https\\:\\/\\/.*\\.(?:css)(\\?.*)?$" ), new wp.serviceWorker.strategies[ "CacheFirst" ]( ( function() {const strategyArgs = {
    "cacheName": "fusion_all_styles"
};strategyArgs.plugins = [new wp.serviceWorker[ "expiration" ].Plugin( {
    "maxEntries": 60,
    "maxAgeSeconds": 2592000,
    "purgeOnQuotaError": true
} )];return strategyArgs;} )() ) );
