// TODO: Remove use of `any` type.
import { initialize, hydrate, version, router, emitter } from "./";
import initOnDemandEntries from "./dev/on-demand-entries-client";
import initWebpackHMR from "./dev/webpack-hot-middleware-client";
import initializeBuildWatcher from "./dev/dev-build-watcher";
import { displayContent } from "./dev/fouc";
import { connectHMR, addMessageListener } from "./dev/error-overlay/websocket";
import { assign, urlQueryToSearchParams } from "../shared/lib/router/utils/querystring";
if (!window._nextSetupHydrationWarning) {
    const origConsoleError = window.console.error;
    window.console.error = function() {
        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
            args[_key] = arguments[_key];
        }
        const isHydrateError = args.some((arg)=>typeof arg === "string" && arg.match(/(hydration|content does not match|did not match)/i));
        if (isHydrateError) {
            args = [
                ...args,
                "\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error"
            ];
        }
        origConsoleError.apply(window.console, args);
    };
    window._nextSetupHydrationWarning = true;
}
window.next = {
    version,
    // router is initialized later so it has to be live-binded
    get router () {
        return router;
    },
    emitter
};
const webpackHMR = initWebpackHMR();
initialize({
    webpackHMR
}).then((param)=>{
    let { assetPrefix  } = param;
    connectHMR({
        assetPrefix,
        path: "/_next/webpack-hmr"
    });
    return hydrate({
        beforeRender: displayContent
    }).then(()=>{
        initOnDemandEntries();
        let buildIndicatorHandler = ()=>{};
        function devPagesHmrListener(event) {
            let payload;
            try {
                payload = JSON.parse(event.data);
            } catch (e) {}
            if (payload.event === "server-error" && payload.errorJSON) {
                const { stack , message  } = JSON.parse(payload.errorJSON);
                const error = new Error(message);
                error.stack = stack;
                throw error;
            } else if (payload.action === "reloadPage") {
                window.location.reload();
            } else if (payload.action === "devPagesManifestUpdate") {
                fetch("" + assetPrefix + "/_next/static/development/_devPagesManifest.json").then((res)=>res.json()).then((manifest)=>{
                    window.__DEV_PAGES_MANIFEST = manifest;
                }).catch((err)=>{
                    console.log("Failed to fetch devPagesManifest", err);
                });
            } else if (payload.event === "middlewareChanges") {
                return window.location.reload();
            } else if (payload.event === "serverOnlyChanges") {
                const { pages  } = payload;
                // Make sure to reload when the dev-overlay is showing for an
                // API route
                if (pages.includes(router.query.__NEXT_PAGE)) {
                    return window.location.reload();
                }
                if (!router.clc && pages.includes(router.pathname)) {
                    console.log("Refreshing page data due to server-side change");
                    buildIndicatorHandler("building");
                    const clearIndicator = ()=>buildIndicatorHandler("built");
                    router.replace(router.pathname + "?" + String(assign(urlQueryToSearchParams(router.query), new URLSearchParams(location.search))), router.asPath, {
                        scroll: false
                    }).catch(()=>{
                        // trigger hard reload when failing to refresh data
                        // to show error overlay properly
                        location.reload();
                    }).finally(clearIndicator);
                }
            }
        }
        addMessageListener(devPagesHmrListener);
        if (process.env.__NEXT_BUILD_INDICATOR) {
            initializeBuildWatcher((handler)=>{
                buildIndicatorHandler = handler;
            }, process.env.__NEXT_BUILD_INDICATOR_POSITION);
        }
    });
}).catch((err)=>{
    console.error("Error was not caught", err);
});

//# sourceMappingURL=next-dev.js.map