/* global BROWSER_ESM_ONLY */ import React from "react" import fs from "fs" import { renderToString, renderToStaticMarkup } from "react-dom/server" import { get, merge, isObject, flatten, uniqBy, concat } from "lodash" import nodePath from "path" import { apiRunner, apiRunnerAsync } from "./api-runner-ssr" import { grabMatchParams } from "./find-path" import syncRequires from "$virtual/ssr-sync-requires" import { RouteAnnouncerProps } from "./route-announcer-props" import { ServerLocation, Router, isRedirect } from "@reach/router" // import testRequireError from "./test-require-error" // For some extremely mysterious reason, webpack adds the above module *after* // this module so that when this code runs, testRequireError is undefined. // So in the meantime, we'll just inline it. const testRequireError = (moduleName, err) => { const regex = new RegExp(`Error: Cannot find module\\s.${moduleName}`) const firstLine = err.toString().split(`\n`)[0] return regex.test(firstLine) } let cachedStats const getStats = publicDir => { if (cachedStats) { return cachedStats } else { cachedStats = JSON.parse( fs.readFileSync(nodePath.join(publicDir, `webpack.stats.json`), `utf-8`) ) return cachedStats } } let Html try { Html = require(`../src/html`) } catch (err) { if (testRequireError(`../src/html`, err)) { Html = require(`./default-html`) } else { console.log(`There was an error requiring "src/html.js"\n\n`, err, `\n\n`) process.exit() } } Html = Html && Html.__esModule ? Html.default : Html export default async function staticPage( pagePath, isClientOnlyPage, publicDir, error, callback ) { let bodyHtml = `` let headComponents = [ , ] let htmlAttributes = {} let bodyAttributes = {} let preBodyComponents = [] let postBodyComponents = [] let bodyProps = {} if (error) { postBodyComponents.push([