Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

2.5 KB
Raw Blame
import type { PageContextServer } from "vike/types";
import { isLocalResource, loadResources, getSystemSearch } from "@webstudio-is/sdk/runtime";
import { getPageMeta, getResources } from "__SERVER__";
import { assets } from "__ASSETS__";
import {
  assetQueryDeploymentId,
  assetQueryDatabase,
} from "__ASSET_QUERY_MANIFEST__";
import { createSsgAssetResourceFetch } from "__ASSET_RESOURCE_FETCH__";

const fetchAssetResource =
  assetQueryDatabase === undefined
    ? undefined
    : createSsgAssetResourceFetch({
        deploymentId: assetQueryDeploymentId,
        artifact: assetQueryDatabase,
        runtimeAssets: assets,
      });

const customFetch: typeof fetch = async (input, init) => {
  const assetResourceResponse = await fetchAssetResource?.(input, init);
  if (assetResourceResponse !== undefined) {
    return assetResourceResponse;
  }
  if (typeof input !== "string") {
    return fetch(input, init);
  }

  if (isLocalResource(input, "current-date")) {
    const now = new Date();
    // Normalize to midnight UTC to prevent hydration mismatches
    const startOfDay = new Date(
      Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
    );
    const data = {
      iso: startOfDay.toISOString(),
      year: startOfDay.getUTCFullYear(),
      month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
      day: startOfDay.getUTCDate(),
      timestamp: startOfDay.getTime(),
    };
    const response = new Response(JSON.stringify(data));
    response.headers.set("content-type", "application/json; charset=utf-8");
    return response;
  }

  return fetch(input, init);
};

export const data = async (pageContext: PageContextServer) => {
  const url = new URL(pageContext.urlOriginal, "http://url");
  const headers = new Headers(pageContext.headers ?? {});
  const host = headers.get("x-forwarded-host") || headers.get("host") || "";
  url.host = host;
  url.protocol = "https";

  const params = pageContext.routeParams;
  const system = {
    params,
    ...getSystemSearch(url.searchParams),
    origin: url.origin,
    pathname: url.pathname,
  };

  const resources = await loadResources(
    customFetch,
    getResources({ system }).data,
    url
  );
  Object.assign(
    resources,
    await loadResources(
      customFetch,
      getResources({ system, resources }).contentData ?? new Map(),
      url
    )
  );
  const pageMeta = getPageMeta({ system, resources });

  return {
    url: url.href,
    system,
    resources,
    pageMeta,
  } satisfies PageContextServer["data"];
};