var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
import {fileURLToPath} from "url";
import fs from "fs";
import path from "path";
import {renderPage, renderSlot} from "../../runtime/server/index.js";
import {canonicalURL as getCanonicalURL, codeFrame} from "../util.js";
import {generatePaginateFunction} from "./paginate.js";
import {getParams, validateGetStaticPathsModule, validateGetStaticPathsResult} from "./routing.js";
const cache = new Map();
async function resolveRenderer(viteServer, renderer) {
  const resolvedRenderer = {};
  const {
    default: {name, client, polyfills, hydrationPolyfills, server}
  } = await import(renderer);
  resolvedRenderer.name = name;
  if (client)
    resolvedRenderer.source = path.posix.join(renderer, client);
  if (Array.isArray(hydrationPolyfills))
    resolvedRenderer.hydrationPolyfills = hydrationPolyfills.map((src) => path.posix.join(renderer, src));
  if (Array.isArray(polyfills))
    resolvedRenderer.polyfills = polyfills.map((src) => path.posix.join(renderer, src));
  const {url} = await viteServer.moduleGraph.ensureEntryFromUrl(path.posix.join(renderer, server));
  const {default: rendererSSR} = await viteServer.ssrLoadModule(url);
  resolvedRenderer.ssr = rendererSSR;
  const completedRenderer = resolvedRenderer;
  return completedRenderer;
}
async function resolveRenderers(viteServer, ids) {
  const renderers = await Promise.all(ids.map((renderer) => {
    if (cache.has(renderer))
      return cache.get(renderer);
    let promise = resolveRenderer(viteServer, renderer);
    cache.set(renderer, promise);
    return promise;
  }));
  return renderers;
}
async function ssr({astroConfig, filePath, logging, mode, origin, pathname, route, routeCache, viteServer}) {
  try {
    const renderers = await resolveRenderers(viteServer, astroConfig.renderers);
    const mod = await viteServer.ssrLoadModule(fileURLToPath(filePath));
    let params = {};
    let pageProps = {};
    if (route && !route.pathname) {
      if (route.params.length) {
        const paramsMatch = route.pattern.exec(pathname);
        if (paramsMatch) {
          params = getParams(route.params)(paramsMatch);
        }
      }
      validateGetStaticPathsModule(mod);
      if (!routeCache[route.component]) {
        routeCache[route.component] = await (await mod.getStaticPaths({
          paginate: generatePaginateFunction(route),
          rss: () => {
          }
        })).flat();
      }
      validateGetStaticPathsResult(routeCache[route.component], logging);
      const routePathParams = routeCache[route.component];
      const matchedStaticPath = routePathParams.find(({params: _params}) => JSON.stringify(_params) === JSON.stringify(params));
      if (!matchedStaticPath) {
        throw new Error(`[getStaticPaths] route pattern matched, but no matching static path found. (${pathname})`);
      }
      pageProps = __spreadValues({}, matchedStaticPath.props) || {};
    }
    const Component = await mod.default;
    if (!Component)
      throw new Error(`Expected an exported Astro component but received typeof ${typeof Component}`);
    if (!Component.isAstroComponentFactory)
      throw new Error(`Unable to SSR non-Astro component (${route == null ? void 0 : route.component})`);
    const result = {
      styles: new Set(),
      scripts: new Set(),
      createAstro(astroGlobal, props, slots) {
        const site = new URL(origin);
        const url = new URL("." + pathname, site);
        const canonicalURL = getCanonicalURL("." + pathname, astroConfig.buildOptions.site || origin);
        return {
          __proto__: astroGlobal,
          props,
          request: {
            canonicalURL,
            params,
            url
          },
          slots: Object.fromEntries(Object.entries(slots || {}).map(([slotName]) => [slotName, true])),
          privateRenderSlotDoNotUse(slotName) {
            return renderSlot(result, slots ? slots[slotName] : null);
          }
        };
      },
      _metadata: {renderers}
    };
    let html = await renderPage(result, Component, pageProps, null);
    if (mode === "development") {
      html = await viteServer.transformIndexHtml(fileURLToPath(filePath), html, pathname);
    }
    return html;
  } catch (e) {
    viteServer.ssrFixStacktrace(e);
    if (e.errors) {
      const {location, pluginName, text} = e.errors[0];
      const err = new Error(text);
      if (location)
        err.loc = {file: location.file, line: location.line, column: location.column};
      const frame = codeFrame(await fs.promises.readFile(filePath, "utf8"), err.loc);
      err.frame = frame;
      err.id = location == null ? void 0 : location.file;
      err.message = `${location == null ? void 0 : location.file}: ${text}

${frame}
`;
      err.stack = e.stack;
      if (pluginName)
        err.plugin = pluginName;
      throw err;
    }
    throw e;
  }
}
export {
  ssr
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vLi4vc3JjL2NvcmUvc3NyL2luZGV4LnRzIl0sCiAgIm1hcHBpbmdzIjogIjs7Ozs7Ozs7Ozs7Ozs7OztBQU1BO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBdUJBLE1BQU0sUUFBUSxJQUFJO0FBR2xCLCtCQUErQixZQUEyQixVQUFrQjtBQUMxRSxRQUFNLG1CQUF3QjtBQUk5QixRQUFNO0FBQUEsSUFDSixTQUFTLENBQUUsTUFBTSxRQUFRLFdBQVcsb0JBQW9CO0FBQUEsTUFDdEQsTUFBTSxPQUFPO0FBRWpCLG1CQUFpQixPQUFPO0FBQ3hCLE1BQUk7QUFBUSxxQkFBaUIsU0FBUyxLQUFLLE1BQU0sS0FBSyxVQUFVO0FBQ2hFLE1BQUksTUFBTSxRQUFRO0FBQXFCLHFCQUFpQixxQkFBcUIsbUJBQW1CLElBQUksQ0FBQyxRQUFnQixLQUFLLE1BQU0sS0FBSyxVQUFVO0FBQy9JLE1BQUksTUFBTSxRQUFRO0FBQVkscUJBQWlCLFlBQVksVUFBVSxJQUFJLENBQUMsUUFBZ0IsS0FBSyxNQUFNLEtBQUssVUFBVTtBQUNwSCxRQUFNLENBQUUsT0FBUSxNQUFNLFdBQVcsWUFBWSxtQkFBbUIsS0FBSyxNQUFNLEtBQUssVUFBVTtBQUMxRixRQUFNLENBQUUsU0FBUyxlQUFnQixNQUFNLFdBQVcsY0FBYztBQUNoRSxtQkFBaUIsTUFBTTtBQUV2Qix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