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.

feat: Updated asset manager: new file types, asset resource, filters, sorting (#5539)

Oleg Isonen011696682202
diff --git a/@types/warn-once.d.ts b/@types/warn-once.d.ts
new file mode 100644
index 0000000000..439bd6fe79
--- /dev/null
+++ b/@types/warn-once.d.ts
@@ -0,0 +1,3 @@
+declare module "warn-once" {
+ export default function warnOnce(condition: boolean, message: string): void;
+}
diff --git a/apps/builder/app/builder/features/assets/assets.tsx b/apps/builder/app/builder/features/assets/assets.tsx
index 9e486b476e..f935a5d0c5 100644
--- a/apps/builder/app/builder/features/assets/assets.tsx
+++ b/apps/builder/app/builder/features/assets/assets.tsx
@@ -1,12 +1,13 @@
import { PanelTitle, Separator } from "@webstudio-is/design-system";
-import { ImageManager } from "~/shared/image-manager";
+import { AssetManager } from "~/builder/shared/asset-manager";
+import { AssetUpload } from "~/builder/shared/assets";
export const AssetsPanel = (_props: { onClose: () => void }) => {
return (
<>
- <PanelTitle>Assets</PanelTitle>
+ <PanelTitle suffix={<AssetUpload type="file" />}>Assets</PanelTitle>
<Separator />
- <ImageManager />
+ <AssetManager />
</>
);
};
diff --git a/apps/builder/app/builder/features/pages/image-info.tsx b/apps/builder/app/builder/features/pages/image-info.tsx
index 4d5a951bd1..4da7102668 100644
--- a/apps/builder/app/builder/features/pages/image-info.tsx
+++ b/apps/builder/app/builder/features/pages/image-info.tsx
@@ -13,7 +13,7 @@ import {
} from "@webstudio-is/icons";
import type { ImageAsset } from "@webstudio-is/sdk";
import { formatAssetName } from "~/builder/shared/assets/asset-utils";
-import { getFormattedAspectRatio } from "~/shared/image-manager/utils";
+import { getFormattedAspectRatio } from "~/builder/shared/asset-manager/utils";
type ImageInfoProps = {
asset: ImageAsset;
diff --git a/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx b/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx
index 29379e69f7..35171333d7 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx
@@ -3,13 +3,14 @@ import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import { Button, Flex, Text, FloatingPanel } from "@webstudio-is/design-system";
import type { Prop } from "@webstudio-is/sdk";
+import { acceptToMimeCategories } from "@webstudio-is/sdk";
import { $assets } from "~/shared/sync/data-stores";
-import { ImageManager } from "~/shared/image-manager";
+import { AssetManager } from "~/builder/shared/asset-manager";
import { type ControlProps } from "../shared";
-import { acceptToMimeCategories } from "@webstudio-is/asset-uploader";
import { formatAssetName } from "~/builder/shared/assets/asset-utils";
+import { AssetUpload } from "~/builder/shared/assets";
-// tests whether we can use ImageManager for the given "accept" value
+// tests whether we can use AssetManager for the given "accept" value
const isImageAccept = (accept?: string) => {
const acceptCategories = acceptToMimeCategories(accept || "");
return (
@@ -45,8 +46,9 @@ export const SelectAsset = ({ prop, onChange, accept }: Props) => {
<Flex gap={2} css={{ flex: 1 }} align="center">
<FloatingPanel
title="Images"
+ titleSuffix={<AssetUpload type="image" accept={accept} />}
content={
- <ImageManager
+ <AssetManager
onChange={(assetId) => onChange({ type: "asset", value: assetId })}
accept={accept}
/>
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index aa34949580..ed68490827 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -29,6 +29,7 @@ import {
serializeValue,
sitemapResourceUrl,
currentDateResourceUrl,
+ assetsResourceUrl,
} from "@webstudio-is/sdk/runtime";
import {
Box,
@@ -999,6 +1000,12 @@ export const SystemResourceForm = forwardRef<
description:
"Provides current date information (year, month, day) normalized to midnight UTC. Time components are set to 00:00:00 to prevent React hydration errors.",
},
+ {
+ label: "Assets",
+ value: JSON.stringify(assetsResourceUrl),
+ description:
+ "Resource that loads the list of assets of the current project.",
+ },
];
const [localResource, setLocalResource] = useState(() => {
diff --git a/apps/builder/app/builder/features/style-panel/controls/font-family/font-family-control.tsx b/apps/builder/app/builder/features/style-panel/controls/font-family/font-family-control.tsx
index 60105e712d..025d72e5ed 100644
--- a/apps/builder/app/builder/features/style-panel/controls/font-family/font-family-control.tsx
+++ b/apps/builder/app/builder/features/style-panel/controls/font-family/font-family-control.tsx
@@ -11,7 +11,7 @@ import { toValue } from "@webstudio-is/css-engine";
import { UploadIcon } from "@webstudio-is/icons";
import { keywordValues, parseCssValue } from "@webstudio-is/css-data";
import { FontsManager } from "~/builder/shared/fonts-manager";
-import { useAssets } from "~/builder/shared/assets";
+import { useAssets, AssetUpload } from "~/builder/shared/assets";
import { toItems } from "~/builder/shared/fonts-manager";
import { useComputedStyleDecl } from "../../shared/model";
import { setProperty } from "../../shared/use-style-data";
@@ -69,6 +69,7 @@ export const FontFamilyControl = () => {
<FloatingPanel
placement="left-start"
title="Fonts"
+ titleSuffix={<AssetUpload type="font" />}
onOpenChange={setIsFontMangerOpen}
content={
<FontsManager
diff --git a/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx b/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx
index 650882833d..bbfb71fd90 100644
--- a/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx
+++ b/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx
@@ -8,13 +8,14 @@ import {
} from "@webstudio-is/design-system";
import type { CssProperty, InvalidValue } from "@webstudio-is/css-engine";
import { $assets } from "~/shared/sync/data-stores";
-import { ImageManager } from "~/shared/image-manager";
+import { AssetManager } from "~/builder/shared/asset-manager";
import { useComputedStyleDecl } from "../../shared/model";
import {
getRepeatedStyleItem,
setRepeatedStyleItem,
} from "../../shared/repeated-style";
import { formatAssetName } from "~/builder/shared/assets/asset-utils";
+import { AssetUpload } from "~/builder/shared/assets";
const isValidURL = (value: string) => {
try {
@@ -101,8 +102,10 @@ export const ImageControl = ({
/>
<FloatingPanel
title="Images"
+ titleSuffix={<AssetUpload type="image" />}
content={
- <ImageManager
+ <AssetManager
+ accept="image/*"
onChange={(assetId) => {
setRepeatedStyleItem(styleDecl, index, {
type: "image",
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx b/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx
new file mode 100644
index 0000000000..03a089b357
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx
@@ -0,0 +1,171 @@
+import { useMemo } from "react";
+import { Select } from "@webstudio-is/design-system";
+import type { AllowedFileExtension } from "@webstudio-is/sdk";
+
+const CATEGORY_ALL = "All" as const;
+
+/**
+ * Display categories for file types in the UI
+ * These match the comment sections in ALLOWED_FILE_TYPES
+ */
+const DISPLAY_CATEGORIES = [
+ CATEGORY_ALL,
+ "Images",
+ "Documents",
+ "Video",
+ "Audio",
+ "Code",
+ "Archives",
+ "Fonts",
+] as const;
+
+type DisplayCategory = (typeof DISPLAY_CATEGORIES)[number];
+
+/**
+ * Type-safe mapping of file extensions to display categories.
+ *
+ * TypeScript enforces that:
+ * 1. All keys must be valid extensions from ALLOWED_FILE_TYPES
+ * 2. All extensions from ALLOWED_FILE_TYPES must be included (completeness check)
+ * 3. All values must be valid DisplayCategory types
+ *
+ * When adding a new file extension to ALLOWED_FILE_TYPES, TypeScript will
+ * produce a compile error until that extension is also added to this mapping.
+ */
+const EXTENSION_TO_DISPLAY_CATEGORY: Record<
+ AllowedFileExtension,
+ DisplayCategory
+> = {
+ // Documents
+ pdf: "Documents",
+ doc: "Documents",
+ docx: "Documents",
+ xls: "Documents",
+ xlsx: "Documents",
+ csv: "Documents",
+ ppt: "Documents",
+ pptx: "Documents",
+
+ // Code
+ txt: "Code",
+ md: "Code",
+ js: "Code",
+ css: "Code",
+ json: "Code",
+ html: "Code",
+ xml: "Code",
+
+ // Archives
+ zip: "Archives",
+ rar: "Archives",
+
+ // Audio
+ mp3: "Audio",
+ wav: "Audio",
+ ogg: "Audio",
+ m4a: "Audio",
+
+ // Video
+ mp4: "Video",
+ mov: "Video",
+ avi: "Video",
+ webm: "Video",
+
+ // Images
+ jpg: "Images",
+ jpeg: "Images",
+ png: "Images",
+ gif: "Images",
+ svg: "Images",
+ webp: "Images",
+ avif: "Images",
+ ico: "Images",
+ bmp: "Images",
+ tif: "Images",
+ tiff: "Images",
+
+ // Fonts
+ woff: "Fonts",
+ woff2: "Fonts",
+ ttf: "Fonts",
+ otf: "Fonts",
+};
+
+/**
+ * Get array of extensions for a given display category
+ */
+const getExtensionsForCategory = (
+ category: DisplayCategory
+): AllowedFileExtension[] | "*" => {
+ if (category === CATEGORY_ALL) {
+ return "*";
+ }
+ return Object.entries(EXTENSION_TO_DISPLAY_CATEGORY)
+ .filter(([, cat]) => cat === category)
+ .map(([ext]) => ext as AllowedFileExtension);
+};
+
+type AssetFiltersProps = {
+ formatCounts: Partial<Record<AllowedFileExtension, number>>;
+ value: AllowedFileExtension[] | "*";
+ onChange: (extensions: AllowedFileExtension[] | "*") => void;
+};
+
+export const AssetFilters = ({
+ formatCounts,
+ value,
+ onChange,
+}: AssetFiltersProps) => {
+ // Aggregate extension counts by display category
+ const categoryCounts = useMemo(() => {
+ const counts: Record<DisplayCategory, number> = {
+ [CATEGORY_ALL]: 0,
+ Images: 0,
+ Documents: 0,
+ Video: 0,
+ Audio: 0,
+ Code: 0,
+ Archives: 0,
+ Fonts: 0,
+ };
+
+ Object.entries(formatCounts).forEach(([ext, count]) => {
+ const category =
+ EXTENSION_TO_DISPLAY_CATEGORY[ext as AllowedFileExtension];
+ if (category && count !== undefined) {
+ counts[category] += count;
+ counts[CATEGORY_ALL] += count;
+ }
+ });
+
+ return counts;
+ }, [formatCounts]);
+
+ // Compute display category from extensions array
+ const selectedCategory: DisplayCategory =
+ value === "*"
+ ? CATEGORY_ALL
+ : (EXTENSION_TO_DISPLAY_CATEGORY[value[0]] as
+ | DisplayCategory
+ | undefined) || CATEGORY_ALL;
+
+ const options = DISPLAY_CATEGORIES.map((category) => ({
+ label: `${category} (${categoryCounts[category] || 0})`,
+ value: category,
+ }));
+
+ const selectedOption = options.find((opt) => opt.value === selectedCategory);
+
+ return (
+ <Select
+ options={options}
+ value={selectedOption}
+ onChange={(option: { label: string; value: DisplayCategory }) => {
+ onChange(getExtensionsForCategory(option.value));
+ }}
+ getLabel={(option) => option.label}
+ getValue={(option) => option.value}
+ css={{ flexGrow: 1 }}
+ />
+ );
+};
diff --git a/apps/builder/app/shared/image-manager/image-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
similarity index 91%
rename from apps/builder/app/shared/image-manager/image-info.tsx
rename to apps/builder/app/builder/shared/asset-manager/asset-info.tsx
index 0648b99366..66ee92b557 100644
--- a/apps/builder/app/shared/image-manager/image-info.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
@@ -3,7 +3,7 @@ import { useEffect, useRef, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import prettyBytes from "pretty-bytes";
import { useStore } from "@nanostores/react";
-import { getMimeByExtension } from "@webstudio-is/asset-uploader";
+import { getMimeTypeByExtension } from "@webstudio-is/sdk";
import {
Box,
Button,
@@ -32,6 +32,7 @@ import {
import {
AspectRatioIcon,
CloudIcon,
+ CopyIcon,
DimensionsIcon,
DownloadIcon,
GearIcon,
@@ -71,8 +72,10 @@ import {
import {
formatAssetName,
parseAssetName,
+ getAssetUrl,
} from "~/builder/shared/assets/asset-utils";
import { getFormattedAspectRatio } from "./utils";
+import { CopyToClipboard } from "~/shared/copy-to-clipboard";
const buttonLinkClass = css({
all: "unset",
@@ -263,7 +266,7 @@ const useLocalValue = <Type extends string>(
] as const;
};
-const ImageInfoContent = ({
+const AssetInfoContent = ({
asset,
usages,
}: {
@@ -341,7 +344,7 @@ const ImageInfoContent = ({
<Flex align="center" css={{ gap: theme.spacing[3] }}>
<PageIcon />
<Text variant="labelsSentenceCase">
- {getMimeByExtension(`.${ext}`)}
+ {getMimeTypeByExtension(ext) ?? "unknown"}
</Text>
</Flex>
{"width" in meta && "height" in meta && (
@@ -377,12 +380,12 @@ const ImageInfoContent = ({
</Box>
<Grid css={{ padding: theme.panel.padding, gap: 4 }}>
- <Label htmlFor="image-manager-filename">Name</Label>
+ <Label htmlFor="asset-manager-filename">Name</Label>
<InputErrorsTooltip
errors={filenameError ? [filenameError] : undefined}
>
<InputField
- id="image-manager-filename"
+ id="asset-manager-filename"
color={filenameError ? "error" : undefined}
value={filename}
onChange={(event) => {
@@ -395,7 +398,7 @@ const ImageInfoContent = ({
<Grid css={{ padding: theme.panel.padding, gap: 4 }}>
<Label
- htmlFor="image-manager-description"
+ htmlFor="asset-manager-description"
css={{ display: "flex", alignItems: "center", gap: 4 }}
>
Description
@@ -407,13 +410,29 @@ const ImageInfoContent = ({
</Tooltip>
</Label>
<InputField
- id="image-manager-description"
+ id="asset-manager-description"
placeholder='Enter "alt" text'
value={description}
onChange={(event) => setDescription(event.target.value)}
/>
</Grid>
+ <Grid css={{ padding: theme.panel.padding, gap: 4 }}>
+ <Label htmlFor="asset-manager-id">ID</Label>
+ <InputField
+ id="asset-manager-id"
+ readOnly
+ value={id}
+ suffix={
+ <Flex justify="center" css={{ paddingInline: theme.spacing[2] }}>
+ <CopyToClipboard text={id}>
+ <SmallIconButton icon={<CopyIcon />} />
+ </CopyToClipboard>
+ </Flex>
+ }
+ />
+ </Grid>
+
<Flex justify="between" css={{ padding: theme.panel.padding }}>
{authPermit === "view" ? (
<Tooltip side="bottom" content="View mode. You can't delete assets.">
@@ -470,7 +489,7 @@ const ImageInfoContent = ({
<IconButton
as="a"
download={formatAssetName(asset)}
- href={`/cgi/image/${asset.name}?format=raw`}
+ href={getAssetUrl(asset, window.location.origin).href}
>
<DownloadIcon />
</IconButton>
@@ -481,13 +500,13 @@ const ImageInfoContent = ({
);
};
-const triggerVisibilityVar = `--ws-image-info-trigger-visibility`;
+const triggerVisibilityVar = `--ws-asset-info-trigger-visibility`;
-export const imageInfoCssVars = ({ show }: { show: boolean }) => ({
+export const assetInfoCssVars = ({ show }: { show: boolean }) => ({
[triggerVisibilityVar]: show ? "visible" : "hidden",
});
-export const ImageInfo = ({ asset }: { asset: Asset }) => {
+export const AssetInfo = ({ asset }: { asset: Asset }) => {
const usagesByAssetId = useStore($usagesByAssetId);
const usages = usagesByAssetId.get(asset.id) ?? [];
return (
@@ -509,7 +528,11 @@ export const ImageInfo = ({ asset }: { asset: Asset }) => {
fill: `oklch(from ${theme.colors.white} l c h / 0.9)`,
},
"&:hover": {
- color: theme.colors.foregroundIconMain,
+ color: theme.colors.backgroundIconSubtle,
+ background: "transparent",
+ "& svg": {
+ fill: `oklch(from ${theme.colors.white} l c h / 1)`,
+ },
},
}}
icon={<GearIcon />}
@@ -517,7 +540,7 @@ export const ImageInfo = ({ asset }: { asset: Asset }) => {
</PopoverTrigger>
<PopoverContent css={{ minWidth: 250 }}>
<PopoverTitle>Asset Details</PopoverTitle>
- <ImageInfoContent asset={asset} usages={usages} />
+ <AssetInfoContent asset={asset} usages={usages} />
</PopoverContent>
</Popover>
{usages.length === 0 && (
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.stories.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.stories.tsx
new file mode 100644
index 0000000000..f4cd2e1963
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.stories.tsx
@@ -0,0 +1,58 @@
+import type { Meta, StoryObj } from "@storybook/react";
+import { AssetManager } from "./asset-manager";
+import {
+ ALLOWED_FILE_TYPES,
+ IMAGE_EXTENSIONS,
+ VIDEO_EXTENSIONS,
+} from "@webstudio-is/sdk";
+import type { Asset, AllowedFileExtension } from "@webstudio-is/sdk";
+import { $assets } from "~/shared/nano-states";
+import { useEffect } from "react";
+
+// Create mock assets for every file type
+const createMockAssets = (): Asset[] => {
+ const extensions = Object.keys(ALLOWED_FILE_TYPES).filter(
+ (ext) =>
+ !IMAGE_EXTENSIONS.includes(ext as AllowedFileExtension) &&
+ !VIDEO_EXTENSIONS.includes(ext as AllowedFileExtension)
+ );
+ const assets: Asset[] = [];
+
+ extensions.forEach((ext, index) => {
+ assets.push({
+ id: `asset-${index}`,
+ name: `example-file.${ext}`,
+ type: "file" as const, // Use "file" type to show icons instead of trying to load images
+ format: ext,
+ size: 1024 * (index + 1),
+ meta: { width: 0, height: 0 },
+ createdAt: new Date().toISOString(),
+ projectId: "mock-project",
+ description: `Example ${ext.toUpperCase()} file`,
+ });
+ });
+
+ return assets;
+};
+
+export default {
+ title: "Asset Manager",
+ component: AssetManager,
+} satisfies Meta;
+
+const AssetManagerStory = () => {
+ useEffect(() => {
+ const assets = createMockAssets();
+ $assets.set(new Map(assets.map((asset) => [asset.id, asset])));
+ }, []);
+
+ return (
+ <div style={{ width: 400, display: "flex" }}>
+ <AssetManager />
+ </div>
+ );
+};
+
+export const AllFileTypes: StoryObj = {
+ render: () => <AssetManagerStory />,
+};
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
new file mode 100644
index 0000000000..6f1f3dd5f8
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
@@ -0,0 +1,199 @@
+import { useState, useMemo } from "react";
+import { matchSorter } from "match-sorter";
+import {
+ Flex,
+ Grid,
+ findNextListItemIndex,
+ theme,
+ useSearchFieldKeys,
+} from "@webstudio-is/design-system";
+import type { Asset, AllowedFileExtension } from "@webstudio-is/sdk";
+import {
+ acceptToMimePatterns,
+ doesAssetMatchMimePatterns,
+} from "@webstudio-is/sdk";
+import { AssetsShell, type AssetContainer, useAssets } from "../assets";
+import { AssetThumbnail } from "./asset-thumbnail";
+import { AssetFilters } from "./asset-filters";
+import { AssetSortSelect, sortAssets, type SortState } from "./asset-sort";
+
+const useLogic = ({
+ onChange,
+ accept = "*",
+}: {
+ onChange?: (assetId: Asset["id"]) => void;
+ accept?: string;
+}) => {
+ const { assetContainers } = useAssets();
+
+ const [selectedIndex, setSelectedIndex] = useState(-1);
+
+ // Initialize selectedExtensions based on accept prop
+ const [selectedExtensions, setSelectedExtensions] = useState<
+ AllowedFileExtension[] | "*"
+ >(() => {
+ const patterns = acceptToMimePatterns(accept);
+ if (patterns === "*") {
+ return "*";
+ }
+ // Convert MIME patterns to extensions
+ const extensions: AllowedFileExtension[] = [];
+ assetContainers.forEach((container) => {
+ if (doesAssetMatchMimePatterns(container.asset, patterns)) {
+ const ext =
+ container.asset.format.toLowerCase() as AllowedFileExtension;
+ if (!extensions.includes(ext)) {
+ extensions.push(ext);
+ }
+ }
+ });
+ return extensions.length > 0 ? extensions : "*";
+ });
+
+ const [sortState, setSortState] = useState<SortState>({
+ sortBy: "createdAt",
+ order: "desc",
+ });
+
+ const searchProps = useSearchFieldKeys({
+ onMove({ direction }) {
+ if (direction === "current") {
+ setSelectedIndex(selectedIndex);
+ const assetContainer = filteredItems[selectedIndex];
+ if (assetContainer.status === "uploaded") {
+ onChange?.(assetContainer.asset.id);
+ }
+ return;
+ }
+ const nextIndex = findNextListItemIndex(
+ selectedIndex,
+ filteredItems.length,
+ direction
+ );
+ setSelectedIndex(nextIndex);
+ },
+ });
+
+ // Filter assets by accept prop first to get the base set
+ const acceptableAssets = useMemo(() => {
+ return assetContainers;
+ }, [assetContainers]);
+
+ // Get available format counts based on all assets
+ const formatCounts = useMemo(() => {
+ const counts: Partial<Record<AllowedFileExtension, number>> = {};
+
+ assetContainers.forEach((container) => {
+ const format =
+ container.asset.format.toLowerCase() as AllowedFileExtension;
+ counts[format] = (counts[format] || 0) + 1;
+ });
+
+ return counts;
+ }, [assetContainers]);
+
+ const filteredItems = useMemo(() => {
+ // Start with all assets
+ let acceptable = acceptableAssets;
+
+ // Filter by selected extensions (user's category selection)
+ if (selectedExtensions !== "*") {
+ acceptable = acceptable.filter((item) =>
+ selectedExtensions.includes(
+ item.asset.format.toLowerCase() as AllowedFileExtension
+ )
+ );
+ }
+
+ let result = acceptable;
+ if (searchProps.value !== "") {
+ result = matchSorter(acceptable, searchProps.value, {
+ keys: [(item) => item.asset.name],
+ });
+ }
+
+ // Apply sorting
+ return sortAssets(result, sortState);
+ }, [acceptableAssets, searchProps.value, selectedExtensions, sortState]);
+
+ const handleSelect = (assetContainer?: AssetContainer) => {
+ const selectedIndex = filteredItems.findIndex(
+ (item) => item.asset.id === assetContainer?.asset.id
+ );
+ setSelectedIndex(selectedIndex);
+ };
+
+ return {
+ searchProps,
+ filteredItems,
+ handleSelect,
+ selectedIndex,
+ formatCounts,
+ selectedExtensions,
+ setSelectedExtensions,
+ sortState,
+ setSortState,
+ };
+};
+
+type AssetManagerProps = {
+ onChange?: (assetId: Asset["id"]) => void;
+ /** acceptable file types in the `<imput accept>` attribute format */
+ accept?: string;
+};
+
+export const AssetManager = ({ accept, onChange }: AssetManagerProps) => {
+ const {
+ handleSelect,
+ filteredItems,
+ searchProps,
+ selectedIndex,
+ formatCounts,
+ selectedExtensions,
+ setSelectedExtensions,
+ sortState,
+ setSortState,
+ } = useLogic({
+ onChange,
+ accept,
+ });
+
+ return (
+ <AssetsShell
+ filters={
+ <Flex gap="2" grow>
+ <AssetFilters
+ formatCounts={formatCounts}
+ value={selectedExtensions}
+ onChange={setSelectedExtensions}
+ />
+ <AssetSortSelect value={sortState} onValueChange={setSortState} />
+ </Flex>
+ }
+ searchProps={searchProps}
+ isEmpty={filteredItems.length === 0}
+ type="file"
+ accept={accept}
+ >
+ <>
+ <Grid
+ columns={3}
+ gap="2"
+ css={{ paddingInline: theme.panel.paddingInline }}
+ >
+ {filteredItems.map((assetContainer, index) => (
+ <AssetThumbnail
+ key={assetContainer.asset.id}
+ assetContainer={assetContainer}
+ onSelect={handleSelect}
+ onChange={(assetContainer) => {
+ onChange?.(assetContainer.asset.id);
+ }}
+ state={index === selectedIndex ? "selected" : undefined}
+ />
+ ))}
+ </Grid>
+ </>
+ </AssetsShell>
+ );
+};
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-sort.tsx b/apps/builder/app/builder/shared/asset-manager/asset-sort.tsx
new file mode 100644
index 0000000000..750467369d
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/asset-sort.tsx
@@ -0,0 +1,175 @@
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuLabel,
+ Button,
+ MenuCheckedIcon,
+} from "@webstudio-is/design-system";
+import {
+ ChevronDownIcon,
+ CalendarIcon,
+ ArrowDownAZIcon,
+ ArrowDownZAIcon,
+ ArrowDownWideNarrowIcon,
+ ArrowDownNarrowWideIcon,
+} from "@webstudio-is/icons";
+import type { AssetContainer } from "../assets";
+
+export type SortField = "name" | "size" | "createdAt";
+export type SortOrder = "asc" | "desc";
+
+export type SortState = {
+ sortBy: SortField;
+ order: SortOrder;
+};
+
+export const sortAssets = (
+ assetContainers: AssetContainer[],
+ sortState: SortState
+): AssetContainer[] => {
+ const { sortBy, order } = sortState;
+ const sorted = [...assetContainers];
+
+ sorted.sort((a, b) => {
+ let comparison = 0;
+
+ if (sortBy === "name") {
+ const aName = a.asset.name.toLowerCase();
+ const bName = b.asset.name.toLowerCase();
+ comparison = aName.localeCompare(bName);
+ } else if (sortBy === "size") {
+ // Uploading assets don't have size yet, put them at the end
+ const aSize =
+ a.status === "uploaded" ? a.asset.size : Number.MAX_SAFE_INTEGER;
+ const bSize =
+ b.status === "uploaded" ? b.asset.size : Number.MAX_SAFE_INTEGER;
+ comparison = aSize - bSize;
+ } else if (sortBy === "createdAt") {
+ // Uploading assets don't have createdAt yet, put them at the end
+ const aCreated = a.status === "uploaded" ? a.asset.createdAt || "" : "";
+ const bCreated = b.status === "uploaded" ? b.asset.createdAt || "" : "";
+ comparison = new Date(aCreated).getTime() - new Date(bCreated).getTime();
+ }
+
+ return order === "asc" ? comparison : -comparison;
+ });
+
+ return sorted;
+};
+
+type AssetSortSelectProps = {
+ value: SortState;
+ onValueChange: (value: SortState) => void;
+};
+
+export const AssetSortSelect = ({
+ value,
+ onValueChange,
+}: AssetSortSelectProps) => {
+ const { sortBy, order } = value;
+
+ const sortLabel =
+ sortBy === "name"
+ ? "Alphabetical"
+ : sortBy === "size"
+ ? "File size"
+ : "Date created";
+
+ const sortIcon =
+ sortBy === "name" ? (
+ order === "asc" ? (
+ <ArrowDownAZIcon />
+ ) : (
+ <ArrowDownZAIcon />
+ )
+ ) : sortBy === "size" ? (
+ order === "desc" ? (
+ <ArrowDownWideNarrowIcon />
+ ) : (
+ <ArrowDownNarrowWideIcon />
+ )
+ ) : (
+ <CalendarIcon />
+ );
+
+ const handleSortChange = (newSortBy: SortField, newOrder: SortOrder) => {
+ // When switching to alphabetical sorting, default to A→Z (asc)
+ // When switching to date/size sorting, default to newest/largest first (desc)
+ if (newSortBy !== sortBy) {
+ onValueChange({
+ sortBy: newSortBy,
+ order: newSortBy === "name" ? "asc" : "desc",
+ });
+ } else {
+ onValueChange({ sortBy: newSortBy, order: newOrder });
+ }
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button color="ghost" prefix={sortIcon} suffix={<ChevronDownIcon />}>
+ {sortLabel}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Sort</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={sortBy}
+ onValueChange={(value) => handleSortChange(value as SortField, order)}
+ >
+ <DropdownMenuRadioItem value="name" icon={<MenuCheckedIcon />}>
+ Alphabetical
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="createdAt" icon={<MenuCheckedIcon />}>
+ Date created
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="size" icon={<MenuCheckedIcon />}>
+ File size
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>Order</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={order}
+ onValueChange={(value) =>
+ handleSortChange(sortBy, value as SortOrder)
+ }
+ >
+ {sortBy === "name" ? (
+ <>
+ <DropdownMenuRadioItem value="asc" icon={<MenuCheckedIcon />}>
+ A→Z
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="desc" icon={<MenuCheckedIcon />}>
+ Z→A
+ </DropdownMenuRadioItem>
+ </>
+ ) : sortBy === "size" ? (
+ <>
+ <DropdownMenuRadioItem value="desc" icon={<MenuCheckedIcon />}>
+ Largest first
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="asc" icon={<MenuCheckedIcon />}>
+ Smallest first
+ </DropdownMenuRadioItem>
+ </>
+ ) : (
+ <>
+ <DropdownMenuRadioItem value="desc" icon={<MenuCheckedIcon />}>
+ Newest first
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="asc" icon={<MenuCheckedIcon />}>
+ Oldest first
+ </DropdownMenuRadioItem>
+ </>
+ )}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/apps/builder/app/shared/image-manager/image-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
similarity index 64%
rename from apps/builder/app/shared/image-manager/image-thumbnail.tsx
rename to apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
index e5d18e171e..6eb2b8da7e 100644
--- a/apps/builder/app/shared/image-manager/image-thumbnail.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
@@ -1,16 +1,44 @@
import type { KeyboardEvent, FocusEvent } from "react";
import { Box, Flex, styled, Text } from "@webstudio-is/design-system";
+import { PageIcon, TextCapitalizeIcon } from "@webstudio-is/icons";
+import { wsVideoLoader } from "@webstudio-is/image";
import { UploadingAnimation } from "./uploading-animation";
-import { ImageInfo, imageInfoCssVars } from "./image-info";
+import { AssetInfo, assetInfoCssVars } from "./asset-info";
import type { AssetContainer } from "~/builder/shared/assets";
import { Image } from "./image";
import brokenImage from "~/shared/images/broken-image-placeholder.svg";
import { theme } from "@webstudio-is/design-system";
import {
formatAssetName,
- isVideoFormat,
parseAssetName,
} from "~/builder/shared/assets/asset-utils";
+import type { IconComponent } from "@webstudio-is/icons";
+import type { AllowedFileExtension } from "@webstudio-is/sdk";
+import {
+ FILE_EXTENSIONS_BY_CATEGORY,
+ detectAssetType,
+} from "@webstudio-is/sdk";
+import type { MimeCategory } from "@webstudio-is/sdk";
+
+const FORMAT_CATEGORIES = FILE_EXTENSIONS_BY_CATEGORY;
+
+const CATEGORY_ICON_MAP: Partial<Record<MimeCategory, IconComponent>> = {
+ font: TextCapitalizeIcon,
+};
+
+const getFileIcon = (format: string): IconComponent => {
+ const lowerFormat = format.toLowerCase();
+
+ // Check which category this format belongs to
+ for (const [category, extensions] of Object.entries(FORMAT_CATEGORIES)) {
+ if (extensions.includes(lowerFormat as AllowedFileExtension)) {
+ return CATEGORY_ICON_MAP[category as MimeCategory] ?? PageIcon;
+ }
+ }
+
+ // Default to PageIcon if not found in any category
+ return PageIcon;
+};
const StyledWebstudioImage = styled(Image, {
position: "absolute",
@@ -76,7 +104,7 @@ const ThumbnailContainer = styled(Box, {
overflow: "hidden",
padding: 2,
"&:hover": {
- ...imageInfoCssVars({ show: true }),
+ ...assetInfoCssVars({ show: true }),
backgroundColor: theme.colors.backgroundAssetcardHover,
},
variants: {
@@ -90,7 +118,7 @@ const ThumbnailContainer = styled(Box, {
outline: `1px solid ${theme.colors.borderFocus}`,
outlineOffset: -1,
backgroundColor: theme.colors.backgroundAssetcardHover,
- ...imageInfoCssVars({ show: true }),
+ ...assetInfoCssVars({ show: true }),
},
},
},
@@ -101,25 +129,60 @@ const Thumbnail = styled(Box, {
height: theme.spacing[19],
flexShrink: 0,
position: "relative",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
});
-type ImageThumbnailProps = {
+const GenericFilePreview = ({
+ ext,
+ format,
+}: {
+ ext: string;
+ format: string;
+}) => {
+ const Icon = getFileIcon(format);
+ const showExtension = Icon === PageIcon;
+
+ return (
+ <Box css={{ position: "relative" }}>
+ <Icon size={48} strokeWidth={0.5} />
+ {showExtension && (
+ <Text
+ variant="tiny"
+ color="subtle"
+ css={{
+ position: "absolute",
+ top: 30,
+ left: "50%",
+ transform: "translateX(-50%)",
+ }}
+ >
+ {ext.toUpperCase()}
+ </Text>
+ )}
+ </Box>
+ );
+};
+
+type AssetThumbnailProps = {
assetContainer: AssetContainer;
onSelect: (assetContainer?: AssetContainer) => void;
onChange?: (assetContainer: AssetContainer) => void;
state?: "selected";
};
-export const ImageThumbnail = ({
+export const AssetThumbnail = ({
assetContainer,
onSelect,
onChange,
state,
-}: ImageThumbnailProps) => {
+}: AssetThumbnailProps) => {
const { asset } = assetContainer;
const { basename, ext } = parseAssetName(asset.name);
const alt = asset.description ?? formatAssetName(asset);
const isUploading = assetContainer.status === "uploading";
+ const assetType = detectAssetType(asset.name);
return (
<ThumbnailContainer
@@ -147,10 +210,8 @@ export const ImageThumbnail = ({
onChange?.(assetContainer);
}}
>
- {isVideoFormat(asset.format) &&
- assetContainer.status === "uploading" ? (
- <StyledWebstudioVideo width={64} src={assetContainer.objectURL} />
- ) : (
+ {assetType === "image" ? (
+ // Image files - show preview
<StyledWebstudioImage
assetId={asset.id}
name={asset.name}
@@ -163,16 +224,28 @@ export const ImageThumbnail = ({
// width={64} used for Image optimizations it should be approximately equal to the width of the picture on the screen in px
width={64}
/>
+ ) : assetType === "video" ? (
+ // Video files - show video thumbnail (first frame)
+ <StyledWebstudioVideo
+ src={
+ assetContainer.status === "uploading"
+ ? assetContainer.objectURL
+ : wsVideoLoader({ src: asset.name })
+ }
+ />
+ ) : (
+ // Other files - show icon based on category
+ <GenericFilePreview ext={ext} format={asset.format} />
)}
</Thumbnail>
- <Flex css={{ width: "100%", paddingBottom: 4 }}>
+ <Flex css={{ width: "100%", paddingBottom: 4 }} justify="center">
<Text variant="tiny" truncate>
{asset.filename ?? basename}
</Text>
<Text variant="tiny">.{ext}</Text>
</Flex>
{assetContainer.status === "uploaded" && (
- <ImageInfo asset={assetContainer.asset} />
+ <AssetInfo asset={assetContainer.asset} />
)}
{isUploading && <UploadingAnimation />}
</ThumbnailContainer>
diff --git a/apps/builder/app/shared/image-manager/image.tsx b/apps/builder/app/builder/shared/asset-manager/image.tsx
similarity index 100%
rename from apps/builder/app/shared/image-manager/image.tsx
rename to apps/builder/app/builder/shared/asset-manager/image.tsx
diff --git a/apps/builder/app/builder/shared/asset-manager/index.ts b/apps/builder/app/builder/shared/asset-manager/index.ts
new file mode 100644
index 0000000000..afdab79767
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/index.ts
@@ -0,0 +1 @@
+export * from "./asset-manager";
diff --git a/apps/builder/app/builder/shared/asset-manager/uploading-animation.tsx b/apps/builder/app/builder/shared/asset-manager/uploading-animation.tsx
new file mode 100644
index 0000000000..73838229ba
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/uploading-animation.tsx
@@ -0,0 +1,23 @@
+import { rawTheme, styled } from "@webstudio-is/design-system";
+import { SpinnerIcon } from "@webstudio-is/icons";
+
+const AnimationContainer = styled("div", {
+ position: "absolute",
+ top: 0,
+ left: 0,
+ height: "100%",
+ width: "100%",
+ display: "flex",
+ flexDirection: "column",
+ justifyContent: "center",
+ alignItems: "center",
+ pointerEvents: "none",
+});
+
+export const UploadingAnimation = () => {
+ return (
+ <AnimationContainer>
+ <SpinnerIcon size={rawTheme.spacing[15]} />
+ </AnimationContainer>
+ );
+};
diff --git a/apps/builder/app/shared/image-manager/utils.ts b/apps/builder/app/builder/shared/asset-manager/utils.ts
similarity index 100%
rename from apps/builder/app/shared/image-manager/utils.ts
rename to apps/builder/app/builder/shared/asset-manager/utils.ts
diff --git a/apps/builder/app/builder/shared/assets/asset-upload.tsx b/apps/builder/app/builder/shared/assets/asset-upload.tsx
index 867742c5ef..0ee1d4decb 100644
--- a/apps/builder/app/builder/shared/assets/asset-upload.tsx
+++ b/apps/builder/app/builder/shared/assets/asset-upload.tsx
@@ -2,15 +2,12 @@ import { type ChangeEvent, useRef } from "react";
import { useStore } from "@nanostores/react";
import { Button, Flex, Tooltip, toast } from "@webstudio-is/design-system";
import { UploadIcon } from "@webstudio-is/icons";
-import {
- type AssetType,
- MAX_UPLOAD_SIZE,
- toBytes,
-} from "@webstudio-is/asset-uploader";
+import { IMAGE_MIME_TYPES, detectAssetType } from "@webstudio-is/sdk";
+import { MAX_UPLOAD_SIZE, toBytes } from "@webstudio-is/asset-uploader";
+import type { AssetType } from "@webstudio-is/asset-uploader";
import { FONT_MIME_TYPES } from "@webstudio-is/fonts";
import { uploadAssets } from "./use-assets";
import { $authPermit } from "~/shared/nano-states";
-import { imageMimeTypes } from "./asset-utils";
const maxSize = toBytes(MAX_UPLOAD_SIZE);
@@ -24,7 +21,7 @@ export const validateFiles = (files: File[]) => {
return files.filter((file) => file.size <= maxSize);
};
-const useUpload = (type: AssetType) => {
+const useUpload = () => {
const inputRef = useRef<HTMLInputElement | null>(null);
const onChange = (event: ChangeEvent<HTMLFormElement>) => {
@@ -34,7 +31,22 @@ const useUpload = (type: AssetType) => {
return;
}
const files = validateFiles(Array.from(input?.files ?? []));
- uploadAssets(type, files);
+
+ // Group files by their detected type
+ const filesByType = new Map<AssetType, File[]>();
+ for (const file of files) {
+ const detectedType = detectAssetType(file.name);
+ if (!filesByType.has(detectedType)) {
+ filesByType.set(detectedType, []);
+ }
+ filesByType.get(detectedType)!.push(file);
+ }
+
+ // Upload each group with the correct type
+ for (const [detectedType, filesOfType] of filesByType) {
+ uploadAssets(detectedType, filesOfType);
+ }
+
form.reset();
};
@@ -42,8 +54,11 @@ const useUpload = (type: AssetType) => {
};
const acceptMap = {
- image: imageMimeTypes.join(", "),
+ image: IMAGE_MIME_TYPES.join(", "),
font: FONT_MIME_TYPES,
+ video: undefined, // Videos can be uploaded through file type
+ // We allow everything by default for files, specific validation happens serverside
+ file: undefined,
};
// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept#unique_file_type_specifiers
@@ -70,7 +85,12 @@ export const acceptUploadType = (
return acceptFileTypeSpecifier(accept, file);
}
- return acceptFileTypeSpecifier(acceptMap[assetType], file);
+ const accepted = acceptMap[assetType];
+ if (accepted === undefined) {
+ return true;
+ }
+
+ return acceptFileTypeSpecifier(accepted, file);
};
type AssetUploadProps = {
@@ -79,7 +99,7 @@ type AssetUploadProps = {
};
const EnabledAssetUpload = ({ accept, type }: AssetUploadProps) => {
- const { inputRef, onChange } = useUpload(type);
+ const { inputRef, onChange } = useUpload();
return (
<form onChange={onChange}>
@@ -92,6 +112,7 @@ const EnabledAssetUpload = ({ accept, type }: AssetUploadProps) => {
style={{ display: "none" }}
/>
<Button
+ color="ghost"
type="button"
onClick={() => inputRef?.current?.click()}
prefix={<UploadIcon />}
diff --git a/apps/builder/app/builder/shared/assets/asset-utils.test.ts b/apps/builder/app/builder/shared/assets/asset-utils.test.ts
index d57d001776..91d1c6d543 100644
--- a/apps/builder/app/builder/shared/assets/asset-utils.test.ts
+++ b/apps/builder/app/builder/shared/assets/asset-utils.test.ts
@@ -1,25 +1,192 @@
-import { expect, test } from "vitest";
-import { parseAssetName } from "./asset-utils";
-
-test("parse asset name", () => {
- expect(parseAssetName("hello_hash.ext")).toEqual({
- basename: "hello",
- hash: "hash",
- ext: "ext",
- });
- expect(parseAssetName("hello.ext")).toEqual({
- basename: "hello",
- hash: "",
- ext: "ext",
- });
- expect(parseAssetName("hello_hash1.ext_hash2")).toEqual({
- basename: "hello",
- hash: "hash1",
- ext: "ext_hash2",
- });
- expect(parseAssetName("hello_hash1_hash2")).toEqual({
- basename: "hello_hash1",
- hash: "hash2",
- ext: "",
+import { expect, test, describe } from "vitest";
+import {
+ parseAssetName,
+ formatAssetName,
+ getImageNameAndType,
+ getSha256Hash,
+ detectAssetType,
+} from "./asset-utils";
+import type { Asset } from "@webstudio-is/sdk";
+
+describe("parseAssetName", () => {
+ test("parses name with hash and extension", () => {
+ expect(parseAssetName("hello_hash.ext")).toEqual({
+ basename: "hello",
+ hash: "hash",
+ ext: "ext",
+ });
+ });
+
+ test("parses name without hash", () => {
+ expect(parseAssetName("hello.ext")).toEqual({
+ basename: "hello",
+ hash: "",
+ ext: "ext",
+ });
+ });
+
+ test("parses name with multiple underscores", () => {
+ expect(parseAssetName("hello_hash1.ext_hash2")).toEqual({
+ basename: "hello",
+ hash: "hash1",
+ ext: "ext_hash2",
+ });
+ });
+
+ test("parses name with hash but no extension", () => {
+ expect(parseAssetName("hello_hash1_hash2")).toEqual({
+ basename: "hello_hash1",
+ hash: "hash2",
+ ext: "",
+ });
+ });
+});
+
+describe("formatAssetName", () => {
+ test("formats asset with filename", () => {
+ const asset: Pick<Asset, "name" | "filename"> = {
+ name: "uploaded_abc123.jpg",
+ filename: "myimage",
+ };
+ expect(formatAssetName(asset)).toBe("myimage.jpg");
+ });
+
+ test("formats asset without filename", () => {
+ const asset: Pick<Asset, "name" | "filename"> = {
+ name: "uploaded_abc123.jpg",
+ filename: undefined,
+ };
+ expect(formatAssetName(asset)).toBe("uploaded.jpg");
+ });
+
+ test("formats asset with no extension", () => {
+ const asset: Pick<Asset, "name" | "filename"> = {
+ name: "uploaded_abc123",
+ filename: "document",
+ };
+ expect(formatAssetName(asset)).toBe("document.");
+ });
+});
+
+describe("getImageNameAndType", () => {
+ test("returns MIME type and filename for valid image", () => {
+ const result = getImageNameAndType("photo.jpg");
+ expect(result).toEqual(["image/jpeg", "photo.jpg"]);
+ });
+
+ test("handles different image extensions", () => {
+ expect(getImageNameAndType("image.png")).toEqual([
+ "image/png",
+ "image.png",
+ ]);
+ expect(getImageNameAndType("graphic.gif")).toEqual([
+ "image/gif",
+ "graphic.gif",
+ ]);
+ expect(getImageNameAndType("vector.svg")).toEqual([
+ "image/svg+xml",
+ "vector.svg",
+ ]);
+ });
+
+ test("is case-insensitive", () => {
+ const result = getImageNameAndType("PHOTO.JPG");
+ expect(result).toEqual(["image/jpeg", "PHOTO.JPG"]);
+ });
+
+ test("returns undefined for non-image files", () => {
+ expect(getImageNameAndType("document.pdf")).toBeUndefined();
+ expect(getImageNameAndType("video.mp4")).toBeUndefined();
+ expect(getImageNameAndType("audio.mp3")).toBeUndefined();
+ });
+
+ test("returns undefined for files without extension", () => {
+ expect(getImageNameAndType("filename")).toBeUndefined();
+ });
+
+ test("handles files with multiple dots", () => {
+ const result = getImageNameAndType("my.photo.file.png");
+ expect(result).toEqual(["image/png", "my.photo.file.png"]);
+ });
+});
+
+describe("getSha256Hash", () => {
+ test("generates consistent hash for same input", async () => {
+ const hash1 = await getSha256Hash("test string");
+ const hash2 = await getSha256Hash("test string");
+ expect(hash1).toBe(hash2);
+ });
+
+ test("generates different hashes for different inputs", async () => {
+ const hash1 = await getSha256Hash("string1");
+ const hash2 = await getSha256Hash("string2");
+ expect(hash1).not.toBe(hash2);
+ });
+
+ test("generates 64 character hex string", async () => {
+ const hash = await getSha256Hash("test");
+ expect(hash).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("handles empty string", async () => {
+ const hash = await getSha256Hash("");
+ expect(hash).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("generates expected hash for known input", async () => {
+ // SHA-256 of "hello" is known
+ const hash = await getSha256Hash("hello");
+ expect(hash).toBe(
+ "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
+ );
+ });
+});
+
+describe("detectAssetType", () => {
+ test("detects image files", () => {
+ expect(detectAssetType("photo.jpg")).toBe("image");
+ expect(detectAssetType("image.png")).toBe("image");
+ expect(detectAssetType("graphic.gif")).toBe("image");
+ expect(detectAssetType("vector.svg")).toBe("image");
+ expect(detectAssetType("picture.webp")).toBe("image");
+ });
+
+ test("detects font files", () => {
+ expect(detectAssetType("font.woff")).toBe("font");
+ expect(detectAssetType("font.woff2")).toBe("font");
+ expect(detectAssetType("font.ttf")).toBe("font");
+ expect(detectAssetType("font.otf")).toBe("font");
+ });
+
+ test("detects video files", () => {
+ expect(detectAssetType("video.mp4")).toBe("video");
+ expect(detectAssetType("video.webm")).toBe("video");
+ expect(detectAssetType("video.mov")).toBe("video");
+ expect(detectAssetType("video.avi")).toBe("video");
+ });
+
+ test("returns file for other types", () => {
+ expect(detectAssetType("document.pdf")).toBe("file");
+ expect(detectAssetType("audio.mp3")).toBe("file");
+ expect(detectAssetType("data.json")).toBe("file");
+ expect(detectAssetType("doc.docx")).toBe("file");
+ });
+
+ test("is case-insensitive", () => {
+ expect(detectAssetType("PHOTO.JPG")).toBe("image");
+ expect(detectAssetType("FONT.WOFF2")).toBe("font");
+ expect(detectAssetType("VIDEO.MP4")).toBe("video");
+ expect(detectAssetType("DOC.PDF")).toBe("file");
+ });
+
+ test("handles files without extension", () => {
+ expect(detectAssetType("filename")).toBe("file");
+ });
+
+ test("handles files with multiple dots", () => {
+ expect(detectAssetType("my.photo.file.png")).toBe("image");
+ expect(detectAssetType("my.font.file.woff2")).toBe("font");
+ expect(detectAssetType("my.video.file.mp4")).toBe("video");
+ expect(detectAssetType("my.doc.file.pdf")).toBe("file");
});
});
diff --git a/apps/builder/app/builder/shared/assets/asset-utils.ts b/apps/builder/app/builder/shared/assets/asset-utils.ts
index 8d5f73a07f..3862e75f5f 100644
--- a/apps/builder/app/builder/shared/assets/asset-utils.ts
+++ b/apps/builder/app/builder/shared/assets/asset-utils.ts
@@ -1,43 +1,34 @@
-import type { Asset, FontAsset, ImageAsset } from "@webstudio-is/sdk";
+import type {
+ Asset,
+ FontAsset,
+ ImageAsset,
+ AllowedFileExtension,
+} from "@webstudio-is/sdk";
import { nanoid } from "nanoid";
+import {
+ getMimeTypeByExtension,
+ IMAGE_EXTENSIONS,
+ detectAssetType,
+ getAssetUrl,
+} from "@webstudio-is/sdk";
import type { UploadingFileData } from "~/shared/nano-states";
-const videoExtensionToMime = [
- [".mp4", "video/mp4"],
- [".webm", "video/webm"],
- [".mpg", "video/mpeg"],
- [".mpeg", "video/mpeg"],
- [".mov", "video/quicktime"],
-] as const;
-
-const extensionToMime = new Map([
- [".gif", "image/gif"],
- [".ico", "image/x-icon"],
- [".jpeg", "image/jpeg"],
- [".jpg", "image/jpeg"],
- [".png", "image/png"],
- [".svg", "image/svg+xml"],
- [".webp", "image/webp"],
- // Support video formats as images
- ...videoExtensionToMime,
-] as const);
-
-export const isVideoFormat = (format: string) => {
- return videoExtensionToMime.some(([extension]) => extension.includes(format));
-};
-
-const extensions = [...extensionToMime.keys()];
-
-export const imageMimeTypes = [...extensionToMime.values()];
+export { detectAssetType, getAssetUrl };
export const getImageNameAndType = (fileName: string) => {
- const extension = extensions.find((ext) => fileName.endsWith(ext));
+ // Extract extension from filename
+ const extractedExt = fileName.split(".").pop()?.toLowerCase();
- if (extension == null) {
+ if (!extractedExt) {
return;
}
- return [extensionToMime.get(extension)!, fileName] as const;
+ // Check if it's a valid image extension
+ if (!IMAGE_EXTENSIONS.includes(extractedExt as AllowedFileExtension)) {
+ return;
+ }
+
+ return [getMimeTypeByExtension(extractedExt)!, fileName] as const;
};
const extractImageNameAndMimeTypeFromUrl = (url: URL) => {
@@ -111,16 +102,18 @@ export const getFileName = (file: File | URL) => {
export const uploadingFileDataToAsset = (
fileData: UploadingFileData
): Asset => {
- const mimeType = getMimeType(
- fileData.source === "file" ? fileData.file : new URL(fileData.url)
- );
+ const fileOrUrl =
+ fileData.source === "file" ? fileData.file : new URL(fileData.url);
+ const fileName = getFileName(fileOrUrl);
+ const mimeType = getMimeType(fileOrUrl);
const format = mimeType.split("/")[1];
+ const assetType = detectAssetType(fileName);
- if (mimeType.startsWith("video/")) {
+ if (assetType === "video") {
// Use image type for now
const asset: ImageAsset = {
id: fileData.assetId,
- name: fileData.objectURL,
+ name: fileName,
format,
type: "image",
description: "",
@@ -137,10 +130,10 @@ export const uploadingFileDataToAsset = (
return asset;
}
- if (mimeType.startsWith("image/")) {
+ if (assetType === "image") {
const asset: ImageAsset = {
id: fileData.assetId,
- name: fileData.objectURL,
+ name: fileName,
format,
type: "image",
description: "",
@@ -157,20 +150,37 @@ export const uploadingFileDataToAsset = (
return asset;
}
- const asset: FontAsset = {
+ if (assetType === "font") {
+ const asset: FontAsset = {
+ id: fileData.assetId,
+ name: fileName,
+ format: format as FontAsset["format"],
+ type: "font",
+ description: "",
+ createdAt: "",
+ projectId: "",
+ size: 0,
+ meta: {
+ family: "system",
+ style: "normal",
+ weight: 400,
+ },
+ };
+
+ return asset;
+ }
+
+ // Default to file type for all other types (documents, code, audio, etc.)
+ const asset: Asset = {
id: fileData.assetId,
- name: fileData.objectURL,
- format: "woff2",
- type: "font",
+ name: fileName,
+ format,
+ type: "file",
description: "",
createdAt: "",
projectId: "",
size: 0,
- meta: {
- family: "system",
- style: "normal",
- weight: 400,
- },
+ meta: {},
};
return asset;
diff --git a/apps/builder/app/builder/shared/assets/assets-shell.tsx b/apps/builder/app/builder/shared/assets/assets-shell.tsx
index df10a17cd9..50787668d5 100644
--- a/apps/builder/app/builder/shared/assets/assets-shell.tsx
+++ b/apps/builder/app/builder/shared/assets/assets-shell.tsx
@@ -13,7 +13,8 @@ import {
Text,
theme,
} from "@webstudio-is/design-system";
-import { AssetUpload, acceptUploadType, validateFiles } from "./asset-upload";
+import { acceptUploadType, validateFiles } from "./asset-upload";
+import { detectAssetType } from "@webstudio-is/sdk";
import { NotFound } from "./not-found";
import { Separator } from "./separator";
import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";
@@ -35,6 +36,7 @@ import {
} from "./drag-monitor";
type AssetsShellProps = {
+ filters?: JSX.Element;
searchProps: ComponentProps<typeof SearchField>;
children: JSX.Element;
type: AssetType;
@@ -52,6 +54,7 @@ const OVER = 2;
type DropTargetState = typeof IDLE | typeof OVER;
export const AssetsShell = ({
+ filters,
searchProps,
isEmpty,
children,
@@ -144,7 +147,21 @@ export const AssetsShell = ({
return false;
});
- uploadAssets(type, files);
+ // Group files by their detected type
+ const filesByType = new Map<string, File[]>();
+ for (const file of files) {
+ const detectedType = detectAssetType(file.name);
+ if (!filesByType.has(detectedType)) {
+ filesByType.set(detectedType, []);
+ }
+ filesByType.get(detectedType)!.push(file);
+ }
+
+ // Upload each group with the correct type
+ for (const [detectedType, filesOfType] of filesByType) {
+ uploadAssets(detectedType as AssetType, filesOfType);
+ }
+
uploadAssets(type, droppedUrls);
},
})
@@ -164,14 +181,14 @@ export const AssetsShell = ({
position: "relative",
}}
>
- <Flex css={{ padding: theme.panel.padding }} gap="2">
+ <Flex css={{ padding: theme.panel.padding }} gap="2" wrap="wrap">
<SearchField
css={{ flexGrow: 1 }}
{...searchProps}
autoFocus
placeholder="Search"
/>
- <AssetUpload type={type} accept={accept} />
+ {filters}
</Flex>
<Separator />
{isEmpty && <NotFound />}
diff --git a/apps/builder/app/builder/shared/assets/index.ts b/apps/builder/app/builder/shared/assets/index.ts
index ef15394620..e779eb8aef 100644
--- a/apps/builder/app/builder/shared/assets/index.ts
+++ b/apps/builder/app/builder/shared/assets/index.ts
@@ -2,3 +2,4 @@ export * from "./use-assets";
export * from "./types";
export * from "./separator";
export * from "./assets-shell";
+export * from "./asset-upload";
diff --git a/apps/builder/app/builder/shared/assets/use-assets.tsx b/apps/builder/app/builder/shared/assets/use-assets.tsx
index cc65c97203..44c81de455 100644
--- a/apps/builder/app/builder/shared/assets/use-assets.tsx
+++ b/apps/builder/app/builder/shared/assets/use-assets.tsx
@@ -279,12 +279,14 @@ const uploadAsset = async ({
authToken,
projectId,
fileOrUrl,
+ assetType,
onCompleted,
onError,
}: {
authToken: undefined | string;
projectId: string;
fileOrUrl: File | URL;
+ assetType: AssetType;
onCompleted: (data: UploadData) => void;
onError: (error: string) => void;
}) => {
@@ -294,7 +296,7 @@ const uploadAsset = async ({
const metaFormData = new FormData();
metaFormData.append("projectId", projectId);
- metaFormData.append("type", mimeType);
+ metaFormData.append("type", assetType);
// sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443
// should be removed after fix
metaFormData.append(
@@ -448,6 +450,7 @@ const processUpload = async (
projectId,
fileOrUrl:
fileData.source === "file" ? fileData.file : new URL(fileData.url),
+ assetType: fileData.type,
onCompleted: (data) => {
URL.revokeObjectURL(fileData.objectURL);
deleteUploadingFileData(assetId);
@@ -544,13 +547,19 @@ export async function uploadAssets(
return res;
}
-const filterByType = (assetContainers: AssetContainer[], type: AssetType) => {
+const filterByType = (
+ assetContainers: AssetContainer[],
+ type: Asset["type"] | undefined
+) => {
+ if (type === undefined) {
+ return assetContainers;
+ }
return assetContainers.filter((assetContainer) => {
return assetContainer.asset.type === type;
});
};
-export const useAssets = (type: AssetType) => {
+export const useAssets = (type?: Asset["type"]) => {
const assetContainers = useStore($assetContainers);
const assetsByType = useMemo(() => {
diff --git a/apps/builder/app/dashboard/projects/sort.tsx b/apps/builder/app/dashboard/projects/sort.tsx
index 439c67b678..dc11a8e64a 100644
--- a/apps/builder/app/dashboard/projects/sort.tsx
+++ b/apps/builder/app/dashboard/projects/sort.tsx
@@ -14,6 +14,7 @@ import {
CalendarIcon,
UploadIcon,
ArrowDownAZIcon,
+ ArrowDownZAIcon,
} from "@webstudio-is/icons";
import type { DashboardProject } from "@webstudio-is/dashboard";
@@ -105,7 +106,11 @@ export const SortSelect = ({ value, onValueChange }: SortSelectProps) => {
sortBy === "createdAt" ? (
<CalendarIcon />
) : sortBy === "title" ? (
- <ArrowDownAZIcon />
+ order === "asc" ? (
+ <ArrowDownAZIcon />
+ ) : (
+ <ArrowDownZAIcon />
+ )
) : sortBy === "publishedAt" ? (
<UploadIcon />
) : (
diff --git a/apps/builder/app/routes/cgi.asset.$.ts b/apps/builder/app/routes/cgi.asset.$.ts
new file mode 100644
index 0000000000..3851756da3
--- /dev/null
+++ b/apps/builder/app/routes/cgi.asset.$.ts
@@ -0,0 +1,65 @@
+import { createReadStream, existsSync } from "node:fs";
+import { join } from "node:path";
+import { createReadableStreamFromReadable } from "@remix-run/node";
+import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
+import {
+ getMimeTypeByFilename,
+ isAllowedExtension,
+ decodePathFragment,
+} from "@webstudio-is/sdk";
+import { fileUploadPath } from "~/shared/asset-client";
+
+// This route serves generic assets without processing
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ const basePath = `/cgi/asset/`;
+
+ const url = new URL(request.url);
+ const name = decodePathFragment(url.pathname.slice(basePath.length));
+
+ // Allow direct asset access, and from the same origin
+ const refererRawUrl = request.headers.get("referer");
+ const refererUrl = refererRawUrl === null ? url : new URL(refererRawUrl);
+ if (refererUrl.host !== url.host) {
+ throw new Response("Forbidden", {
+ status: 403,
+ });
+ }
+
+ // Support absolute urls locally
+ if (URL.canParse(name)) {
+ return fetch(name);
+ }
+
+ const filePath = join(process.cwd(), fileUploadPath, name);
+
+ if (existsSync(filePath) === false) {
+ throw new Response("Not found", {
+ status: 404,
+ });
+ }
+
+ // Validate file extension against allowed types
+ const extension = name.split(".").pop()?.toLowerCase();
+ const contentType = getMimeTypeByFilename(name);
+
+ // Reject files with disallowed extensions or MIME types
+ if (
+ contentType === "application/octet-stream" ||
+ !extension ||
+ !isAllowedExtension(extension)
+ ) {
+ throw new Response("File type not allowed", {
+ status: 403,
+ });
+ }
+
+ return new Response(
+ createReadableStreamFromReadable(createReadStream(filePath)),
+ {
+ headers: {
+ "content-type": contentType,
+ "Access-Control-Allow-Origin": url.origin,
+ },
+ }
+ );
+};
diff --git a/apps/builder/app/routes/cgi.image.$.ts b/apps/builder/app/routes/cgi.image.$.ts
index 8013e8c332..1fc518ba5e 100644
--- a/apps/builder/app/routes/cgi.image.$.ts
+++ b/apps/builder/app/routes/cgi.image.$.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import { createReadableStreamFromReadable } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
import { wsImageLoader } from "@webstudio-is/image";
+import { decodePathFragment } from "@webstudio-is/sdk";
import env from "~/env/env.server";
import { getImageNameAndType } from "~/builder/shared/assets/asset-utils";
import { fileUploadPath } from "~/shared/asset-client";
@@ -29,10 +30,6 @@ const ImageParams = z.object({
]),
});
-const decodePathFragment = (fragment: string) => {
- return decodeURIComponent(fragment);
-};
-
// this route used as proxy for images to cloudflare endpoint
// https://developers.cloudflare.com/fundamentals/get-started/reference/cdn-cgi-endpoint/
diff --git a/apps/builder/app/routes/cgi.video.$.ts b/apps/builder/app/routes/cgi.video.$.ts
index 4954aab45c..119976c96b 100644
--- a/apps/builder/app/routes/cgi.video.$.ts
+++ b/apps/builder/app/routes/cgi.video.$.ts
@@ -1,19 +1,28 @@
+import { createReadStream, existsSync } from "node:fs";
+import { join } from "node:path";
+import { createReadableStreamFromReadable } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
import env from "~/env/env.server";
+import { getMimeTypeByFilename, decodePathFragment } from "@webstudio-is/sdk";
+import { fileUploadPath } from "~/shared/asset-client";
-// this route used as proxy for images to cloudflare endpoint
+// this route used as proxy for videos to cloudflare endpoint or serve local files
// https://developers.cloudflare.com/fundamentals/get-started/reference/cdn-cgi-endpoint/
export const loader = async ({ request }: LoaderFunctionArgs) => {
+ const basePath = `/cgi/video/`;
+ const url = new URL(request.url);
+ const name = decodePathFragment(url.pathname.slice(basePath.length));
+
if (env.RESIZE_ORIGIN !== undefined) {
- const url = new URL(request.url);
- const imgUrl = new URL(env.RESIZE_ORIGIN + url.pathname);
- imgUrl.search = url.search;
+ const videoUrl = new URL(env.RESIZE_ORIGIN + url.pathname);
+ videoUrl.search = url.search;
- const response = await fetch(imgUrl.href, {
+ const response = await fetch(videoUrl.href, {
headers: {
accept: request.headers.get("accept") ?? "",
"accept-encoding": request.headers.get("accept-encoding") ?? "",
+ range: request.headers.get("range") ?? "",
},
});
@@ -21,14 +30,37 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
if (false === responseWHeaders.ok) {
console.error(
- `Request to Image url ${imgUrl.href} responded with status = ${responseWHeaders.status}`
+ `Request to Video url ${videoUrl.href} responded with status = ${responseWHeaders.status}`
);
}
+ responseWHeaders.headers.set("Access-Control-Allow-Origin", url.origin);
+
return responseWHeaders;
}
- return new Response("Not supported", {
- status: 200,
- });
+ // support absolute urls locally
+ if (URL.canParse(name)) {
+ return fetch(name);
+ }
+
+ const filePath = join(process.cwd(), fileUploadPath, name);
+
+ if (existsSync(filePath) === false) {
+ throw new Response("Not found", {
+ status: 404,
+ });
+ }
+
+ const contentType = getMimeTypeByFilename(name);
+
+ return new Response(
+ createReadableStreamFromReadable(createReadStream(filePath)),
+ {
+ headers: {
+ "content-type": contentType,
+ "accept-ranges": "bytes",
+ },
+ }
+ );
};
diff --git a/apps/builder/app/routes/rest.assets_.$name.tsx b/apps/builder/app/routes/rest.assets_.$name.tsx
index dcc5b3d320..65eca88ade 100644
--- a/apps/builder/app/routes/rest.assets_.$name.tsx
+++ b/apps/builder/app/routes/rest.assets_.$name.tsx
@@ -2,6 +2,11 @@ import { z } from "zod";
import type { ActionFunctionArgs } from "@remix-run/server-runtime";
import type { Asset } from "@webstudio-is/sdk";
import { uploadFile } from "@webstudio-is/asset-uploader/index.server";
+import {
+ isAllowedMimeCategory,
+ IMAGE_MIME_TYPES,
+ ALLOWED_FILE_TYPES,
+} from "@webstudio-is/sdk";
import type { ActionData } from "~/builder/shared/assets";
import { createAssetClient } from "~/shared/asset-client";
import { createContext } from "~/shared/context.server";
@@ -33,34 +38,66 @@ export const action = async (
const contentType = request.headers.get("Content-Type");
+ // Check if this is a request to download from URL (has url field in JSON body)
+ // vs uploading a JSON file directly (JSON file content in body)
if (contentType?.includes("application/json")) {
- const { url } = UrlBody.parse(await request.json());
- const imageRequest = await fetch(url, {
- method: "GET",
- headers: {
- // Image formats we support
- Accept:
- "image/jpeg,image/png,image/gif,image/webp,image/svg+xml,image/x-icon,image/ico",
- },
- });
-
- if (false === imageRequest.ok) {
- const error = await imageRequest.text();
- const errors = `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`;
- throw new Error(errors);
+ const jsonBody = await request.json();
+ const urlParse = UrlBody.safeParse(jsonBody);
+
+ // Only fetch from URL if the body has a valid url field
+ if (urlParse.success) {
+ const { url } = urlParse.data;
+
+ const imageRequest = await fetch(url, {
+ method: "GET",
+ headers: {
+ Accept: IMAGE_MIME_TYPES.join(","),
+ },
+ });
+
+ if (false === imageRequest.ok) {
+ const error = await imageRequest.text();
+ const errors = `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`;
+ throw new Error(errors);
+ }
+
+ if (imageRequest.body === null) {
+ throw new Error(
+ `An error occurred while fetching the image at ${url}: Image body is null`
+ );
+ }
+
+ body = imageRequest.body;
+ } else {
+ // This is a JSON file being uploaded, use the JSON content as body
+ body = new Blob([JSON.stringify(jsonBody)], {
+ type: "application/json",
+ }).stream();
}
-
- if (imageRequest.body === null) {
- throw new Error(
- `An error occurred while fetching the image at ${url}: Image body is null`
- );
- }
-
- body = imageRequest.body;
}
const url = new URL(request.url);
- const contentTypeArr = contentType?.split(";")[0]?.split("/") ?? [];
+
+ // Get file extension from filename
+ const fileExtension = params.name.split(".").pop()?.toLowerCase();
+
+ // Use the file extension to determine the correct MIME type
+ // This handles cases where browsers send legacy MIME types (e.g., application/font-woff instead of font/woff)
+ const correctMimeType = fileExtension
+ ? ALLOWED_FILE_TYPES[fileExtension as keyof typeof ALLOWED_FILE_TYPES]
+ : contentType?.split(";")[0];
+
+ const contentTypeArr = correctMimeType?.split("/") ?? [];
+
+ // Validate MIME type against allowed categories
+ const mimeCategory = contentTypeArr[0];
+ if (
+ mimeCategory &&
+ correctMimeType &&
+ !isAllowedMimeCategory(mimeCategory)
+ ) {
+ throw new Error(`MIME type "${mimeCategory}/*" is not allowed`);
+ }
const format =
contentTypeArr[0] === "video" ? contentTypeArr[1] : undefined;
diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.ts
index f59248d308..5ae0baf13a 100644
--- a/apps/builder/app/routes/rest.resources-loader.ts
+++ b/apps/builder/app/routes/rest.resources-loader.ts
@@ -4,6 +4,7 @@ import { ResourceRequest } from "@webstudio-is/sdk";
import { isLocalResource, loadResource } from "@webstudio-is/sdk/runtime";
import { loader as siteMapLoader } from "../shared/$resources/sitemap.xml.server";
import { loader as currentDateLoader } from "../shared/$resources/current-date.server";
+import { loader as assetsLoader } from "../shared/$resources/assets.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { checkCsrf } from "~/services/csrf-session.server";
import { getResourceKey } from "~/shared/resources";
@@ -26,6 +27,10 @@ export const action = async ({ request }: ActionFunctionArgs) => {
return currentDateLoader({ request });
}
+ if (isLocalResource(input, "assets")) {
+ return assetsLoader({ request });
+ }
+
return fetch(input, init);
};
diff --git a/apps/builder/app/shared/$resources/assets.server.ts b/apps/builder/app/shared/$resources/assets.server.ts
new file mode 100644
index 0000000000..63571f615e
--- /dev/null
+++ b/apps/builder/app/shared/$resources/assets.server.ts
@@ -0,0 +1,46 @@
+import { json } from "@remix-run/server-runtime";
+import { parseBuilderUrl } from "@webstudio-is/http-client";
+import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
+import { isBuilder } from "../router-utils";
+import { createContext } from "../context.server";
+import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
+
+/**
+ * System Resource that provides the list of assets for the current project.
+ * This allows assets to be dynamically referenced in the builder using the expression editor.
+ */
+export const loader = async ({ request }: { request: Request }) => {
+ if (isBuilder(request) === false) {
+ throw new Error(
+ "Asset resource loader can only be accessed from the builder interface"
+ );
+ }
+
+ const { projectId } = parseBuilderUrl(request.url);
+
+ if (projectId === undefined) {
+ throw new Error(
+ "Project ID is required to load assets. Ensure the request includes a valid project context."
+ );
+ }
+
+ const context = await createContext(request);
+
+ const assets = await loadAssetsByProject(projectId, context);
+
+ const requestUrl = new URL(request.url);
+ const origin = `${requestUrl.protocol}//${requestUrl.host}`;
+
+ // Convert array to object with asset IDs as keys and add URL to each asset
+ const assetsById = Object.fromEntries(
+ assets.map((asset) => [
+ asset.id,
+ {
+ ...asset,
+ url: getAssetUrl(asset, origin).href,
+ },
+ ])
+ );
+
+ return json(assetsById);
+};
diff --git a/apps/builder/app/shared/image-manager/image-manager.tsx b/apps/builder/app/shared/image-manager/image-manager.tsx
deleted file mode 100644
index 686e46df97..0000000000
--- a/apps/builder/app/shared/image-manager/image-manager.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { useState, useMemo } from "react";
-import { matchSorter } from "match-sorter";
-import {
- Grid,
- findNextListItemIndex,
- theme,
- useSearchFieldKeys,
-} from "@webstudio-is/design-system";
-import type { ImageAsset } from "@webstudio-is/sdk";
-import {
- acceptToMimePatterns,
- doesAssetMatchMimePatterns,
-} from "@webstudio-is/asset-uploader";
-import {
- AssetsShell,
- type AssetContainer,
- useAssets,
-} from "~/builder/shared/assets";
-import { ImageThumbnail } from "./image-thumbnail";
-
-const useLogic = ({
- onChange,
- accept,
-}: {
- onChange?: (assetId: ImageAsset["id"]) => void;
- accept?: string;
-}) => {
- const { assetContainers } = useAssets("image");
-
- const [selectedIndex, setSelectedIndex] = useState(-1);
-
- const searchProps = useSearchFieldKeys({
- onMove({ direction }) {
- if (direction === "current") {
- setSelectedIndex(selectedIndex);
- const assetContainer = filteredItems[selectedIndex];
- if (
- assetContainer.status === "uploaded" &&
- assetContainer.asset.type === "image"
- ) {
- onChange?.(assetContainer.asset.id);
- }
- return;
- }
- const nextIndex = findNextListItemIndex(
- selectedIndex,
- filteredItems.length,
- direction
- );
- setSelectedIndex(nextIndex);
- },
- });
-
- const filteredItems = useMemo(() => {
- let acceptable = assetContainers;
- const patterns = acceptToMimePatterns(accept ?? "");
-
- if (patterns !== "*") {
- acceptable = assetContainers.filter((item) =>
- doesAssetMatchMimePatterns(item.asset, patterns)
- );
- } else if (accept !== undefined) {
- // Filter by file extension
- const extensions = accept.split(",").map((ext) => ext.trim());
- acceptable = assetContainers.filter((item) =>
- extensions.some((ext) => item.asset.name.endsWith(ext))
- );
- }
-
- if (searchProps.value === "") {
- return acceptable;
- }
- return matchSorter(acceptable, searchProps.value, {
- keys: [(item) => item.asset.name],
- });
- }, [assetContainers, accept, searchProps.value]);
-
- const handleSelect = (assetContainer?: AssetContainer) => {
- const selectedIndex = filteredItems.findIndex(
- (item) => item.asset.id === assetContainer?.asset.id
- );
- setSelectedIndex(selectedIndex);
- };
-
- return {
- searchProps,
- filteredItems,
- handleSelect,
- selectedIndex,
- };
-};
-
-type ImageManagerProps = {
- onChange?: (assetId: ImageAsset["id"]) => void;
- /** acceptable file types in the `<imput accept>` attribute format */
- accept?: string;
-};
-
-export const ImageManager = ({ accept, onChange }: ImageManagerProps) => {
- const { handleSelect, filteredItems, searchProps, selectedIndex } = useLogic({
- onChange,
- accept,
- });
-
- // https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/accept
- // https://github.com/webstudio-is/webstudio/blob/83503e39b0e1561ea93cfcff92aa35b54c15fefa/packages/sdk-components-react/src/video.ws.ts#L34
- //
- // To reproduce:
- // 1. Create Video Animation
- // 2. Open "Video" component properties
- // 3. Click "Choose source" button
- // 4. See ImageManager allows upload all image and video files
- // 5. See ImageManager do not filter video files based on accept parameter
- // 6. But see accept = ".mp4,.webm,.mpg,.mpeg,.mov" is right here
- console.info(
- "@todo accept for video tag should allow only video uploads and filter items",
- accept
- );
-
- return (
- <AssetsShell
- searchProps={searchProps}
- isEmpty={filteredItems.length === 0}
- type="image"
- accept={accept}
- >
- <Grid
- columns={3}
- gap="2"
- css={{ paddingInline: theme.panel.paddingInline }}
- >
- {filteredItems.map((assetContainer, index) => (
- <ImageThumbnail
- key={assetContainer.asset.id}
- assetContainer={assetContainer}
- onSelect={handleSelect}
- onChange={(assetContainer) => {
- if (assetContainer.asset.type === "image") {
- onChange?.(assetContainer.asset.id);
- }
- }}
- state={index === selectedIndex ? "selected" : undefined}
- />
- ))}
- </Grid>
- </AssetsShell>
- );
-};
diff --git a/apps/builder/app/shared/image-manager/index.ts b/apps/builder/app/shared/image-manager/index.ts
deleted file mode 100644
index 8132cbdd08..0000000000
--- a/apps/builder/app/shared/image-manager/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./image-manager";
diff --git a/apps/builder/app/shared/image-manager/uploading-animation.tsx b/apps/builder/app/shared/image-manager/uploading-animation.tsx
deleted file mode 100644
index 5a589303b0..0000000000
--- a/apps/builder/app/shared/image-manager/uploading-animation.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useEffect, useState } from "react";
-import { ProgressRadial, styled } from "@webstudio-is/design-system";
-
-const useFakeProgress = () => {
- const [progressBarPercentage, setProgressBarPercentage] = useState(0);
-
- // @todo rewrite this fake indication to show real progress
- useEffect(() => {
- const intervalId = setInterval(() => {
- setProgressBarPercentage((percentage) =>
- percentage < 60 ? percentage + 1 : 0
- );
- }, 100);
- return () => {
- clearInterval(intervalId);
- };
- }, []);
-
- return progressBarPercentage;
-};
-
-const AnimationContainer = styled("div", {
- position: "absolute",
- top: 0,
- left: 0,
- height: "100%",
- width: "100%",
- display: "flex",
- flexDirection: "column",
- justifyContent: "center",
- alignItems: "center",
- pointerEvents: "none",
-});
-
-export const UploadingAnimation = () => {
- const progressBarPercentage = useFakeProgress();
- return (
- <AnimationContainer>
- <ProgressRadial value={progressBarPercentage} max={60} />
- </AnimationContainer>
- );
-};
diff --git a/apps/builder/app/shared/project-settings/image-control.tsx b/apps/builder/app/shared/project-settings/image-control.tsx
index 9e4c7d90a2..6ef4183081 100644
--- a/apps/builder/app/shared/project-settings/image-control.tsx
+++ b/apps/builder/app/shared/project-settings/image-control.tsx
@@ -1,6 +1,6 @@
import type { ReactElement } from "react";
import { FloatingPanel } from "@webstudio-is/design-system";
-import { ImageManager } from "~/shared/image-manager";
+import { AssetManager } from "~/builder/shared/asset-manager";
// @todo should be moved to shared as its being reused in another feature
export const ImageControl = (props: {
@@ -12,7 +12,8 @@ export const ImageControl = (props: {
title="Images"
placement="bottom-within"
content={
- <ImageManager
+ <AssetManager
+ accept="image/*"
onChange={(assetId) => {
props.onAssetIdChange(assetId);
}}
diff --git a/packages/asset-uploader/src/clients/fs/upload.ts b/packages/asset-uploader/src/clients/fs/upload.ts
index 787c64d1c2..d30e5846c6 100644
--- a/packages/asset-uploader/src/clients/fs/upload.ts
+++ b/packages/asset-uploader/src/clients/fs/upload.ts
@@ -26,7 +26,11 @@ export const uploadToFs = async ({
await writeFile(filepath, data);
const assetData = await getAssetData({
- type: type.startsWith("image") ? "image" : "font",
+ type: type.startsWith("image")
+ ? "image"
+ : type === "font"
+ ? "font"
+ : "file",
size: data.byteLength,
data,
name,
diff --git a/packages/asset-uploader/src/clients/s3/upload.ts b/packages/asset-uploader/src/clients/s3/upload.ts
index f45b65c6ad..96ce1e5b1c 100644
--- a/packages/asset-uploader/src/clients/s3/upload.ts
+++ b/packages/asset-uploader/src/clients/s3/upload.ts
@@ -81,7 +81,11 @@ export const uploadToS3 = async ({
}
const assetData = await getAssetData({
- type: type.startsWith("image") ? "image" : "font",
+ type: type.startsWith("image")
+ ? "image"
+ : type === "font"
+ ? "font"
+ : "file",
size: data.byteLength,
data: new Uint8Array(data),
name,
diff --git a/packages/asset-uploader/src/index.ts b/packages/asset-uploader/src/index.ts
index ed0e291cda..feff34e0af 100644
--- a/packages/asset-uploader/src/index.ts
+++ b/packages/asset-uploader/src/index.ts
@@ -3,4 +3,3 @@ export * from "./schema";
export * from "./constants";
export * from "./utils/to-bytes";
export * from "./utils/sanitize-s3-key";
-export * from "./utils/mime";
diff --git a/packages/asset-uploader/src/types.ts b/packages/asset-uploader/src/types.ts
index 389629be98..4cacf624e6 100644
--- a/packages/asset-uploader/src/types.ts
+++ b/packages/asset-uploader/src/types.ts
@@ -1 +1 @@
-export type AssetType = "image" | "font";
+export type AssetType = "image" | "font" | "video" | "file";
diff --git a/packages/asset-uploader/src/utils/format-asset.ts b/packages/asset-uploader/src/utils/format-asset.ts
index 08b5f5a00e..8bfc009d80 100644
--- a/packages/asset-uploader/src/utils/format-asset.ts
+++ b/packages/asset-uploader/src/utils/format-asset.ts
@@ -22,6 +22,7 @@ export const formatAsset = ({
};
}): Asset => {
const isFont = FONT_FORMATS.has(file.format as FontFormat);
+ const parsedMeta = JSON.parse(file.meta);
if (isFont) {
return {
@@ -34,10 +35,32 @@ export const formatAsset = ({
type: "font",
createdAt: file.createdAt,
format: file.format as FontFormat,
- meta: FontMeta.parse(JSON.parse(file.meta)),
+ meta: FontMeta.parse(parsedMeta),
};
}
+ // Check if it's an image by checking if meta has width and height
+ const isImage =
+ parsedMeta &&
+ typeof parsedMeta.width === "number" &&
+ typeof parsedMeta.height === "number";
+
+ if (isImage) {
+ return {
+ id: assetId,
+ name: file.name,
+ projectId,
+ filename: filename ?? undefined,
+ description: description ?? undefined,
+ size: file.size,
+ type: "image",
+ format: file.format,
+ createdAt: file.createdAt,
+ meta: ImageMeta.parse(parsedMeta),
+ };
+ }
+
+ // Default to file type for everything else
return {
id: assetId,
name: file.name,
@@ -45,9 +68,9 @@ export const formatAsset = ({
filename: filename ?? undefined,
description: description ?? undefined,
size: file.size,
- type: "image",
+ type: "file",
format: file.format,
createdAt: file.createdAt,
- meta: ImageMeta.parse(JSON.parse(file.meta)),
+ meta: {},
};
};
diff --git a/packages/asset-uploader/src/utils/get-asset-data.ts b/packages/asset-uploader/src/utils/get-asset-data.ts
index 89d8a6982a..77d0ec5ca5 100644
--- a/packages/asset-uploader/src/utils/get-asset-data.ts
+++ b/packages/asset-uploader/src/utils/get-asset-data.ts
@@ -1,19 +1,19 @@
import { z } from "zod";
import { imageMeta } from "image-meta";
import { FontMeta } from "@webstudio-is/fonts";
-import { ImageMeta } from "@webstudio-is/sdk";
+import { ImageMeta, validateFileName } from "@webstudio-is/sdk";
import { getFontData } from "./font-data";
export type AssetData = {
size: number;
format: string;
- meta: ImageMeta | FontMeta;
+ meta: ImageMeta | FontMeta | object;
};
export const AssetData: z.ZodType<AssetData> = z.object({
size: z.number(),
format: z.string(),
- meta: z.union([ImageMeta, FontMeta]),
+ meta: z.union([ImageMeta, FontMeta, z.object({})]),
});
type BaseAssetOptions = {
@@ -26,7 +26,8 @@ type AssetOptions =
| ({
type: "image";
} & BaseAssetOptions)
- | ({ type: "font" } & BaseAssetOptions);
+ | ({ type: "font" } & BaseAssetOptions)
+ | ({ type: "file" } & BaseAssetOptions);
export const getAssetData = async (
options: AssetOptions
@@ -56,11 +57,23 @@ export const getAssetData = async (
meta: { width, height },
};
}
- const { format, ...meta } = getFontData(options.data, options.name);
+
+ if (options.type === "font") {
+ const { format, ...meta } = getFontData(options.data, options.name);
+
+ return {
+ size: options.size,
+ format,
+ meta,
+ };
+ }
+
+ // Validate file name and get extension
+ const { extension } = validateFileName(options.name);
return {
size: options.size,
- format,
- meta,
+ format: extension,
+ meta: {},
};
};
diff --git a/packages/asset-uploader/src/utils/mime.test.ts b/packages/asset-uploader/src/utils/mime.test.ts
deleted file mode 100644
index 486ac3665e..0000000000
--- a/packages/asset-uploader/src/utils/mime.test.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import { describe, test, expect } from "vitest";
-import {
- acceptToMimePatterns,
- acceptToMimeCategories,
- getAssetMime,
- doesAssetMatchMimePatterns,
-} from "./mime";
-
-describe("acceptToMimePatterns", () => {
- test("returns * if accept is empty or * or */*", () => {
- expect(acceptToMimePatterns("")).toBe("*");
- expect(acceptToMimePatterns("*")).toBe("*");
- expect(acceptToMimePatterns("*/*")).toBe("*");
- expect(acceptToMimePatterns("*,.png")).toBe("*");
- });
-
- test("returns * if it doesn't recognise a pattern", () => {
- expect(acceptToMimePatterns("image/wrong")).toBe("*");
- expect(acceptToMimePatterns("wrong/*")).toBe("*");
- expect(acceptToMimePatterns(".wrong")).toBe("*");
- });
-
- test("leaves full mimes as is", () => {
- expect(acceptToMimePatterns("image/png,font/otf")).toEqual(
- new Set(["image/png", "font/otf"])
- );
- });
-
- test("leaves mime patterns as is", () => {
- expect(acceptToMimePatterns("image/*,font/*")).toEqual(
- new Set(["image/*", "font/*"])
- );
- });
-
- test("converts extensions to mimes", () => {
- expect(acceptToMimePatterns(".svg,.otf")).toEqual(
- new Set(["image/svg+xml", "font/otf"])
- );
- });
-});
-
-describe("acceptToMimeCategories", () => {
- test("returns * if accept is empty or * or */*", () => {
- expect(acceptToMimeCategories("")).toBe("*");
- expect(acceptToMimeCategories("*")).toBe("*");
- expect(acceptToMimeCategories("*/*")).toBe("*");
- expect(acceptToMimeCategories("*,.png")).toBe("*");
- });
-
- test("returns * if it doesn't recognise a pattern", () => {
- expect(acceptToMimeCategories("image/wrong")).toBe("*");
- expect(acceptToMimeCategories("wrong/*")).toBe("*");
- expect(acceptToMimeCategories(".wrong")).toBe("*");
- });
-
- test("handles full mimes", () => {
- expect(acceptToMimeCategories("image/png,font/otf")).toEqual(
- new Set(["image", "font"])
- );
- });
-
- test("handles mime patterns", () => {
- expect(acceptToMimeCategories("image/*,font/*")).toEqual(
- new Set(["image", "font"])
- );
- });
-
- test("handles extensions", () => {
- expect(acceptToMimeCategories(".svg,.otf")).toEqual(
- new Set(["image", "font"])
- );
- });
-});
-
-describe("getAssetMime", () => {
- test("handles woff", () => {
- expect(getAssetMime({ type: "font", format: "woff" })).toBe("font/woff");
- });
-
- test("handles png", () => {
- expect(getAssetMime({ type: "image", format: "png" })).toBe("image/png");
- });
-
- test("handles svg", () => {
- expect(getAssetMime({ type: "image", format: "svg" })).toBe(
- "image/svg+xml"
- );
- });
-
- test("returns undefined for unknown format", () => {
- expect(getAssetMime({ type: "image", format: "unknown" })).toBeUndefined();
- });
-});
-
-describe("doesAssetMatchMimePatterns", () => {
- test("returns true if mime patterns is *", () => {
- expect(
- doesAssetMatchMimePatterns({ type: "image", format: "png" }, "*")
- ).toBe(true);
- });
-
- test("handles full mimes", () => {
- expect(
- doesAssetMatchMimePatterns(
- { type: "image", format: "svg" },
- new Set(["image/svg+xml"])
- )
- ).toBe(true);
- expect(
- doesAssetMatchMimePatterns(
- { type: "image", format: "svg" },
- new Set(["image/png"])
- )
- ).toBe(false);
- });
-
- test("handles mime patterns", () => {
- expect(
- doesAssetMatchMimePatterns(
- { type: "image", format: "svg" },
- new Set(["image/*"])
- )
- ).toBe(true);
- expect(
- doesAssetMatchMimePatterns(
- { type: "image", format: "svg" },
- new Set(["font/*"])
- )
- ).toBe(false);
- });
-
- test("if asset format has unexpected value, returns false", () => {
- expect(
- doesAssetMatchMimePatterns(
- { type: "image", format: "unknown" },
- new Set(["image/*"])
- )
- ).toBe(false);
- });
-});
diff --git a/packages/asset-uploader/src/utils/mime.ts b/packages/asset-uploader/src/utils/mime.ts
deleted file mode 100644
index d1fd0cadb7..0000000000
--- a/packages/asset-uploader/src/utils/mime.ts
+++ /dev/null
@@ -1,231 +0,0 @@
-// Utils related to MIME types and the `accept` attribute value format
-// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept
-
-import warnOnce from "warn-once";
-import type { Asset } from "@webstudio-is/sdk";
-
-const mimeCategories = [
- "image",
- "audio",
- "video",
- "font",
- "text",
- "application",
-] as const;
-
-type MimeCategory = (typeof mimeCategories)[number];
-
-const extensionToMime = new Map([
- [".avif", "image/avif"],
- [".bmp", "image/bmp"],
- [".gif", "image/gif"],
- [".ico", "image/vnd.microsoft.icon"],
- [".jpeg", "image/jpeg"],
- [".jpg", "image/jpeg"],
- [".png", "image/png"],
- [".svg", "image/svg+xml"],
- [".tif", "image/tiff"],
- [".tiff", "image/tiff"],
- [".webp", "image/webp"],
- [".woff", "font/woff"],
- [".woff2", "font/woff2"],
- [".ttf", "font/ttf"],
- [".otf", "font/otf"],
-]);
-
-const mimeTypes = new Set(extensionToMime.values());
-
-const mimePatterns = new Set([
- ...mimeTypes.values(),
- ...mimeCategories.map((category): `${MimeCategory}/*` => `${category}/*`),
-]);
-
-const getCategory = (pattern: string): MimeCategory => {
- const categoryAsString = pattern.split("/")[0];
- const category = mimeCategories.find(
- (category) => category === categoryAsString
- );
- if (category === undefined) {
- throw new Error(`Invalid mime pattern: ${pattern}`);
- }
- return category;
-};
-
-/** `".svg,font/otf,text/*"` -> `"image/svg+xml", "font/otf", "text/*"` */
-export const acceptToMimePatterns = (accept: string): Set<string> | "*" => {
- const result = new Set<string>();
-
- if (accept === "") {
- return "*";
- }
-
- for (const type of accept.split(",")) {
- const trimmed = type.trim();
- if (trimmed === "*" || trimmed === "*/*") {
- return "*";
- }
- if (mimePatterns.has(trimmed)) {
- result.add(trimmed);
- continue;
- }
- const mime = extensionToMime.get(trimmed);
-
- if (mime === undefined) {
- warnOnce(
- true,
- `Couldn't not parse accept attribute value: ${trimmed}. Falling back to "*".`
- );
- return "*";
- }
-
- result.add(mime);
- }
-
- return result;
-};
-
-/** `".svg,font/otf,text/*"` -> `"image", "font", "text"` */
-export const acceptToMimeCategories = (accept: string): Set<string> | "*" => {
- const patterns = acceptToMimePatterns(accept);
- if (patterns === "*") {
- return "*";
- }
- return new Set(Array.from(patterns).map(getCategory));
-};
-
-export const getAssetMime = ({
- type,
- format,
-}: {
- type: "image" | "font";
- format: string;
-}): string | undefined => {
- const mime = `${type}/${format}`;
- if (mimeTypes.has(mime)) {
- return mime;
- }
- const mime2 = extensionToMime.get(`.${format}`);
- if (mime2 === undefined) {
- warnOnce(
- true,
- `Couldn't determine mime type of asset: ${type}, ${format}.`
- );
- }
- return mime2;
-};
-
-export const doesAssetMatchMimePatterns = (
- asset: Pick<Asset, "format" | "type">,
- patterns: Set<string> | "*"
-): boolean => {
- if (patterns === "*") {
- return true;
- }
-
- const mime = getAssetMime(asset);
-
- if (mime === undefined) {
- return false;
- }
-
- return patterns.has(mime) || patterns.has(`${getCategory(mime)}/*`);
-};
-
-export const getMimeByExtension = (ext: string): string => {
- return extensionToMime.get(ext) ?? "unknown";
-};
-
-// Didn't delete because we may need this later
-// From https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
-// const extentionToMime: [
-// string,
-// Array<`${(typeof mimeCategories)[number]}/${string}`>
-// ][] = [
-// [".aac", ["audio/aac"]], // AAC audio
-// [".abw", ["application/x-abiword"]], // AbiWord document
-// [".arc", ["application/x-freearc"]], // Archive document (multiple files embedded)
-// [".avif", ["image/avif"]], // AVIF image
-// [".avi", ["video/x-msvideo"]], // AVI: Audio Video Interleave
-// [".azw", ["application/vnd.amazon.ebook"]], // Amazon Kindle eBook format
-// [".bin", ["application/octet-stream"]], // Any kind of binary data
-// [".bmp", ["image/bmp"]], // Windows OS/2 Bitmap Graphics
-// [".bz", ["application/x-bzip"]], // BZip archive
-// [".bz2", ["application/x-bzip2"]], // BZip2 archive
-// [".cda", ["application/x-cdf"]], // CD audio
-// [".csh", ["application/x-csh"]], // C-Shell script
-// [".css", ["text/css"]], // Cascading Style Sheets (CSS)
-// [".csv", ["text/csv"]], // Comma-separated values (CSV)
-// [".doc", ["application/msword"]], // Microsoft Word
-// [
-// ".docx",
-// ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
-// ], // Microsoft Word (OpenXML)
-// [".eot", ["application/vnd.ms-fontobject"]], // MS Embedded OpenType fonts
-// [".epub", ["application/epub+zip"]], // Electronic publication (EPUB)
-// [".gz", ["application/gzip"]], // GZip Compressed Archive
-// [".gif", ["image/gif"]], // Graphics Interchange Format (GIF)
-// [".htm", ["text/html"]], // HyperText Markup Language (HTML)
-// [".html", ["text/html"]],
-// [".ico", ["image/vnd.microsoft.icon"]], // Icon format
-// [".ics", ["text/calendar"]], // iCalendar format
-// [".jar", ["application/java-archive"]], // Java Archive (JAR)
-// [".jpeg", ["image/jpeg"]], // JPEG images
-// [".jpg", ["image/jpeg"]],
-// [".js", ["text/javascript"]], // JavaScript
-// [".json", ["application/json"]], // JSON format
-// [".jsonld", ["application/ld+json"]], // JSON-LD format
-// [".mid", ["audio/midi", "audio/x-midi"]], // Musical Instrument Digital Interface (MIDI)
-// [".midi", ["audio/midi", "audio/x-midi"]],
-// [".mjs", ["text/javascript"]], // JavaScript module
-// [".mp3", ["audio/mpeg"]], // MP3 audio
-// [".mp4", ["video/mp4"]], // MP4 video
-// [".mpeg", ["video/mpeg"]], // MPEG Video
-// [".mpkg", ["application/vnd.apple.installer+xml"]], // Apple Installer Package
-// [".odp", ["application/vnd.oasis.opendocument.presentation"]], // OpenDocument presentation document
-// [".ods", ["application/vnd.oasis.opendocument.spreadsheet"]], // OpenDocument spreadsheet document
-// [".odt", ["application/vnd.oasis.opendocument.text"]], // OpenDocument text document
-// [".oga", ["audio/ogg"]], // OGG audio
-// [".ogv", ["video/ogg"]], // OGG video
-// [".ogx", ["application/ogg"]], // OGG
-// [".opus", ["audio/opus"]], // Opus audio
-// [".otf", ["font/otf"]], // OpenType font
-// [".png", ["image/png"]], // Portable Network Graphics
-// [".pdf", ["application/pdf"]], // Adobe Portable Document Format (PDF)
-// [".php", ["application/x-httpd-php"]], // Hypertext Preprocessor (Personal Home Page)
-// [".ppt", ["application/vnd.ms-powerpoint"]], // Microsoft PowerPoint
-// [
-// ".pptx",
-// [
-// "application/vnd.openxmlformats-officedocument.presentationml.presentation",
-// ],
-// ], // Microsoft PowerPoint (OpenXML)
-// [".rar", ["application/vnd.rar"]], // RAR archive
-// [".rtf", ["application/rtf"]], // Rich Text Format (RTF)
-// [".sh", ["application/x-sh"]], // Bourne shell script
-// [".svg", ["image/svg+xml"]], // Scalable Vector Graphics (SVG)
-// [".tar", ["application/x-tar"]], // Tape Archive (TAR)
-// [".tif", ["image/tiff"]], // Tagged Image File Format (TIFF)
-// [".tiff", ["image/tiff"]],
-// [".ts", ["video/mp2t"]], // MPEG transport stream
-// [".ttf", ["font/ttf"]], // TrueType Font
-// [".txt", ["text/plain"]], // Text, (generally ASCII or ISO 8859-n)
-// [".vsd", ["application/vnd.visio"]], // Microsoft Visio
-// [".wav", ["audio/wav"]], // Waveform Audio Format
-// [".weba", ["audio/webm"]], // WEBM audio
-// [".webm", ["video/webm"]], // WEBM video
-// [".webp", ["image/webp"]], // WEBP image
-// [".woff", ["font/woff"]], // Web Open Font Format (WOFF)
-// [".woff2", ["font/woff2"]], // Web Open Font Format (WOFF)
-// [".xhtml", ["application/xhtml+xml"]], // XHTML
-// [".xls", ["application/vnd.ms-excel"]], // Microsoft Excel
-// [
-// ".xlsx",
-// ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
-// ], // Microsoft Excel (OpenXML)
-// [".xml", ["application/xml", "text/xml"]], // XML
-// [".xul", ["application/vnd.mozilla.xul+xml"]], // XUL
-// [".zip", ["application/zip"]], // ZIP archive
-// [".3gp", ["video/3gpp", "audio/3gpp"]], // 3GPP audio/video container
-// [".3g2", ["video/3gpp2", "audio/3gpp2"]], // 3GPP2 audio/video container
-// [".7z", ["application/x-7z-compressed"]], // 7-zip archive
-// ];
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 1a02b4ed05..2fcb8b6b2f 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -44,6 +44,7 @@
"picocolors": "^1.1.1",
"reserved-identifiers": "^1.0.0",
"tinyexec": "^0.3.2",
+ "warn-once": "^0.1.1",
"yargs": "^17.7.2",
"zod": "^3.24.2"
},
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 29f777cc52..2b99621e9c 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -46,6 +46,7 @@ import {
generateCss,
ROOT_INSTANCE_ID,
elementComponent,
+ getAssetUrl,
} from "@webstudio-is/sdk";
import type { Data } from "@webstudio-is/http-client";
import { LOCAL_DATA_FILE } from "./config";
@@ -427,24 +428,16 @@ export const prebuild = async (options: {
if (options.assets === true) {
const assetOrigin = siteData.origin;
- for (const asset of siteData.assets) {
- if (asset.type === "image") {
- assetsToDownload.push(
- limit(() =>
- downloadAsset(
- `${assetOrigin}/cgi/image/${asset.name}?format=raw`,
- asset.name,
- assetBaseUrl
- )
- )
- );
- }
+ if (!assetOrigin) {
+ console.warn("Warning: Asset origin is not defined in project data.");
+ }
- if (asset.type === "font") {
+ for (const asset of siteData.assets) {
+ if (asset.type === "image" || asset.type === "font") {
assetsToDownload.push(
limit(() =>
downloadAsset(
- `${assetOrigin}/cgi/asset/${asset.name}`,
+ getAssetUrl(asset, assetOrigin || "").href,
asset.name,
assetBaseUrl
)
diff --git a/packages/design-system/src/components/progress-radial.tsx b/packages/design-system/src/components/progress-radial.tsx
deleted file mode 100644
index acd3e9e3ae..0000000000
--- a/packages/design-system/src/components/progress-radial.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { type ComponentProps, type ElementRef, forwardRef } from "react";
-import type { CSS } from "../stitches.config";
-import * as ProgressPrimitive from "@radix-ui/react-progress";
-import { Box } from "./box";
-
-type ProgressBarPrimitiveProps = ComponentProps<typeof ProgressPrimitive.Root>;
-type ProgressRadialProps = ProgressBarPrimitiveProps & { css?: CSS };
-
-export const ProgressRadial = forwardRef<
- ElementRef<typeof ProgressPrimitive.Root>,
- ProgressRadialProps
->(({ value, max = 100, css, ...props }, forwardedRef) => {
- const percentage = value != null ? Math.round((value / max) * 100) : 0;
- const multiplicate = 360 / max;
-
- return (
- <ProgressPrimitive.Root
- {...props}
- value={value}
- max={max}
- ref={forwardedRef}
- >
- <Box
- css={css}
- as="svg"
- width="64"
- height="64"
- viewBox="0 0 64 64"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- <circle cx="32" cy="32" r="24" />
- <path
- d="M36.3989 32.0385C36.9929 32.616 37.9425 32.6026 38.52 32.0086C39.0975 31.4147 39.0841 30.465 38.4901 29.8875L36.3989 32.0385ZM32.1112 25.7778L33.1568 24.7023C32.5746 24.1363 31.6477 24.1363 31.0655 24.7023L32.1112 25.7778ZM25.7322 29.8875C25.1382 30.465 25.1249 31.4147 25.7023 32.0086C26.2798 32.6026 27.2295 32.616 27.8234 32.0385L25.7322 29.8875ZM30.6112 38.2223C30.6112 39.0507 31.2827 39.7223 32.1112 39.7223C32.9396 39.7223 33.6112 39.0507 33.6112 38.2223H30.6112ZM38.4901 29.8875L33.1568 24.7023L31.0655 26.8533L36.3989 32.0385L38.4901 29.8875ZM31.0655 24.7023L25.7322 29.8875L27.8234 32.0385L33.1568 26.8533L31.0655 24.7023ZM33.6112 38.2223V25.7778H30.6112V38.2223H33.6112Z"
- fill="white"
- />
- <circle
- fill="none"
- stroke="white"
- strokeWidth="3"
- cx="32"
- cy="32"
- r="18"
- strokeDasharray={360}
- strokeDashoffset={360 - percentage * multiplicate}
- ></circle>
- </Box>
- </ProgressPrimitive.Root>
- );
-});
-ProgressRadial.displayName = "ProgressRadial";
diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.ts
index 83628c588f..898ed28645 100644
--- a/packages/design-system/src/index.ts
+++ b/packages/design-system/src/index.ts
@@ -67,7 +67,6 @@ export * from "./components/toast";
export * as Collapsible from "@radix-ui/react-collapsible";
export { AccessibleIcon } from "@radix-ui/react-accessible-icon";
export * from "./components/toggle-group";
-export * from "./components/progress-radial";
export * from "./components/progress";
export { SearchField, useSearchFieldKeys } from "./components/search-field";
export { Tabs, TabsContent, TabsList, TabsTrigger } from "@radix-ui/react-tabs";
diff --git a/packages/icons/icons/arrow-down-narrow-wide.svg b/packages/icons/icons/arrow-down-narrow-wide.svg
new file mode 100644
index 0000000000..6bada34c9e
--- /dev/null
+++ b/packages/icons/icons/arrow-down-narrow-wide.svg
@@ -0,0 +1,43 @@
+<svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+>
+ <path
+ d="M2 10.6667L4.66667 13.3333L7.33333 10.6667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M4.66669 13.3333V2.66667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M7.33331 2.66667H9.99998"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M7.33331 5.33333H12"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M7.33331 8H14"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+</svg>
diff --git a/packages/icons/icons/arrow-down-wide-narrow.svg b/packages/icons/icons/arrow-down-wide-narrow.svg
new file mode 100644
index 0000000000..aa9011ab83
--- /dev/null
+++ b/packages/icons/icons/arrow-down-wide-narrow.svg
@@ -0,0 +1,43 @@
+<svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+>
+ <path
+ d="M2 10.6667L4.66667 13.3333L7.33333 10.6667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M4.66669 13.3333V2.66667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M7.33331 2.66667H14"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M7.33331 5.33333H12"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M7.33331 8H9.99998"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+</svg>
diff --git a/packages/icons/icons/arrow-down-z-a.svg b/packages/icons/icons/arrow-down-z-a.svg
new file mode 100644
index 0000000000..305f9b6f9c
--- /dev/null
+++ b/packages/icons/icons/arrow-down-z-a.svg
@@ -0,0 +1,43 @@
+<svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+>
+ <path
+ d="M2 10.6667L4.66667 13.3333L7.33333 10.6667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M4.66669 2.66667V13.3333"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M10 2.66667H13.3333L10 6.66667H13.3333"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M10 13.3333V11C10 10.558 10.1756 10.134 10.4882 9.82148C10.8007 9.50892 11.2246 9.33333 11.6667 9.33333C12.1087 9.33333 12.5326 9.50892 12.8452 9.82148C13.1577 10.134 13.3333 10.558 13.3333 11V13.3333"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M13.3333 12H10"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+</svg>
diff --git a/packages/icons/src/__generated__/components.tsx b/packages/icons/src/__generated__/components.tsx
index f81ae50fa7..ddfff73570 100644
--- a/packages/icons/src/__generated__/components.tsx
+++ b/packages/icons/src/__generated__/components.tsx
@@ -795,6 +795,81 @@ export const ArrowDownAZIcon: IconComponent = forwardRef(
);
ArrowDownAZIcon.displayName = "ArrowDownAZIcon";
+export const ArrowDownNarrowWideIcon: IconComponent = forwardRef(
+ ({ fill = "none", size = 16, ...props }, forwardedRef) => {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 16 16"
+ width={size}
+ height={size}
+ fill={fill}
+ {...props}
+ ref={forwardedRef}
+ >
+ <path
+ stroke="#000"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth=".667"
+ d="m2 10.667 2.667 2.666 2.666-2.666M4.667 13.333V2.667M7.333 2.667H10M7.333 5.333H12M7.333 8H14"
+ />
+ </svg>
+ );
+ }
+);
+ArrowDownNarrowWideIcon.displayName = "ArrowDownNarrowWideIcon";
+
+export const ArrowDownWideNarrowIcon: IconComponent = forwardRef(
+ ({ fill = "none", size = 16, ...props }, forwardedRef) => {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 16 16"
+ width={size}
+ height={size}
+ fill={fill}
+ {...props}
+ ref={forwardedRef}
+ >
+ <path
+ stroke="#000"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth=".667"
+ d="m2 10.667 2.667 2.666 2.666-2.666M4.667 13.333V2.667M7.333 2.667H14M7.333 5.333H12M7.333 8H10"
+ />
+ </svg>
+ );
+ }
+);
+ArrowDownWideNarrowIcon.displayName = "ArrowDownWideNarrowIcon";
+
+export const ArrowDownZAIcon: IconComponent = forwardRef(
+ ({ fill = "none", size = 16, ...props }, forwardedRef) => {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 16 16"
+ width={size}
+ height={size}
+ fill={fill}
+ {...props}
+ ref={forwardedRef}
+ >
+ <path
+ stroke="#000"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth=".667"
+ d="m2 10.667 2.667 2.666 2.666-2.666M4.667 2.667v10.666M10 2.667h3.333l-3.333 4h3.333M10 13.333V11a1.667 1.667 0 1 1 3.333 0v2.333M13.333 12H10"
+ />
+ </svg>
+ );
+ }
+);
+ArrowDownZAIcon.displayName = "ArrowDownZAIcon";
+
export const ArrowDownIcon: IconComponent = forwardRef(
({ fill = "none", size = 16, ...props }, forwardedRef) => {
return (
diff --git a/packages/icons/src/__generated__/svg.ts b/packages/icons/src/__generated__/svg.ts
index 9feb59e17c..cf0abf7eaf 100644
--- a/packages/icons/src/__generated__/svg.ts
+++ b/packages/icons/src/__generated__/svg.ts
@@ -54,6 +54,12 @@ export const AnimationGroupIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill=
export const ArrowDownAZIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width=".667" d="m2 10.667 2.667 2.666 2.666-2.666M4.667 13.333V2.667M13.333 5.333H10M10 6.667V4.333a1.667 1.667 0 1 1 3.333 0v2.334M10 9.333h3.333l-3.333 4h3.333"/></svg>`;
+export const ArrowDownNarrowWideIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width=".667" d="m2 10.667 2.667 2.666 2.666-2.666M4.667 13.333V2.667M7.333 2.667H10M7.333 5.333H12M7.333 8H14"/></svg>`;
+
+export const ArrowDownWideNarrowIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width=".667" d="m2 10.667 2.667 2.666 2.666-2.666M4.667 13.333V2.667M7.333 2.667H14M7.333 5.333H12M7.333 8H10"/></svg>`;
+
+export const ArrowDownZAIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width=".667" d="m2 10.667 2.667 2.666 2.666-2.666M4.667 2.667v10.666M10 2.667h3.333l-3.333 4h3.333M10 13.333V11a1.667 1.667 0 1 1 3.333 0v2.333M13.333 12H10"/></svg>`;
+
export const ArrowDownIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M8 3.333v9.334M12.667 8 8 12.667 3.333 8"/></svg>`;
export const ArrowLeftIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12.667 8H3.333M8 3.333 3.333 8 8 12.667"/></svg>`;
diff --git a/packages/sdk-components-react/src/image.ws.ts b/packages/sdk-components-react/src/image.ws.ts
index 4da1c2164f..197d8a1d3b 100644
--- a/packages/sdk-components-react/src/image.ws.ts
+++ b/packages/sdk-components-react/src/image.ws.ts
@@ -52,6 +52,7 @@ export const meta: WsComponentMeta = {
control: "file",
label: "Source",
required: false,
+ accept: "image/*",
},
},
};
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index 0cef9f8c0a..b1f64b6b7c 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -50,6 +50,7 @@
"change-case": "^5.4.4",
"reserved-identifiers": "^1.0.0",
"type-fest": "^4.37.0",
+ "warn-once": "^0.1.1",
"zod": "^3.24.2"
},
"devDependencies": {
diff --git a/packages/sdk/src/assets.test.ts b/packages/sdk/src/assets.test.ts
new file mode 100644
index 0000000000..f7aad41d3e
--- /dev/null
+++ b/packages/sdk/src/assets.test.ts
@@ -0,0 +1,836 @@
+import { describe, test, expect } from "vitest";
+import {
+ ALLOWED_FILE_TYPES,
+ getMimeTypeByExtension,
+ getMimeTypeByFilename,
+ isAllowedExtension,
+ isAllowedMimeCategory,
+ validateFileName,
+ IMAGE_EXTENSIONS,
+ IMAGE_MIME_TYPES,
+ VIDEO_EXTENSIONS,
+ VIDEO_MIME_TYPES,
+ FONT_EXTENSIONS,
+ FILE_EXTENSIONS_BY_CATEGORY,
+ detectAssetType,
+ decodePathFragment,
+ getAssetUrl,
+ acceptToMimePatterns,
+ acceptToMimeCategories,
+ getAssetMime,
+ doesAssetMatchMimePatterns,
+} from "./assets";
+
+describe("allowed-file-types", () => {
+ describe("getMimeTypeByExtension", () => {
+ test("returns correct MIME type for valid extension", () => {
+ expect(getMimeTypeByExtension("jpg")).toBe("image/jpeg");
+ expect(getMimeTypeByExtension("png")).toBe("image/png");
+ expect(getMimeTypeByExtension("pdf")).toBe("application/pdf");
+ expect(getMimeTypeByExtension("mp4")).toBe("video/mp4");
+ });
+
+ test("is case-insensitive", () => {
+ expect(getMimeTypeByExtension("JPG")).toBe("image/jpeg");
+ expect(getMimeTypeByExtension("PNG")).toBe("image/png");
+ expect(getMimeTypeByExtension("PDF")).toBe("application/pdf");
+ });
+
+ test("returns undefined for invalid extension", () => {
+ expect(getMimeTypeByExtension("exe")).toBeUndefined();
+ expect(getMimeTypeByExtension("xyz")).toBeUndefined();
+ });
+ });
+
+ describe("getMimeTypeByFilename", () => {
+ test("extracts extension and returns MIME type", () => {
+ expect(getMimeTypeByFilename("image.jpg")).toBe("image/jpeg");
+ expect(getMimeTypeByFilename("document.pdf")).toBe("application/pdf");
+ expect(getMimeTypeByFilename("video.mp4")).toBe("video/mp4");
+ });
+
+ test("handles files with multiple dots", () => {
+ expect(getMimeTypeByFilename("my.file.name.jpg")).toBe("image/jpeg");
+ expect(getMimeTypeByFilename("archive.tar.gz")).toBe(
+ "application/octet-stream"
+ );
+ });
+
+ test("is case-insensitive", () => {
+ expect(getMimeTypeByFilename("IMAGE.JPG")).toBe("image/jpeg");
+ expect(getMimeTypeByFilename("Document.PDF")).toBe("application/pdf");
+ });
+
+ test("returns octet-stream for invalid extension", () => {
+ expect(getMimeTypeByFilename("file.exe")).toBe(
+ "application/octet-stream"
+ );
+ expect(getMimeTypeByFilename("file.xyz")).toBe(
+ "application/octet-stream"
+ );
+ });
+
+ test("returns octet-stream for files without extension", () => {
+ expect(getMimeTypeByFilename("filename")).toBe(
+ "application/octet-stream"
+ );
+ expect(getMimeTypeByFilename("")).toBe("application/octet-stream");
+ });
+ });
+
+ describe("isAllowedExtension", () => {
+ test("returns true for valid extensions", () => {
+ expect(isAllowedExtension("jpg")).toBe(true);
+ expect(isAllowedExtension("png")).toBe(true);
+ expect(isAllowedExtension("pdf")).toBe(true);
+ expect(isAllowedExtension("mp4")).toBe(true);
+ });
+
+ test("is case-insensitive", () => {
+ expect(isAllowedExtension("JPG")).toBe(true);
+ expect(isAllowedExtension("PNG")).toBe(true);
+ expect(isAllowedExtension("PDF")).toBe(true);
+ });
+
+ test("returns false for invalid extensions", () => {
+ expect(isAllowedExtension("exe")).toBe(false);
+ expect(isAllowedExtension("sh")).toBe(false);
+ expect(isAllowedExtension("bat")).toBe(false);
+ });
+ });
+
+ describe("isAllowedMimeCategory", () => {
+ test("returns true for valid MIME categories", () => {
+ expect(isAllowedMimeCategory("image")).toBe(true);
+ expect(isAllowedMimeCategory("video")).toBe(true);
+ expect(isAllowedMimeCategory("audio")).toBe(true);
+ expect(isAllowedMimeCategory("font")).toBe(true);
+ expect(isAllowedMimeCategory("text")).toBe(true);
+ expect(isAllowedMimeCategory("application")).toBe(true);
+ });
+
+ test("returns false for invalid MIME categories", () => {
+ expect(isAllowedMimeCategory("executable/binary")).toBe(false);
+ expect(isAllowedMimeCategory("script/javascript")).toBe(false);
+ });
+
+ test("handles malformed MIME types", () => {
+ expect(isAllowedMimeCategory("notamimetype")).toBe(false);
+ expect(isAllowedMimeCategory("")).toBe(false);
+ });
+ });
+
+ describe("validateFileName", () => {
+ test("returns extension and MIME type for valid files", () => {
+ expect(validateFileName("image.jpg")).toEqual({
+ extension: "jpg",
+ mimeType: "image/jpeg",
+ });
+ expect(validateFileName("document.pdf")).toEqual({
+ extension: "pdf",
+ mimeType: "application/pdf",
+ });
+ });
+
+ test("is case-insensitive", () => {
+ expect(validateFileName("IMAGE.JPG")).toEqual({
+ extension: "jpg",
+ mimeType: "image/jpeg",
+ });
+ });
+
+ test("handles files with multiple dots", () => {
+ expect(validateFileName("my.file.name.png")).toEqual({
+ extension: "png",
+ mimeType: "image/png",
+ });
+ });
+
+ test("throws error for files without extension", () => {
+ expect(() => validateFileName("filename")).toThrow(
+ 'File type "filename" is not allowed'
+ );
+ // Empty string results in no extension either
+ expect(() => validateFileName("file.")).toThrow(
+ "File must have an extension"
+ );
+ });
+
+ test("throws error for disallowed extensions", () => {
+ expect(() => validateFileName("malware.exe")).toThrow(
+ 'File type "exe" is not allowed'
+ );
+ expect(() => validateFileName("script.sh")).toThrow(
+ 'File type "sh" is not allowed'
+ );
+ });
+
+ test("error message includes list of allowed types", () => {
+ try {
+ validateFileName("bad.xyz");
+ } catch (error) {
+ expect((error as Error).message).toContain("Allowed types:");
+ expect((error as Error).message).toContain("jpg");
+ expect((error as Error).message).toContain("png");
+ }
+ });
+ });
+
+ describe("IMAGE_EXTENSIONS", () => {
+ test("is an array", () => {
+ expect(Array.isArray(IMAGE_EXTENSIONS)).toBe(true);
+ expect(IMAGE_EXTENSIONS.length).toBeGreaterThan(0);
+ });
+
+ test("all extensions are image types", () => {
+ IMAGE_EXTENSIONS.forEach((ext) => {
+ const mimeType = getMimeTypeByExtension(ext);
+ expect(mimeType?.startsWith("image/")).toBe(true);
+ });
+ });
+ });
+
+ describe("IMAGE_MIME_TYPES", () => {
+ test("is an array of MIME types", () => {
+ expect(Array.isArray(IMAGE_MIME_TYPES)).toBe(true);
+ expect(IMAGE_MIME_TYPES.length).toBeGreaterThan(0);
+ });
+
+ test("all MIME types start with image/", () => {
+ IMAGE_MIME_TYPES.forEach((mime) => {
+ expect(mime.startsWith("image/")).toBe(true);
+ });
+ });
+ });
+
+ describe("VIDEO_EXTENSIONS", () => {
+ test("is an array", () => {
+ expect(Array.isArray(VIDEO_EXTENSIONS)).toBe(true);
+ expect(VIDEO_EXTENSIONS.length).toBeGreaterThan(0);
+ });
+
+ test("all extensions are video types", () => {
+ VIDEO_EXTENSIONS.forEach((ext) => {
+ const mimeType = getMimeTypeByExtension(ext);
+ expect(mimeType?.startsWith("video/")).toBe(true);
+ });
+ });
+ });
+
+ describe("VIDEO_MIME_TYPES", () => {
+ test("is an array of MIME types", () => {
+ expect(Array.isArray(VIDEO_MIME_TYPES)).toBe(true);
+ expect(VIDEO_MIME_TYPES.length).toBeGreaterThan(0);
+ });
+
+ test("all MIME types start with video/", () => {
+ VIDEO_MIME_TYPES.forEach((mime) => {
+ expect(mime.startsWith("video/")).toBe(true);
+ });
+ });
+ });
+
+ describe("FONT_EXTENSIONS", () => {
+ test("is an array", () => {
+ expect(Array.isArray(FONT_EXTENSIONS)).toBe(true);
+ expect(FONT_EXTENSIONS.length).toBeGreaterThan(0);
+ });
+
+ test("all extensions are font types", () => {
+ FONT_EXTENSIONS.forEach((ext) => {
+ const mimeType = getMimeTypeByExtension(ext);
+ expect(mimeType?.startsWith("font/")).toBe(true);
+ });
+ });
+
+ test("includes common font formats", () => {
+ expect(FONT_EXTENSIONS).toContain("woff");
+ expect(FONT_EXTENSIONS).toContain("woff2");
+ expect(FONT_EXTENSIONS).toContain("ttf");
+ expect(FONT_EXTENSIONS).toContain("otf");
+ });
+ });
+
+ describe("FILE_EXTENSIONS_BY_CATEGORY", () => {
+ test("has all expected categories", () => {
+ expect(FILE_EXTENSIONS_BY_CATEGORY).toHaveProperty("image");
+ expect(FILE_EXTENSIONS_BY_CATEGORY).toHaveProperty("font");
+ expect(FILE_EXTENSIONS_BY_CATEGORY).toHaveProperty("text");
+ expect(FILE_EXTENSIONS_BY_CATEGORY).toHaveProperty("application");
+ expect(FILE_EXTENSIONS_BY_CATEGORY).toHaveProperty("audio");
+ expect(FILE_EXTENSIONS_BY_CATEGORY).toHaveProperty("video");
+ });
+
+ test("image category contains image extensions", () => {
+ expect(FILE_EXTENSIONS_BY_CATEGORY.image).toContain("jpg");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.image).toContain("png");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.image).toContain("gif");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.image).toContain("svg");
+ });
+
+ test("font category contains font extensions", () => {
+ expect(FILE_EXTENSIONS_BY_CATEGORY.font).toContain("woff");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.font).toContain("woff2");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.font).toContain("ttf");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.font).toContain("otf");
+ });
+
+ test("application category contains document extensions", () => {
+ // Office documents
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("pdf");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("doc");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("docx");
+ // Spreadsheets
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("xls");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("xlsx");
+ // Presentations
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("ppt");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("pptx");
+ // Archives
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("zip");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.application).toContain("rar");
+ });
+
+ test("text category contains text file extensions", () => {
+ expect(FILE_EXTENSIONS_BY_CATEGORY.text).toContain("txt");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.text).toContain("md");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.text).toContain("csv");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.text).toContain("js");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.text).toContain("css");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.text).toContain("html");
+ });
+
+ test("audio category contains audio extensions", () => {
+ expect(FILE_EXTENSIONS_BY_CATEGORY.audio).toContain("mp3");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.audio).toContain("wav");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.audio).toContain("ogg");
+ });
+
+ test("video category contains video extensions", () => {
+ expect(FILE_EXTENSIONS_BY_CATEGORY.video).toContain("mp4");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.video).toContain("webm");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.video).toContain("mov");
+ expect(FILE_EXTENSIONS_BY_CATEGORY.video).toContain("avi");
+ });
+
+ test("all extensions are accounted for", () => {
+ const allCategoryExtensions = Object.values(
+ FILE_EXTENSIONS_BY_CATEGORY
+ ).flat();
+ const allExtensions = Object.keys(ALLOWED_FILE_TYPES);
+
+ // Every extension should be in at least one category
+ allExtensions.forEach((ext) => {
+ expect(allCategoryExtensions).toContain(ext);
+ });
+ });
+ });
+
+ describe("detectAssetType", () => {
+ test("detects image files", () => {
+ expect(detectAssetType("photo.jpg")).toBe("image");
+ expect(detectAssetType("image.png")).toBe("image");
+ expect(detectAssetType("graphic.gif")).toBe("image");
+ expect(detectAssetType("vector.svg")).toBe("image");
+ expect(detectAssetType("picture.webp")).toBe("image");
+ });
+
+ test("detects font files", () => {
+ expect(detectAssetType("font.woff")).toBe("font");
+ expect(detectAssetType("font.woff2")).toBe("font");
+ expect(detectAssetType("font.ttf")).toBe("font");
+ expect(detectAssetType("font.otf")).toBe("font");
+ });
+
+ test("detects video files", () => {
+ expect(detectAssetType("video.mp4")).toBe("video");
+ expect(detectAssetType("video.webm")).toBe("video");
+ expect(detectAssetType("video.mov")).toBe("video");
+ expect(detectAssetType("video.avi")).toBe("video");
+ });
+
+ test("returns file for other types", () => {
+ expect(detectAssetType("document.pdf")).toBe("file");
+ expect(detectAssetType("audio.mp3")).toBe("file");
+ expect(detectAssetType("data.json")).toBe("file");
+ expect(detectAssetType("doc.docx")).toBe("file");
+ });
+
+ test("is case-insensitive", () => {
+ expect(detectAssetType("PHOTO.JPG")).toBe("image");
+ expect(detectAssetType("FONT.WOFF2")).toBe("font");
+ expect(detectAssetType("VIDEO.MP4")).toBe("video");
+ expect(detectAssetType("DOC.PDF")).toBe("file");
+ });
+
+ test("handles files without extension", () => {
+ expect(detectAssetType("filename")).toBe("file");
+ });
+
+ test("handles files with multiple dots", () => {
+ expect(detectAssetType("my.photo.file.png")).toBe("image");
+ expect(detectAssetType("my.font.file.woff2")).toBe("font");
+ expect(detectAssetType("my.video.file.mp4")).toBe("video");
+ expect(detectAssetType("my.doc.file.pdf")).toBe("file");
+ });
+ });
+
+ describe("decodePathFragment", () => {
+ test("decodes URI components correctly", () => {
+ expect(decodePathFragment("hello%20world.jpg")).toBe("hello world.jpg");
+ expect(decodePathFragment("image%2Btest.png")).toBe("image+test.png");
+ expect(decodePathFragment("file%40name.pdf")).toBe("[email protected]");
+ });
+
+ test("throws error on path traversal attempts with ..", () => {
+ expect(() => decodePathFragment("../secret.txt")).toThrow(
+ "Invalid file path"
+ );
+ expect(() => decodePathFragment("folder/../secret.txt")).toThrow(
+ "Invalid file path"
+ );
+ expect(() => decodePathFragment("..%2Fsecret.txt")).toThrow(
+ "Invalid file path"
+ );
+ });
+
+ test("throws error on absolute path attempts", () => {
+ expect(() => decodePathFragment("/etc/passwd")).toThrow(
+ "Invalid file path"
+ );
+ expect(() => decodePathFragment("%2Fetc%2Fpasswd")).toThrow(
+ "Invalid file path"
+ );
+ });
+
+ test("handles normal filenames", () => {
+ expect(decodePathFragment("image.jpg")).toBe("image.jpg");
+ expect(decodePathFragment("my-file.pdf")).toBe("my-file.pdf");
+ expect(decodePathFragment("file_123.png")).toBe("file_123.png");
+ });
+ });
+
+ describe("getAssetUrl", () => {
+ const mockImageAsset = {
+ id: "image-1",
+ name: "photo.jpg",
+ projectId: "project-1",
+ size: 1024,
+ type: "image" as const,
+ format: "jpg",
+ description: "",
+ createdAt: "2024-01-01",
+ meta: { width: 100, height: 100 },
+ };
+
+ const mockVideoAsset = {
+ id: "video-1",
+ name: "video.mp4",
+ projectId: "project-1",
+ size: 2048,
+ type: "file" as const,
+ format: "mp4",
+ description: "",
+ createdAt: "2024-01-01",
+ meta: {},
+ };
+
+ const mockFontAsset = {
+ id: "font-1",
+ name: "font.woff2",
+ projectId: "project-1",
+ size: 512,
+ type: "font" as const,
+ format: "woff2" as const,
+ description: "",
+ createdAt: "2024-01-01",
+ meta: { family: "Arial", style: "normal" as const, weight: 400 },
+ };
+
+ const mockGenericAsset = {
+ id: "doc-1",
+ name: "document.pdf",
+ projectId: "project-1",
+ size: 4096,
+ type: "file" as const,
+ format: "pdf",
+ description: "",
+ createdAt: "2024-01-01",
+ meta: {},
+ };
+
+ test("generates correct URL for image assets", () => {
+ const url = getAssetUrl(mockImageAsset, "https://example.com");
+ expect(url.href).toBe(
+ "https://example.com/cgi/image/photo.jpg?format=raw"
+ );
+ expect(url.pathname).toBe("/cgi/image/photo.jpg");
+ expect(url.search).toBe("?format=raw");
+ });
+
+ test("generates correct URL for video assets", () => {
+ const url = getAssetUrl(mockVideoAsset, "https://example.com");
+ expect(url.href).toBe("https://example.com/cgi/video/video.mp4");
+ expect(url.pathname).toBe("/cgi/video/video.mp4");
+ });
+
+ test("generates correct URL for font assets", () => {
+ const url = getAssetUrl(mockFontAsset, "https://example.com");
+ expect(url.href).toBe("https://example.com/cgi/asset/font.woff2");
+ expect(url.pathname).toBe("/cgi/asset/font.woff2");
+ });
+
+ test("generates correct URL for generic file assets", () => {
+ const url = getAssetUrl(mockGenericAsset, "https://example.com");
+ expect(url.href).toBe("https://example.com/cgi/asset/document.pdf");
+ expect(url.pathname).toBe("/cgi/asset/document.pdf");
+ });
+
+ test("works with different origins", () => {
+ const url1 = getAssetUrl(mockImageAsset, "https://example.com");
+ const url2 = getAssetUrl(mockImageAsset, "http://localhost:3000");
+ const url3 = getAssetUrl(mockImageAsset, "https://cdn.example.org");
+
+ expect(url1.origin).toBe("https://example.com");
+ expect(url2.origin).toBe("http://localhost:3000");
+ expect(url3.origin).toBe("https://cdn.example.org");
+
+ // All should have the same pathname
+ expect(url1.pathname).toBe(url2.pathname);
+ expect(url2.pathname).toBe(url3.pathname);
+ });
+
+ test("pathname can be used for relative URLs", () => {
+ const url = getAssetUrl(mockGenericAsset, "https://example.com");
+ expect(url.pathname).toBe("/cgi/asset/document.pdf");
+ // pathname is suitable for href attribute in same-origin context
+ });
+
+ test("detects video format case-insensitively", () => {
+ const upperCaseVideo = {
+ ...mockVideoAsset,
+ format: "MP4",
+ };
+ const url = getAssetUrl(upperCaseVideo, "https://example.com");
+ expect(url.pathname).toBe("/cgi/video/video.mp4");
+ });
+
+ test("handles assets with special characters in name", () => {
+ const specialAsset = {
+ ...mockGenericAsset,
+ name: "my document (1).pdf",
+ };
+ const url = getAssetUrl(specialAsset, "https://example.com");
+ // URL constructor automatically encodes special characters in pathname
+ expect(url.pathname).toBe("/cgi/asset/my%20document%20(1).pdf");
+ });
+ });
+
+ describe("acceptToMimePatterns", () => {
+ test("returns * if accept is empty or * or */*", () => {
+ expect(acceptToMimePatterns("")).toBe("*");
+ expect(acceptToMimePatterns("*")).toBe("*");
+ expect(acceptToMimePatterns("*/*")).toBe("*");
+ expect(acceptToMimePatterns("*,.png")).toBe("*");
+ });
+
+ test("returns * if it doesn't recognise a pattern", () => {
+ expect(acceptToMimePatterns("image/wrong")).toBe("*");
+ expect(acceptToMimePatterns("wrong/*")).toBe("*");
+ expect(acceptToMimePatterns(".wrong")).toBe("*");
+ });
+
+ test("leaves full mimes as is", () => {
+ expect(acceptToMimePatterns("image/png,font/otf")).toEqual(
+ new Set(["image/png", "font/otf"])
+ );
+ });
+
+ test("leaves mime patterns as is", () => {
+ expect(acceptToMimePatterns("image/*,font/*")).toEqual(
+ new Set(["image/*", "font/*"])
+ );
+ });
+
+ test("converts extensions to mimes", () => {
+ expect(acceptToMimePatterns(".svg,.otf")).toEqual(
+ new Set(["image/svg+xml", "font/otf"])
+ );
+ });
+ });
+
+ describe("acceptToMimeCategories", () => {
+ test("returns * if accept is empty or * or */*", () => {
+ expect(acceptToMimeCategories("")).toBe("*");
+ expect(acceptToMimeCategories("*")).toBe("*");
+ expect(acceptToMimeCategories("*/*")).toBe("*");
+ expect(acceptToMimeCategories("*,.png")).toBe("*");
+ });
+
+ test("returns * if it doesn't recognise a pattern", () => {
+ expect(acceptToMimeCategories("image/wrong")).toBe("*");
+ expect(acceptToMimeCategories("wrong/*")).toBe("*");
+ expect(acceptToMimeCategories(".wrong")).toBe("*");
+ });
+
+ test("handles full mimes", () => {
+ expect(acceptToMimeCategories("image/png,font/otf")).toEqual(
+ new Set(["image", "font"])
+ );
+ });
+
+ test("handles mime patterns", () => {
+ expect(acceptToMimeCategories("image/*,font/*")).toEqual(
+ new Set(["image", "font"])
+ );
+ });
+
+ test("handles extensions", () => {
+ expect(acceptToMimeCategories(".svg,.otf")).toEqual(
+ new Set(["image", "font"])
+ );
+ });
+ });
+
+ describe("getAssetMime", () => {
+ test("handles woff", () => {
+ expect(getAssetMime({ type: "font", format: "woff" })).toBe("font/woff");
+ });
+
+ test("handles png", () => {
+ expect(getAssetMime({ type: "image", format: "png" })).toBe("image/png");
+ });
+
+ test("handles svg", () => {
+ expect(getAssetMime({ type: "image", format: "svg" })).toBe(
+ "image/svg+xml"
+ );
+ });
+
+ test("returns undefined for unknown format", () => {
+ expect(
+ getAssetMime({ type: "image", format: "unknown" })
+ ).toBeUndefined();
+ });
+ });
+
+ describe("doesAssetMatchMimePatterns", () => {
+ test("returns true if mime patterns is *", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "png", name: "test.png" },
+ "*"
+ )
+ ).toBe(true);
+ });
+
+ test("handles full mimes", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "svg", name: "test.svg" },
+ new Set(["image/svg+xml"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "svg", name: "test.svg" },
+ new Set(["image/png"])
+ )
+ ).toBe(false);
+ });
+
+ test("handles mime patterns", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "svg", name: "test.svg" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "svg", name: "test.svg" },
+ new Set(["font/*"])
+ )
+ ).toBe(false);
+ });
+
+ test("if asset format has unexpected value, returns false", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "unknown", name: "test.unknown" },
+ new Set(["image/*"])
+ )
+ ).toBe(false);
+ });
+
+ test("handles uppercase format extensions", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "JPG", name: "test.JPG" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "PNG", name: "test.PNG" },
+ new Set(["image/png"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "font", format: "WOFF2", name: "font.WOFF2" },
+ new Set(["font/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("handles normal image assets", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "jpg", name: "test.jpg" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("handles legacy assets with type 'file' but image extension", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "jpg", name: "test.jpg" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "JPG", name: "test.JPG" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "png", name: "test.png" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("handles legacy assets with type 'file' but font extension", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "woff2", name: "font.woff2" },
+ new Set(["font/*"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "ttf", name: "font.ttf" },
+ new Set(["font/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("handles video assets stored as type 'file'", () => {
+ // Videos are always stored as type "file" in the database
+ // They should match video/* patterns via normal MIME matching
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "mp4", name: "video.mp4" },
+ new Set(["video/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("does not match legacy file assets with wrong pattern", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "jpg", name: "test.jpg" },
+ new Set(["font/*"])
+ )
+ ).toBe(false);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "pdf", name: "doc.pdf" },
+ new Set(["image/*"])
+ )
+ ).toBe(false);
+ });
+
+ test("handles real file assets (not legacy)", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "pdf", name: "doc.pdf" },
+ new Set(["application/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("handles assets without extension in name", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "unknown", name: "test" },
+ new Set(["image/*"])
+ )
+ ).toBe(false);
+ });
+
+ test("handles assets with mismatched format and extension", () => {
+ // Format says jpg but filename says png - should match based on format first
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "jpg", name: "test.png" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ // If format is unknown, falls back to filename extension
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "unknown", name: "test.png" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("handles uppercase extensions in filenames", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "unknown", name: "test.JPG" },
+ new Set(["image/*"])
+ )
+ ).toBe(true);
+ });
+
+ test("handles specific MIME types with fallback", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "unknown", name: "test.jpg" },
+ new Set(["image/jpeg"])
+ )
+ ).toBe(true);
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "unknown", name: "test.jpg" },
+ new Set(["image/png"])
+ )
+ ).toBe(false);
+ });
+
+ test("handles multiple patterns with fallback", () => {
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "file", format: "unknown", name: "test.jpg" },
+ new Set(["image/png", "image/jpeg", "image/gif"])
+ )
+ ).toBe(true);
+ });
+
+ test("only uses fallback for type 'file' assets", () => {
+ // Image type with unknown format should not fallback to name
+ expect(
+ doesAssetMatchMimePatterns(
+ { type: "image", format: "unknown", name: "test.jpg" },
+ new Set(["image/*"])
+ )
+ ).toBe(false);
+ });
+ });
+});
diff --git a/packages/sdk/src/assets.ts b/packages/sdk/src/assets.ts
new file mode 100644
index 0000000000..492b3dd8d9
--- /dev/null
+++ b/packages/sdk/src/assets.ts
@@ -0,0 +1,422 @@
+import warnOnce from "warn-once";
+import type { Asset } from "./schema/assets";
+
+/**
+ * Central registry of allowed file types, extensions, and MIME types
+ * for asset uploads and serving.
+ *
+ * IMPORTANT: For images, we only support formats that Cloudflare Image Resizing can process.
+ * Supported by Cloudflare: JPEG, PNG, GIF, WebP, SVG, AVIF
+ * See: https://developers.cloudflare.com/images/image-resizing/format-limitations/
+ *
+ * Other formats (BMP, ICO, TIFF) are allowed for upload but served as-is without optimization.
+ */
+
+export const ALLOWED_FILE_TYPES = {
+ // Documents
+ pdf: "application/pdf",
+ doc: "application/msword",
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ xls: "application/vnd.ms-excel",
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ csv: "text/csv",
+ ppt: "application/vnd.ms-powerpoint",
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+
+ // Code
+ txt: "text/plain",
+ md: "text/markdown",
+ js: "text/javascript",
+ css: "text/css",
+ json: "application/json",
+ html: "text/html",
+ xml: "application/xml",
+
+ // Archives
+ zip: "application/zip",
+ rar: "application/vnd.rar",
+
+ // Audio
+ mp3: "audio/mpeg",
+ wav: "audio/wav",
+ ogg: "audio/ogg",
+ m4a: "audio/mp4",
+
+ // Video
+ mp4: "video/mp4",
+ mov: "video/quicktime",
+ avi: "video/x-msvideo",
+ webm: "video/webm",
+
+ // Images
+ // Note: Cloudflare Image Resizing supports: jpg, jpeg, png, gif, webp, svg, avif
+ // Other formats (bmp, ico, tif, tiff) are served as-is without optimization
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ png: "image/png",
+ gif: "image/gif",
+ svg: "image/svg+xml",
+ webp: "image/webp",
+ avif: "image/avif",
+ ico: "image/vnd.microsoft.icon", // Used for favicons
+ bmp: "image/bmp", // Served without optimization
+ tif: "image/tiff", // Served without optimization
+ tiff: "image/tiff", // Served without optimization
+
+ // Fonts
+ woff: "font/woff",
+ woff2: "font/woff2",
+ ttf: "font/ttf",
+ otf: "font/otf",
+} as const;
+
+export type AllowedFileExtension = keyof typeof ALLOWED_FILE_TYPES;
+
+/**
+ * Set of allowed file extensions for quick lookup
+ */
+export const ALLOWED_FILE_EXTENSIONS: ReadonlySet<AllowedFileExtension> =
+ new Set<AllowedFileExtension>(
+ Object.keys(ALLOWED_FILE_TYPES) as AllowedFileExtension[]
+ );
+
+/**
+ * Set of allowed MIME type categories
+ */
+export const MIME_CATEGORIES = [
+ "image",
+ "video",
+ "audio",
+ "font",
+ "text",
+ "application",
+] as const;
+
+export type MimeCategory = (typeof MIME_CATEGORIES)[number];
+
+/**
+ * File extensions grouped by MIME category for UI display and filtering
+ */
+export const FILE_EXTENSIONS_BY_CATEGORY: Readonly<
+ Record<MimeCategory, AllowedFileExtension[]>
+> = (() => {
+ const categories = Object.fromEntries(
+ MIME_CATEGORIES.map((category) => [category, []])
+ ) as unknown as Record<MimeCategory, AllowedFileExtension[]>;
+
+ Object.entries(ALLOWED_FILE_TYPES).forEach(([ext, mimeType]) => {
+ const [category] = mimeType.split("/") as [MimeCategory];
+
+ if (category in categories) {
+ categories[category].push(ext as AllowedFileExtension);
+ }
+ });
+
+ return categories;
+})();
+
+// Create extension-to-MIME map for utilities
+const extensionToMime = new Map(
+ Object.entries(ALLOWED_FILE_TYPES).map(([ext, mime]) => [`.${ext}`, mime])
+);
+
+const mimeTypes = new Set<string>(extensionToMime.values());
+
+const mimePatterns = new Set<string>([
+ ...mimeTypes.values(),
+ ...MIME_CATEGORIES.map((category): `${MimeCategory}/*` => `${category}/*`),
+]);
+
+const getCategory = (pattern: string): MimeCategory => {
+ const categoryAsString = pattern.split("/")[0];
+ const category = MIME_CATEGORIES.find(
+ (category) => category === categoryAsString
+ );
+ if (category === undefined) {
+ throw new Error(`Invalid mime pattern: ${pattern}`);
+ }
+ return category;
+};
+
+/**
+ * All image file extensions
+ */
+export const IMAGE_EXTENSIONS: readonly AllowedFileExtension[] =
+ FILE_EXTENSIONS_BY_CATEGORY.image;
+
+/**
+ * All image MIME types
+ */
+export const IMAGE_MIME_TYPES: readonly string[] = IMAGE_EXTENSIONS.map(
+ (ext) => ALLOWED_FILE_TYPES[ext as keyof typeof ALLOWED_FILE_TYPES]
+);
+
+/**
+ * All video file extensions
+ */
+export const VIDEO_EXTENSIONS: readonly AllowedFileExtension[] =
+ FILE_EXTENSIONS_BY_CATEGORY.video;
+
+/**
+ * All video MIME types
+ */
+export const VIDEO_MIME_TYPES: readonly string[] = VIDEO_EXTENSIONS.map(
+ (ext) => ALLOWED_FILE_TYPES[ext as keyof typeof ALLOWED_FILE_TYPES]
+);
+
+/**
+ * All font file extensions
+ */
+export const FONT_EXTENSIONS: readonly AllowedFileExtension[] =
+ FILE_EXTENSIONS_BY_CATEGORY.font;
+
+/**
+ * Get MIME type for a given file extension
+ */
+export const getMimeTypeByExtension = (
+ extension: string
+): string | undefined => {
+ return ALLOWED_FILE_TYPES[extension.toLowerCase() as AllowedFileExtension];
+};
+
+/**
+ * Get MIME type from a filename
+ */
+export const getMimeTypeByFilename = (fileName: string): string => {
+ const extension = fileName.split(".").pop()?.toLowerCase();
+ if (!extension) {
+ return "application/octet-stream";
+ }
+ return getMimeTypeByExtension(extension) ?? "application/octet-stream";
+};
+
+/**
+ * Check if a file extension is allowed
+ */
+export const isAllowedExtension = (extension: string): boolean => {
+ return ALLOWED_FILE_EXTENSIONS.has(
+ extension.toLowerCase() as AllowedFileExtension
+ );
+};
+
+/**
+ * Check if a MIME type category is allowed
+ */
+export const isAllowedMimeCategory = (category: string): boolean => {
+ return MIME_CATEGORIES.includes(category as MimeCategory);
+};
+
+/**
+ * Convert accept attribute value to MIME patterns.
+ * `".svg,font/otf,text/*"` -> `"image/svg+xml", "font/otf", "text/*"`
+ */
+export const acceptToMimePatterns = (accept: string): Set<string> | "*" => {
+ const result = new Set<string>();
+
+ if (accept === "") {
+ return "*";
+ }
+
+ for (const type of accept.split(",")) {
+ const trimmed = type.trim();
+ if (trimmed === "*" || trimmed === "*/*") {
+ return "*";
+ }
+ if (mimePatterns.has(trimmed)) {
+ result.add(trimmed);
+ continue;
+ }
+ const mime = extensionToMime.get(trimmed);
+
+ if (mime === undefined) {
+ warnOnce(
+ true,
+ `Couldn't not parse accept attribute value: ${trimmed}. Falling back to "*".`
+ );
+ return "*";
+ }
+
+ result.add(mime);
+ }
+
+ return result;
+};
+
+/**
+ * Convert accept attribute value to MIME categories.
+ * `".svg,font/otf,text/*"` -> `"image", "font", "text"`
+ */
+export const acceptToMimeCategories = (
+ accept: string
+): Set<MimeCategory> | "*" => {
+ const patterns = acceptToMimePatterns(accept);
+ if (patterns === "*") {
+ return "*";
+ }
+ const categories = new Set<MimeCategory>();
+ for (const pattern of patterns) {
+ categories.add(getCategory(pattern));
+ }
+ return categories;
+};
+
+/**
+ * Get MIME type for an asset based on its type and format
+ */
+export const getAssetMime = ({
+ type,
+ format,
+}: {
+ type: "image" | "font" | "file";
+ format: string;
+}): string | undefined => {
+ const lowerFormat = format.toLowerCase();
+ const mime = `${type}/${lowerFormat}`;
+ if (mimeTypes.has(mime)) {
+ return mime;
+ }
+ const mime2 = extensionToMime.get(`.${lowerFormat}`);
+ if (mime2 === undefined) {
+ warnOnce(
+ true,
+ `Couldn't determine mime type of asset: ${type}, ${format}.`
+ );
+ }
+ return mime2;
+};
+
+/**
+ * Check if an asset matches the given MIME patterns.
+ * Supports legacy assets that were incorrectly stored with type "file".
+ */
+export const doesAssetMatchMimePatterns = (
+ asset: Pick<Asset, "format" | "type" | "name">,
+ patterns: Set<string> | "*"
+): boolean => {
+ if (patterns === "*") {
+ return true;
+ }
+
+ // Try matching based on asset type and format
+ const mime = getAssetMime(asset);
+ if (mime !== undefined) {
+ if (patterns.has(mime) || patterns.has(`${getCategory(mime)}/*`)) {
+ return true;
+ }
+ }
+
+ // If it doesn't match and the asset type is "file" and has a name,
+ // try detecting the actual MIME type from the filename extension
+ // This handles legacy assets that were incorrectly stored as type "file"
+ if (asset.type === "file" && asset.name) {
+ const extension = asset.name.split(".").pop()?.toLowerCase();
+ if (extension) {
+ const mimeFromExtension = extensionToMime.get(`.${extension}`);
+ if (mimeFromExtension) {
+ return (
+ patterns.has(mimeFromExtension) ||
+ patterns.has(`${getCategory(mimeFromExtension)}/*`)
+ );
+ }
+ }
+ }
+
+ return false;
+};
+
+/**
+ * Validate a filename and return its extension and MIME type
+ * @throws Error if file extension is not allowed
+ */
+export const validateFileName = (
+ fileName: string
+): { extension: string; mimeType: string } => {
+ const extension = fileName.split(".").pop()?.toLowerCase();
+
+ if (!extension) {
+ throw new Error("File must have an extension");
+ }
+
+ if (!isAllowedExtension(extension)) {
+ throw new Error(
+ `File type "${extension}" is not allowed. Allowed types: ${Array.from(
+ ALLOWED_FILE_EXTENSIONS
+ ).join(", ")}`
+ );
+ }
+
+ const mimeType = getMimeTypeByExtension(extension);
+ if (!mimeType) {
+ throw new Error(
+ `Could not determine MIME type for extension: ${extension}`
+ );
+ }
+
+ return { extension, mimeType };
+};
+
+/**
+ * Detect the asset type from a file based on its extension
+ */
+export const detectAssetType = (
+ fileName: string
+): "image" | "font" | "video" | "file" => {
+ const ext = fileName.split(".").pop()?.toLowerCase();
+ if (!ext) {
+ return "file";
+ }
+
+ if (IMAGE_EXTENSIONS.includes(ext as AllowedFileExtension)) {
+ return "image";
+ }
+
+ if (FONT_EXTENSIONS.includes(ext as AllowedFileExtension)) {
+ return "font";
+ }
+
+ if (VIDEO_EXTENSIONS.includes(ext as AllowedFileExtension)) {
+ return "video";
+ }
+
+ return "file";
+};
+
+/**
+ * Safely decode a URL path fragment, preventing path traversal attacks
+ * @throws Error if the decoded path contains path traversal attempts
+ */
+export const decodePathFragment = (fragment: string): string => {
+ const decoded = decodeURIComponent(fragment);
+
+ // Prevent path traversal attacks
+ if (decoded.includes("..") || decoded.startsWith("/")) {
+ throw new Error("Invalid file path");
+ }
+
+ return decoded;
+};
+
+/**
+ * Generates the appropriate URL for an asset based on its type and format.
+ * - Images use /cgi/image/ with format=raw
+ * - Videos use /cgi/video/
+ * - Other assets use /cgi/asset/
+ *
+ * @param asset - The asset to generate URL for
+ * @param origin - Origin to prepend (e.g., "https://example.com"). When provided, returns an absolute URL.
+ * @returns A URL object. Use .pathname for relative paths, .href for absolute URLs
+ */
+export const getAssetUrl = (asset: Asset, origin: string): URL => {
+ let path: string;
+ const assetType = detectAssetType(asset.name);
+
+ if (assetType === "image") {
+ path = `/cgi/image/${asset.name}?format=raw`;
+ } else if (assetType === "video") {
+ path = `/cgi/video/${asset.name}`;
+ } else {
+ path = `/cgi/asset/${asset.name}`;
+ }
+
+ return new URL(path, origin);
+};
diff --git a/packages/sdk/src/expression.ts b/packages/sdk/src/expression.ts
index a259d5ff39..ad75bda98f 100644
--- a/packages/sdk/src/expression.ts
+++ b/packages/sdk/src/expression.ts
@@ -43,7 +43,13 @@ export const allowedStringMethods = new Set([
"toLocaleUpperCase",
]);
-export const allowedArrayMethods = new Set(["at", "includes", "join", "slice"]);
+export const allowedArrayMethods = new Set([
+ "at",
+ "includes",
+ "join",
+ "slice",
+ "filter",
+]);
export const lintExpression = ({
expression,
@@ -87,6 +93,7 @@ export const lintExpression = ({
// support parsing import to forbid explicitly
sourceType: "module",
});
+
simple(root, {
Identifier(node) {
if (availableVariables.has(node.name) === false) {
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 0ffa639bbd..35d0b1dde2 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -13,6 +13,7 @@ export * from "./schema/webstudio";
export * from "./schema/prop-meta";
export * from "./schema/component-meta";
+export * from "./assets";
export * from "./core-metas";
export * from "./instances-utils";
export * from "./page-utils";
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index 6a522d34a1..7aa7a7cd18 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -19,6 +19,7 @@ export const isLocalResource = (pathname: string, resourceName?: string) => {
export const sitemapResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/sitemap.xml`;
export const currentDateResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/current-date`;
+export const assetsResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/assets`;
export const loadResource = async (
customFetch: typeof fetch,
diff --git a/packages/sdk/src/schema/assets.ts b/packages/sdk/src/schema/assets.ts
index f9c85c7478..607f1e3596 100644
--- a/packages/sdk/src/schema/assets.ts
+++ b/packages/sdk/src/schema/assets.ts
@@ -35,7 +35,15 @@ export const ImageAsset = z.object({
});
export type ImageAsset = z.infer<typeof ImageAsset>;
-export const Asset = z.union([FontAsset, ImageAsset]);
+export const FileAsset = z.object({
+ ...baseAsset,
+ format: z.string(),
+ meta: z.object({}),
+ type: z.literal("file"),
+});
+export type FileAsset = z.infer<typeof FileAsset>;
+
+export const Asset = z.union([FontAsset, ImageAsset, FileAsset]);
export type Asset = z.infer<typeof Asset>;
export const Assets = z.map(AssetId, Asset);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b892ecd58a..ffc0977db3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1101,6 +1101,9 @@ importers:
tinyexec:
specifier: ^0.3.2
version: 0.3.2
+ warn-once:
+ specifier: ^0.1.1
+ version: 0.1.1
yargs:
specifier: ^17.7.2
version: 17.7.2
@@ -1835,6 +1838,9 @@ importers:
type-fest:
specifier: ^4.37.0
version: 4.37.0
+ warn-once:
+ specifier: ^0.1.1
+ version: 0.1.1
zod:
specifier: ^3.24.2
version: 3.24.2