         yield Promise.all([
                    serviceWorkerCacheHelper.purgeCacheAsync(ServiceWorkerCacheName.base),
                    serviceWorkerCacheHelper.purgeCacheAsync(ServiceWorkerCacheName.followedTopics),
                    serviceWorkerCacheHelper.purgeCacheAsync(ServiceWorkerCacheName.subscribedPublishers),
                    serviceWorkerCacheHelper.purgeCacheAsync(ServiceWorkerCacheName.publishersProfile)
                ]);
            })
        });
        // appEnvironment target scope has changed due to WpoData so update on the resolver as well.
        resolver.setTargetScopeAndConfigServiceParams();
        // Send sendAppErrorEvent as callback to resolver since Core cannot depend on Telemetry repo.
        resolver.initialize(Telemetry.sendAppErrorEvent.bind(Telemetry));
        const configRef = { experienceType: "EdgeChromiumPageWC", instanceSrc: "default" };
        const experienceConfigWrapper = yield resolver.getConfig(configRef);
        const edgeChromiumPageConfig = experienceConfigWrapper && experienceConfigWrapper.properties;
        // Enable the OneService auth endpoints
        appEnvironment.UseOneServiceAuthEndpoints = true;
        appEnvironment.UseOneServiceAnonAuthEndpoints = true;
        // Enable 5 column layout
        appEnvironment.EnableFiveColLayout = true;
        // Check if 6 column layout is enabled
        if (((pageExperiments === null || pageExperiments === void 0 ? void 0 : pageExperiments.includes("prg-wpo-sixcol")) && ((_a = appEnvironment === null || appEnvironment === void 0 ? void 0 : appEnvironment.CurrentRequestTargetScope) === null || _a === void 0 ? void 0 : _a.audienceMode) === AudienceModeType.Adult)
            || (pageExperiments === null || pageExperiments === void 0 ? void 0 : pageExperiments.includes("prg-wpo-sixcol2"))) {
            appEnvironment.EnableSixColLayout = true;
        }
        if ((edgeChromiumPageConfig.linearZoomRatio || edgeChromiumPageConfig.leftNavColumnWidth) && isScreenSuitableZoom(edgeChromiumPageConfig.enableZoomForSmallScreen)) {
            updateLinearFeedWidths(edgeChromiumPageConfig.linearZoomRatio, edgeChromiumPageConfig.leftNavColumnWidth);
        }
        let hasAccount = false;
        if (headData.CurrentFlightSet.has("prg-newpc-lininfo") || headData.CurrentFlightSet.has("prg-newpc-lininsp") || headData.CurrentFlightSet.has("prg-newpc-ctrl")) {
            hasAccount = yield new Promise((resolve) => {
                const authPrivateApi = window && window.chrome && window.chrome.authPrivate;
                if (authPrivateApi && authPrivateApi.getPrimaryAccountInfo) {
                    try {
                        authPrivateApi.getPrimaryAccountInfo((response) => resolve(!!response[primaryAccountInfoStringMap.accountId]));
                    }
                    catch (e) {
                        resolve(false);
                    }
                }
                else {
                    resolve(false);
                }
            });
        }
        yield Promise.all([edgeNextLayoutOptimizer.checkForSingleColumnPromotion(edgeChromiumPageConfig.enableWpoLayoutPromoCoolDown, edgeChromiumPageConfig.coolDownTimeInSecondsPromoted, edgeChromiumPageConfig.coolDownTimeInSecondsSelected), feedLayoutManager.loadPslFeedLayout(hasAccount)]);
        // Initialize cookie management state
        initCookieManagementState();
        // Create an instance of the Experiences shared state data connector
        const sharedStateConnector = initSharedStateConnector(appRootReducer, appStore, requestContext);
        // Create an instance of the Milestone shared state data connector
        const milestoneConnector = new MilestoneDataConnector(ConnectorNamespaces.MilestoneData, "", appRootReducer, new MilestoneDataReducer(), appStore, undefined, requestContext);
        // Create an instance of the bing image data connector
        new BingImageDataConnector(ConnectorNamespaces.BingImageData, "", app.rootReducer, new BingImageDataReducer(), app.store, undefined, requestContext);
        // Create an instance of the TopSitesLayout data connector
        new TopSitesLayoutDataConnector(ConnectorNamespaces.TopSitesLayoutData, "", app.rootReducer, new TopSitesLayoutDataReducer(), app.store, undefined, requestContext);
        // Create an instance of the Coachmark data connector
        new CoachmarkDataConnector(ConnectorNamespaces.CoachmarkData, "", app.rootReducer, new CoachmarkDataReducer(), app.store, undefined, requestContext);
        new ExperienceLoadedDataConnector(ConnectorNamespaces.ExperienceLoadedData, "", app.rootReducer, new ExperienceLoadedDataReducer(), app.store, undefined, requestContext);
        // Create an instance of the Sign in data connector
        new SignInDataConnector(ConnectorNamespaces.SignInData, "", app.rootReducer, new SignInDataReducer(), app.store, undefined, requestContext);
        new DefaultBrowserReclaimDataConnector(ConnectorNamespaces.DefaultBrowserReclaimData, "", app.rootReducer, new DefaultBrowserReclaimDataReducer(), app.store, undefined, requestContext);
        new BackgroundDataConnector(ConnectorNamespaces.BackgroundData, "", app.rootReducer, new BackgroundDataReducer(), app.store, undefined, requestContext);
        // For Enterprise audience create and Init Auth Manager which will provide Auth token.
        if (isEnterpriseAudience()) {
            const getEdgeChromiumAuthCaller = () => __awaiter(void 0, void 0, void 0, function* () {
                const account = yield (appEnvironment === null || appEnvironment === void 0 ? void 0 : appEnvironment.AccountInfoPromise);
                const client = {
                    id: clientId,
                    friendlyName: "Enterprise NTP App"
                };
                return {
                    client,
                    account
                };
            });
            let authFetchStrategy = new EdgeChromiumFetchStrategy(new AadEdgeChromiumAuthCallerValidator(getEdgeChromiumAuthCaller));
            if ((_b = edgeChromiumPageConfig.authManager) === null || _b === void 0 ? void 0 : _b.useRetryDecorator) {
                authFetchStrategy = retryAuthDataFetchDecorator(authFetchStrategy);
            }
            const authCacheStrategy = ((_c = edgeChromiumPageConfig.authManager) === null || _c === void 0 ? void 0 : _c.useInMemoryCache) ?
                new InMemoryAuthCacheStrategy() :
                new NoCacheAuthCacheStrategy();
            InitAuthManager(new ModularAuthManager(authFetchStrategy, authCacheStrategy, LogAuthEventAll));
        }
        const style = document.createElement("style");
        style.setAttribute("type", "text/css");
        style.innerHTML = `
                            body {
                                margin: 0;
                                font-family: Segoe UI, Segoe UI Midlevel, Segoe WP, Arial, sans-serif;
                            }`;
        document.head.appendChild(style);
        if (edgeChromiumPageConfig.enableDelayVariableFont) {
            requestAnimationFrame(() => __awaiter(void 0, void 0, void 0, function* () {
                /**  waitForTtvr internally handles all error cases. It has timeout of 20 sec,
                /* in case of error/failure promise will be resolved as timeout is complete.
                */
                yield waitForTtvr();
                FontUtility.addSegoeUIVariableFont();
            }));
        }
        else if (edgeChromiumPageConfig.enableVariableFont) {
            FontUtility.addSegoeUIVariableFont();
        }
        provideFluentDesignSystem().withShadowRootMode("closed").withElementDisambiguation(() => ElementDisambiguation.ignoreDuplicate)
            .register(fluentDesignSystemProvider());
        // default after Fast vNext upgrade is 4 (previous to that it was 2)
        controlCornerRadius.withDefault(2);
        // Start the App (only after all the base data connectors are initialized, otherwise it won't work)
        pageTimings["AppStartStart"] = Math.round(performance.now());
        perfMarker.startMark("AppStart");
        app.start();
        pageTimings["AppStartEnd"] = Math.round(performance.now());
        perfMarker.endMark("AppStart");
        // For telemetry, we consider a user signed in if they are signed into the page with their MSA account
        // or if they are on an enterprise page and signed into the browser with an AAD account
        const sharedState = sharedStateConnector.getCurrentState();
        const signedInStatus = sharedState.signedIn;
        const isMsaUser = signedInStatus === SignedInStatus.SignedIn;
        const isAadUser = isAadAccountUser();
        const cookieConsentStatus = cookieManagementState.get(CookieManagementStateKey.CookieConsentStatus);
        if (cookieConsentStatus !== CookieConsentStatus.NotRequired) {
            Telemetry.disableTrackingSystem(TrackingSystemType.CTag);
            Telemetry.disableTrackingSystem(TrackingSystemType.Comscore);
        }
        const consentProvider = cookieManagementState.get(CookieManagementStateKey.CookieConsentProvider);
        if (consentProvider === CookieConsentProvider.OneTrustBanner) {
            window.addEventListener(oneTrustConsentEventName, () => {
                const metadata = Telemetry.getPageMetadata();
                if (metadata && metadata.contract && metadata.contract.page) {
                    metadata.contract.page.consentChanged = "occ";
                    Telemetry.enableTrackingSystem(TrackingSystemType.CTag);
                    Telemetry.sendPageView(null, true, null, TrackingSystemType.CTag);
                }
            });
        }
        let telemetryPropertyConfig;
        if (appEnvironment.CurrentRequestTargetScope.audienceMode === AudienceModeType.Enterprise) {
            telemetryPropertyConfig = {
                msnocid: "entnewsntp",
                pageName: yield getInitialPageName(),
                pageProduct: "entnews"
            };
        }
        else if (appEnvironment.CurrentRequestTargetScope.os === OperatingSystemType.Xbox) {
            telemetryPropertyConfig = {
                msnocid: "xboxntp",
                pageName: yield getInitialPageName(),
                pageProduct: OperatingSystemType.Xbox
            };
        }
        const telemetryProperties = EdgeNextTelemetry.getTelemetryProperties(window, telemetryPropertyConfig, isMsaUser || isAadUser, locationHref);
        if (!telemetryProperties.enable) {
            Telemetry.disableTrackingSystem(TrackingSystemType.All);
        }
        const isMobile = ((clientSettings.browser && clientSettings.browser.ismobile === "true") || clientSettings.deviceFormFactor === DeviceFormFactorType.Phone);
        // Initialize appEnvironment.TrackInfo
        appEnvironment.TrackInfo = {
            sitePage: {
                page_product: "anaheim",
                page_type: clientSettings.pagetype
            }
        };
        // This is also configured under EdgeChromiumPageWC. We are loading it early here with a matching configRef.
        yield loadDataConnector({
            instanceId: null,
            configRef: {
                experienceType: "ChromiumPageSettings",
                instanceSrc: "default"
            }
        });
        const pageSettingsDataConnector = yield getDataConnector(ConnectorNamespaces.ChromiumPageSettings);
        const horizontalGap = (_d = edgeChromiumPageConfig.horizontalTabLayoutGap) !== null && _d !== void 0 ? _d : defaultGap;
        const newBuffer = (_e = edgeChromiumPageConfig.bufferSizeOverride) !== null && _e !== void 0 ? _e : defaultBuffer;
        const leftRailBuffer = pageSettingsDataConnector.officeLeftRailEnabled() ? 100 : 0;
        const pageSettingsLayoutState = yield pageSettingsDataConnector.getLayoutStateAsync();
        setTopSitesCollapsibleControlConfig(edgeChromiumPageConfig.enableWpoTopSitesConfigOverride, edgeChromiumPageConfig.topSitesCollapsibleControlConfig);
        const pageSettingsState = pageSettingsDataConnector.getCurrentState();
        let shouldOverrideLayoutToCustom = false;
        if (edgeChromiumPageConfig.enableBackgroundGallery && pageSettingsState.currentBackgroundImageType !== BackgroundImageType.off) {
            shouldOverrideLayoutToCustom = yield backgroundStorageHelper.shouldOverrideLayoutToCustom();
        }
        const expectedMappedLayout = shouldOverrideLayoutToCustom ? LayoutOptions.custom : getLayoutPresets(pageSettingsState.selectedFeedDisplaySetting, pageSettingsState.currentBackgroundImageType, pageSettingsState.greetingEnabled, pageSettingsState.hideDefaultTopSites);
        /**
         * In the event that a user does not immediately change settings,
         * but current settings map to a preset/custom, change the layout automatically.
         */
        if (pageSettingsState.currentLayout !== expectedMappedLayout) {
            let updatedLayoutState;
            if (expectedMappedLayout !== LayoutOptions.custom) {
                const predefinedToggleValues = LayoutToggleMapper[expectedMappedLayout];
                updatedLayoutState = {
                    currentBackgroundImageType: predefinedToggleValues.current_background_image_type,
                    currentLayout: expectedMappedLayout,
                    greetingEnabled: predefinedToggleValues.greeting,
                    imageOfTheDayEnabled: predefinedToggleValues.current_background_image_type !== BackgroundImageType.off,
                    quickLinksEnabled: predefinedToggleValues.quick_links,
                    hideDefaultTopSites: predefinedToggleValues.hide_promoted_links,
                    selectedFeedDisplaySetting: predefinedToggleValues.feeds_position
                };
            }
            else {
                updatedLayoutState = Object.assign(Object.assign({}, pageSettingsLayoutState), { currentLayout: expectedMappedLayout });
            }
            pageSettingsDataConnector.updateLayout(updatedLayoutState);
            invalidatePrerenderedPage(PageInvalidationReasons.FeedLayoutSwitch);
        }
        if (pageSettingsLayoutState.verticalTabsOpened && edgeChromiumPageConfig.verticalLayoutGap) {
            updateColumnWidths(edgeChromiumPageConfig.verticalLayoutGap);
        }
        else {
            updateColumnWidths(horizontalGap);
        }
        // Override the breakpoints to account for the max width of the page while in an iframe
        // (this removes the 32 px buffer that is automatically set into the breakpoints by the FastBreakpointManager)
        let breakpoints = [
            Size1ColumnWidth + newBuffer + leftRailBuffer,
            Size2ColumnWidth + newBuffer + leftRailBuffer,
            Size3ColumnWidth + newBuffer + leftRailBuffer,
            Size4ColumnWidth + newBuffer + leftRailBuffer,
            Size5ColumnWidth + newBuffer + leftRailBuffer
        ];
        // Override Media Query bounds so that it will not add the 32 pixel buffer to media queries.
        const newViewportWidths = new Map([
            [ColumnArrangement.c1, Size1ColumnWidth + newBuffer + leftRailBuffer],
            [ColumnArrangement.c2, Size2ColumnWidth + newBuffer + leftRailBuffer],
            [ColumnArrangement.c3, Size3ColumnWidth + newBuffer + leftRailBuffer],
            [ColumnArrangement.c4, Size4ColumnWidth + newBuffer + leftRailBuffer],
            [ColumnArrangement.c5, Size5ColumnWidth + newBuffer + leftRailBuffer]
        ]);
        if (PageUtility.sixColSupported()) {
            const sixColBuffer = edgeChromiumPageConfig.sixColBufferSize || newBuffer;
            breakpoints.push(Size6ColumnWidth + sixColBuffer + leftRailBuffer);
            newViewportWidths.set(ColumnArrangement.c6, Size6ColumnWidth + sixColBuffer + leftRailBuffer);
        }
        // Check if zoom should be enabled
        const { zoomRatio, maxWidthForZoom } = edgeChromiumPageConfig || {};
        const viewportWidth = (_f = document === null || document === void 0 ? void 0 : document.documentElement) === null || _f === void 0 ? void 0 : _f.clientWidth;
        const shouldApplyZoom = zoomRatio && zoomRatio !== 0 && (viewportWidth < (maxWidthForZoom !== null && maxWidthForZoom !== void 0 ? maxWidthForZoom : 10000));
        if (shouldApplyZoom) {
            breakpoints = breakpoints.map(value => value * zoomRatio);
            newViewportWidths.forEach((value, key) => {
                newViewportWidths.set(key, value * zoomRatio);
            });
        }
        fastBreakpointManager().breakpoints = breakpoints;
        overrideMinViewportWidths(newViewportWidths);
        // set page telemetry contract after breakpoints are set to ensure viewType is correctly set.
        const pageTelemetryContract = EdgeNextTelemetry.getPageTelemetryContract(telemetryProperties, telemetryProperties.isStaticPage, isMobile, isMsaUser, isAadUser, locationHref);
        // Set custom property to investigate MUID mismatch\Auth\Market issues.
        Telemetry.updatePageMetadata(pageTelemetryContract);
        // end the 'init' measure here before we construct the connector. This will measure the total initialization cost
        // of the page before the main EntryPoint connector is created. The perf timeline will continue to get tracked from
        // within the EntryPoint connector itself.
        if (initEndMeasure) {
            initEndMeasure();
        }
        // initialize the Wpo routine which will get the Wpo flight recommendations and store locally.
        // This basically queue a call back to execute WPO intialization code after TTVR
        if (edgeChromiumPageConfig.enablePgcForTreatmentAPI) {
            const page_Config = edgeNextGetPageConfiguration(pageSettingsLayoutState, isMsaUser);
            wpoTreatment.initialize(appEnvironment.CurrentRequestTargetScope, appEnvironment.AppType, appEnvironment.ActivityId, /** loadAfterTTVR */ true, page_Config);
        }
        else {
            wpoTreatment.initialize(appEnvironment.CurrentRequestTargetScope, appEnvironment.AppType, appEnvironment.ActivityId, /** loadAfterTTVR */ true);
        }
        // TODO: revisit all this sign-in logic to avoid multiple page refreshes
        // (see scottbi, author of this comment, for ideas if you tackle this)
        getDataConnector(ConnectorNamespaces.ChromiumPageSettings).then((pageSettingsDataConnector) => __awaiter(void 0, void 0, void 0, function* () {
            var _h, _j, _k;
            // Get/update the core authentication state/cookies.
            // Must be called after the initial track.trackPage() call to ensure page impressions are fired in order
            yield updateAuthState(handleAppAnonFetchError, signedInStatus);
            // We make a client side call to get the user's MSA token directly from the browser via window.chrome.authPrivate API
            // because the browser sometimes fails to drop the LT cookie on the request due to a race condition in the browser;
            // Our ability to get an MSA token for the user will confirm that the user should be signed in/out,
            // which we will compare with the result of the updateAuthState request above.
            // If there is a sign-in state mismatch, establishEdgeChromiumSignedInState will refresh the page to get back in sync.
            // TODO: Unfortunately, right now, not all experiences that need to react to a sign-in state change listen for it
            // and instead react only if the page is reloaded -- which is what the logic below does.
            const accountInfo = yield pageSettingsDataConnector.getPrimaryAccountInfoAsync();
            if (window.chrome && window.chrome.authPrivate) {
                // If we detect a change in the page sign in state, re-fetch the sign in state from the browser and call establishEdgeChromiumSignedInState again.
                window.chrome.authPrivate.onSignInStateChanged.addListener(() => __awaiter(void 0, void 0, void 0, function* () {
                    const newAccountInfo = yield pageSettingsDataConnector.getPrimaryAccountInfoAsync(false);
                    const browserAuthTokenCookie = getCookie(browserAuthTokenCookieName);
                    // if the user is signed into a new MSA account and token is not available, hard refresh the page without setting signInActive state
                    // to allow the page to refresh two times, once to fetch the token and once to fetch the APP_APP_ANON cookie.
                    // this is needed because the page cannot fetch the new user token from the browser API until the page has been refreshed
                    if (newAccountInfo.accountType === PrimaryAccountType.MSA
                        && newAccountInfo.accountId !== accountInfo.accountId
                        && isNullOrUndefined(browserAuthTokenCookie)) {
                        Telemetry.sendAppErrorEvent(Object.assign(Object.assign({}, AuthenticationAppMessages.EstablishSignedInState), { message: "Sign In Refresh Required. New browser account found." }));
                        refreshPage();
                        return;
                    }
                    // otherwise call establishEdgeChromiumSignInState with signInStateChanged: true to handle the page refresh
                    establishEdgeChromiumSignedInState(newAccountInfo, null, true);
                }));
                yield establishEdgeChromiumSignedInState(accountInfo);
            }
            else {
                // Fire app error that tracks auth private property is not available
                Telemetry.sendAppErrorEvent(Object.assign(Object.assign({}, AuthenticationAppMessages.EdgeChromiumAuthPropertyNotAvailable), { message: "AuthPrivate property is not available" }));
            }
            // after the page has been set up, begin the SSO process to pre-sign in users to other microsoft sites
            // do not make this call if we are supposed to be serving .cn content (China has url restrictions)
            // if the user is signed into the browser with MSA but no 'ace' cookie exists, attempt to sign them in
            const anonCookieExistsCookie = getCookie(AuthCookieExistsCookieName.AnonCookieExists);
            if (accountInfo.accountType === PrimaryAccountType.MSA
                && isNullOrUndefined(anonCookieExistsCookie)
                && !appEnvironment.IsChinaCompliance) {
                const pageReadyForSSOPromises = [waitForTtvr()];
                // for prerender pages, wait for the page to be revealed to prevent prerender crashes
                if (headData.IsPrerender) {
                    pageReadyForSSOPromises.push(waitForPageVisible());
                }
                // we set this as fire and forget since the NTP does not respond to the SSO calls
                // this will pre-set sign in cookies for other sites like microsoftnews.msn.com
                Promise.all(pageReadyForSSOPromises).then(() => __awaiter(void 0, void 0, void 0, function* () {
                    // the true passed in here ensures our app state isn't changed by the results of the SSO.
                    initiateSSO(true);
                }));
            }
            pageSettingsDataConnector.setAccountFlag(hasAccount);
            const pageSettingsLayoutState = yield pageSettingsDataConnector.getLayoutStateAsync();
            const page_Config = edgeNextGetPageConfiguration(pageSettingsLayoutState, accountInfo.accountType === PrimaryAccountType.MSA);
            if (Telemetry) {
                Telemetry.updatePageConfiguration(page_Config);
                // wait for page to be visible and then fire pageview
                waitForPageVisible().then(() => {
                    const isSingleColumn = feedLayoutManager.getPslFeedLayoutType === FeedLayoutType.SingleColumn;
                    const pageMetadataContract = {
                        feed: {
                            layout: isSingleColumn ? "singlecol" : "multicol"
                        }
                    };
                    Telemetry.updatePageMetadata(pageMetadataContract, true);
                    const localStoragePivotId = GetSelectedNavItem();
                    if (localStoragePivotId) {
                        // for blended, we want to try and add selected pivot information for all layouts
                        // to do so, we can read the value from local storage if it exists
                        Telemetry.updatePageMetadata({ feed: { id: localStoragePivotId } });
                        // Change "init" users to "sticky" once they've revisited NTP
                        if (GetPivotSelectionSourceType() == PivotSelectionSourceType.Init) {
                            SetPivotSelectionSourceType(PivotSelectionSourceType.Sticky);
                        }
                        // Add Gaming-specific telemetry properties when selected feed is Gaming
                        if (localStoragePivotId === "gaming") {
                            Telemetry.updatePageMetadata({
                                page: {
                                    content: {
                                        vertical: "gaming"
                                    },
                                    type: "verthp",
                                    isCorePV: true // For Gaming scenarios, we want all initial pageviews and tab clicks to be Core Pageviews
                                },
                                feed: {
                                    id: `gaming/${GetPivotSelectionSourceType()}`
                                }
                            });
                        }
                        // Add Play-specific telemetry properties when selected feed is Play
                        if (localStoragePivotId === "play") {
                            Telemetry.updatePageMetadata({
                                page: {
                                    content: {
                                        vertical: "play"
                                    },
                                    type: "verthp"
                                },
                                feed: {
                                    id: `play/${GetPivotSelectionSourceType()}`
                                }
                            });
                        }
                    }
                    const isGamerUserType = "IsGamer";
                    const isXboxGamerUserType = "IsXboxGamer";
                    const isPCGamerUserType = "IsPCGamer";
                    // Add TMPL properties to mark the user's gamer type
                    const gamerType = getLocalStorage().getItem("userType");
                    Telemetry.addOrUpdateTmplProperty(isGamerUserType, gamerType && gamerType.includes(isGamerUserType) ? "1" : "0");
                    Telemetry.addOrUpdateTmplProperty(isXboxGamerUserType, gamerType && gamerType.includes(isXboxGamerUserType) ? "1" : "0");
                    Telemetry.addOrUpdateTmplProperty(isPCGamerUserType, gamerType && gamerType.includes(isPCGamerUserType) ? "1" : "0");
                    Telemetry.sendPageView(null, !headData.newRidNeeded, null);
                });
                waitForAboveTheFoldVisuallyReadyAsync().then(() => __awaiter(void 0, void 0, void 0, function* () {
                    const ocvFeedback = yield import(/* webpackChunkName: "ocvFeedback" */ "./ocv-feedback-data");
                    ocvFeedback.setupOcvTelemetryData();
                }));
            }
            if (page_Config % 4 === 3 || page_Config % 4 == 2) {
                try {
                    if (window && window.chrome && window.chrome.ntpSettingsPrivate && window.chrome.ntpSettingsPrivate.activateTrigger) {
                        window.chrome.ntpSettingsPrivate.activateTrigger((_k = (_j = (_h = window === null || window === void 0 ? void 0 : window.chrome) === null || _h === void 0 ? void 0 : _h.ntpSettingsPrivate) === null || _j === void 0 ? void 0 : _j.NTPTrigger) === null || _k === void 0 ? void 0 : _k.TOP_SITES_VISIBLE);
                    }
                }
                catch (error) {
                    logException(error, NtpActivateTriggerFailedError, "Error invoking activateTrigger function");
                }
            }
            // If we sign in and have child cookie for Kids MSA accounts,
            // but the page was loaded with a non-Kids-audience-mode scope
            // we need to refresh page with the updated scope.
            establishKidsModeState();
        }));
        // After TTVR and page reveal, we check if one trust cookie banner consent is required.
        // If it is required, we check if one trust cookie banner is present.
        // If it is not present, we fire app error.
        Promise.all([waitForPageVisible(), waitForAboveTheFoldVisuallyReadyAsync()]).then(() => {
            var _a;
            const oneTrustConsentSdkPresent = !!document.getElementById("onetrust-consent-sdk");
            if (isOneTrustCookieBannerConsentRequired() && !oneTrustConsentSdkPresent) {
                Telemetry.sendAppErrorEvent(Object.assign(Object.assign({}, OneTrustCookieBannerElementMissing), { pb: Object.assign(Object.assign({}, OneTrustCookieBannerElementMissing.pb), { customMessage: `oneTrustBannerScript: ${(_a = document.getElementById(oneTrustBannerScriptId)) === null || _a === void 0 ? void 0 : _a.getAttribute("src")}` }) }));
            }
        });
        // Render the page experience
        pageTimings["RenderRootStart"] = Math.round(performance.now());
        perfMarker.startMark("RenderRoot");
        renderRootElement(yield resolver.getEntryPointConfigRef(), "fluent-design-system-provider");
        pageTimings["RenderRootEnd"] = Math.round(performance.now());
        perfMarker.endMark("RenderRoot");
        pageTimings["RenderRoot"] = pageTimings["RenderRootEnd"] - pageTimings["RenderRootStart"];
        // Clarity is a user behavior analytics tool that is enabled by adding a script tag to the <head>. Visit clarity.microsoft.com for details.
        if ((_g = headData === null || headData === void 0 ? void 0 : headData.CurrentFlightSet) === null || _g === void 0 ? void 0 : _g.has("prg-wpo-clarity")) {
            const isCookieWallBannerPresent = cookieConsentStatus !== CookieConsentStatus.NotRequired;
            if (!isMsaUser && !isAadUser && !isCookieWallBannerPresent) {
                waitForAboveTheFoldVisuallyReadyAsync().then(() => __awaiter(void 0, void 0, void 0, function* () {
                    const clarity = yield import(/* webpackChunkName: "clarity" */ "@msnews/clarity-lib");
                    clarity.setupClarity();
                    appEnvironment.ClarityEnabled = true;
                    clarity.writeBasicTags();
                }));
            }
        }
        pageTimings["ClientInit"] = Math.round(performance.now() - clientStart);
    }
    catch (e) {
        // This may be a React exception thrown from ReactDom.hydrate() which was already handled by the error boundary at root.
        if (!criticalErrorHandled) {
            yield handleCriticalError(e);
        }
    }
    finally {
        // Check if localStorage and sessionStorage is not available
        localStorageExists(() => Telemetry.sendAppErrorEvent);
        sessionStorageExists(() => Telemetry.sendAppErrorEvent);
    }
}))();
/**
 * Handles a critical error that prevents using the current page.
 * @param error The error.
 * @param info React error information, if available.
 * @param disableFallbackOnReactExceptions Flag to indicate if fallback should be disabled
 */
function handleCriticalError(error, disableFallbackOnReactExceptions) {
    return __awaiter(this, void 0, void 0, function* () {
        const isNetworkFailure = ("isNetworkFailure" in error) && error.isNetworkFailure;
        const errorMessage = "Encountered a critical app error.";
        const appError = isNetworkFailure ? EdgeNextAppErrors.EdgeNextPageRenderFailedDueToNetwork : EdgeNextAppErrors.EdgeNextErrorPage;
        logException(error, appError, errorMessage);
        // do not reload or fallback to local NTP when disabled
        // this allows to safely rollout the fallback logic to Prod
        if (!disableFallbackOnReactExceptions) {
            const refreshAppError = isNetworkFailure ? EdgeNextAppErrors.EdgeNextPageReloadedDueToNetwork : EdgeNextAppErrors.EdgeNextPageReloadedPageExceptionError;
            const localNtpAppError = isNetworkFailure ? EdgeNextAppErrors.EdgeNextLocalNtpDueToNetwork : EdgeNextAppErrors.EdgeNextLocalNTPPageShownPageExceptionError;
            fallbackHandler.tryReloadNtpPage(refreshAppError, localNtpAppError, errorMessage, error);
        }
    });
}
/**
 * Handles any error during the attempt to fetch the APP_ANON cookie
 * @param e The error to handle
 */
function handleAppAnonFetchError(e) {
    Telemetry.sendAppErrorEvent(Object.assign(Object.assign({}, EdgeNextAppErrors.ErrorFetchingAppAnonCookie), { message: "Error while fetching APP_ANON cookie.", pb: Object.assign(Object.assign({}, EdgeNextAppErrors.ErrorFetchingAppAnonCookie.pb), { customMessage: `Error: ${e}` }) }));
}
/**
 * Returns true if the user is logged into an AAD account, else false
 */
function isAadAccountUser() {
    if (isEnterpriseAudience()) {
        const accountInfo = appEnvironment.ResolvedAccountInfo;
        return accountInfo && accountInfo.account_type && accountInfo.account_type === AccountType.AAD;
    }
    return false;
}
/**
 * Returns true if the user is in the enterprise audience scenario, false otherwise
 */
function isEnterpriseAudience() {
    return appEnvironment.CurrentRequestTargetScope && appEnvironment.CurrentRequestTargetScope.audienceMode === AudienceModeType.Enterprise;
}
/**
 * Sets the refreshDelay page timing, which includes the total page-load delay caused by an auto-refresh
 * If the page is auto-refreshed for the user this value will include the time spent constructing and refreshing the initial page
 * If the page was not auto-refreshed, this will be 0
 */
function setRefreshDelayTiming(pageTimings) {
    let refreshDelay = 0;
    const initialPageNavTime = getInitialPageNavTime();
    if (initialPageNavTime) {
        const secondPageNavTime = Date.now() - Math.round(window.performance.now());
        refreshDelay = secondPageNavTime - initialPageNavTime;
    }
    // this is not currently set with setMark so that it is not included in overall TTVR calculations
    pageTimings["refreshDelay"] = refreshDelay;
}
function getInitialPageName() {
    return __awaiter(this, void 0, void 0, function* () {
        const configRef = { experienceType: "ExperienceTrackerEdgeNextData", instanceSrc: "default" };
        const experienceConfigWrapper = yield resolver.getConfig(configRef);
        const experienceTrackerEdgeNextDataConfig = experienceConfigWrapper === null || experienceConfigWrapper === void 0 ? void 0 : experienceConfigWrapper.properties;
        const { feedContentSourceMap } = experienceTrackerEdgeNextDataConfig || {};
        const feedContentSource = feedContentSourceMap && getPivotContentSource(feedContentSourceMap);
        let initialPageName = "default";
        if (feedContentSource === ContentSource.Office365) {
            initialPageName = "entnewshp";
        }
        else if (feedContentSource === ContentSource.Gaming) {
            initialPageName = "gaming";
        }
        return initialPageName;
    });
}
//# sourceMappingURL=page.js.mapA
Eo