import {
  executeCodeLoaders,
  mergeLoaderResults
} from "./chunk-M5KTLZTD.mjs";
import {
  prefetchBlockData
} from "./chunk-7DS4Q3GA.mjs";

// src/rendering/helpers/loadPage.ts
async function loadPage(params) {
  const { client, siteId, path, pageId, preview = false, dataLoaderOverrides } = params;
  const [site, pageResponse] = await Promise.all([
    client.getSite({ id: siteId }),
    client.getPage({ siteId, path, preview })
  ]);
  if ("entry" in pageResponse) {
    throw new Error(
      "This path resolves to a content entry, not a page. Use loadContent() instead, which handles both pages and entries. For entries, loadContent() returns the raw entry data for custom rendering."
    );
  }
  const { page: pageData } = pageResponse;
  const blocks = pageData.blocks.map((block) => {
    if (!block || typeof block !== "object") {
      throw new Error("Invalid block format in API response");
    }
    if (typeof block.id !== "string" && block.id !== null) {
      throw new Error(`Invalid block id: expected string or null, got ${typeof block.id}`);
    }
    if (typeof block.kind !== "string") {
      throw new Error(`Invalid block kind: expected string, got ${typeof block.kind}`);
    }
    if (typeof block.purpose !== "string") {
      throw new Error(`Invalid block purpose: expected string, got ${typeof block.purpose}`);
    }
    const typedBlock = block;
    return {
      id: typedBlock.id,
      kind: typedBlock.kind,
      purpose: typedBlock.purpose,
      // Include content for PageRenderer's getRenderableContent()
      content: typedBlock.content ?? {},
      // Include draftContent if available (for preview mode)
      draftContent: typedBlock.draftContent?.data ?? null
    };
  });
  const pageOutline = {
    name: pageData.name,
    path: pageData.path,
    purpose: pageData.purpose,
    blocks
  };
  const prefetchContext = {
    siteId,
    pageId: pageId ?? pageData.id,
    previewStage: preview ? "preview" : "published"
  };
  const configData = await prefetchBlockData(
    pageOutline,
    prefetchContext,
    client,
    {
      // Pass custom blocks so their config-based loaders are discovered
      customBlocks: site.sdkConfig?.customBlocks
    }
  );
  let resolvedData = configData;
  if (dataLoaderOverrides && Object.keys(dataLoaderOverrides).length > 0) {
    const codeData = await executeCodeLoaders(pageOutline, prefetchContext, dataLoaderOverrides);
    resolvedData = mergeLoaderResults(configData, codeData);
  }
  return {
    page: pageOutline,
    theme: site.theme,
    sdkConfig: site.sdkConfig ?? null,
    siteId,
    resolvedData
    // Note: routeMap is optional and can be built from site data if needed for internal links.
    // Consumers can construct it from site.pages and pass explicitly via Page component props.
    // Example: const routeMap = site.pages.reduce((map, p) => ({ ...map, [p.id]: p.path }), {});
  };
}

export {
  loadPage
};
//# sourceMappingURL=chunk-VVFYHAUD.mjs.map