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.

4.5 KB
Raw Blame
import { isProtectedResourceReentry } from "@webstudio-is/sdk/protected-resource-fetch";
import { renderToString } from "react-dom/server";
import { type LoaderFunctionArgs, redirect } from "react-router";
import { isLocalResource, loadResources, getSystemSearch } from "@webstudio-is/sdk/runtime";
import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
  ReactSdkContext,
  xmlNodeTagSuffix,
} from "@webstudio-is/react-sdk/runtime";
import { Page, breakpoints, projectId, projectDomain } from "__CLIENT__";
import { getPageMeta, getRemixParams, getResources } from "__SERVER__";
import { assetBaseUrl, imageLoader } from "__CONSTANTS__";
import { sitemap } from "__SITEMAP__";
import { authRoutes } from "__AUTH__";
import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";

const customFetch: typeof fetch = (input, init) => {
  if (typeof input !== "string") {
    return fetch(input, init);
  }

  if (isLocalResource(input, "sitemap.xml")) {
    // @todo: dynamic import sitemap ???
    const response = new Response(JSON.stringify(sitemap));
    response.headers.set("content-type", "application/json; charset=utf-8");
    return Promise.resolve(response);
  }

  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 Promise.resolve(response);
  }

  return fetch(input, init);
};

export const loader = async (arg: LoaderFunctionArgs) => {
  if (isProtectedResourceReentry(arg.request, projectId)) {
    throw new Response(null, { status: 508 });
  }

  const authRoute = authenticateProjectRequest(
    arg.request,
    authRoutes,
    projectDomain
  );

  const url = new URL(arg.request.url);
  const host =
    arg.request.headers.get("x-forwarded-host") ||
    arg.request.headers.get("host") ||
    "";
  url.host = host;
  url.protocol = "https";

  const params = getRemixParams(arg.params);

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

  const generatedFetch = await createGeneratedAssetResourceFetch({
    request: arg.request,
    context: arg.context,
    fallback: customFetch,
  });
  const resources = await loadResources(
    generatedFetch,
    getResources({ system }).data,
    url,
    { signal: arg.request.signal }
  );
  Object.assign(
    resources,
    await loadResources(
      generatedFetch,
      getResources({ system, resources }).contentData ?? new Map(),
      url,
      { signal: arg.request.signal }
    )
  );
  const pageMeta = getPageMeta({ system, resources });

  if (pageMeta.redirect) {
    const status =
      pageMeta.status === 301 || pageMeta.status === 302
        ? pageMeta.status
        : 302;
    return redirect(pageMeta.redirect, status);
  }

  // typecheck
  arg.context.EXCLUDE_FROM_SEARCH satisfies boolean;

  let text = renderToString(
    <ReactSdkContext.Provider
      value={{
        imageLoader,
        assetBaseUrl,
        resources,
        breakpoints,
        onError: console.error,
      }}
    >
      <Page system={system} />
    </ReactSdkContext.Provider>
  );

  // Xml is wrapped with <svg> to prevent React from hoisting elements like <title>, <meta>, and <link> out of their intended scope during rendering.
  // More details: https://github.com/facebook/react/blob/7c8e5e7ab8bb63de911637892392c5efd8ce1d0f/packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js#L3083
  text = text.replace(/^<svg>/g, "").replace(/<\/svg>$/g, "");

  // React has issues rendering certain elements, such as errors when a <link> element has children.
  // To render XML, we wrap it with an <svg> tag and add a suffix to avoid React's default behavior on these elements.
  text = text.replaceAll(xmlNodeTagSuffix, "");

  return new Response(`<?xml version="1.0" encoding="UTF-8"?>\n${text}`, {
    headers: {
      "Content-Type": "application/xml",
      "Cache-Control":
        authRoute === undefined ? "public, max-age=600" : "private, no-store",
    },
  });
};