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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
import {
bundleVersion,
type PublishedProjectBundle,
type ProjectBundle,
} from "@webstudio-is/protocol";
import {
loadBuildById,
loadDevBuildByProjectId,
} from "@webstudio-is/project-build/server";
import {
createBuildContentCompilationPlan,
createPublishedMdxDependencyClosureResolver,
createPublishedBuildContentCompilationPlan,
getDynamicPublishedMdxSourceBlockIds,
getPublishedMdxContentDatabaseMaxBytes,
resolvePublishedMdxAssetCandidates,
type PublishedMdxTemplateOmission,
type PublishedMdxDependencyReadFailure,
} from "@webstudio-is/project-build";
import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";
import {
loadAssetDataByProject,
preparePublishedAssetData,
validatePublishedAssetCollections,
} from "@webstudio-is/asset-uploader/server";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import {
findPageByIdOrPath,
getAllPages,
getStyleDeclKey,
type Asset,
type AssetFolder,
} from "@webstudio-is/sdk";
import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
import { loadById } from "@webstudio-is/project/index.server";
import { getUserById } from "./user.server";
import { createAssetClient } from "../asset-client";
import { getContentDatabaseMaxBytes } from "~/services/content-database.server";
const getPair = <Item extends { id: string }>(item: Item): [string, Item] => [
item.id,
item,
];
type Project = NonNullable<Awaited<ReturnType<typeof loadById>>>;
type Build = Awaited<ReturnType<typeof loadBuildById>>;
class ProjectNotPublishedError extends Error {
webstudioCode = "PROJECT_NOT_PUBLISHED" as const;
}
const serializeProjectBundle = ({
build,
assets,
assetFolders = [],
}: {
build: Build;
assets: Asset[];
assetFolders?: AssetFolder[];
}): ProjectBundle => {
const page = findPageByIdOrPath("/", build.pages);
if (page === undefined) {
throw new Error(`Page / not found`);
}
const fontFamilies = collectFontFamiliesFromStyleDecls(build.styles);
// Filter unused font assets but include all other asset types (images, videos, audio, documents)
const usedAssets = assets.filter(
(asset) =>
asset.type === "image" ||
asset.type === "video" ||
asset.type === "file" ||
(asset.type === "font" && fontFamilies.has(asset.meta.family))
);
return {
build: {
id: build.id,
projectId: build.projectId,
version: build.version,
createdAt: build.createdAt,
updatedAt: build.updatedAt,
pages: serializePages(build.pages),
breakpoints: build.breakpoints.map(getPair),
styles: build.styles.map((item) => [getStyleDeclKey(item), item]),
styleSources: build.styleSources.map(getPair),
styleSourceSelections: build.styleSourceSelections.map((item) => [
item.instanceId,
item,
]),
props: build.props.map(getPair),
dataSources: build.dataSources.map(getPair),
resources: build.resources.map(getPair),
instances: build.instances.map(getPair),
marketplaceProduct: build.marketplaceProduct,
projectSettings: build.projectSettings,
deployment: build.deployment,
},
page,
pages: getAllPages(build.pages),
assets: usedAssets,
assetFolders,
};
};
const createProjectBundle = async (
build: Build,
context: AppContext
): Promise<ProjectBundle> => {
return serializeProjectBundle({
build,
...(await loadAssetDataByProject(build.projectId, context)),
});
};
const loadProductionCanvasDataAndProject = async (
buildId: string,
context: AppContext,
project?: Project
): Promise<{ data: ProjectBundle; project: Project }> => {
const build = await loadBuildById(context, buildId);
if (build === undefined) {
throw new ProjectNotPublishedError("The project is not published");
}
const { deployment } = build;
if (deployment === undefined) {
throw new ProjectNotPublishedError("The project is not published");
}
project = project ?? (await loadById(build.projectId, context));
if (project === null) {
throw new Error(`Project "${build.projectId}" not found`);
}
const currentProjectDomains = project.domainsVirtual;
// Check that build deployment domains are still active and verified
// for examle: redeploy created few days later
if (deployment.destination !== "static") {
deployment.domains = deployment.domains.filter(
(domain) =>
project.domain === domain ||
currentProjectDomains.some(
(projectDomain) =>
projectDomain.domain === domain &&
projectDomain.status === "ACTIVE" &&
projectDomain.verified
)
);
}
return {
data: await createProjectBundle({ ...build, deployment }, context),
project,
};
};
const addProjectMetadataDependencies = {
getUserById,
preparePublishedAssetData,
validatePublishedAssetCollections,
createAssetClient,
};
const addProjectMetadata = async (
data: ProjectBundle,
project: Project,
context: AppContext,
dependencies = addProjectMetadataDependencies,
options: {
onMdxTemplateOmissions?: (
issues: readonly PublishedMdxTemplateOmission[]
) => void;
onMdxDependencyReadFailures?: (
failures: readonly PublishedMdxDependencyReadFailure[]
) => void;
onMdxBlockInstanceId?: (blockInstanceId: string) => void;
loadMdxDependencySource?: (input: {
id: string;
revision: string;
contentRef: string;
}) => Promise<string>;
contentIndex?: "client";
} = {}
): Promise<PublishedProjectBundle> => {
const user =
project.userId === null
? undefined
: await dependencies.getUserById(context, project.userId);
const publicationBuild = {
...data.build,
pages: migratePages(data.build.pages),
};
let candidateDiscoveryPlan: ReturnType<
typeof createBuildContentCompilationPlan
>;
let assetRequirements: ReturnType<
typeof createPublishedBuildContentCompilationPlan
>;
if (options.contentIndex === "client") {
// Static builds compile downloaded sources in the runner. Hosted builds
// still need query metadata; Markdown body references resolve at runtime.
if (data.build.deployment?.destination !== "static") {
assetRequirements = createBuildContentCompilationPlan(publicationBuild);
}
} else {
const dynamicBlockIds =
getDynamicPublishedMdxSourceBlockIds(publicationBuild);
const projectCandidates = resolvePublishedMdxAssetCandidates({
build: publicationBuild,
allowUnresolved: true,
});
const needsCandidateDiscovery = dynamicBlockIds.some(
(blockId) => projectCandidates.has(blockId) === false
);
candidateDiscoveryPlan = needsCandidateDiscovery
? createBuildContentCompilationPlan(data.build)
: undefined;
assetRequirements =
candidateDiscoveryPlan ??
createPublishedBuildContentCompilationPlan(
publicationBuild,
projectCandidates
);
}
let assetIndex: PublishedProjectBundle["assetIndex"];
let publishedAssets = data.assets;
let publishedAssetFolders = data.assetFolders;
let mdxTemplateOmissions: PublishedMdxTemplateOmission[] = [];
let mdxDependencyReadFailures: PublishedMdxDependencyReadFailure[] = [];
if (assetRequirements !== undefined) {
const resolveMdxDependencies =
createPublishedMdxDependencyClosureResolver();
const publishedAssetData = await dependencies.preparePublishedAssetData({
projectId: project.id,
context,
assetStore: dependencies.createAssetClient(),
contentDatabaseMaxBytes: getPublishedMdxContentDatabaseMaxBytes({
baseBytes: getContentDatabaseMaxBytes(),
assets: data.assets,
}),
plan: assetRequirements,
retainedAssetIds: data.assets
.filter((asset) => asset.type === "font")
.map((asset) => asset.id),
...(assetRequirements.queries.some(({ id }) =>
id.startsWith("__content-block-mdx__:")
) || candidateDiscoveryPlan !== undefined
? {
resolvePlan: async (
artifact: NonNullable<PublishedProjectBundle["assetIndex"]>,
loadDocumentSource
) => {
const nextOmissions: PublishedMdxTemplateOmission[] = [];
const nextReadFailures: PublishedMdxDependencyReadFailure[] = [];
const plan = await resolveMdxDependencies({
build: publicationBuild,
artifact,
loadDocumentSource:
options.loadMdxDependencySource ?? loadDocumentSource,
onTemplateOmission: (issue) => nextOmissions.push(issue),
onDependencyReadFailure: (failure) =>
nextReadFailures.push(failure),
onMdxBlockInstanceId: options.onMdxBlockInstanceId,
});
mdxTemplateOmissions = nextOmissions;
mdxDependencyReadFailures = nextReadFailures;
return plan!;
},
}
: {}),
});
assetIndex = publishedAssetData.artifact;
publishedAssets = publishedAssetData.assets;
publishedAssetFolders = publishedAssetData.assetFolders;
} else {
const publishedAssetData =
await dependencies.validatePublishedAssetCollections({
projectId: project.id,
context,
assetStore: dependencies.createAssetClient(),
});
const retainedFontIds = new Set(
data.assets
.filter((asset) => asset.type === "font")
.map((asset) => asset.id)
);
publishedAssets = publishedAssetData.assets.filter(
(asset) => asset.type !== "font" || retainedFontIds.has(asset.id)
);
publishedAssetFolders = publishedAssetData.assetFolders;
}
options.onMdxTemplateOmissions?.(mdxTemplateOmissions);
options.onMdxDependencyReadFailures?.(mdxDependencyReadFailures);
return {
...data,
assets: publishedAssets,
assetFolders: publishedAssetFolders,
bundleVersion,
user: user ? { email: user.email, username: user.username } : undefined,
projectDomain: project.domain,
projectTitle: project.title,
assetIndex,
};
};
type LoadPublishedProjectBundleByProjectIdDependencies = {
addProjectMetadata: typeof addProjectMetadata;
loadProductionCanvasDataAndProject: typeof loadProductionCanvasDataAndProject;
loadProjectById: typeof loadById;
};
const createLoadPublishedProjectBundleByProjectId =
({
addProjectMetadata,
loadProductionCanvasDataAndProject,
loadProjectById,
}: LoadPublishedProjectBundleByProjectIdDependencies) =>
async (
projectId: string,
context: AppContext
): Promise<PublishedProjectBundle> => {
const project = await loadProjectById(projectId, context);
if (project === null) {
throw new Error(`Project "${projectId}" not found`);
}
const buildId = project.latestBuildVirtual?.buildId;
if (buildId === undefined || buildId === null) {
throw new ProjectNotPublishedError("The project is not published yet");
}
const { data } = await loadProductionCanvasDataAndProject(
buildId,
context,
project
);
return await addProjectMetadata(data, project, context);
};
export const loadProductionCanvasData = async (
buildId: string,
context: AppContext
): Promise<ProjectBundle> => {
const { data } = await loadProductionCanvasDataAndProject(buildId, context);
return data;
};
export const loadPublishedProjectBundleByBuildId = async (
buildId: string,
context: AppContext
): Promise<PublishedProjectBundle> => {
const { data, project } = await loadProductionCanvasDataAndProject(
buildId,
context
);
return await addProjectMetadata(data, project, context);
};
export const loadPublishedProjectBundleByProjectId =
createLoadPublishedProjectBundleByProjectId({
addProjectMetadata,
loadProductionCanvasDataAndProject,
loadProjectById: loadById,
});
export const loadProjectBundleByBuildId = async (
buildId: string,
context: AppContext,
{ contentIndex }: { contentIndex?: "client" } = {}
): Promise<PublishedProjectBundle> => {
const build = await loadBuildById(context, buildId);
const project = await loadById(build.projectId, context);
if (project === null) {
throw new Error(`Project "${build.projectId}" not found`);
}
return await addProjectMetadata(
await createProjectBundle(build, context),
project,
context,
addProjectMetadataDependencies,
{ contentIndex }
);
};
export const loadProjectBundleByProjectId = async (
projectId: string,
context: AppContext,
options: {
build?: Build;
onMdxTemplateOmissions?: (
issues: readonly PublishedMdxTemplateOmission[]
) => void;
onMdxDependencyReadFailures?: (
failures: readonly PublishedMdxDependencyReadFailure[]
) => void;
onMdxBlockInstanceId?: (blockInstanceId: string) => void;
loadMdxDependencySource?: (input: {
id: string;
revision: string;
contentRef: string;
}) => Promise<string>;
} = {}
): Promise<PublishedProjectBundle> => {
const project = await loadById(projectId, context);
if (project === null) {
throw new Error(`Project "${projectId}" not found`);
}
return await addProjectMetadata(
await createProjectBundle(
options.build ?? (await loadDevBuildByProjectId(context, projectId)),
context
),
project,
context,
addProjectMetadataDependencies,
options
);
};
export const __testing__ = {
addProjectMetadata,
createLoadPublishedProjectBundleByProjectId,
serializeProjectBundle,
};