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.

(cli): Download images to local build in cli projects (#2133)

Jaya Krishna Namburuaa6f05b5e6d1
diff --git a/apps/cli/package.json b/apps/cli/package.json
index e9eac1f728..d02addbe62 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -16,12 +16,14 @@
"dependencies": {
"@webstudio-is/asset-uploader": "workspace:^",
"@webstudio-is/http-client": "workspace:^",
+ "@webstudio-is/image": "workspace:^",
"@webstudio-is/project-build": "workspace:^",
"@webstudio-is/react-sdk": "workspace:^",
"@webstudio-is/sdk-components-react": "workspace:^",
"@webstudio-is/sdk-components-react-remix": "workspace:^",
"env-paths": "^3.0.0",
"ora": "^7.0.1",
+ "p-limit": "^4.0.0",
"strip-indent": "^4.0.0"
},
"devDependencies": {
diff --git a/apps/cli/src/prebuild.ts b/apps/cli/src/prebuild.ts
index 22c4e95c82..a53d090aff 100644
--- a/apps/cli/src/prebuild.ts
+++ b/apps/cli/src/prebuild.ts
@@ -1,6 +1,7 @@
import { join, relative, dirname } from "node:path";
-import { writeFileSync } from "node:fs";
-import { rm, mkdir } from "node:fs/promises";
+import { createWriteStream, writeFileSync } from "node:fs";
+import { rm, mkdir, access, mkdtemp, rename } from "node:fs/promises";
+import { tmpdir } from "node:os";
import {
generateCssText,
generateUtilsExport,
@@ -16,11 +17,17 @@ import {
} from "@webstudio-is/project-build";
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
import * as remixComponentMetas from "@webstudio-is/sdk-components-react-remix/metas";
-import type { Asset, ImageAsset } from "@webstudio-is/asset-uploader";
+import type { Asset, FontAsset } from "@webstudio-is/asset-uploader";
+import pLimit from "p-limit";
+import ora from "ora";
import { getRouteTemplate } from "./__generated__/router";
import { ASSETS_BASE, LOCAL_DATA_FILE } from "./config";
import { ensureFileInPath, ensureFolderExists, loadJSONFile } from "./fs-utils";
+import { getImageAttributes, createImageLoader } from "@webstudio-is/image";
+import { pipeline } from "node:stream/promises";
+
+const limit = pLimit(10);
type ComponentsByPage = {
[path: string]: Set<string>;
@@ -43,13 +50,51 @@ type RemixRoutes = {
}>;
};
+export const downloadAsset = async (
+ url: string,
+ name: string,
+ temporaryDir: string
+) => {
+ const assetPath = join("public", ASSETS_BASE, name);
+ const tempAssetPath = join(temporaryDir, name);
+ try {
+ await access(assetPath);
+ } catch {
+ try {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
+ }
+
+ const writableStream = createWriteStream(tempAssetPath);
+ /*
+ We need to cast the response body to a NodeJS.ReadableStream.
+ Since the node typings for `@types/node` doesn't add typings for fetch.
+ And it inherits types from lib.dom.d.ts
+ */
+ await pipeline(
+ response.body as unknown as NodeJS.ReadableStream,
+ writableStream
+ );
+
+ await rename(tempAssetPath, assetPath);
+ } catch (error) {
+ console.error(`Error in downloading file ${name} \n ${error}`);
+ }
+ }
+};
+
export const prebuild = async () => {
+ const spinner = ora("Scaffolding the project files");
const appRoot = "app";
+ spinner.start();
const routesDir = join(appRoot, "routes");
await rm(routesDir, { recursive: true, force: true });
await mkdir(routesDir, { recursive: true });
+ const temporaryDir = await mkdtemp(join(tmpdir(), "webstudio-"));
+
const generatedDir = join(appRoot, "__generated__");
await rm(generatedDir, { recursive: true, force: true });
await mkdir(generatedDir, { recursive: true });
@@ -66,21 +111,9 @@ export const prebuild = async () => {
);
}
- const {
- assets,
- build: { deployment },
- } = siteData;
- const fontAssets: Data["assets"] = [];
- const imageAssets: ImageAsset[] = [];
-
- for (const asset of assets) {
- if (asset.type === "image") {
- imageAssets.push(asset);
- }
-
- if (asset.type === "font") {
- fontAssets.push(asset);
- }
+ const domain = siteData.build.deployment?.projectDomain;
+ if (domain === undefined) {
+ throw new Error(`Project domain is missing from the site data`);
}
const remixRoutes: RemixRoutes = {
@@ -139,21 +172,53 @@ export const prebuild = async () => {
}
}
- const cssText = generateCssText(
- {
- assets: siteData.assets,
- breakpoints: siteData.build?.breakpoints,
- styles: siteData.build?.styles,
- styleSourceSelections: siteData.build?.styleSourceSelections,
- componentMetas,
- },
- {
- assetBaseUrl: ASSETS_BASE,
+ const assetsToDownload: Promise<void>[] = [];
+ const fontAssets: FontAsset[] = [];
+ const assetBuildUrl = `https://${domain}.wstd.io/cgi/asset/`;
+
+ for (const asset of siteData.assets) {
+ if (asset.type === "image") {
+ const image = getImageAttributes({
+ /*
+ TODO:
+ https://github.com/webstudio-is/webstudio-builder/issues/2135
+ There should be a option in the loader, that allows to download
+ original image instead of the processed one. Right now, we are using
+ the width from the asset meta
+ */
+ width: asset.meta.width,
+ optimize: true,
+ src: asset.name,
+ quality: 100,
+ srcSet: undefined,
+ sizes: undefined,
+ loader: createImageLoader({
+ imageBaseUrl: assetBuildUrl,
+ }),
+ });
+
+ if (image?.src) {
+ assetsToDownload.push(
+ limit(() => downloadAsset(image.src, asset.name, temporaryDir))
+ );
+ }
}
- );
- await ensureFileInPath(join(generatedDir, "index.css"), cssText);
+ if (asset.type === "font") {
+ assetsToDownload.push(
+ limit(() =>
+ downloadAsset(
+ `${assetBuildUrl}${asset.name}`,
+ asset.name,
+ temporaryDir
+ )
+ )
+ );
+ fontAssets.push(asset);
+ }
+ }
+ spinner.text = "Generating routes and pages";
for (const [pathName, pageComponents] of Object.entries(componentsByPage)) {
let relativePath = "../__generated__";
const statements = Array.from(pageComponents).join(", ");
@@ -174,7 +239,7 @@ export const prebuild = async () => {
import { ${statements} } from "@webstudio-is/sdk-components-react";
import * as remixComponents from "@webstudio-is/sdk-components-react-remix";
export const components = new Map(Object.entries(Object.assign({ ${statements} }, remixComponents ))) as Components;
- export const fontAssets = ${JSON.stringify(fontAssets)};
+ export const fontAssets = ${JSON.stringify(fontAssets)}
export const pageData: PageData = ${JSON.stringify(pageData)};
export const user: { email: string | null } | undefined = ${JSON.stringify(
siteData.user
@@ -248,7 +313,24 @@ export const prebuild = async () => {
}
}
- if (deployment?.projectDomain === undefined) {
- throw new Error("Project is not deployed yet, cannot download assets");
- }
+ spinner.text = "Generating css files";
+ const cssText = generateCssText(
+ {
+ assets: siteData.assets,
+ breakpoints: siteData.build?.breakpoints,
+ styles: siteData.build?.styles,
+ styleSourceSelections: siteData.build?.styleSourceSelections,
+ componentMetas,
+ },
+ {
+ assetBaseUrl: ASSETS_BASE,
+ }
+ );
+
+ await ensureFileInPath(join(generatedDir, "index.css"), cssText);
+
+ spinner.text = "Downloading fonts and images";
+ await Promise.all(assetsToDownload);
+
+ spinner.succeed("Build finished");
};
diff --git a/packages/image/src/index.ts b/packages/image/src/index.ts
index 52cfdbcc67..f6aa1f8545 100644
--- a/packages/image/src/index.ts
+++ b/packages/image/src/index.ts
@@ -1,3 +1,4 @@
export { Image } from "./image";
export type { ImageLoader } from "./image-optimize";
export * from "./image-loaders";
+export * from "./image-optimize";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fd4537d74e..a3cf235c7e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -364,6 +364,9 @@ importers:
'@webstudio-is/http-client':
specifier: workspace:^
version: link:../../packages/http-client
+ '@webstudio-is/image':
+ specifier: workspace:^
+ version: link:../../packages/image
'@webstudio-is/project-build':
specifier: workspace:^
version: link:../../packages/project-build
@@ -382,6 +385,9 @@ importers:
ora:
specifier: ^7.0.1
version: 7.0.1
+ p-limit:
+ specifier: ^4.0.0
+ version: 4.0.0
strip-indent:
specifier: ^4.0.0
version: 4.0.0
@@ -13524,6 +13530,13 @@ packages:
dependencies:
yocto-queue: 0.1.0
+ resolution: {integrity: sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ dependencies:
+ yocto-queue: 1.0.0
+ dev: false
+
resolution: {integrity: sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==}
engines: {node: '>=6'}
@@ -16577,6 +16590,11 @@ packages:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==}
+ engines: {node: '>=12.20'}
+ dev: false
+
resolution: {integrity: sha512-/FaCeG3GkuJwaMR34GHVg0l8jCbafZLHiFowSjqLlqhC6OMyf2tPJBu8UirF7/NI9X/R5ai4QfEKUCOxMAGxZQ==}
dependencies: