/*__ESM_BODY_START__*/
((function initPrefetchiFrameMSW() {
	const CACHE_KEY = 'POLARIS_SHELL';
	const TARGET_URL_REGEXP = /\/now\/nav\/ui\/classic\/params\/target\/(.+)$/;

	const shouldRespond = event => {
		const isNavigation = event.request.mode === 'navigate';
		const targetsClassicUi = TARGET_URL_REGEXP.test(event.request.url) || TARGET_URL_REGEXP.test(event.request.referrer);
		return isNavigation && targetsClassicUi;
	};

	const fetchEventHandler = (event) => {
		if (shouldRespond(event))
			event.respondWith(respondTo(event));
		
		return;
	};

	const respondTo = async event => {
		const cache = await caches.open(CACHE_KEY);
		const cached = await cache.match(event.request);

		if (cached) {
			await cache.delete(event.request);
			return cached;
		}

		const match = event.request.url.match(TARGET_URL_REGEXP);

		if (match) {
			const prefetchUrl = decodeURIComponent(match[1]);
			const prefetchRequest = new Request(`${location.origin}/${prefetchUrl}`);
			// Prefetch only when url is not the same as the referrer (to exclude session expired redirection case where url and referrer are same)
			// We do not want to send a prefetch request and overwrite the starting_page, thus keeping the platform redirection url intact post login
			if (event.request.url !== event.request.referrer) {
				self.queueMicrotask(() => {
					fetch(prefetchRequest)
						.then((prefetchResponse) => {
							if (!prefetchResponse.redirected)
								cache.put(prefetchRequest, prefetchResponse);
						})
						.catch(console.error);
				});
			}
		}

		return fetch(event.request);
	};

	self.handleFallbackResponse && self.handleFallbackResponse(shouldRespond);

	self.addEventListener('fetch', fetchEventHandler);
})());

/*__ESM_BODY_END__*/