Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Redirects improvements (#5619)
Oleg Isonen9f497a3513b7
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 47a7c969fb..6820048bed 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -4,6 +4,7 @@ import { TooltipProvider } from "@radix-ui/react-tooltip";import {theme,Box,+ Toaster,type CSS,Flex,Grid,@@ -480,6 +481,7 @@ export const Builder = ({<KeyboardShortcutsDialog /><TokenConflictDialog /><RemoteDialog />+ <Toaster /></div></TooltipProvider>);diff --git a/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.ts b/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.tsindex 09385dc392..73b44f6325 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.ts+++ b/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.ts@@ -66,7 +66,7 @@ export const buildBreakpointFromEditorState = (newBreakpoint.condition = originalBreakpoint.condition;} else {// Invalid: no condition and no valid width- return undefined;+ return;}return newBreakpoint;diff --git a/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsx b/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsxindex 38271b6aca..bf7fcc589b 100644--- a/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsx+++ b/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsx@@ -26,7 +26,7 @@ export const ConfirmationDialog = ({return (<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onAbort()}><DialogContent>- <DialogTitle>Delete Breakpoint</DialogTitle>+ <DialogTitle>Delete breakpoint</DialogTitle><Flex gap="2" direction="column" css={{ padding: theme.spacing[5] }}><Text>{`Are you sure you want to delete "${breakpoint.label}"?`}</Text><Text>diff --git a/apps/builder/app/builder/features/pages/confirmation-dialogs.tsx b/apps/builder/app/builder/features/pages/confirmation-dialogs.tsxindex 7233ee8f63..6a392c0450 100644--- a/apps/builder/app/builder/features/pages/confirmation-dialogs.tsx+++ b/apps/builder/app/builder/features/pages/confirmation-dialogs.tsx@@ -31,7 +31,7 @@ export const DeletePageConfirmationDialog = ({}}><DialogContent>- <DialogTitle>Delete Page</DialogTitle>+ <DialogTitle>Delete page</DialogTitle><Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}><Text>{`Are you sure you want to delete "${page.name}"?`}</Text><Text>diff --git a/apps/builder/app/builder/features/pages/custom-metadata.tsx b/apps/builder/app/builder/features/pages/custom-metadata.tsxindex 84a998483b..cef4615b25 100644--- a/apps/builder/app/builder/features/pages/custom-metadata.tsx+++ b/apps/builder/app/builder/features/pages/custom-metadata.tsx@@ -143,7 +143,7 @@ const MetadataItem = (props: {export const CustomMetadata = (props: CustomMetadataProps) => {return (<Grid gap={2} css={{ my: theme.spacing[5], mx: theme.spacing[8] }}>- <Label text="title">Custom Metadata</Label>+ <Label text="title">Custom metadata</Label><Text color="subtle">Use this section to input metadata for the document, which will be usedto generate{" "}diff --git a/apps/builder/app/builder/features/pages/folder-settings.tsx b/apps/builder/app/builder/features/pages/folder-settings.tsxindex 7de7e05229..3b7fbe960c 100644--- a/apps/builder/app/builder/features/pages/folder-settings.tsx+++ b/apps/builder/app/builder/features/pages/folder-settings.tsx@@ -131,7 +131,7 @@ const FormFields = ({<ScrollArea><Grid gap={3} css={{ padding: theme.panel.padding }}><Grid gap={1}>- <Label htmlFor={fieldIds.name}>Folder Name</Label>+ <Label htmlFor={fieldIds.name}>Folder name</Label><InputErrorsTooltip errors={errors.name}><InputFieldtabIndex={1}diff --git a/apps/builder/app/builder/features/pages/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings.tsxindex 04f1d3f283..5cbec27394 100644--- a/apps/builder/app/builder/features/pages/page-settings.tsx+++ b/apps/builder/app/builder/features/pages/page-settings.tsx@@ -76,6 +76,7 @@ import {$userPlanFeatures,$isDesignMode,} from "~/shared/nano-states";+import { $openProjectSettings } from "~/shared/nano-states/project-settings";import {BindingControl,BindingPopover,@@ -106,6 +107,11 @@ import {} from "./page-utils";import { Form } from "./form";import { CustomMetadata } from "./custom-metadata";+import { findMatchingRedirect } from "~/shared/project-settings/utils";+import {+ LOOP_ERROR,+ wouldCreateLoop,+} from "~/shared/redirects/redirect-loop-detection";const fieldDefaultValues = {name: "Untitled",@@ -250,6 +256,24 @@ const validateValues = (errors.path.push(...messages);}}++ // Validate redirect doesn't create a loop+ if (+ pages !== undefined &&+ values.path !== undefined &&+ computedValues.redirect &&+ typeof computedValues.redirect === "string" &&+ computedValues.redirect !== ""+ ) {+ const existingRedirects = pages.redirects ?? [];+ if (+ wouldCreateLoop(values.path, computedValues.redirect, existingRedirects)+ ) {+ errors.redirect = errors.redirect ?? [];+ errors.redirect.push(LOOP_ERROR);+ }+ }+return errors;};@@ -368,7 +392,7 @@ const StatusField = ({return (<Grid gap={1}><Flex align="center" gap={1}>- <Label htmlFor={id}>Status Code </Label>+ <Label htmlFor={id}>Status code </Label><Tooltipcontent={<Text>@@ -524,14 +548,24 @@ const LanguageField = ({);};-const usePageUrl = (values: Values) => {- const pages = useStore($pages);- const foldersPath =- pages === undefined ? "" : getPagePath(values.parentFolderId, pages);- const path = [foldersPath, values.path]+/**+ * Compute the full page path from form values.+ * This combines folder path with page path, handling home page special case.+ */+const computePagePath = (values: Values, pages: Pages): string => {+ if (values.isHomePage) {+ return "/";+ }+ const foldersPath = getPagePath(values.parentFolderId, pages);+ return [foldersPath, values.path].filter(Boolean).join("/").replace(/\/+/g, "/");+};++const usePageUrl = (values: Values) => {+ const pages = useStore($pages);+ const path = pages === undefined ? "" : computePagePath(values, pages);const system = useStore($currentSystem);const publishedOrigin = useStore($publishedOrigin);@@ -621,7 +655,7 @@ const MarketplaceSection = ({/>)}<Grid gap={1}>- <Label>Marketplace Preview</Label>+ <Label>Marketplace preview</Label><Boxcss={{padding: theme.spacing[5],@@ -683,15 +717,39 @@ const FormFields = ({computeExpression(values.excludePageFromSearch, variableValues));+ // Check if any redirect matches this page's path+ const fullPagePath = computePagePath(values, pages);+ const matchingRedirect = findMatchingRedirect(+ fullPagePath,+ pages.redirects ?? []+ );+return (<Grid css={{ height: "100%" }}><ScrollArea>+ {matchingRedirect && (+ <PanelBanner variant="warning">+ <Text>+ A redirect from "{matchingRedirect.old}" will override this page.+ The page will not be rendered when published.{" "}+ <Link+ color="inherit"+ underline="always"+ onClick={() => {+ $openProjectSettings.set("redirects");+ }}+ >+ Go to Redirects settings+ </Link>+ </Text>+ </PanelBanner>+ )}{/*** ----------------------========<<<Page props>>>>========----------------------*/}<Grid gap={2} css={{ padding: theme.panel.padding }}><Grid gap={1}>- <Label htmlFor={fieldIds.name}>Page Name</Label>+ <Label htmlFor={fieldIds.name}>Page name</Label><InputErrorsTooltip errors={errors.name}><InputFieldcolor={errors.name && "error"}@@ -814,7 +872,7 @@ const FormFields = ({)}<Grid gap={1}>- <Label htmlFor={fieldIds.documentType}>Document Type</Label>+ <Label htmlFor={fieldIds.documentType}>Document type</Label><Selectoptions={documentTypes}getValue={(docType: (typeof documentTypes)[number]) => docType}@@ -850,7 +908,7 @@ const FormFields = ({pages.</Text><Grid gap={1}>- <Label>Search Result Preview</Label>+ <Label>Search result preview</Label><Boxcss={{padding: theme.spacing[5],@@ -1038,7 +1096,7 @@ const FormFields = ({<Text color="subtle">This image appears when you share a link to this page on socialmedia sites. If no image is set here, the Social Image set in the- Project Settings will be used. The optimal dimensions for the+ project settings will be used. The optimal dimensions for theimage are 1200x630 px or larger with a 1.91:1 aspect ratio.</Text><BindingControl>diff --git a/apps/builder/app/builder/features/pages/social-preview.tsx b/apps/builder/app/builder/features/pages/social-preview.tsxindex 3fe15a86b0..8c2c14169d 100644--- a/apps/builder/app/builder/features/pages/social-preview.tsx+++ b/apps/builder/app/builder/features/pages/social-preview.tsx@@ -33,7 +33,7 @@ export const SocialPreview = ({}: SocialPreviewProps) => {return (<Grid gap={1}>- <Label>Social Sharing Preview</Label>+ <Label>Social sharing preview</Label><Gridgap={1}diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsxindex ca5151cf79..1e88c604c1 100644--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx@@ -208,7 +208,7 @@ export const CodeControl = ({}><Flex gap="1" align="center">- <Text variant="labels">Code Editor</Text>+ <Text variant="labels">Code editor</Text>{errorInfo}</Flex></DialogTitle>diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsxindex f7dc429241..0c80e9ca10 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx@@ -126,7 +126,7 @@ export const TextContent = ({</DialogTitleActions>}>- <Text variant="labels">Text Content</Text>+ <Text variant="labels">Text content</Text></DialogTitle>}size="small"diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxindex ed68490827..4e0c90f87e 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -321,7 +321,7 @@ export const SearchParams = ({return (<Grid gap={1}><Flex justify="between" align="center">- <Label>Search Params</Label>+ <Label>Search params</Label><SmallIconButtonaria-label="Add another search param"icon={<PlusIcon />}@@ -495,7 +495,7 @@ const CacheMaxAge = ({}) => {return (<Grid gap={1}>- <Label htmlFor="resource-panel-max-age">Cache Max Age</Label>+ <Label htmlFor="resource-panel-max-age">Cache max age</Label><InputFieldid="resource-panel-max-age"suffix={@@ -1225,7 +1225,7 @@ export const GraphqlResourceForm = forwardRef<</Grid><Grid gap={1}>- <Label>GraphQL Variables</Label>+ <Label>GraphQL variables</Label>{/* use invisible text input to reflect expression editor in formtype=hidden does not emit invalid event */}<inputdiff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsxindex cad3ee2ce6..9e0db0603f 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx@@ -16,21 +16,21 @@ export const BackgroundImage = ({ index }: { index: number }) => {const newValue = parsed.get("background-image");if (newValue === undefined || newValue?.type === "invalid") {- return undefined;+ return;}const [layer] = newValue.type === "layers" ? newValue.value : [newValue];// Only validate image URLs, not keywords or other typesif (layer?.type !== "image" || layer.value.type !== "url") {- return undefined;+ return;}const url = layer.value.url;// If it's an absolute URL, no validation neededif (isAbsoluteUrl(url)) {- return undefined;+ return;}// Check if the asset exists in the project@@ -42,7 +42,7 @@ export const BackgroundImage = ({ index }: { index: number }) => {return [`Asset ${url} is not found in project`];}- return undefined;+ return;},[]);diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsxindex 6ce8399839..9aa9802f0a 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx@@ -486,7 +486,7 @@ export const StyleSourceInput = (const { key, ...itemProps } = getItemProps({ item, index });return (<Fragment key={index}>- <ComboboxLabel>New Token</ComboboxLabel>+ <ComboboxLabel>New token</ComboboxLabel><ComboboxListboxItem{...itemProps}key={key}@@ -509,7 +509,7 @@ export const StyleSourceInput = (label = (<>{hasNewTokenItem && <ComboboxSeparator />}- <ComboboxLabel>Global Tokens</ComboboxLabel>+ <ComboboxLabel>Global tokens</ComboboxLabel></>);}diff --git a/apps/builder/app/builder/features/topbar/domain-checkbox.tsx b/apps/builder/app/builder/features/topbar/domain-checkbox.tsxindex dfd1ff792e..3039fbb016 100644--- a/apps/builder/app/builder/features/topbar/domain-checkbox.tsx+++ b/apps/builder/app/builder/features/topbar/domain-checkbox.tsx@@ -31,7 +31,7 @@ export const DomainCheckbox = (props: DomainCheckboxProps) => {const tooltipContentForFreeUsers = allowStagingPublish ? undefined : (<Flex direction="column" gap="2" css={{ maxWidth: theme.spacing[28] }}>- <Text variant="titles">Publish to Staging</Text>+ <Text variant="titles">Publish to staging</Text><Text><Flex direction="column">Staging allows you to preview a production version of your sitediff --git a/apps/builder/app/builder/features/workspace/workspace.tsx b/apps/builder/app/builder/features/workspace/workspace.tsxindex ea77b4419c..15e5e51bd7 100644--- a/apps/builder/app/builder/features/workspace/workspace.tsx+++ b/apps/builder/app/builder/features/workspace/workspace.tsx@@ -1,6 +1,6 @@import { useEffect, useRef, type ReactNode } from "react";import { useStore } from "@nanostores/react";-import { theme, Toaster, css } from "@webstudio-is/design-system";+import { theme, css } from "@webstudio-is/design-system";import {$canvasWidth,$scale,@@ -131,15 +131,12 @@ export const CanvasToolsContainer = () => {const outlineStyle = useOutlineStyle();return (- <>- <div- data-name="canvas-tools-wrapper"- className={canvasContainerStyle()}- style={outlineStyle}- >- <CanvasTools />- </div>- <Toaster />- </>+ <div+ data-name="canvas-tools-wrapper"+ className={canvasContainerStyle()}+ style={outlineStyle}+ >+ <CanvasTools />+ </div>);};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsxindex 873d8d5453..d436066133 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx@@ -654,7 +654,7 @@ export const AssetInfo = ({ asset }: { asset: Asset }) => {/></PopoverTrigger><PopoverContent css={{ minWidth: 250 }}>- <PopoverTitle>Asset Details</PopoverTitle>+ <PopoverTitle>Asset details</PopoverTitle><AssetInfoContent asset={asset} usages={usages} /></PopoverContent></Popover>diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsxindex f9f9580c09..6c0afac1c3 100644--- a/apps/builder/app/builder/shared/binding-popover.tsx+++ b/apps/builder/app/builder/shared/binding-popover.tsx@@ -191,7 +191,7 @@ const BindingPanel = ({</CssValueListArrowFocus></Box><Flex gap="1" css={{ padding: theme.panel.padding }}>- <Text variant="labels">Expression Editor</Text>+ <Text variant="labels">Expression editor</Text><Tooltipvariant="wrapped"content={diff --git a/apps/builder/app/builder/shared/css-variable-utils.tsx b/apps/builder/app/builder/shared/css-variable-utils.tsxindex 33527872b8..c7eb88690b 100644--- a/apps/builder/app/builder/shared/css-variable-utils.tsx+++ b/apps/builder/app/builder/shared/css-variable-utils.tsx@@ -444,7 +444,7 @@ export const renameCssVariable = (}});- return undefined;+ return;};export const deleteUnusedCssVariables = () => {diff --git a/apps/builder/app/builder/shared/data-variable-utils.tsx b/apps/builder/app/builder/shared/data-variable-utils.tsxindex f92baeba81..5fd1aa610f 100644--- a/apps/builder/app/builder/shared/data-variable-utils.tsx+++ b/apps/builder/app/builder/shared/data-variable-utils.tsx@@ -245,7 +245,7 @@ export const RenameDataVariableDialog = ({}}}>- <DialogTitle>Rename Variable</DialogTitle>+ <DialogTitle>Rename variable</DialogTitle><Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}><Flex direction="column" gap="1"><InputFielddiff --git a/apps/builder/app/builder/shared/style-source-actions.tsx b/apps/builder/app/builder/shared/style-source-actions.tsxindex a9f93fce07..5346537446 100644--- a/apps/builder/app/builder/shared/style-source-actions.tsx+++ b/apps/builder/app/builder/shared/style-source-actions.tsx@@ -233,7 +233,7 @@ export const RenameStyleSourceDialog = ({}}}>- <DialogTitle>Rename Token</DialogTitle>+ <DialogTitle>Rename token</DialogTitle><Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}><Flex direction="column" gap="1"><InputFielddiff --git a/apps/builder/app/builder/shared/url-pattern.test.ts b/apps/builder/app/builder/shared/url-pattern.test.tsindex 40473a0bad..444f6c9fa9 100644--- a/apps/builder/app/builder/shared/url-pattern.test.ts+++ b/apps/builder/app/builder/shared/url-pattern.test.ts@@ -1,4 +1,4 @@-import { expect, test } from "vitest";+import { expect, test, describe } from "vitest";import {compilePathnamePattern,isPathnamePattern,@@ -6,6 +6,34 @@ import {tokenizePathnamePattern,validatePathnamePattern,} from "./url-pattern";+import { VALID_URLPATTERN_PATHS } from "@webstudio-is/sdk/router-paths.test";++/**+ * These tests use the shared test data from @webstudio-is/sdk to ensure+ * URLPattern matching is consistent with schema validation.+ */+describe("Shared router path tests - URLPattern matching", () => {+ describe("all valid paths can be used as URLPattern patterns", () => {+ test.each(VALID_URLPATTERN_PATHS)("accepts pattern: %s", (pattern) => {+ // Pattern should be valid for URLPattern+ // Some patterns may have validation errors due to our custom rules+ // but they should still work with URLPattern itself+ expect(() => matchPathnamePattern(pattern, pattern)).not.toThrow();+ });+ });++ describe("all valid static paths can be matched exactly", () => {+ // Filter out patterns (those with : or *)+ const staticPaths = VALID_URLPATTERN_PATHS.filter(+ (p) => !p.includes(":") && !p.includes("*")+ );++ test.each(staticPaths)("matches exactly: %s", (path) => {+ const result = matchPathnamePattern(path, path);+ expect(result).toEqual({});+ });+ });+});test("decode matched params", () => {expect(matchPathnamePattern("/blog/:slug", "/blog/привет")).toEqual({@@ -21,6 +49,115 @@ test("decode matched params", () => {});});+describe("URLPattern Unicode/non-Latin character support", () => {+ // These tests verify that the URLPattern-based router properly handles+ // non-Latin characters in redirect paths, which is important for+ // international websites (Chinese, Japanese, Korean, etc.)++ describe("exact path matching with non-Latin characters", () => {+ test("matches Chinese Simplified paths", () => {+ expect(matchPathnamePattern("/关于我们", "/关于我们")).toEqual({});+ expect(matchPathnamePattern("/产品/手机", "/产品/手机")).toEqual({});+ });++ test("matches Chinese Traditional paths", () => {+ expect(matchPathnamePattern("/關於我們", "/關於我們")).toEqual({});+ expect(matchPathnamePattern("/港聞", "/港聞")).toEqual({});+ });++ test("matches Japanese paths (Hiragana, Katakana, Kanji)", () => {+ expect(matchPathnamePattern("/こんにちは", "/こんにちは")).toEqual({});+ expect(matchPathnamePattern("/カテゴリ", "/カテゴリ")).toEqual({});+ expect(matchPathnamePattern("/日本語", "/日本語")).toEqual({});+ });++ test("matches Korean paths (Hangul)", () => {+ expect(matchPathnamePattern("/한국어", "/한국어")).toEqual({});+ expect(matchPathnamePattern("/블로그/포스트", "/블로그/포스트")).toEqual(+ {}+ );+ });++ test("matches Cyrillic paths", () => {+ expect(matchPathnamePattern("/о-нас", "/о-нас")).toEqual({});+ expect(matchPathnamePattern("/блог/статья", "/блог/статья")).toEqual({});+ });++ test("matches Arabic paths", () => {+ expect(matchPathnamePattern("/مرحبا", "/مرحبا")).toEqual({});+ });++ test("matches Hebrew paths", () => {+ expect(matchPathnamePattern("/שלום", "/שלום")).toEqual({});+ });++ test("matches Greek paths", () => {+ expect(matchPathnamePattern("/σχετικά", "/σχετικά")).toEqual({});+ });++ test("matches European diacritics", () => {+ expect(matchPathnamePattern("/über-uns", "/über-uns")).toEqual({});+ expect(matchPathnamePattern("/café", "/café")).toEqual({});+ expect(matchPathnamePattern("/niño", "/niño")).toEqual({});+ });+ });++ describe("dynamic segments with non-Latin characters", () => {+ test("captures Chinese characters in :slug parameter", () => {+ expect(matchPathnamePattern("/:slug", "/关于我们")).toEqual({+ slug: "关于我们",+ });+ });++ test("captures Japanese characters in :slug parameter", () => {+ expect(matchPathnamePattern("/blog/:slug", "/blog/日本語")).toEqual({+ slug: "日本語",+ });+ });++ test("captures Korean characters in :slug parameter", () => {+ expect(+ matchPathnamePattern("/:category/:post", "/블로그/포스트")+ ).toEqual({+ category: "블로그",+ post: "포스트",+ });+ });+ });++ describe("wildcard patterns with non-Latin characters", () => {+ test("matches wildcard with Chinese paths", () => {+ expect(matchPathnamePattern("/blog/*", "/blog/中文/测试")).toEqual({+ 0: "中文/测试",+ });+ });++ test("matches wildcard with Japanese paths", () => {+ expect(+ matchPathnamePattern("/カテゴリ/*", "/カテゴリ/記事/詳細")+ ).toEqual({+ 0: "記事/詳細",+ });+ });+ });++ describe("URL-encoded vs literal matching", () => {+ test("matches URL-encoded paths and decodes them", () => {+ // %E6%B8%AF%E8%81%9E is URL-encoded 港聞+ expect(matchPathnamePattern("/:slug", "/%E6%B8%AF%E8%81%9E")).toEqual({+ slug: "港聞",+ });+ });++ test("matches mixed Latin and non-Latin paths", () => {+ expect(matchPathnamePattern("/blog/关于", "/blog/关于")).toEqual({});+ expect(matchPathnamePattern("/news/:slug", "/news/港聞")).toEqual({+ slug: "港聞",+ });+ });+ });+});+test("check pathname is pattern", () => {expect(isPathnamePattern("/:name")).toEqual(true);expect(isPathnamePattern("/:slug*")).toEqual(true);diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex 50f465bcf3..c0c4fcff53 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -488,7 +488,7 @@ const isSelectionFirstNode = () => {const getDomSelectionRect = () => {const domSelection = window.getSelection();if (!domSelection || !domSelection.focusNode) {- return undefined;+ return;}// Get current line positiondiff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex b48be2e277..7a168ecd4b 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -282,7 +282,7 @@ const getInstanceSelector = (return [...selector, ...rootInstanceSelector];}}- return undefined;+ return;};const $indexesWithinAncestors = computed(diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsxindex 60917e7e42..3bde5ddcbc 100644--- a/apps/builder/app/dashboard/dashboard.tsx+++ b/apps/builder/app/dashboard/dashboard.tsx@@ -130,7 +130,7 @@ const $data = atom<DashboardData | undefined>();export const DashboardSetup = ({ data }: { data: DashboardData }) => {$data.set(data);globalStyles();- return undefined;+ return null;};const getView = (pathname: string, hasProjects: boolean) => {@@ -153,7 +153,7 @@ export const Dashboard = () => {const location = useLocation();if (data === undefined) {- return;+ return null;}const {diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsxindex 1157a0caa1..df8e593740 100644--- a/apps/builder/app/dashboard/projects/project-card.tsx+++ b/apps/builder/app/dashboard/projects/project-card.tsx@@ -213,7 +213,7 @@ export const ProjectCard = ({{isPublished ? (<PublishedLink domain={displayDomain} tabIndex={-1} />) : (- <Text color="subtle">Not Published</Text>+ <Text color="subtle">Not published</Text>)}</Flex><ProjectMenu projectId={id} onOpenChange={setOpenDialog} />diff --git a/apps/builder/app/shared/awareness.ts b/apps/builder/app/shared/awareness.tsindex 7f9e02ef90..6774b323e9 100644--- a/apps/builder/app/shared/awareness.ts+++ b/apps/builder/app/shared/awareness.ts@@ -140,7 +140,7 @@ export const getInstancePath = (// all consuming code expect at least one instance to be selected// though it is possible to get empty array when undo created pageif (instancePath.length === 0) {- return undefined;+ return;}return instancePath;};diff --git a/apps/builder/app/shared/clone-project.tsx b/apps/builder/app/shared/clone-project.tsxindex a09cd109cd..bde27f9748 100644--- a/apps/builder/app/shared/clone-project.tsx+++ b/apps/builder/app/shared/clone-project.tsx@@ -102,7 +102,7 @@ const CloneProjectView = ({}}gap="1">- <Label>Project Title</Label>+ <Label>Project title</Label><InputFieldname="title"defaultValue={title}@@ -124,7 +124,7 @@ const CloneProjectView = ({</DialogClose></DialogActions></form>- <DialogTitle>Clone Project</DialogTitle>+ <DialogTitle>Clone project</DialogTitle></DialogContent></Dialog>);diff --git a/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx b/apps/builder/app/shared/project-settings/import-redirects-dialog.tsxnew file mode 100644index 0000000000..83e0c61f86--- /dev/null+++ b/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx@@ -0,0 +1,553 @@+import { useRef, useState, type DragEvent, type ChangeEvent } from "react";+import {+ Box,+ Button,+ Dialog,+ DialogActions,+ DialogClose,+ DialogContent,+ DialogTitle,+ Flex,+ Grid,+ Label,+ Radio,+ RadioAndLabel,+ RadioGroup,+ ScrollArea,+ Text,+ TextArea,+ theme,+ toast,+} from "@webstudio-is/design-system";+import { UploadIcon } from "@webstudio-is/icons";+import type { PageRedirect } from "@webstudio-is/sdk";+import {+ parseRedirects,+ type ParsedRedirect,+ type SkippedLine,+} from "~/shared/redirects/redirect-parsers";+import { detectLoopsInBatch } from "~/shared/redirects/redirect-loop-detection";++type ImportStep = "input" | "preview";+type MergeMode = "add" | "replace";++type ImportRedirectsDialogProps = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ existingRedirects: PageRedirect[];+ onImport: (redirects: PageRedirect[], mode: MergeMode) => void;+};++const ACCEPTED_EXTENSIONS = [".csv", ".json", ".txt", ".htaccess"];++const formatSupportsText = `Supports: CSV, JSON, Netlify _redirects, Apache .htaccess`;++export const ImportRedirectsDialog = ({+ isOpen,+ onOpenChange,+ existingRedirects,+ onImport,+}: ImportRedirectsDialogProps) => {+ const [step, setStep] = useState<ImportStep>("input");+ const [textContent, setTextContent] = useState("");+ const [fileName, setFileName] = useState<string | null>(null);+ const [isDragOver, setIsDragOver] = useState(false);+ const [parsedRedirects, setParsedRedirects] = useState<ParsedRedirect[]>([]);+ const [skippedLines, setSkippedLines] = useState<SkippedLine[]>([]);+ const [mergeMode, setMergeMode] = useState<MergeMode>("add");+ const fileInputRef = useRef<HTMLInputElement>(null);++ const resetState = () => {+ setStep("input");+ setTextContent("");+ setFileName(null);+ setParsedRedirects([]);+ setSkippedLines([]);+ setMergeMode("add");+ };++ const handleOpenChange = (open: boolean) => {+ if (!open) {+ resetState();+ }+ onOpenChange(open);+ };++ const handleFileRead = (content: string, name: string) => {+ setTextContent(content);+ setFileName(name);+ };++ const handleFileSelect = (event: ChangeEvent<HTMLInputElement>) => {+ const file = event.target.files?.[0];+ if (file) {+ const reader = new FileReader();+ reader.onload = (e) => {+ const content = e.target?.result as string;+ handleFileRead(content, file.name);+ };+ reader.readAsText(file);+ }+ // Reset input so same file can be selected again+ event.target.value = "";+ };++ const handleDragOver = (event: DragEvent<HTMLDivElement>) => {+ event.preventDefault();+ setIsDragOver(true);+ };++ const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {+ event.preventDefault();+ setIsDragOver(false);+ };++ const handleDrop = (event: DragEvent<HTMLDivElement>) => {+ event.preventDefault();+ setIsDragOver(false);++ const file = event.dataTransfer.files[0];+ if (file) {+ const reader = new FileReader();+ reader.onload = (e) => {+ const content = e.target?.result as string;+ handleFileRead(content, file.name);+ };+ reader.readAsText(file);+ }+ };++ const handleParse = () => {+ if (!textContent.trim()) {+ toast.error("Please upload a file or paste redirect content");+ return;+ }++ const result = parseRedirects(textContent);+ setParsedRedirects(result.redirects);+ setSkippedLines(result.skipped);++ if (result.redirects.length === 0 && result.skipped.length === 0) {+ toast.error("No redirects found in the provided content");+ return;+ }++ if (result.redirects.length === 0) {+ toast.error(+ `No valid redirects found. ${result.skipped.length} line(s) were skipped.`+ );+ return;+ }++ setStep("preview");+ };++ const handleImport = () => {+ // Convert parsed redirects to PageRedirect format+ const newRedirects: PageRedirect[] = parsedRedirects.map((r) => ({+ old: r.old,+ new: r.new,+ status: r.status === 301 ? "301" : "302",+ }));++ // Find duplicates with existing redirects+ const existingPaths = new Set(existingRedirects.map((r) => r.old));+ const duplicates = newRedirects.filter((r) => existingPaths.has(r.old));+ const uniqueNew = newRedirects.filter((r) => !existingPaths.has(r.old));++ if (mergeMode === "add") {+ // Detect loops with existing redirects+ const { valid, looped } = detectLoopsInBatch(+ uniqueNew,+ existingRedirects+ );+ const loopCount = looped.length;++ onImport(valid, "add");+ const skippedParts = [+ duplicates.length > 0 &&+ `${duplicates.length} duplicate${duplicates.length !== 1 ? "s" : ""}`,+ loopCount > 0 && `${loopCount} loop${loopCount !== 1 ? "s" : ""}`,+ ].filter(Boolean);+ const skippedMessage =+ skippedParts.length > 0 ? ` (${skippedParts.join(", ")} skipped)` : "";+ toast.success(+ `Imported ${valid.length} redirect${valid.length !== 1 ? "s" : ""}${skippedMessage}`+ );+ } else {+ // Replace all - detect loops within the new set+ const { valid, looped } = detectLoopsInBatch(newRedirects, []);+ const loopCount = looped.length;++ onImport(valid, "replace");+ const skippedMessage =+ loopCount > 0+ ? ` (${loopCount} loop${loopCount !== 1 ? "s" : ""} skipped)`+ : "";+ toast.success(+ `Replaced all redirects with ${valid.length} new redirect${valid.length !== 1 ? "s" : ""}${skippedMessage}`+ );+ }++ handleOpenChange(false);+ };++ // Count duplicates for display+ const existingPaths = new Set(existingRedirects.map((r) => r.old));+ const duplicateRedirects = parsedRedirects.filter((r) =>+ existingPaths.has(r.old)+ );+ const duplicateCount = duplicateRedirects.length;+ const uniqueCount = parsedRedirects.length - duplicateCount;++ return (+ <Dialog open={isOpen} onOpenChange={handleOpenChange}>+ <DialogContent css={{ width: 520, maxHeight: "80vh" }}>+ <ScrollArea>+ <Flex+ direction="column"+ css={{+ padding: theme.panel.padding,+ }}+ gap="3"+ >+ {step === "input" && (+ <InputStep+ textContent={textContent}+ fileName={fileName}+ isDragOver={isDragOver}+ fileInputRef={fileInputRef}+ onTextChange={setTextContent}+ onFileSelect={handleFileSelect}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ onUploadClick={() => fileInputRef.current?.click()}+ />+ )}++ {step === "preview" && (+ <PreviewStep+ parsedRedirects={parsedRedirects}+ skippedLines={skippedLines}+ duplicateRedirects={duplicateRedirects}+ duplicateCount={duplicateCount}+ uniqueCount={uniqueCount}+ mergeMode={mergeMode}+ existingRedirectsCount={existingRedirects.length}+ onMergeModeChange={setMergeMode}+ />+ )}+ </Flex>+ </ScrollArea>++ <DialogActions>+ {step === "input" && (+ <>+ <Button onClick={handleParse} disabled={!textContent.trim()}>+ Parse+ </Button>+ <DialogClose>+ <Button color="ghost">Cancel</Button>+ </DialogClose>+ </>+ )}++ {step === "preview" && (+ <>+ <Button+ onClick={handleImport}+ disabled={parsedRedirects.length === 0}+ >+ Import+ </Button>+ <DialogClose>+ <Button color="ghost">Cancel</Button>+ </DialogClose>+ </>+ )}+ </DialogActions>++ <DialogTitle>Import redirects</DialogTitle>+ </DialogContent>+ </Dialog>+ );+};++// Input Step Component+const InputStep = ({+ textContent,+ fileName,+ isDragOver,+ fileInputRef,+ onTextChange,+ onFileSelect,+ onDragOver,+ onDragLeave,+ onDrop,+ onUploadClick,+}: {+ textContent: string;+ fileName: string | null;+ isDragOver: boolean;+ fileInputRef: React.RefObject<HTMLInputElement>;+ onTextChange: (value: string) => void;+ onFileSelect: (event: ChangeEvent<HTMLInputElement>) => void;+ onDragOver: (event: DragEvent<HTMLDivElement>) => void;+ onDragLeave: (event: DragEvent<HTMLDivElement>) => void;+ onDrop: (event: DragEvent<HTMLDivElement>) => void;+ onUploadClick: () => void;+}) => {+ return (+ <>+ <Text color="subtle">{formatSupportsText}</Text>++ {/* Hidden file input */}+ <input+ ref={fileInputRef}+ type="file"+ accept={ACCEPTED_EXTENSIONS.join(",")}+ onChange={onFileSelect}+ style={{ display: "none" }}+ />++ {/* Drop zone */}+ <Box+ onDragOver={onDragOver}+ onDragLeave={onDragLeave}+ onDrop={onDrop}+ css={{+ border: `2px dashed ${isDragOver ? theme.colors.borderFocus : theme.colors.borderMain}`,+ borderRadius: theme.borderRadius[6],+ padding: theme.spacing[9],+ textAlign: "center",+ backgroundColor: isDragOver+ ? theme.colors.backgroundHover+ : "transparent",+ transition: "all 0.2s ease",+ cursor: "pointer",+ }}+ onClick={onUploadClick}+ >+ <Flex direction="column" align="center" gap="2">+ <UploadIcon size={24} />+ <Text>{fileName ? fileName : "Upload file or drag & drop"}</Text>+ <Text color="subtle">{ACCEPTED_EXTENSIONS.join(", ")}</Text>+ </Flex>+ </Box>++ <Flex align="center" gap="2">+ <Box+ css={{ flex: 1, height: 1, backgroundColor: theme.colors.borderMain }}+ />+ <Text color="subtle">OR</Text>+ <Box+ css={{ flex: 1, height: 1, backgroundColor: theme.colors.borderMain }}+ />+ </Flex>++ <Grid gap="1">+ <Label>Paste content</Label>+ <TextArea+ rows={6}+ maxRows={10}+ autoGrow+ value={textContent}+ onChange={onTextChange}+ placeholder={`/old-path,/new-path,301\n/about-us,/about,301`}+ />+ </Grid>+ </>+ );+};++// Preview Step Component+const PreviewStep = ({+ parsedRedirects,+ skippedLines,+ duplicateRedirects,+ duplicateCount,+ uniqueCount,+ mergeMode,+ existingRedirectsCount,+ onMergeModeChange,+}: {+ parsedRedirects: ParsedRedirect[];+ skippedLines: SkippedLine[];+ duplicateRedirects: ParsedRedirect[];+ duplicateCount: number;+ uniqueCount: number;+ mergeMode: MergeMode;+ existingRedirectsCount: number;+ onMergeModeChange: (mode: MergeMode) => void;+}) => {+ return (+ <>+ {/* Preview list */}+ <Grid gap="1">+ <Label>Preview ({parsedRedirects.length})</Label>++ <ScrollArea+ css={{+ border: `1px solid ${theme.colors.borderMain}`,+ borderRadius: theme.borderRadius[4],+ maxHeight: 200,+ overflow: "auto",+ }}+ >+ <Flex direction="column" css={{ padding: theme.spacing[3] }}>+ {parsedRedirects.map((redirect, index) => (+ <Flex+ key={index}+ gap="2"+ align="center"+ css={{+ paddingBlock: theme.spacing[1],+ }}+ >+ <Text+ truncate+ css={{+ flex: 1,+ minWidth: 0,+ }}+ >+ {redirect.old}+ </Text>+ <Text color="subtle" css={{ flexShrink: 0 }}>+ {redirect.status}+ </Text>+ <Text color="subtle" css={{ flexShrink: 0 }}>+ →+ </Text>+ <Text+ truncate+ css={{+ flex: 1,+ minWidth: 0,+ }}+ >+ {redirect.new}+ </Text>+ </Flex>+ ))}+ </Flex>+ </ScrollArea>+ </Grid>++ {/* Unsupported lines */}+ {skippedLines.length > 0 && (+ <Grid gap="1">+ <Label>Unsupported ({skippedLines.length})</Label>+ <ScrollArea+ css={{+ border: `1px solid ${theme.colors.borderMain}`,+ borderRadius: theme.borderRadius[4],+ maxHeight: 120,+ overflow: "auto",+ }}+ >+ <Flex direction="column" css={{ padding: theme.spacing[3] }}>+ {skippedLines.map((skipped, index) => (+ <Flex+ key={index}+ direction="column"+ css={{ paddingBlock: theme.spacing[1] }}+ >+ <Text color="subtle">+ Line {skipped.line}: {skipped.reason}+ </Text>+ <Text truncate>{skipped.content}</Text>+ </Flex>+ ))}+ </Flex>+ </ScrollArea>+ </Grid>+ )}++ {/* Duplicates */}+ {duplicateRedirects.length > 0 && (+ <Grid gap="1">+ <Label>Duplicates ({duplicateRedirects.length})</Label>+ <ScrollArea+ css={{+ border: `1px solid ${theme.colors.borderMain}`,+ borderRadius: theme.borderRadius[4],+ maxHeight: 120,+ overflow: "auto",+ }}+ >+ <Flex direction="column" css={{ padding: theme.spacing[3] }}>+ {duplicateRedirects.map((redirect, index) => (+ <Flex+ key={index}+ gap="2"+ align="center"+ css={{+ paddingBlock: theme.spacing[1],+ }}+ >+ <Text+ truncate+ css={{+ flex: 1,+ minWidth: 0,+ }}+ >+ {redirect.old}+ </Text>+ <Text color="subtle" css={{ flexShrink: 0 }}>+ {redirect.status}+ </Text>+ <Text color="subtle" css={{ flexShrink: 0 }}>+ →+ </Text>+ <Text+ truncate+ css={{+ flex: 1,+ minWidth: 0,+ }}+ >+ {redirect.new}+ </Text>+ </Flex>+ ))}+ </Flex>+ </ScrollArea>+ </Grid>+ )}++ {/* Merge options */}+ {existingRedirectsCount > 0 && (+ <Grid gap="2">+ <Label>Import mode</Label>+ <RadioGroup+ value={mergeMode}+ onValueChange={(value) => onMergeModeChange(value as MergeMode)}+ >+ <Flex direction="column" gap="2">+ <RadioAndLabel>+ <Radio value="add" id="import-mode-add" />+ <Label htmlFor="import-mode-add">+ Add to existing ({uniqueCount} new+ {duplicateCount > 0+ ? `, ${duplicateCount} duplicate${duplicateCount !== 1 ? "s" : ""} skipped`+ : ""}+ )+ </Label>+ </RadioAndLabel>+ <RadioAndLabel>+ <Radio value="replace" id="import-mode-replace" />+ <Label htmlFor="import-mode-replace">+ Replace all ({parsedRedirects.length} total, removes{" "}+ {existingRedirectsCount} existing)+ </Label>+ </RadioAndLabel>+ </Flex>+ </RadioGroup>+ </Grid>+ )}+ </>+ );+};diff --git a/apps/builder/app/shared/project-settings/project-settings.stories.tsx b/apps/builder/app/shared/project-settings/project-settings.stories.tsxindex db04810e43..e541fed723 100644--- a/apps/builder/app/shared/project-settings/project-settings.stories.tsx+++ b/apps/builder/app/shared/project-settings/project-settings.stories.tsx@@ -5,7 +5,7 @@ import { $pages, $project } from "~/shared/sync/data-stores";import type { Project } from "@webstudio-is/project";export default {- title: "Project Settings",+ title: "Project settings",component: ProjectSettingsDialog,};diff --git a/apps/builder/app/shared/project-settings/project-settings.tsx b/apps/builder/app/shared/project-settings/project-settings.tsxindex 888606295a..8b3f1b5cbb 100644--- a/apps/builder/app/shared/project-settings/project-settings.tsx+++ b/apps/builder/app/shared/project-settings/project-settings.tsx@@ -25,6 +25,7 @@ import { SectionRedirects } from "./section-redirects";import { SectionPublish } from "./section-publish";import { SectionMarketplace } from "./section-marketplace";import { SectionBackups } from "./section-backups";+import { titleCase } from "title-case";const sections = new Map<SectionName,@@ -108,7 +109,7 @@ export const ProjectSettingsDialog = ({align="center"><Text variant="labels" truncate>- {name}+ {titleCase(name)}</Text></Flex></ListItem>@@ -133,7 +134,7 @@ export const ProjectSettingsDialog = ({{/* Title is at the end intentionally,* to make the close button last in the tab order*/}- <DialogTitle>Project Settings</DialogTitle>+ <DialogTitle>Project settings</DialogTitle></fieldset></DialogContent></Dialog>diff --git a/apps/builder/app/shared/project-settings/section-general.tsx b/apps/builder/app/shared/project-settings/section-general.tsxindex 80a9dc9158..d016b31452 100644--- a/apps/builder/app/shared/project-settings/section-general.tsx+++ b/apps/builder/app/shared/project-settings/section-general.tsx@@ -142,7 +142,7 @@ export const SectionGeneral = ({ projectId }: { projectId?: string }) => {<Grid gap={1} css={sectionSpacing}><Flex gap={1} align="center">- <Label htmlFor={siteNameId}>Site Name</Label>+ <Label htmlFor={siteNameId}>Site name</Label><Tooltipvariant="wrapped"content="Used in search results and social previews."@@ -163,7 +163,7 @@ export const SectionGeneral = ({ projectId }: { projectId?: string }) => {<Grid gap={1} css={sectionSpacing}><Flex gap={1} align="center">- <Label htmlFor={contactEmailId}>Contact Email</Label>+ <Label htmlFor={contactEmailId}>Contact email</Label><Tooltipvariant="wrapped"content="Used as the email recipient when submitting a webhook form without an action."@@ -219,7 +219,7 @@ export const SectionGeneral = ({ projectId }: { projectId?: string }) => {<Separator /><Grid gap={2} css={sectionSpacing}>- <Label>Custom Code</Label>+ <Label>Custom code</Label><Text color="subtle">Custom code and scripts will be added at the end of the <head>tag to every page across the published project.diff --git a/apps/builder/app/shared/project-settings/section-marketplace.tsx b/apps/builder/app/shared/project-settings/section-marketplace.tsxindex ac27761f66..bb75115dd3 100644--- a/apps/builder/app/shared/project-settings/section-marketplace.tsx+++ b/apps/builder/app/shared/project-settings/section-marketplace.tsx@@ -177,7 +177,7 @@ export const SectionMarketplace = () => {Marketplace</Text><Grid gap={1} css={sectionSpacing}>- <Label htmlFor={ids.name}>Product Name</Label>+ <Label htmlFor={ids.name}>Product name</Label><InputErrorsTooltip errors={errors?.name}><InputFieldid={ids.name}@@ -279,7 +279,7 @@ export const SectionMarketplace = () => {</Grid><Grid gap={1} css={sectionSpacing}>- <Label htmlFor={ids.issues}>Issues Tracker</Label>+ <Label htmlFor={ids.issues}>Issues tracker</Label><InputErrorsTooltip errors={errors?.issues}><InputFieldid={ids.issues}diff --git a/apps/builder/app/shared/project-settings/section-redirects.test.ts b/apps/builder/app/shared/project-settings/section-redirects.test.tsnew file mode 100644index 0000000000..584734959b--- /dev/null+++ b/apps/builder/app/shared/project-settings/section-redirects.test.ts@@ -0,0 +1,344 @@+import { describe, expect, test } from "vitest";+import type { PageRedirect } from "@webstudio-is/sdk";+import { __testing__ } from "./section-redirects";++const { validateFromPath, validateToPath } = __testing__;++describe("validateFromPath", () => {+ describe("format validation", () => {+ test("returns error for empty path", () => {+ const result = validateFromPath("", [], new Set());+ expect(result.errors).toContain("Can't be empty");+ expect(result.warnings).toEqual([]);+ });++ test("returns error for just /", () => {+ const result = validateFromPath("/", [], new Set());+ expect(result.errors).toContain("Can't be just a /");+ expect(result.warnings).toEqual([]);+ });++ test("returns error for path not starting with /", () => {+ const result = validateFromPath("page", [], new Set());+ expect(result.errors).toContain(+ "Must start with a / or a full URL e.g. https://website.org"+ );+ expect(result.warnings).toEqual([]);+ });++ test("returns error for path ending with /", () => {+ const result = validateFromPath("/page/", [], new Set());+ expect(result.errors).toContain("Can't end with a /");+ expect(result.warnings).toEqual([]);+ });++ test("returns error for path with double slashes", () => {+ const result = validateFromPath("/page//subpage", [], new Set());+ expect(result.errors).toContain("Can't contain repeating /");+ expect(result.warnings).toEqual([]);+ });++ test("returns error for path with invalid characters", () => {+ const result = validateFromPath("/page name", [], new Set());+ expect(result.errors).toContain(+ "Path contains invalid characters (spaces or URL-unsafe characters are not allowed)"+ );+ expect(result.warnings).toEqual([]);+ });++ test("returns error for reserved /s prefix", () => {+ const result = validateFromPath("/s/something", [], new Set());+ expect(result.errors).toContain("/s prefix is reserved for the system");+ expect(result.warnings).toEqual([]);+ });++ test("returns error for reserved /build prefix", () => {+ const result = validateFromPath("/build/something", [], new Set());+ expect(result.errors).toContain(+ "/build prefix is reserved for the system"+ );+ expect(result.warnings).toEqual([]);+ });++ test("accepts valid path", () => {+ const result = validateFromPath("/valid-path", [], new Set());+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts path with allowed special characters", () => {+ const result = validateFromPath(+ "/path-name_123:param?query",+ [],+ new Set()+ );+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts path with uppercase letters", () => {+ const result = validateFromPath("/Path/SubPage", [], new Set());+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts path with wildcard", () => {+ const result = validateFromPath("/blog/*", [], new Set());+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts path with named parameter", () => {+ const result = validateFromPath("/blog/:slug", [], new Set());+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts path with optional parameter", () => {+ const result = validateFromPath("/page/:id?", [], new Set());+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts path with multiple parameters", () => {+ const result = validateFromPath(+ "/blog/:year/:month/:slug",+ [],+ new Set()+ );+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts path with named splat", () => {+ const result = validateFromPath("/docs/:path*", [], new Set());+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("accepts deeply nested path with wildcard", () => {+ const result = validateFromPath("/api/v1/users/*", [], new Set());+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });++ test("skips duplicate/warning checks for paths not starting with /", () => {+ // External URLs or other formats that pass schema validation+ // but don't start with / should skip the duplicate redirect+ // and existing page checks (since those only apply to local paths)+ const existingRedirects: Array<PageRedirect> = [+ { old: "https://old.com/page", new: "/new", status: "301" },+ ];+ const existingPaths = new Set(["https://old.com/page"]);++ // Even though this path "exists" in redirects and pages,+ // no error/warning because it doesn't start with /+ // Note: This tests the current behavior - external URLs bypass checks+ const result = validateFromPath(+ "https://old.com/page",+ existingRedirects,+ existingPaths+ );+ // The schema may reject this, but if it passes, no duplicate check+ // If schema rejects, we get format errors instead+ expect(result.warnings).toEqual([]);+ });+ });++ describe("duplicate redirect validation", () => {+ const existingRedirects: Array<PageRedirect> = [+ { old: "/old-page", new: "/new-page", status: "301" },+ { old: "/another-old", new: "/another-new", status: "302" },+ { old: "/blog/*", new: "/articles", status: "301" },+ { old: "/posts/:slug", new: "/blog", status: "301" },+ ];++ test("returns error when redirect already exists for path", () => {+ const result = validateFromPath(+ "/old-page",+ existingRedirects,+ new Set()+ );+ expect(result.errors).toContain("This path is already being redirected");+ expect(result.warnings).toEqual([]);+ });++ test("returns error when wildcard redirect already exists", () => {+ const result = validateFromPath("/blog/*", existingRedirects, new Set());+ expect(result.errors).toContain("This path is already being redirected");+ expect(result.warnings).toEqual([]);+ });++ test("returns error when parameterized redirect already exists", () => {+ const result = validateFromPath(+ "/posts/:slug",+ existingRedirects,+ new Set()+ );+ expect(result.errors).toContain("This path is already being redirected");+ expect(result.warnings).toEqual([]);+ });++ test("returns error for duplicate even if page exists (error takes precedence)", () => {+ const existingPaths = new Set(["/old-page"]);+ const result = validateFromPath(+ "/old-page",+ existingRedirects,+ existingPaths+ );+ expect(result.errors).toContain("This path is already being redirected");+ expect(result.warnings).toEqual([]);+ });++ test("allows path that is not already redirected", () => {+ const result = validateFromPath(+ "/different-path",+ existingRedirects,+ new Set()+ );+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });+ });++ describe("existing page warning", () => {+ const existingPaths = new Set(["/about", "/contact", "/blog/:id"]);++ test("returns warning when redirecting from existing page path", () => {+ const result = validateFromPath("/about", [], existingPaths);+ expect(result.errors).toEqual([]);+ expect(result.warnings).toContain(+ "This redirect will override an existing page"+ );+ });++ test("returns warning for dynamic route path", () => {+ const result = validateFromPath("/blog/:id", [], existingPaths);+ expect(result.errors).toEqual([]);+ expect(result.warnings).toContain(+ "This redirect will override an existing page"+ );+ });++ test("no warning for path that doesn't exist as page", () => {+ const result = validateFromPath("/new-redirect", [], existingPaths);+ expect(result.errors).toEqual([]);+ expect(result.warnings).toEqual([]);+ });+ });+});++describe("validateToPath", () => {+ // Note: ProjectNewRedirectPath uses `new URL(data, baseURL)` which is permissive+ // for most strings. However, empty strings are explicitly rejected.++ test("rejects empty path", () => {+ const errors = validateToPath("");+ expect(errors).toContain("Path is required");+ });++ test("accepts relative path with spaces (URL-encoded)", () => {+ const errors = validateToPath("path with spaces");+ expect(errors).toEqual([]);+ });++ test("accepts relative path starting with /", () => {+ const errors = validateToPath("/new-page");+ expect(errors).toEqual([]);+ });++ test("accepts absolute URL", () => {+ const errors = validateToPath("https://example.com/page");+ expect(errors).toEqual([]);+ });++ test("accepts home page path", () => {+ const errors = validateToPath("/");+ expect(errors).toEqual([]);+ });++ test("accepts path with query parameters", () => {+ const errors = validateToPath("/page?param=value");+ expect(errors).toEqual([]);+ });++ test("accepts path with hash fragment", () => {+ const errors = validateToPath("/page#section");+ expect(errors).toEqual([]);+ });++ test("accepts external URL with path", () => {+ const errors = validateToPath("https://other-site.com/path/to/page");+ expect(errors).toEqual([]);+ });++ test("accepts protocol-relative URL", () => {+ const errors = validateToPath("//example.com/page");+ expect(errors).toEqual([]);+ });+});++describe("redirect patterns (integration tests)", () => {+ // These tests document the supported redirect patterns+ // and how they should be validated together++ test("exact path redirect: /old → /new", () => {+ const fromResult = validateFromPath("/old-about", [], new Set());+ const toErrors = validateToPath("/about");+ expect(fromResult.errors).toEqual([]);+ expect(toErrors).toEqual([]);+ });++ test("wildcard redirect: /old/* → /new (all paths go to single destination)", () => {+ const fromResult = validateFromPath("/old-blog/*", [], new Set());+ const toErrors = validateToPath("/blog");+ expect(fromResult.errors).toEqual([]);+ expect(toErrors).toEqual([]);+ });++ test("parameterized from path: /old/:slug → /new (param captured but not substituted)", () => {+ // Note: The :slug is captured by the router but cannot be substituted+ // into the "to" path - all matching URLs redirect to the same destination+ const fromResult = validateFromPath("/old/:slug", [], new Set());+ const toErrors = validateToPath("/new");+ expect(fromResult.errors).toEqual([]);+ expect(toErrors).toEqual([]);+ });++ test("complex pattern: /posts/:year/:month/* → /archive", () => {+ const fromResult = validateFromPath("/posts/:year/:month/*", [], new Set());+ const toErrors = validateToPath("/archive");+ expect(fromResult.errors).toEqual([]);+ expect(toErrors).toEqual([]);+ });++ test("redirect to external URL", () => {+ const fromResult = validateFromPath("/legacy-page", [], new Set());+ const toErrors = validateToPath("https://new-domain.com/page");+ expect(fromResult.errors).toEqual([]);+ expect(toErrors).toEqual([]);+ });++ test("redirect to home page", () => {+ const fromResult = validateFromPath("/old-home", [], new Set());+ const toErrors = validateToPath("/");+ expect(fromResult.errors).toEqual([]);+ expect(toErrors).toEqual([]);+ });+});++describe("shared schema validation", () => {+ // This test documents that validateToPath uses the same ProjectNewRedirectPath+ // schema that is used in page-settings.tsx for page redirect destinations.+ // This ensures consistent validation across the codebase.++ test("validateToPath uses ProjectNewRedirectPath schema (shared with page settings)", () => {+ // Valid paths that should work in both places+ expect(validateToPath("/page")).toEqual([]);+ expect(validateToPath("https://example.com")).toEqual([]);+ expect(validateToPath("/")).toEqual([]);++ // The schema is imported from @webstudio-is/sdk and shared+ // between section-redirects.tsx and page-settings.tsx+ });+});diff --git a/apps/builder/app/shared/project-settings/section-redirects.tsx b/apps/builder/app/shared/project-settings/section-redirects.tsxindex cbc3288103..1a1940954a 100644--- a/apps/builder/app/shared/project-settings/section-redirects.tsx+++ b/apps/builder/app/shared/project-settings/section-redirects.tsx@@ -1,31 +1,109 @@import { useStore } from "@nanostores/react";import {+ Box,Button,+ Combobox,+ Dialog,+ DialogActions,+ DialogClose,+ DialogContent,+ DialogTitle,Flex,Grid,InputErrorsTooltip,- InputField,Link,List,ListItem,+ rawTheme,+ ScrollArea,+ SearchField,Select,SmallIconButton,Text,theme,Tooltip,} from "@webstudio-is/design-system";-import { ArrowRightIcon, TrashIcon } from "@webstudio-is/icons";import {- OldPagePath,- PageRedirect,- ProjectNewRedirectPath,-} from "@webstudio-is/sdk";-import { useRef, useState, type ChangeEvent } from "react";+ AlertIcon,+ ArrowRightIcon,+ InfoCircleIcon,+ TrashIcon,+ UploadIcon,+} from "@webstudio-is/icons";+import { ImportRedirectsDialog } from "./import-redirects-dialog";+import { OldPagePath, ProjectNewRedirectPath } from "@webstudio-is/sdk";+import type { PageRedirect } from "@webstudio-is/sdk";+import { useRef, useState } from "react";import { flushSync } from "react-dom";import { $pages } from "~/shared/sync/data-stores";import { $publishedOrigin } from "~/shared/nano-states";import { serverSyncStore } from "~/shared/sync/sync-stores";import { getExistingRoutePaths, sectionSpacing } from "./utils";+import {+ LOOP_ERROR,+ wouldCreateLoop,+} from "~/shared/redirects/redirect-loop-detection";++const statusCodeOptions = ["301", "302"] as const;++const statusCodeDescriptions: Record<string, string> = {+ "301": "Moved permanently. SEO ranking transfers to new URL.",+ "302": "Moved temporarily. SEO ranking stays with original URL.",+};++type ValidationResult = {+ errors: string[];+ warnings: string[];+};++const validateFromPath = (+ fromPath: string,+ redirects: Array<PageRedirect>,+ existingPaths: Set<string>+): ValidationResult => {+ const fromPathValidationResult = OldPagePath.safeParse(fromPath);++ if (fromPathValidationResult.success) {+ if (fromPath.startsWith("/")) {+ // Check for duplicate redirect first (error takes precedence)+ if (redirects.some((redirect) => redirect.old === fromPath)) {+ return {+ errors: ["This path is already being redirected"],+ warnings: [],+ };+ }++ // Show warning if redirecting from an existing page path+ // The redirect will take precedence over the page when published+ if (existingPaths.has(fromPath)) {+ return {+ errors: [],+ warnings: ["This redirect will override an existing page"],+ };+ }+ }+ return { errors: [], warnings: [] };+ }++ return {+ errors: fromPathValidationResult.error.format()?._errors,+ warnings: [],+ };+};++const validateToPath = (toPath: string): string[] => {+ const toPathValidationResult = ProjectNewRedirectPath.safeParse(toPath);+ if (toPathValidationResult.success) {+ return [];+ }+ return toPathValidationResult.error.format()._errors;+};++// Exported for testing+export const __testing__ = {+ validateFromPath,+ validateToPath,+};export const SectionRedirects = () => {const publishedOrigin = useStore($publishedOrigin);@@ -33,65 +111,49 @@ export const SectionRedirects = () => {() => $pages.get()?.redirects ?? []);- const [oldPath, setOldPath] = useState<string>("");- const [newPath, setNewPath] = useState<string>("");+ const [fromPath, setFromPath] = useState<string>("");+ const [toPath, setToPath] = useState<string>("");const [httpStatus, setHttpStatus] =useState<PageRedirect["status"]>(undefined);- const [oldPathErrors, setOldPathErrors] = useState<string[]>([]);- const [newPathErrors, setNewPathErrors] = useState<string[]>([]);+ const [fromPathErrors, setFromPathErrors] = useState<string[]>([]);+ const [fromPathWarnings, setFromPathWarnings] = useState<string[]>([]);+ const [toPathErrors, setToPathErrors] = useState<string[]>([]);+ const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);+ const [isDeleteAllDialogOpen, setIsDeleteAllDialogOpen] = useState(false);+ const [searchQuery, setSearchQuery] = useState("");const pages = useStore($pages);const existingPaths = getExistingRoutePaths(pages);- const oldPathRef = useRef<HTMLInputElement>(null);+ const fromPathRef = useRef<HTMLInputElement>(null);- const redirectKeys = Object.keys(redirects);const isValidRedirects =- oldPathErrors.length === 0 && newPathErrors.length === 0;-- const handleOldPathChange = (event: ChangeEvent<HTMLInputElement>) => {- setOldPath(event.target.value);- setOldPathErrors(validateOldPath(event.target.value));- };+ fromPathErrors.length === 0 && toPathErrors.length === 0;- const handleNewPathChange = (event: ChangeEvent<HTMLInputElement>) => {- setNewPath(event.target.value);- setNewPathErrors(validateNewPath(event.target.value));- };+ // Filter redirects based on search query+ const filteredRedirects = searchQuery+ ? redirects.filter(+ (redirect) =>+ redirect.old.toLowerCase().includes(searchQuery.toLowerCase()) ||+ redirect.new.toLowerCase().includes(searchQuery.toLowerCase())+ )+ : redirects;- const validateOldPath = (oldPath: string): string[] => {- const oldPathValidationResult = OldPagePath.safeParse(oldPath);-- if (oldPathValidationResult.success === true) {- if (oldPath.startsWith("/") === true) {- /*- This is the path, that users want to redirect to.- If the path already exists in the project. Then we can't add a redirect- */- if (existingPaths.has(oldPath) === true) {- return ["This path already exists in the project"];- }-- if (redirects.some((redirect) => redirect.old === oldPath)) {- return ["This path is already being redirected"];- }- }- return [];- }+ // Get all page paths for combobox suggestions+ const pagePaths = Array.from(existingPaths).sort();- return oldPathValidationResult.error.format()?._errors;+ const handleFromPathChange = (value: string) => {+ setFromPath(value);+ const { errors, warnings } = validateFromPath(+ value,+ redirects,+ existingPaths+ );+ setFromPathErrors(errors);+ setFromPathWarnings(warnings);};- const validateNewPath = (newPath: string): string[] => {- const newPathValidationResult = ProjectNewRedirectPath.safeParse(newPath);- if (newPathValidationResult.success) {- return [];- }- return newPathValidationResult.error.format()._errors;- };-- const handleOnKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {- if (event.key === "Enter") {- handleAddRedirect();- }+ const handleToPathChange = (value: string) => {+ setToPath(value);+ setToPathErrors(validateToPath(value));};const handleSave = (redirects: Array<PageRedirect>) => {@@ -105,10 +167,26 @@ export const SectionRedirects = () => {};const handleAddRedirect = () => {- const validOldPath = validateOldPath(oldPath);- const validNewPath = validateNewPath(newPath);+ const { errors: fromPathValidationErrors, warnings } = validateFromPath(+ fromPath,+ redirects,+ existingPaths+ );+ const toPathValidationErrors = validateToPath(toPath);+ const hasLoop = wouldCreateLoop(fromPath, toPath, redirects);++ // Update error state so user sees what went wrong+ setFromPathErrors(fromPathValidationErrors);+ setFromPathWarnings(warnings);+ setToPathErrors(+ hasLoop ? [...toPathValidationErrors, LOOP_ERROR] : toPathValidationErrors+ );- if (validOldPath.length > 0 || validNewPath.length > 0) {+ if (+ fromPathValidationErrors.length > 0 ||+ toPathValidationErrors.length > 0 ||+ hasLoop+ ) {return;}@@ -116,16 +194,17 @@ export const SectionRedirects = () => {flushSync(() => {handleSave([{- old: oldPath,- new: newPath,+ old: fromPath,+ new: toPath,status: httpStatus ?? "301",},...redirects,]);- setOldPath("");- setNewPath("");+ setFromPath("");+ setToPath("");+ setFromPathWarnings([]);});- oldPathRef.current?.focus();+ fromPathRef.current?.focus();};const handleDeleteRedirect = (index: number) => {@@ -134,87 +213,219 @@ export const SectionRedirects = () => {handleSave(newRedirects);};+ const handleImportRedirects = (+ importedRedirects: PageRedirect[],+ mode: "add" | "replace"+ ) => {+ if (mode === "replace") {+ handleSave(importedRedirects);+ } else {+ // Add mode - prepend new redirects+ handleSave([...importedRedirects, ...redirects]);+ }+ };++ const handleDeleteAll = () => {+ handleSave([]);+ setIsDeleteAllDialogOpen(false);+ };+return (<>- <Grid gap={2} css={sectionSpacing}>- <Text variant="titles">Redirects</Text>- <Text color="subtle">- Redirects old URLs to new ones so that you don’t lose any traffic or- search engine rankings.- </Text>+ <ImportRedirectsDialog+ isOpen={isImportDialogOpen}+ onOpenChange={setIsImportDialogOpen}+ existingRedirects={redirects}+ onImport={handleImportRedirects}+ />++ <Grid gap={3} css={sectionSpacing}>+ <Flex gap={1} align="center">+ <Text variant="titles">Redirects</Text>+ <Tooltip+ variant="wrapped"+ content={+ <Flex direction="column" gap="2">+ <Text>+ Redirect old URLs to new ones so you don't lose traffic or+ search engine rankings.+ </Text>+ <Flex direction="column" gap="1">+ <Text>Supported patterns:</Text>+ <Text>/path → Exact match</Text>+ <Text>/blog/* → All paths under /blog/</Text>+ <Text>/:slug → Dynamic segment</Text>+ <Text>/:id? → Optional segment</Text>+ </Flex>+ </Flex>+ }+ >+ <InfoCircleIcon+ color={rawTheme.colors.foregroundSubtle}+ tabIndex={0}+ />+ </Tooltip>+ </Flex>++ <Flex gap="2" justify="between">+ <SearchField+ placeholder="Search"+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ onAbort={() => setSearchQuery("")}+ disabled={redirects.length === 0}+ />+ <Flex gap="2">+ <Button+ color="ghost"+ prefix={<TrashIcon />}+ onClick={() => setIsDeleteAllDialogOpen(true)}+ disabled={redirects.length === 0}+ >+ Delete all+ </Button>+ <Button+ color="ghost"+ prefix={<UploadIcon />}+ onClick={() => setIsImportDialogOpen(true)}+ >+ Import+ </Button>+ </Flex>+ </Flex>++ <Dialog+ open={isDeleteAllDialogOpen}+ onOpenChange={setIsDeleteAllDialogOpen}+ >+ <DialogContent>+ <DialogTitle>Delete all redirects</DialogTitle>+ <Flex css={{ padding: theme.panel.padding }}>+ <Text>+ Are you sure you want to delete all {redirects.length} redirect+ {redirects.length !== 1 ? "s" : ""}? This action cannot be+ undone.+ </Text>+ </Flex>+ <DialogActions>+ <Button color="destructive" onClick={handleDeleteAll}>+ Delete all+ </Button>+ <DialogClose>+ <Button color="ghost">Cancel</Button>+ </DialogClose>+ </DialogActions>+ </DialogContent>+ </Dialog><Flex gap="2" align="center"><InputErrorsTooltip- errors={oldPathErrors.length > 0 ? oldPathErrors : undefined}+ errors={fromPathErrors.length > 0 ? fromPathErrors : undefined}side="top">- <InputField- ref={oldPathRef}+ <Combobox<string>+ inputRef={fromPathRef}autoFocus- type="text"- placeholder="/old-path"- value={oldPath}- css={{ flexGrow: 1 }}- onKeyDown={handleOnKeyDown}- onChange={handleOldPathChange}- color={oldPathErrors.length === 0 ? undefined : "error"}+ placeholder="/old-path or /old/*"+ value={fromPath}+ color={fromPathErrors.length === 0 ? undefined : "error"}+ getItems={() => pagePaths}+ itemToString={(item) => item ?? ""}+ onItemSelect={(value) => handleFromPathChange(value ?? "")}+ onChange={(value) => {+ // Don't reset value on blur (when value is undefined)+ if (value !== undefined) {+ handleFromPathChange(value);+ }+ }}/></InputErrorsTooltip><Selectid="redirect-type"placeholder="301"- options={["301", "302"]}+ options={[...statusCodeOptions]}value={httpStatus ?? "301"}css={{ width: theme.spacing[18] }}+ getDescription={(option) => (+ <Box css={{ width: theme.spacing[25] }}>+ {statusCodeDescriptions[option]}+ </Box>+ )}onChange={(value) => {setHttpStatus(value as PageRedirect["status"]);}}/>- <ArrowRightIcon size={16} style={{ flexShrink: 0 }} />-<InputErrorsTooltip- errors={newPathErrors.length > 0 ? newPathErrors : undefined}+ errors={toPathErrors.length > 0 ? toPathErrors : undefined}side="top">- <InputField- type="text"- placeholder="/new-path or URL"- value={newPath}- onKeyDown={handleOnKeyDown}- onChange={handleNewPathChange}- color={newPathErrors.length === 0 ? undefined : "error"}+ <Combobox<string>+ placeholder="/to-path or URL"+ value={toPath}+ color={toPathErrors.length === 0 ? undefined : "error"}+ getItems={() => pagePaths}+ itemToString={(item) => item ?? ""}+ onItemSelect={(value) => handleToPathChange(value ?? "")}+ onChange={(value) => {+ // Don't reset value on blur (when value is undefined)+ if (value !== undefined) {+ handleToPathChange(value);+ }+ }}/></InputErrorsTooltip><Button- disabled={isValidRedirects === false || oldPath === newPath}+ disabled={isValidRedirects === false || fromPath === toPath}onClick={handleAddRedirect}css={{ flexShrink: 0 }}>Add</Button></Flex>+ {fromPathWarnings.length > 0 && (+ <Flex gap="1" align="center">+ <AlertIcon+ color={rawTheme.colors.backgroundAlertMain}+ style={{ flexShrink: 0 }}+ />+ <Text color="subtle">{fromPathWarnings.join(". ")}</Text>+ </Flex>+ )}</Grid>-- {redirectKeys.length > 0 ? (- <Grid css={sectionSpacing}>- <List asChild>- <Flex direction="column" gap="1" align="stretch">- {redirects.map((redirect, index) => {- return (- <ListItem asChild key={redirect.old} index={index}>- <Flex- justify="between"- align="center"- gap="2"- css={{- p: theme.spacing[3],- overflow: "hidden",- }}- >- <Flex gap="2" align="center">+ {redirects.length > 0 ? (+ <ScrollArea>+ <Grid css={sectionSpacing}>+ <List asChild>+ <Flex direction="column" gap="1" align="stretch">+ {filteredRedirects.map((redirect, index) => {+ return (+ <ListItem asChild key={redirect.old}>+ <Grid+ align="center"+ gap="2"+ css={{+ p: theme.spacing[3],+ overflow: "hidden",+ gridTemplateColumns: `1fr auto auto 1fr`,+ position: "relative",+ "& > button": {+ opacity: 0,+ position: "absolute",+ right: 0,+ top: 0,+ bottom: 0,+ height: "auto",+ borderRadius: 0,+ background: theme.colors.backgroundPanel,+ },+ "&:hover > button, &:focus-within > button": {+ opacity: 1,+ },+ }}+ ><Tooltip content={redirect.old}><Linkunderline="hover"@@ -223,8 +434,9 @@ export const SectionRedirects = () => {publishedOrigin).toString()}css={{- width: theme.spacing[18],wordBreak: "break-all",+ overflow: "hidden",+ textOverflow: "ellipsis",}}target="_blank">@@ -232,9 +444,7 @@ export const SectionRedirects = () => {</Link></Tooltip><Text>{redirect.status ?? "301"}</Text>- <Flex shrink={false} align="center">- <ArrowRightIcon size={16} aria-disabled />- </Flex>+ <ArrowRightIcon size={16} /><Tooltip content={redirect.new}><Linkunderline="hover"@@ -244,29 +454,28 @@ export const SectionRedirects = () => {).toString()}css={{wordBreak: "break-all",- maxWidth: theme.spacing[30],+ overflow: "hidden",+ textOverflow: "ellipsis",}}target="_blank">{redirect.new}</Link></Tooltip>- </Flex>- <Flex gap="2"><SmallIconButtonvariant="destructive"icon={<TrashIcon />}aria-label={`Delete redirect from ${redirect.old}`}onClick={() => handleDeleteRedirect(index)}/>- </Flex>- </Flex>- </ListItem>- );- })}- </Flex>- </List>- </Grid>+ </Grid>+ </ListItem>+ );+ })}+ </Flex>+ </List>+ </Grid>+ </ScrollArea>) : null}</>);diff --git a/apps/builder/app/shared/project-settings/utils.test.ts b/apps/builder/app/shared/project-settings/utils.test.tsindex ffde0c3404..0951a9284a 100644--- a/apps/builder/app/shared/project-settings/utils.test.ts+++ b/apps/builder/app/shared/project-settings/utils.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from "vitest";import { createDefaultPages } from "@webstudio-is/project-build";-import { getExistingRoutePaths } from "./utils";+import type { PageRedirect } from "@webstudio-is/sdk";+import { getExistingRoutePaths, findMatchingRedirect } from "./utils";describe("getExistingRoutePaths", () => {test("gets all the route paths that exists in the project", () => {@@ -31,3 +32,142 @@ describe("getExistingRoutePaths", () => {expect(Array.from(result)).toEqual(["/page", "/blog/:id"]);});});++describe("findMatchingRedirect", () => {+ const createRedirect = (+ old: string,+ newPath: string = "/new"+ ): PageRedirect => ({+ old,+ new: newPath,+ status: "301",+ });++ describe("exact matches", () => {+ test("finds redirect with exact path match", () => {+ const redirects = [createRedirect("/about")];+ const result = findMatchingRedirect("/about", redirects);+ expect(result?.old).toBe("/about");+ });++ test("returns undefined when no match found", () => {+ const redirects = [createRedirect("/about")];+ const result = findMatchingRedirect("/contact", redirects);+ expect(result).toBeUndefined();+ });++ test("matches home page path /", () => {+ const redirects = [createRedirect("/old-home")];+ const result = findMatchingRedirect("/", redirects);+ expect(result).toBeUndefined();+ });+ });++ describe("wildcard patterns", () => {+ test("matches wildcard pattern /*", () => {+ const redirects = [createRedirect("/blog/*")];+ const result = findMatchingRedirect("/blog/post-1", redirects);+ expect(result?.old).toBe("/blog/*");+ });++ test("matches nested path with wildcard", () => {+ const redirects = [createRedirect("/docs/*")];+ const result = findMatchingRedirect("/docs/api/v1/users", redirects);+ expect(result?.old).toBe("/docs/*");+ });++ test("does not match path outside wildcard scope", () => {+ const redirects = [createRedirect("/blog/*")];+ const result = findMatchingRedirect("/posts/article", redirects);+ expect(result).toBeUndefined();+ });++ test("matches wildcard at root level", () => {+ const redirects = [createRedirect("/*")];+ const result = findMatchingRedirect("/anything", redirects);+ expect(result?.old).toBe("/*");+ });+ });++ describe("dynamic segment patterns", () => {+ test("matches single dynamic segment", () => {+ const redirects = [createRedirect("/:slug")];+ const result = findMatchingRedirect("/about", redirects);+ expect(result?.old).toBe("/:slug");+ });++ test("matches dynamic segment in middle of path", () => {+ const redirects = [createRedirect("/blog/:id/comments")];+ const result = findMatchingRedirect("/blog/123/comments", redirects);+ expect(result?.old).toBe("/blog/:id/comments");+ });++ test("matches multiple dynamic segments", () => {+ const redirects = [createRedirect("/users/:userId/posts/:postId")];+ const result = findMatchingRedirect("/users/42/posts/99", redirects);+ expect(result?.old).toBe("/users/:userId/posts/:postId");+ });++ test("does not match when segment count differs", () => {+ const redirects = [createRedirect("/blog/:id")];+ const result = findMatchingRedirect("/blog/123/extra", redirects);+ expect(result).toBeUndefined();+ });+ });++ describe("optional segments", () => {+ test("matches optional segment when present", () => {+ const redirects = [createRedirect("/blog/:id?")];+ const result = findMatchingRedirect("/blog/123", redirects);+ expect(result?.old).toBe("/blog/:id?");+ });++ test("matches optional segment when absent", () => {+ const redirects = [createRedirect("/blog/:id?")];+ const result = findMatchingRedirect("/blog", redirects);+ expect(result?.old).toBe("/blog/:id?");+ });+ });++ describe("priority and order", () => {+ test("returns first matching redirect", () => {+ const redirects = [+ createRedirect("/about", "/new-about"),+ createRedirect("/:slug", "/catch-all"),+ ];+ const result = findMatchingRedirect("/about", redirects);+ expect(result?.new).toBe("/new-about");+ });++ test("falls through to wildcard if no exact match", () => {+ const redirects = [createRedirect("/specific"), createRedirect("/*")];+ const result = findMatchingRedirect("/other", redirects);+ expect(result?.old).toBe("/*");+ });+ });++ describe("edge cases", () => {+ test("handles empty redirects array", () => {+ const result = findMatchingRedirect("/about", []);+ expect(result).toBeUndefined();+ });++ test("handles path with special characters", () => {+ const redirects = [createRedirect("/path-with-dashes")];+ const result = findMatchingRedirect("/path-with-dashes", redirects);+ expect(result?.old).toBe("/path-with-dashes");+ });++ test("handles path with underscores", () => {+ const redirects = [createRedirect("/path_with_underscores")];+ const result = findMatchingRedirect("/path_with_underscores", redirects);+ expect(result?.old).toBe("/path_with_underscores");+ });++ test("handles deeply nested paths", () => {+ const redirects = [createRedirect("/a/b/c/d/e")];+ const result = findMatchingRedirect("/a/b/c/d/e", redirects);+ expect(result?.old).toBe("/a/b/c/d/e");+ });+ });+});diff --git a/apps/builder/app/shared/project-settings/utils.ts b/apps/builder/app/shared/project-settings/utils.tsindex 14bf18280b..cfa15997ec 100644--- a/apps/builder/app/shared/project-settings/utils.ts+++ b/apps/builder/app/shared/project-settings/utils.ts@@ -1,5 +1,6 @@import { rawTheme, theme, type CSS } from "@webstudio-is/design-system";-import { getPagePath, type Pages } from "@webstudio-is/sdk";+import { getPagePath, type Pages, type PageRedirect } from "@webstudio-is/sdk";+import { matchPathnamePattern } from "~/builder/shared/url-pattern";export const leftPanelWidth = rawTheme.spacing[26];export const rightPanelWidth = rawTheme.spacing[35];@@ -22,3 +23,20 @@ export const getExistingRoutePaths = (pages?: Pages): Set<string> => {}return paths;};++/**+ * Find a redirect that would match the given page path.+ * Uses URLPattern for proper pattern matching (wildcards, dynamic segments).+ */+export const findMatchingRedirect = (+ pagePath: string,+ redirects: Array<PageRedirect>+): PageRedirect | undefined => {+ for (const redirect of redirects) {+ // matchPathnamePattern returns matched groups if pattern matches, undefined otherwise+ const match = matchPathnamePattern(redirect.old, pagePath);+ if (match !== undefined) {+ return redirect;+ }+ }+};diff --git a/apps/builder/app/shared/redirects/README.md b/apps/builder/app/shared/redirects/README.mdnew file mode 100644index 0000000000..0289da75ad--- /dev/null+++ b/apps/builder/app/shared/redirects/README.md@@ -0,0 +1,534 @@+# Redirect Parsers++Import redirects from popular formats (CSV, JSON, Netlify `_redirects`, Apache `.htaccess`) into Webstudio.++## Webstudio Redirect Format++Webstudio stores redirects with this schema:++```typescript+type PageRedirect = {+ old: string; // Source path (must start with /, cannot end with /)+ new: string; // Target path or URL+ status?: "301" | "302"; // Optional, defaults to 301+};+```++### Path Requirements++| Requirement | Valid | Invalid |+| ------------------- | ------------------ | ---------------------- |+| Must start with `/` | `/about` | `about` |+| Cannot end with `/` | `/about` | `/about/` |+| No double slashes | `/a/b/c` | `/a//b` |+| Allowed chars | `a-zA-Z0-9-_/:?.*` | `<>{}` |+| Reserved paths | `/home` | `/s/...`, `/build/...` |++### Slash Normalization++The parser **strips trailing slashes** from source paths to match Webstudio's requirements:++```+Input: /old-path/ → Output: /old-path+Input: /old-path → Output: /old-path+```++Target paths preserve their original form (Webstudio allows trailing slashes in targets).++---++## Supported Formats++### 1. CSV++**Platforms:** Shopify, HubSpot, WordPress (Redirection plugin), manual exports++#### Column Name Variations++| Source Column | Target Column | Status Column |+| --------------- | ------------- | ------------- |+| `source` | `target` | `status` |+| `from` | `to` | `code` |+| `old` | `new` | `statuscode` |+| `redirect from` | `redirect to` | |+| `original url` | `target url` | |+| `original url` | `destination` | |++#### Shopify Format++```csv+Redirect from,Redirect to+/old-product,/new-product+/old-collection,/new-collection+```++- No status column (all redirects are 301)++#### HubSpot Format++```csv+Original URL,Target URL+/old-landing,/new-landing+/old-blog-post,/blog/new-post+```++- No status column (all redirects are 301)++#### Generic Format++```csv+source,target,status+/page1,/newpage1,301+/page2,/newpage2,302+/page3,/newpage3,permanent+/page4,/newpage4,temporary+```++---++### 2. JSON++**Platforms:** Vercel, Next.js, WordPress (Redirection plugin), custom exports++#### Vercel / Next.js Format++```json+{+ "redirects": [+ {+ "source": "/old-page",+ "destination": "/new-page",+ "permanent": true+ },+ {+ "source": "/temp-redirect",+ "destination": "/landing",+ "permanent": false+ }+ ]+}+```++#### Next.js with statusCode++```json+{+ "redirects": [+ {+ "source": "/old-page",+ "destination": "/new-page",+ "statusCode": 301+ }+ ]+}+```++#### Generic Array Format++```json+[+ { "from": "/old", "to": "/new", "status": 301 },+ { "source": "/a", "target": "/b", "code": 302 },+ { "old": "/x", "new": "/y" }+]+```++#### Key Name Variations++| Source Keys | Target Keys | Status Keys |+| ----------- | ------------- | ------------------ |+| `source` | `destination` | `statusCode` |+| `from` | `target` | `status` |+| `old` | `to` | `code` |+| | `new` | `permanent` (bool) |++---++### 3. Netlify `_redirects`++**Platform:** Netlify++#### Format++```+# Comment+/source /destination [status]+```++#### Examples++```+# Basic redirects+/old /new 301+/temp /landing 302++# No status (defaults to 301)+/about-us /about++# External URLs+/github https://github.com/example 301++# Force redirect (! is ignored)+/override /new 301!+```++---++### 4. Apache `.htaccess`++**Platforms:** Apache, cPanel, traditional hosting++#### Supported Directives++```apache+Redirect 301 /old-page /new-page+Redirect 302 /temp-page /landing+Redirect permanent /legacy /modern+Redirect temp /maintenance /coming-soon+Redirect /simple /destination # defaults to 302+```++#### Case Insensitive++```apache+redirect 301 /lowercase /target+REDIRECT 301 /uppercase /target+```++---++## Status Code Handling++### Supported Codes++| Code | Meaning | Webstudio |+| ---- | --------------------------- | ----------------------- |+| 301 | Permanent redirect | ✅ `"301"` |+| 302 | Temporary redirect | ✅ `"302"` |+| 307 | Temporary (preserve method) | ⚠️ Converted to `"302"` |+| 308 | Permanent (preserve method) | ⚠️ Converted to `"301"` |++### Text Status Values++| Text | Converted To |+| ------------------------- | ------------ |+| `permanent` | `"301"` |+| `temporary` | `"302"` |+| `true` (permanent field) | `"301"` |+| `false` (permanent field) | `"302"` |++### Skipped Codes++| Code | Reason |+| ----- | ---------------------------------- |+| 200 | Rewrite (proxy without URL change) |+| 404 | Not found |+| Other | Invalid redirect status |++---++## Unsupported Features++These patterns are **skipped with a warning** (not imported):++### Dynamic Placeholders++```+/blog/:slug → /posts/:slug+/news/:year/:month/:slug → /archive/:year-:month-:slug+```++### Splat Wildcards++```+/docs/* → /documentation/:splat+/old/* → /new/*+```++### Conditions++```+# Netlify+/ /en 302 Country=us+/admin /login 302 Role=admin++# Vercel/Next.js+{+ "source": "/",+ "has": [{ "type": "header", "key": "x-country", "value": "DE" }],+ "destination": "/de"+}+```++### Query Parameter Matching++```+/store id=:id → /products/:id+```++### Apache Regex Rules++```apache+RedirectMatch ^/blog/(.*)$ /posts/$1+RewriteRule ^old/(.*)$ /new/$1 [R=301,L]+```++---++## User Documentation++_This section contains user-friendly copy for the Import dialog and help content._++### Supported File Formats++**CSV** — Spreadsheet exports from Shopify, HubSpot, WordPress, or any custom CSV with columns for source path, target path, and optional status code.++**JSON** — Configuration exports from Vercel, Next.js, or any JSON array of redirect objects.++**Netlify \_redirects** — The `_redirects` file format used by Netlify hosting.++**Apache .htaccess** — Redirect directives from Apache server configuration files.++### How It Works++1. Upload or paste your redirect file+2. We automatically detect the format+3. Review the parsed redirects before importing+4. Choose to add to or replace your existing redirects++### Supported Routing Patterns++Webstudio supports these path patterns in redirects:++| Pattern | Example | Matches |+| ---------- | --------- | ------------------------------------- |+| Exact path | `/about` | Only `/about` |+| Wildcard | `/blog/*` | `/blog/post`, `/blog/2024/post`, etc. |+| Segment | `/:slug` | `/anything` (single segment) |+| Optional | `/:id?` | `/` or `/123` |++**Important:** Captured values (like `:slug`) cannot be inserted into the destination path. The destination is always a fixed path or URL.++### What Gets Imported++✅ **Imported:**++- Simple path-to-path redirects (`/old` → `/new`)+- Redirects to external URLs (`/github` → `https://github.com/...`)+- 301 (permanent) and 302 (temporary) status codes+- 307 and 308 status codes (converted to 302 and 301)++### What Gets Skipped++⚠️ **Skipped (with explanation):**++- Dynamic placeholders like `/blog/:slug` → `/posts/:slug`+- Wildcard substitutions like `/old/*` → `/new/*`+- Conditional redirects (country, header, cookie-based)+- Query parameter matching+- Regex-based rules (Apache RewriteRule, RedirectMatch)+- Rewrites (status 200) and "not found" rules (status 404)++### Limitations vs. Other Platforms++Webstudio redirects are designed for simplicity and performance. Some advanced features from other platforms are not supported:++| Feature | Netlify | Vercel | Apache | Webstudio |+| ------------------------ | ------- | ------ | ------ | --------- |+| Simple redirects | ✅ | ✅ | ✅ | ✅ |+| External URLs | ✅ | ✅ | ✅ | ✅ |+| Wildcard source | ✅ | ✅ | ✅ | ✅ |+| Wildcard substitution | ✅ | ✅ | ✅ | ❌ |+| Regex patterns | ❌ | ❌ | ✅ | ❌ |+| Header/cookie conditions | ✅ | ✅ | ✅ | ❌ |+| Geo/country conditions | ✅ | ✅ | ❌ | ❌ |+| Query string matching | ✅ | ✅ | ✅ | ❌ |+| Rewrites (proxy) | ✅ | ✅ | ✅ | ❌ |++### Status Codes Explained++| Code | Name | When to Use |+| ---- | --------- | ---------------------------------------------------- |+| 301 | Permanent | Page has moved forever. SEO transfers to new URL. |+| 302 | Temporary | Page is temporarily elsewhere. SEO stays at old URL. |++---++## Auto-Detection Priority++The parser detects formats in this order:++1. **JSON** - Content starts with `[` or `{`+2. **CSV** - First line contains known column headers+3. **htaccess** - Any line starts with `Redirect` (case-insensitive)+4. **Netlify** - Lines match pattern `/path /path [status]`++---++## UI Plan++### Location++Add an "Import" button next to the "Redirects" title in `section-redirects.tsx`.++```+┌─────────────────────────────────────────────────────────────┐+│ Redirects ℹ️ [Import] │+│ Redirect old URLs to new ones... │+└─────────────────────────────────────────────────────────────┘+```++### Import Dialog++When clicking "Import", open a dialog with:++```+┌─────────────────────────────────────────────────────────────┐+│ Import Redirects [X] │+├─────────────────────────────────────────────────────────────┤+│ │+│ Paste or drop a file containing redirects. │+│ Supports: CSV, JSON, Netlify _redirects, Apache .htaccess │+│ │+│ ┌─────────────────────────────────────────────────────┐ │+│ │ │ │+│ │ [Upload File] or drag & drop here │ │+│ │ │ │+│ └─────────────────────────────────────────────────────┘ │+│ │+│ ── OR ── │+│ │+│ ┌─────────────────────────────────────────────────────┐ │+│ │ Paste content here... │ │+│ │ │ │+│ │ │ │+│ └─────────────────────────────────────────────────────┘ │+│ │+│ [Cancel] [Parse] │+└─────────────────────────────────────────────────────────────┘+```++### Preview State++After parsing, show a preview before importing:++```+┌─────────────────────────────────────────────────────────────┐+│ Import Redirects [X] │+├─────────────────────────────────────────────────────────────┤+│ │+│ ✓ Found 47 redirects │+│ ⚠ 3 lines skipped (see below) │+│ │+│ Preview: │+│ ┌─────────────────────────────────────────────────────┐ │+│ │ /old-page 301 → /new-page │ │+│ │ /about-us 301 → /about │ │+│ │ /blog/post-1 302 → /posts/1 │ │+│ │ ... (44 more) │ │+│ └─────────────────────────────────────────────────────┘ │+│ │+│ Skipped: │+│ ┌─────────────────────────────────────────────────────┐ │+│ │ Line 5: /docs/* → wildcard patterns not supported │ │+│ │ Line 8: /:slug → placeholders not supported │ │+│ │ Line 12: missing target path │ │+│ └─────────────────────────────────────────────────────┘ │+│ │+│ ○ Add to existing redirects │+│ ○ Replace all redirects │+│ │+│ [Back] [Import 47] │+└─────────────────────────────────────────────────────────────┘+```++### Conflict Handling++If importing redirects that already exist:++```+┌─────────────────────────────────────────────────────────────┐+│ ⚠ 5 redirects have the same source path as existing ones │+│ │+│ ○ Skip duplicates (import 42 new) │+│ ○ Overwrite existing (update 5, import 42 new) │+└─────────────────────────────────────────────────────────────┘+```++### Component Structure++```+section-redirects.tsx+├── ImportButton # Opens the dialog+└── ImportRedirectsDialog # The dialog component+ ├── InputStep # File upload / paste textarea+ │ ├── DropZone # Drag & drop file area+ │ ├── FileInput # Hidden file input+ │ └── TextArea # Paste content+ ├── PreviewStep # Shows parsed results+ │ ├── SuccessSummary # "Found X redirects"+ │ ├── RedirectPreviewList # Scrollable list of redirects+ │ ├── SkippedList # Collapsed/expandable skipped items+ │ └── MergeOptions # Radio: add vs replace+ └── useImportRedirects # Hook managing dialog state+```++### State Machine++```+ ┌──────────┐+ │ CLOSED │+ └────┬─────┘+ │ open+ ▼+ ┌──────────┐+ ┌─────│ INPUT │◄────────┐+ │ └────┬─────┘ │+ │ │ parse │ back+ │ ▼ │+ │ ┌──────────┐ │+ │ │ PARSING │ │+ │ └────┬─────┘ │+ │ │ │+ │ ┌────┴────┐ │+ │ ▼ ▼ │+ │ ┌───────┐ ┌─────────┐ │+ │ │ ERROR │ │ PREVIEW │────┘+ │ └───┬───┘ └────┬────┘+ │ │ │ import+ │ │ ▼+ │ │ ┌──────────┐+ │ │ │ IMPORTED │+ │ │ └────┬─────┘+ │ │ │+ └─────┴──────────┘+ │ close+ ▼+ ┌──────────┐+ │ CLOSED │+ └──────────┘+```++### Design System Components++From `@webstudio-is/design-system`:++- `Dialog`, `DialogContent`, `DialogTitle`, `DialogClose`+- `Button`, `Text`, `Flex`, `Grid`, `Box`+- `TextArea` (for paste input)+- `RadioGroup` (for merge options)+- `ScrollArea` (for preview list)+- `PanelBanner` (for warnings/errors)++### Acceptance Criteria++1. **File Upload**: Accept `.csv`, `.json`, `.txt`, `.htaccess` files+2. **Drag & Drop**: Support dropping files onto the dialog+3. **Paste**: Support pasting content directly+4. **Auto-detect**: Automatically detect format from content+5. **Preview**: Show parsed redirects before importing+6. **Skipped Feedback**: Show why lines were skipped with line numbers+7. **Merge Options**: Let user choose add vs replace+8. **Duplicate Handling**: Detect and handle conflicts with existing redirects+9. **Validation**: Run Webstudio's `OldPagePath` validation on import+10. **Toast Feedback**: Show success/error toast after importdiff --git a/apps/builder/app/shared/redirects/fixtures/apache.htaccess b/apps/builder/app/shared/redirects/fixtures/apache.htaccessnew file mode 100644index 0000000000..38f034d79d--- /dev/null+++ b/apps/builder/app/shared/redirects/fixtures/apache.htaccess@@ -0,0 +1,74 @@+# Apache .htaccess Redirect Configuration+# =========================================+# Comprehensive test fixture for Apache redirect directives+# Docs: https://httpd.apache.org/docs/current/mod/mod_alias.html++# -----------------------------------------------------------------+# ENABLE REWRITE ENGINE (ignored by parser)+# -----------------------------------------------------------------+RewriteEngine On+RewriteBase /++# -----------------------------------------------------------------+# BASIC REDIRECTS (supported)+# -----------------------------------------------------------------++# Simple redirects with status codes+Redirect 301 /old-page /new-page+Redirect 302 /temp-page /landing+Redirect 301 /about-us /about+Redirect 302 /contact-us /contact++# Redirect with permanent/temp keywords+Redirect permanent /legacy /modern+Redirect temp /maintenance /coming-soon++# Redirect without status (defaults to 302 in Apache)+Redirect /simple /destination++# External URL redirects+Redirect 301 /github https://github.com/example/repo+Redirect 301 /docs https://docs.example.com/++# -----------------------------------------------------------------+# CASE VARIATIONS (all should work)+# -----------------------------------------------------------------+redirect 301 /lowercase /target1+REDIRECT 301 /uppercase /target2++# -----------------------------------------------------------------+# WHITESPACE VARIATIONS+# -----------------------------------------------------------------+Redirect 301 /extra-spaces /target3++# -----------------------------------------------------------------+# STATUS CODE CONVERSION+# -----------------------------------------------------------------+Redirect 307 /temp-307 /temp-destination+Redirect 308 /perm-308 /perm-destination++# -----------------------------------------------------------------+# REDIRECTMATCH - REGEX (skipped with warning)+# -----------------------------------------------------------------+RedirectMatch 301 ^/blog/([0-9]+)/([0-9]+)/(.*)$ /posts/$1-$2-$3+RedirectMatch ^/category/(.*)$ /topics/$1++# -----------------------------------------------------------------+# REWRITERULE (skipped with warning)+# -----------------------------------------------------------------+RewriteRule ^old/(.*)$ /new/$1 [R=301,L]+RewriteRule ^api/(.*)$ https://api.example.com/$1 [P]+RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]+RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]++# -----------------------------------------------------------------+# OTHER DIRECTIVES (ignored, not reported as skipped)+# -----------------------------------------------------------------+Options +FollowSymLinks+ErrorDocument 404 /404.html+Header set X-Frame-Options "SAMEORIGIN"++# -----------------------------------------------------------------+# MORE REDIRECTS AFTER OTHER DIRECTIVES+# -----------------------------------------------------------------+Redirect 301 /final-redirect /final-destinationdiff --git a/apps/builder/app/shared/redirects/fixtures/generic.csv b/apps/builder/app/shared/redirects/fixtures/generic.csvnew file mode 100644index 0000000000..c4ab36cdcc--- /dev/null+++ b/apps/builder/app/shared/redirects/fixtures/generic.csv@@ -0,0 +1,56 @@+source,target,status+# CSV Redirects - Comprehensive Test Fixture+# Columns: source,target,status (generic naming)+# Other supported column names shown in sections below++# -----------------------------------------------------------------+# BASIC REDIRECTS (supported)+# -----------------------------------------------------------------+/page1,/newpage1,301+/page2,/newpage2,302+/temp-page,/landing,307+/perm-page,/destination,308++# -----------------------------------------------------------------+# TEXT STATUS VALUES+# -----------------------------------------------------------------+/text-permanent,/target1,permanent+/text-temporary,/target2,temporary++# -----------------------------------------------------------------+# NO STATUS (defaults to 301)+# -----------------------------------------------------------------+/no-status,/default-301,++# -----------------------------------------------------------------+# EXTERNAL URLS+# -----------------------------------------------------------------+/external,https://example.com/external,301+/github,https://github.com/example,301++# -----------------------------------------------------------------+# SPECIAL CHARACTERS+# -----------------------------------------------------------------+/path-with-query?ref=old,/path-with-query?ref=new,301+/url%20encoded,/url-encoded,301+"/path,with,commas","/new-path",301+"/path ""with quotes""","/target",301++# -----------------------------------------------------------------+# TRAILING SLASH (normalized)+# -----------------------------------------------------------------+/trailing/,/trailing-new,301++# -----------------------------------------------------------------+# ROOT PATH+# -----------------------------------------------------------------+/,/home,301++# -----------------------------------------------------------------+# INVALID ENTRIES (skipped)+# -----------------------------------------------------------------+invalid-no-slash,/valid,301+,/missing-source,301+/missing-target,,301+/invalid-status,/target,999+/rewrite,/proxy,200diff --git a/apps/builder/app/shared/redirects/fixtures/generic.json b/apps/builder/app/shared/redirects/fixtures/generic.jsonnew file mode 100644index 0000000000..41038f3df1--- /dev/null+++ b/apps/builder/app/shared/redirects/fixtures/generic.json@@ -0,0 +1,102 @@+[+ {+ "$comment": "Generic JSON array - various key naming conventions",+ "$sources": "WordPress Redirection plugin exports, custom tools, manual exports"+ },++ {+ "$comment": "from/to naming (common generic format)",+ "from": "/legacy/endpoint",+ "to": "/modern/endpoint",+ "status": 301+ },+ {+ "from": "/old-api",+ "to": "/api/v2",+ "status": 302+ },++ {+ "$comment": "source/destination naming (Vercel-style)",+ "source": "/v1/users",+ "destination": "/api/v2/users",+ "code": 301+ },+ {+ "source": "/v1/posts",+ "destination": "/api/v2/posts",+ "code": 308+ },++ {+ "$comment": "source/target naming (alternative)",+ "source": "/redirect-permanent",+ "target": "/destination",+ "permanent": true+ },+ {+ "source": "/redirect-temporary",+ "target": "/landing",+ "permanent": false+ },++ {+ "$comment": "old/new naming (Webstudio native format)",+ "old": "/deprecated",+ "new": "/current",+ "status": 302+ },++ {+ "$comment": "No status (defaults to 301)",+ "source": "/no-status",+ "target": "/should-default-301"+ },++ {+ "$comment": "External URLs",+ "source": "/external",+ "target": "https://external.example.com/page"+ },++ {+ "$comment": "INVALID ENTRIES (skipped with reason)",+ "source": "invalid-no-slash",+ "target": "/valid",+ "status": 301+ },+ {+ "$comment": "Missing source field",+ "target": "/missing-source",+ "status": 301+ },+ {+ "$comment": "Missing target field",+ "source": "/missing-target",+ "status": 301+ },+ {+ "$comment": "Invalid status code",+ "source": "/invalid-status",+ "target": "/destination",+ "status": 999+ },+ {+ "$comment": "Rewrite status (skipped)",+ "source": "/rewrite-status",+ "target": "/proxy",+ "status": 200+ },++ {+ "$comment": "Status code conversion",+ "source": "/status-307",+ "target": "/temp",+ "status": 307+ },+ {+ "source": "/status-308",+ "target": "/perm",+ "status": 308+ }+]diff --git a/apps/builder/app/shared/redirects/fixtures/hubspot.csv b/apps/builder/app/shared/redirects/fixtures/hubspot.csvnew file mode 100644index 0000000000..ae822c13a2--- /dev/null+++ b/apps/builder/app/shared/redirects/fixtures/hubspot.csv@@ -0,0 +1,13 @@+Original URL,Target URL+# HubSpot URL Mapping Export Format+# Columns: "Original URL", "Target URL"+# Note: HubSpot does not export status codes (all are 301)+# Docs: https://knowledge.hubspot.com/website-pages/set-up-url-redirects++/old-landing,/new-landing+/blog/2023/post-title,/blog/post-title+/resources/ebook-download,/resources/guides/ebook+/pricing-old,/pricing+/demo-request,/get-started+/case-studies/company-a,/customers/company-a+/webinar-archive,/resources/webinarsdiff --git a/apps/builder/app/shared/redirects/fixtures/netlify._redirects b/apps/builder/app/shared/redirects/fixtures/netlify._redirectsnew file mode 100644index 0000000000..43407c7b5d--- /dev/null+++ b/apps/builder/app/shared/redirects/fixtures/netlify._redirects@@ -0,0 +1,129 @@+# Netlify _redirects Format - Comprehensive Test Fixture+# ========================================================+# Syntax: /from /to [status]+# Official docs: https://docs.netlify.com/routing/redirects/++# -----------------------------------------------------------------+# BASIC REDIRECTS (supported)+# -----------------------------------------------------------------++# Simple permanent redirects (301)+/home /+/about-us /about 301+/contact-us /contact 301++# Temporary redirects (302)+/sale /offers 302+/promo /campaigns 302++# No status code (defaults to 301)+/default /target++# External URL redirects+/github https://github.com/example/repo 301+/twitter https://twitter.com/example++# -----------------------------------------------------------------+# COMMENTS AND WHITESPACE+# -----------------------------------------------------------------++# This is a comment+ # Indented comment++ /indented-source /indented-target 301++/lots-of-space /destination 301++# Empty lines are ignored+++# -----------------------------------------------------------------+# STATUS CODES+# -----------------------------------------------------------------++/moved /new-location 301+/found /temporary 302+/temp-redirect /temp 307+/perm-redirect /perm 308++# -----------------------------------------------------------------+# PATH PATTERNS (skipped - unsupported)+# -----------------------------------------------------------------++# Splat wildcards+/blog/* /posts/:splat 301+/old-docs/* /docs/:splat++# Placeholders+/news/:year/:month/:day/:slug /blog/:year-:month-:day-:slug 301+/products/:category/:id /shop/:category/item/:id++# Mixed patterns from real-world (Astro docs)+/:lang/install/auto /:lang/install-and-setup/+/:lang/guides/deploy/:service /:lang/deploy/:service+/docs/* /:splat+/:lang/docs/* /:lang/:splat++# -----------------------------------------------------------------+# CONDITIONS (skipped - unsupported)+# -----------------------------------------------------------------++# Country-based+/ /en 302 Country=us,ca,gb+/ /de 302 Country=de,at,ch++# Language-based+/products /en/products 301 Language=en++# Role-based+/admin/* /login 302 Role=admin++# -----------------------------------------------------------------+# REWRITES (skipped - status 200)+# -----------------------------------------------------------------++/api/* https://api.example.com/:splat 200++# -----------------------------------------------------------------+# FORCE REDIRECTS (the ! is ignored, redirect is processed)+# -----------------------------------------------------------------++/override /new-override 301!++# -----------------------------------------------------------------+# QUERY PARAMETER MATCHING (skipped - unsupported)+# -----------------------------------------------------------------++/store id=:id /products/:id 301+/search q=:query /results?search=:query++# -----------------------------------------------------------------+# TRAILING SLASH HANDLING+# -----------------------------------------------------------------++# Will be normalized (trailing slash stripped from source)+/old-path/ /new-path 301++# -----------------------------------------------------------------+# 404 CATCH-ALLS (skipped - status 404)+# -----------------------------------------------------------------++/:lang/* /:lang/404/ 404++# -----------------------------------------------------------------+# REAL-WORLD EXAMPLES (from Astro, React Router, Redux)+# -----------------------------------------------------------------++# Simple path moves (Astro)+/en/getting-started/quick-start /en/install-and-setup/+/reference/renderer-reference /en/reference/integrations-reference/+/en/core-concepts/component-hydration /en/concepts/islands/++# External API docs (React Router)+/en/main/routers/create-browser-router https://api.reactrouter.com/v7/functions/react_router.createBrowserRouter.html+/en/main/hooks/use-navigate https://api.reactrouter.com/v7/functions/react_router.useNavigate.html++# Tutorial migrations (Redux)+/basics/usagewithreact /tutorials/fundamentals/part-5-ui-react+/advanced/asyncactions /tutorials/fundamentals/part-6-async-logic+/recipes/computingderiveddata /usage/deriving-data-selectorsdiff --git a/apps/builder/app/shared/redirects/fixtures/shopify.csv b/apps/builder/app/shared/redirects/fixtures/shopify.csvnew file mode 100644index 0000000000..71290e4255--- /dev/null+++ b/apps/builder/app/shared/redirects/fixtures/shopify.csv@@ -0,0 +1,13 @@+Redirect from,Redirect to+# Shopify URL Redirect Export Format+# Columns: "Redirect from", "Redirect to"+# Note: Shopify does not export status codes (all are 301)+# Docs: https://help.shopify.com/en/manual/online-store/menus-and-links/url-redirect++/products/old-product,/products/new-product+/collections/summer-2024,/collections/summer-2025+/pages/about-old,/pages/about+/blogs/news/old-post,/blogs/news/new-post+/products/discontinued-item,/collections/clearance+/products/variant-123,/products/new-variant+/collections/sale-2023,/collections/archivediff --git a/apps/builder/app/shared/redirects/fixtures/vercel-nextjs.json b/apps/builder/app/shared/redirects/fixtures/vercel-nextjs.jsonnew file mode 100644index 0000000000..89be6134c4--- /dev/null+++ b/apps/builder/app/shared/redirects/fixtures/vercel-nextjs.json@@ -0,0 +1,120 @@+{+ "$comment": "JSON Redirects - Comprehensive Test Fixture",+ "$formats": "Vercel vercel.json, Next.js next.config.js, generic array format",+ "$docs": "https://vercel.com/docs/edge-network/redirects, https://nextjs.org/docs/app/api-reference/next-config-js/redirects",++ "redirects": [+ {+ "$comment": "BASIC REDIRECTS (supported)",+ "source": "/old-page",+ "destination": "/new-page",+ "permanent": true+ },+ {+ "source": "/temp-redirect",+ "destination": "/landing",+ "permanent": false+ },+ {+ "$comment": "Vercel/Next.js statusCode variant",+ "source": "/with-status-code",+ "destination": "/target",+ "statusCode": 301+ },+ {+ "source": "/temp-status-code",+ "destination": "/other-target",+ "statusCode": 302+ },+ {+ "$comment": "External URLs",+ "source": "/external",+ "destination": "https://example.com",+ "permanent": true+ },+ {+ "source": "/docs-external",+ "destination": "https://docs.example.com/",+ "permanent": true+ },++ {+ "$comment": "DYNAMIC PATTERNS (skipped - unsupported)",+ "source": "/blog/:slug",+ "destination": "/posts/:slug",+ "permanent": true+ },+ {+ "source": "/docs/:path*",+ "destination": "https://docs.example.com/:path*",+ "permanent": true+ },+ {+ "source": "/old-blog/:year/:month/:slug",+ "destination": "/blog/:year-:month-:slug",+ "permanent": true+ },++ {+ "$comment": "CONDITIONS (skipped - unsupported)",+ "source": "/with-query",+ "has": [+ {+ "type": "query",+ "key": "page"+ }+ ],+ "destination": "/paginated?p=:page",+ "permanent": false+ },+ {+ "source": "/geo-redirect",+ "has": [+ {+ "type": "header",+ "key": "x-vercel-ip-country",+ "value": "DE"+ }+ ],+ "destination": "/de",+ "permanent": false+ },+ {+ "source": "/missing-cookie",+ "missing": [+ {+ "type": "cookie",+ "key": "session"+ }+ ],+ "destination": "/login",+ "permanent": false+ },++ {+ "$comment": "LOCALE HANDLING (skipped - unsupported)",+ "source": "/with-locale/:path*",+ "destination": "/:nextInternalLocale/:path*",+ "locale": false,+ "permanent": true+ },++ {+ "$comment": "NO STATUS (defaults to 301)",+ "source": "/no-status",+ "destination": "/default-permanent"+ },++ {+ "$comment": "STATUS CODE CONVERSION",+ "source": "/redirect-307",+ "destination": "/temp-307-target",+ "statusCode": 307+ },+ {+ "source": "/redirect-308",+ "destination": "/perm-308-target",+ "statusCode": 308+ }+ ]+}diff --git a/apps/builder/app/shared/redirects/redirect-loop-detection.test.ts b/apps/builder/app/shared/redirects/redirect-loop-detection.test.tsnew file mode 100644index 0000000000..bfd01be7fc--- /dev/null+++ b/apps/builder/app/shared/redirects/redirect-loop-detection.test.ts@@ -0,0 +1,229 @@+import { describe, test, expect } from "vitest";+import { wouldCreateLoop, detectLoopsInBatch } from "./redirect-loop-detection";+import type { PageRedirect } from "@webstudio-is/sdk";++describe("wouldCreateLoop", () => {+ describe("self-redirect detection", () => {+ test("returns true for direct self-redirect", () => {+ expect(wouldCreateLoop("/about", "/about", [])).toBe(true);+ });++ test("returns true for self-redirect with existing redirects", () => {+ const existing: PageRedirect[] = [+ { old: "/other", new: "/page", status: "301" },+ ];+ expect(wouldCreateLoop("/about", "/about", existing)).toBe(true);+ });+ });++ describe("direct loop detection (A → B → A)", () => {+ test("returns true when target redirects back to source", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/a", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(true);+ });++ test("returns false when no loop exists", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/c", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(false);+ });+ });++ describe("chain loop detection (A → B → C → A)", () => {+ test("returns true for 3-node loop", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/c", status: "301" },+ { old: "/c", new: "/a", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(true);+ });++ test("returns true for longer chain loop", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/c", status: "301" },+ { old: "/c", new: "/d", status: "301" },+ { old: "/d", new: "/e", status: "301" },+ { old: "/e", new: "/a", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(true);+ });++ test("returns false for chain that doesn't loop back", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/c", status: "301" },+ { old: "/c", new: "/d", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(false);+ });+ });++ describe("external URLs", () => {+ test("returns false for external http URL target", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/a", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "http://example.com/b", existing)).toBe(+ false+ );+ });++ test("returns false for external https URL target", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/a", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "https://example.com/b", existing)).toBe(+ false+ );+ });++ test("returns false for protocol-relative URL target", () => {+ expect(wouldCreateLoop("/a", "//example.com/b", [])).toBe(false);+ });+ });++ describe("edge cases", () => {+ test("returns false when no existing redirects", () => {+ expect(wouldCreateLoop("/a", "/b", [])).toBe(false);+ });++ test("returns false when target is not redirected anywhere", () => {+ const existing: PageRedirect[] = [+ { old: "/other", new: "/somewhere", status: "301" },+ ];+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(false);+ });++ test("handles redirect to home page", () => {+ const existing: PageRedirect[] = [{ old: "/", new: "/a", status: "301" }];+ expect(wouldCreateLoop("/a", "/", existing)).toBe(true);+ });++ test("prevents infinite loop in detection with circular existing redirects", () => {+ // Existing redirects already have a loop (shouldn't happen but be defensive)+ const existing: PageRedirect[] = [+ { old: "/b", new: "/c", status: "301" },+ { old: "/c", new: "/b", status: "301" },+ ];+ // Should return true because following /b leads to a cycle+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(true);+ });+ });+});++describe("detectLoopsInBatch", () => {+ describe("loops within imported set", () => {+ test("detects direct loop in imported redirects", () => {+ const newRedirects: PageRedirect[] = [+ { old: "/a", new: "/b", status: "301" },+ { old: "/b", new: "/a", status: "301" },+ ];+ const result = detectLoopsInBatch(newRedirects, []);++ expect(result.valid).toHaveLength(1);+ expect(result.valid[0]).toEqual({ old: "/a", new: "/b", status: "301" });+ expect(result.looped).toHaveLength(1);+ expect(result.looped[0].redirect).toEqual({+ old: "/b",+ new: "/a",+ status: "301",+ });+ expect(result.looped[0].reason).toContain("loop");+ });++ test("detects chain loop in imported redirects", () => {+ const newRedirects: PageRedirect[] = [+ { old: "/a", new: "/b", status: "301" },+ { old: "/b", new: "/c", status: "301" },+ { old: "/c", new: "/a", status: "301" },+ ];+ const result = detectLoopsInBatch(newRedirects, []);++ expect(result.valid).toHaveLength(2);+ expect(result.looped).toHaveLength(1);+ expect(result.looped[0].redirect.old).toBe("/c");+ });++ test("detects self-redirect in imported redirects", () => {+ const newRedirects: PageRedirect[] = [+ { old: "/a", new: "/a", status: "301" },+ { old: "/b", new: "/c", status: "301" },+ ];+ const result = detectLoopsInBatch(newRedirects, []);++ expect(result.valid).toHaveLength(1);+ expect(result.valid[0].old).toBe("/b");+ expect(result.looped).toHaveLength(1);+ expect(result.looped[0].redirect.old).toBe("/a");+ });+ });++ describe("loops with existing redirects", () => {+ test("detects loop that would form with existing redirects", () => {+ const existing: PageRedirect[] = [+ { old: "/b", new: "/a", status: "301" },+ ];+ const newRedirects: PageRedirect[] = [+ { old: "/a", new: "/b", status: "301" },+ ];+ const result = detectLoopsInBatch(newRedirects, existing);++ expect(result.valid).toHaveLength(0);+ expect(result.looped).toHaveLength(1);+ });++ test("detects chain loop with existing redirects", () => {+ const existing: PageRedirect[] = [+ { old: "/c", new: "/a", status: "301" },+ ];+ const newRedirects: PageRedirect[] = [+ { old: "/a", new: "/b", status: "301" },+ { old: "/b", new: "/c", status: "301" },+ ];+ const result = detectLoopsInBatch(newRedirects, existing);++ // First redirect is fine: /a → /b (no loop yet)+ // Second redirect creates: /a → /b → /c → /a (loop!)+ expect(result.valid).toHaveLength(1);+ expect(result.looped).toHaveLength(1);+ expect(result.looped[0].redirect.old).toBe("/b");+ });+ });++ describe("valid imports", () => {+ test("returns all redirects as valid when no loops", () => {+ const newRedirects: PageRedirect[] = [+ { old: "/a", new: "/b", status: "301" },+ { old: "/c", new: "/d", status: "301" },+ { old: "/e", new: "/f", status: "301" },+ ];+ const result = detectLoopsInBatch(newRedirects, []);++ expect(result.valid).toHaveLength(3);+ expect(result.looped).toHaveLength(0);+ });++ test("handles empty input", () => {+ const result = detectLoopsInBatch([], []);++ expect(result.valid).toHaveLength(0);+ expect(result.looped).toHaveLength(0);+ });++ test("allows external URL targets", () => {+ const existing: PageRedirect[] = [+ { old: "https://example.com/a", new: "/a", status: "301" },+ ];+ const newRedirects: PageRedirect[] = [+ { old: "/a", new: "https://example.com/a", status: "301" },+ ];+ const result = detectLoopsInBatch(newRedirects, existing);++ // External URL can't create a loop+ expect(result.valid).toHaveLength(1);+ expect(result.looped).toHaveLength(0);+ });+ });+});diff --git a/apps/builder/app/shared/redirects/redirect-loop-detection.ts b/apps/builder/app/shared/redirects/redirect-loop-detection.tsnew file mode 100644index 0000000000..7992ddfbac--- /dev/null+++ b/apps/builder/app/shared/redirects/redirect-loop-detection.ts@@ -0,0 +1,117 @@+import type { PageRedirect } from "@webstudio-is/sdk";++export const LOOP_ERROR = "This redirect would create a loop";++/**+ * Checks if adding a redirect from `fromPath` to `toPath` would create a loop+ * given the existing redirects.+ *+ * A loop occurs when following the redirect chain eventually leads back to fromPath.+ */+export const wouldCreateLoop = (+ fromPath: string,+ toPath: string,+ existingRedirects: PageRedirect[]+): boolean => {+ // Self-redirect is always a loop+ if (fromPath === toPath) {+ return true;+ }++ // External URLs can't create loops (they leave the site)+ if (+ toPath.startsWith("http://") ||+ toPath.startsWith("https://") ||+ toPath.startsWith("//")+ ) {+ return false;+ }++ // Build a map for O(1) lookup+ const redirectMap = new Map<string, string>();+ for (const redirect of existingRedirects) {+ redirectMap.set(redirect.old, redirect.new);+ }++ // Follow the chain from toPath and check if we reach fromPath+ const visited = new Set<string>([fromPath]);+ let current = toPath;++ while (current) {+ // Found a loop back to the source+ if (current === fromPath) {+ return true;+ }++ // Cycle detected in existing redirects (defensive)+ if (visited.has(current)) {+ return true;+ }++ visited.add(current);++ // Get next hop+ const next = redirectMap.get(current);+ if (!next) {+ // Chain ends without looping back+ return false;+ }++ // External URL ends the chain+ if (+ next.startsWith("http://") ||+ next.startsWith("https://") ||+ next.startsWith("//")+ ) {+ return false;+ }++ current = next;+ }++ return false;+};++export type LoopedRedirect = {+ redirect: PageRedirect;+ reason: string;+};++export type BatchLoopResult = {+ valid: PageRedirect[];+ looped: LoopedRedirect[];+};++/**+ * Detects loops in a batch of new redirects, checking both:+ * 1. Loops within the new set itself+ * 2. Loops that would form with existing redirects+ *+ * Processes redirects in order, adding valid ones to the check map+ * so subsequent redirects are checked against the growing set.+ */+export const detectLoopsInBatch = (+ newRedirects: PageRedirect[],+ existingRedirects: PageRedirect[]+): BatchLoopResult => {+ const valid: PageRedirect[] = [];+ const looped: LoopedRedirect[] = [];++ // Start with existing redirects+ const currentRedirects = [...existingRedirects];++ for (const redirect of newRedirects) {+ if (wouldCreateLoop(redirect.old, redirect.new, currentRedirects)) {+ looped.push({+ redirect,+ reason: "Creates redirect loop",+ });+ } else {+ valid.push(redirect);+ // Add to current set so subsequent redirects check against it+ currentRedirects.push(redirect);+ }+ }++ return { valid, looped };+};diff --git a/apps/builder/app/shared/redirects/redirect-parsers.test.ts b/apps/builder/app/shared/redirects/redirect-parsers.test.tsnew file mode 100644index 0000000000..54deea31ea--- /dev/null+++ b/apps/builder/app/shared/redirects/redirect-parsers.test.ts@@ -0,0 +1,1251 @@+import { describe, test, expect } from "vitest";+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { parseRedirects } from "./redirect-parsers";++describe("parseRedirects", () => {+ describe("CSV format", () => {+ test("parses basic CSV with header", () => {+ const input = `source,target,status+/old,/new,301+/about,/about-us,302`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ expect(result.skipped).toEqual([]);+ });++ test("parses CSV without header (detects by first row being a redirect)", () => {+ const input = `/old,/new,301+/about,/about-us,302`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("parses CSV with different column names", () => {+ const input = `from,to,code+/old,/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("parses CSV with alternative column names", () => {+ const input = `old,new,status+/old,/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("parses semicolon-delimited CSV", () => {+ const input = `source;target;status+/old;/new;301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("parses tab-delimited CSV", () => {+ const input = `source\ttarget\tstatus+/old\t/new\t301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("handles CSV with only source and target (defaults status to 301)", () => {+ const input = `source,target+/old,/new`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("parses Shopify redirect export format", () => {+ const input = `Redirect from,Redirect to+/old-page,/new-page+/about,/about-us`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old-page", new: "/new-page", status: 301 },+ { old: "/about", new: "/about-us", status: 301 },+ ]);+ });++ test("parses HubSpot redirect export format", () => {+ const input = `Original URL,Target URL+/old-page,/new-page+/blog/old-post,/blog/new-post`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old-page", new: "/new-page", status: 301 },+ { old: "/blog/old-post", new: "/blog/new-post", status: 301 },+ ]);+ });++ test("handles CSV with quoted values containing commas", () => {+ const input = `source,target,status+"/old,path",/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old,path", new: "/new", status: 301 },+ ]);+ });++ test("handles CSV with external URL as target", () => {+ const input = `source,target,status+/old,https://example.com/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "https://example.com/new", status: 301 },+ ]);+ });++ test("skips empty lines", () => {+ const input = `source,target,status+/old,/new,301++/about,/about-us,302`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toEqual([]);+ });++ test("skips invalid rows and reports them", () => {+ const input = `source,target,status+/old,/new,301+invalid-no-slash,/new,301+/about,/about-us,302`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0]).toMatchObject({+ line: 3,+ reason: expect.stringContaining("source"),+ });+ });++ test("handles columns in different order", () => {+ const input = `target,status,source+/new,301,/old+/about-us,302,/about`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("ignores extra columns", () => {+ const input = `source,target,status,notes,author+/old,/new,301,legacy redirect,john+/about,/about-us,302,rebranding,jane`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("handles BOM at start of file", () => {+ const input = `\uFEFFsource,target,status+/old,/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });+ });++ describe("JSON format", () => {+ test("parses JSON array of redirects", () => {+ const input = `[+ { "source": "/old", "target": "/new", "status": 301 },+ { "source": "/about", "target": "/about-us", "status": 302 }+ ]`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("parses JSON with nested redirects array", () => {+ const input = `{+ "redirects": [+ { "source": "/old", "target": "/new", "status": 301 }+ ]+ }`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("parses JSON with alternative key names", () => {+ const input = `[+ { "from": "/old", "to": "/new", "code": 301 }+ ]`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("parses Vercel-style JSON with permanent flag", () => {+ const input = `{+ "redirects": [+ { "source": "/old", "destination": "/new", "permanent": true },+ { "source": "/temp", "destination": "/new", "permanent": false }+ ]+ }`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/temp", new: "/new", status: 302 },+ ]);+ });++ test("defaults status to 301 when not provided", () => {+ const input = `[+ { "source": "/old", "target": "/new" }+ ]`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("skips invalid entries in JSON array", () => {+ const input = `[+ { "source": "/old", "target": "/new", "status": 301 },+ { "source": "no-slash", "target": "/new", "status": 301 },+ { "target": "/new", "status": 301 }+ ]`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(2);+ });++ test("reports error for invalid JSON", () => {+ const input = `{ invalid json }`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([]);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("Invalid JSON");+ });++ test("handles empty JSON array", () => {+ const input = `[]`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([]);+ expect(result.skipped).toEqual([]);+ });++ test("ignores extra properties in JSON objects", () => {+ const input = `[+ { "source": "/old", "target": "/new", "status": 301, "comment": "legacy", "author": "john" }+ ]`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("skips JSON redirects with has/missing conditions (unsupported)", () => {+ const input = `{+ "redirects": [+ { "source": "/simple", "destination": "/target", "permanent": true },+ { "source": "/conditional", "destination": "/special", "permanent": false, "has": [{"type": "header", "key": "x-custom"}] },+ { "source": "/another", "destination": "/dest", "permanent": true }+ ]+ }`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("condition");+ });++ test("skips JSON redirects with placeholders in source (unsupported)", () => {+ const input = `[+ { "source": "/simple", "target": "/target", "status": 301 },+ { "source": "/blog/:slug", "target": "/posts/:slug", "status": 301 },+ { "source": "/docs/:path*", "target": "/documentation/:path*", "status": 301 }+ ]`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(2);+ expect(result.skipped[0].reason).toContain("placeholder");+ });+ });++ describe("Netlify _redirects format", () => {+ test("parses basic Netlify redirects", () => {+ const input = `/old /new 301+/about /about-us 302`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("defaults to 301 when status not provided", () => {+ const input = `/old /new`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("skips splat redirects (unsupported)", () => {+ const input = `/simple /target 301+/blog/* /articles/:splat 301+/other /other-target`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("wildcard");+ });++ test("ignores comment lines", () => {+ const input = `# This is a comment+/old /new 301+# Another comment+/about /about-us`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toEqual([]);+ });++ test("skips lines with conditions (unsupported)", () => {+ const input = `/old /new 301+/admin /login 302 Role=admin+/about /about-us`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0]).toMatchObject({+ line: 2,+ reason: expect.stringContaining("condition"),+ });+ });++ test("handles external URLs as target", () => {+ const input = `/old https://example.com/new 301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "https://example.com/new", status: 301 },+ ]);+ });++ test("skips force redirects (200 status rewrites)", () => {+ const input = `/old /new 200+/about /about-us 301`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("rewrite");+ });++ test("handles force flag with !", () => {+ const input = `/old /new 301!+/about /about-us 302!`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("handles multiple spaces between parts", () => {+ const input = `/old /new 301+/about /about-us`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 301 },+ ]);+ });++ test("handles tabs as separators", () => {+ const input = "/old\t/new\t301";++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("skips redirects with placeholders (unsupported)", () => {+ const input = `/simple /target 301+/blog/:year/:slug /posts/:year-:slug 301+/other /other-target`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("placeholder");+ });++ test("skips redirects with query parameter matching (unsupported)", () => {+ const input = `/simple /target 301+/store id=:id /products/:id 301+/other /other-target`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("query");+ });++ test("skips 303 status code", () => {+ const input = `/old /new 301+/see-other /other 303+/about /about-us 302`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(1);+ });+ });++ describe("htaccess format", () => {+ test("parses basic Redirect directive", () => {+ const input = `Redirect 301 /old /new+Redirect 302 /about /about-us`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("parses Redirect without status code (defaults to 302)", () => {+ const input = `Redirect /old /new`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 302 },+ ]);+ });++ test("parses Redirect with permanent/temp keywords", () => {+ const input = `Redirect permanent /old /new+Redirect temp /about /about-us`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("handles external URLs as target", () => {+ const input = `Redirect 301 /old https://example.com/new`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "https://example.com/new", status: 301 },+ ]);+ });++ test("ignores comment lines", () => {+ const input = `# Redirect old pages+Redirect 301 /old /new+# End of redirects`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toEqual([]);+ });++ test("ignores non-redirect directives", () => {+ const input = `RewriteEngine On+Redirect 301 /old /new+RewriteBase /`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toEqual([]);+ });++ test("skips RewriteRule and reports as unsupported", () => {+ const input = `Redirect 301 /old /new+RewriteRule ^/blog/(.*)$ /posts/$1 [R=301,L]`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0]).toMatchObject({+ line: 2,+ reason: expect.stringContaining("RewriteRule"),+ });+ });++ test("skips RedirectMatch and reports as unsupported", () => {+ const input = `Redirect 301 /old /new+RedirectMatch 301 ^/category/(.*)$ /new-category/$1`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0]).toMatchObject({+ line: 2,+ reason: expect.stringContaining("RedirectMatch"),+ });+ });++ test("handles case-insensitive Redirect directive", () => {+ const input = `redirect 301 /old /new+REDIRECT 301 /about /about-us`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ });++ test("handles multiple spaces between parts", () => {+ const input = `Redirect 301 /old /new`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("handles tabs in Redirect directive", () => {+ const input = "Redirect\t301\t/old\t/new";++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });+ });++ describe("auto-detection", () => {+ test("detects JSON format", () => {+ const input = `[{"source": "/old", "target": "/new"}]`;+ const result = parseRedirects(input);+ expect(result.redirects).toHaveLength(1);+ });++ test("detects CSV format by header", () => {+ const input = `source,target,status+/old,/new,301`;+ const result = parseRedirects(input);+ expect(result.redirects).toHaveLength(1);+ });++ test("detects htaccess format by Redirect keyword", () => {+ const input = `Redirect 301 /old /new`;+ const result = parseRedirects(input);+ expect(result.redirects).toHaveLength(1);+ });++ test("detects Netlify format by line structure", () => {+ const input = `/old /new 301`;+ const result = parseRedirects(input);+ expect(result.redirects).toHaveLength(1);+ });++ test("returns empty result for empty input", () => {+ const result = parseRedirects("");+ expect(result.redirects).toEqual([]);+ expect(result.skipped).toEqual([]);+ });++ test("returns empty result for whitespace-only input", () => {+ const result = parseRedirects(" \n\n ");+ expect(result.redirects).toEqual([]);+ expect(result.skipped).toEqual([]);+ });+ });++ describe("edge cases", () => {+ test("handles mixed valid and invalid entries", () => {+ const input = `source,target,status+/old,/new,301+,/missing-source,301+/about,/about-us,invalid-status+/valid,/valid-target,302`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.skipped).toHaveLength(2);+ });++ test("trims whitespace from paths", () => {+ const input = `source,target,status+ /old , /new ,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("handles Windows-style line endings", () => {+ const input =+ "source,target,status\r\n/old,/new,301\r\n/about,/about-us,302";++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ });++ test("handles duplicate redirects (keeps all, validation happens later)", () => {+ const input = `source,target,status+/old,/new,301+/old,/different,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ });++ test("handles status codes as text", () => {+ const input = `source,target,status+/old,/new,permanent+/about,/about-us,temporary`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ ]);+ });++ test("converts 307 to 302 and 308 to 301", () => {+ const input = `source,target,status+/old,/new,301+/about,/about-us,307+/contact,/contact-us,308`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ { old: "/about", new: "/about-us", status: 302 },+ { old: "/contact", new: "/contact-us", status: 301 },+ ]);+ expect(result.skipped).toHaveLength(0);+ });++ test("skips unsupported status codes (200, 404, etc.)", () => {+ const input = `source,target,status+/old,/new,301+/rewrite,/target,200+/error,/not-found,404`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(2);+ });++ test("handles Mac-style line endings (CR only)", () => {+ const input = "source,target,status\r/old,/new,301\r/about,/about-us,302";++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ });++ test("handles paths with query strings", () => {+ const input = `source,target,status+/old?ref=123,/new?ref=456,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old?ref=123", new: "/new?ref=456", status: 301 },+ ]);+ });++ test("handles URL-encoded characters in paths", () => {+ const input = `source,target,status+/hello%20world,/hello-world,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/hello%20world", new: "/hello-world", status: 301 },+ ]);+ });++ test("handles paths with hash fragments", () => {+ const input = `source,target,status+/old#section,/new#section,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old#section", new: "/new#section", status: 301 },+ ]);+ });++ test("handles root path redirect", () => {+ const input = `source,target,status+/,/home,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/", new: "/home", status: 301 },+ ]);+ });++ test("strips trailing slashes from source paths", () => {+ // Webstudio requires: paths cannot end with /+ const input = `source,target,status+/old/,/new/,301+/about,/about-us/,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new/", status: 301 },+ { old: "/about", new: "/about-us/", status: 301 },+ ]);+ });+ });++ describe("fixture files", () => {+ test("parses Shopify CSV fixture", () => {+ const content = readFileSync(+ join(__dirname, "fixtures/shopify.csv"),+ "utf-8"+ );++ const result = parseRedirects(content);++ expect(result.redirects.length).toBeGreaterThan(0);+ expect(result.redirects[0]).toMatchObject({+ old: expect.stringMatching(/^\//),+ new: expect.stringMatching(/^\//),+ status: 301,+ });+ expect(result.skipped).toHaveLength(0);+ });++ test("parses HubSpot CSV fixture", () => {+ const content = readFileSync(+ join(__dirname, "fixtures/hubspot.csv"),+ "utf-8"+ );++ const result = parseRedirects(content);++ expect(result.redirects.length).toBeGreaterThan(0);+ expect(result.skipped).toHaveLength(0);+ });++ test("parses Vercel/Next.js JSON fixture", () => {+ const content = readFileSync(+ join(__dirname, "fixtures/vercel-nextjs.json"),+ "utf-8"+ );++ const result = parseRedirects(content);++ // Should parse simple redirects and skip ones with placeholders/conditions+ expect(result.redirects.length).toBeGreaterThan(0);+ // Some should be skipped due to placeholders and conditions+ expect(result.skipped.length).toBeGreaterThan(0);+ });++ test("parses Netlify _redirects fixture", () => {+ const content = readFileSync(+ join(__dirname, "fixtures/netlify._redirects"),+ "utf-8"+ );++ const result = parseRedirects(content);++ // Should parse simple redirects+ expect(result.redirects.length).toBeGreaterThan(0);+ // Many should be skipped: conditions, placeholders, rewrites+ expect(result.skipped.length).toBeGreaterThan(0);+ });++ test("parses Apache htaccess fixture", () => {+ const content = readFileSync(+ join(__dirname, "fixtures/apache.htaccess"),+ "utf-8"+ );++ const result = parseRedirects(content);++ // Should parse Redirect directives+ expect(result.redirects.length).toBeGreaterThan(0);+ // RewriteRule and RedirectMatch should be skipped+ expect(result.skipped.length).toBeGreaterThan(0);+ });++ test("parses generic CSV fixture", () => {+ const content = readFileSync(+ join(__dirname, "fixtures/generic.csv"),+ "utf-8"+ );++ const result = parseRedirects(content);++ // Should parse all valid redirects, converting 307/308+ expect(result.redirects.length).toBeGreaterThanOrEqual(10);+ });++ test("parses generic JSON fixture", () => {+ const content = readFileSync(+ join(__dirname, "fixtures/generic.json"),+ "utf-8"+ );++ const result = parseRedirects(content);++ // Should parse valid redirects, skip invalid ones+ expect(result.redirects.length).toBeGreaterThan(0);+ expect(result.skipped.length).toBeGreaterThan(0);+ });+ });++ describe("additional edge cases", () => {+ // JSON edge cases+ test("handles JSON with null values", () => {+ const input = `[+ { "source": null, "target": "/new", "status": 301 },+ { "source": "/valid", "target": "/new", "status": 301 }+ ]`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("missing source");+ });++ test("handles JSON with mixed $comment and real data", () => {+ const input = `[+ { "$comment": "This is a comment", "source": "/old", "target": "/new", "status": 301 }+ ]`;++ const result = parseRedirects(input);++ // Should parse the redirect, ignoring the $comment field+ expect(result.redirects).toHaveLength(1);+ expect(result.redirects[0]).toEqual({+ old: "/old",+ new: "/new",+ status: 301,+ });+ });++ test("handles JSON with statusCode (Next.js camelCase)", () => {+ const input = `{+ "redirects": [+ { "source": "/old", "destination": "/new", "statusCode": 301 }+ ]+ }`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("handles JSON with both permanent and statusCode (permanent takes precedence)", () => {+ const input = `[+ { "source": "/old", "destination": "/new", "permanent": true, "statusCode": 302 }+ ]`;++ const result = parseRedirects(input);++ // statusCode should be found first since we check STATUS_KEYS before permanent+ expect(result.redirects).toHaveLength(1);+ });++ test("handles empty JSON object", () => {+ const input = `{}`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([]);+ expect(result.skipped).toEqual([]);+ });++ test("handles JSON with non-array redirects property", () => {+ const input = `{ "redirects": "not an array" }`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([]);+ expect(result.skipped).toEqual([]);+ });++ // CSV edge cases+ test("handles CSV with mixed case column headers", () => {+ const input = `SOURCE,Target,STATUS+/old,/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("handles CSV row with fewer columns than header", () => {+ const input = `source,target,status+/old,/new+/about,/about-us,302`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ // First row should default to 301+ expect(result.redirects[0].status).toBe(301);+ });++ test("handles CSV with quoted values containing quotes", () => {+ const input = `source,target,status+"/old""path",/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: '/old"path', new: "/new", status: 301 },+ ]);+ });++ test("handles CSV with empty target", () => {+ const input = `source,target,status+/old,,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(0);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("missing target");+ });++ // Netlify edge cases+ test("handles Netlify with only two parts (no status)", () => {+ const input = `/old /new`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/new", status: 301 },+ ]);+ });++ test("handles Netlify condition without status code", () => {+ const input = `/old /new Country=us`;++ const result = parseRedirects(input);++ // Should be skipped because Country= looks like a condition+ expect(result.redirects).toHaveLength(0);+ expect(result.skipped).toHaveLength(1);+ });++ test("handles Netlify with indented lines", () => {+ const input = ` /old /new 301+ /about /about-us 302`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ });++ test("handles Netlify single line only", () => {+ const input = `/old /new`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ });++ // htaccess edge cases+ test("handles htaccess with seeother keyword (303)", () => {+ const input = `Redirect seeother /old /new`;++ const result = parseRedirects(input);++ // seeother is not a recognized keyword, so it's treated as the path+ // This results in: from="/old", to="/new", status defaulting+ // Actually, "seeother" would be parsed as status, which is invalid+ expect(result.skipped).toHaveLength(1);+ });++ test("handles htaccess with gone keyword", () => {+ const input = `Redirect gone /old`;++ const result = parseRedirects(input);++ // "gone" is a status keyword in Apache (410), but we only have from+ // The implementation treats "gone" as path if no target follows+ expect(result.redirects).toHaveLength(0);+ });++ test("handles htaccess RewriteCond (ignored silently)", () => {+ const input = `RewriteCond %{HTTP_HOST} ^www\\.example\\.com$+Redirect 301 /old /new`;++ const result = parseRedirects(input);++ // RewriteCond should be ignored (not reported as skipped)+ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(0);+ });++ test("handles htaccess Options directive (ignored silently)", () => {+ const input = `Options +FollowSymLinks+Redirect 301 /old /new`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.skipped).toHaveLength(0);+ });++ test("handles htaccess with target containing spaces", () => {+ const input = `Redirect 301 /old /path/with spaces/target`;++ const result = parseRedirects(input);++ expect(result.redirects).toEqual([+ { old: "/old", new: "/path/with spaces/target", status: 301 },+ ]);+ });++ // Path validation edge cases+ test("skips paths with double slashes", () => {+ const input = `source,target,status+//double-slash,/new,301`;++ const result = parseRedirects(input);++ // Double slash still starts with /, so it passes basic validation+ // Webstudio's OldPagePath schema will reject it later+ expect(result.redirects).toHaveLength(1);+ });++ test("handles http URLs as source (invalid)", () => {+ const input = `source,target,status+https://example.com/old,/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(0);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain(+ "source path must start with /"+ );+ });++ test("handles protocol-relative URLs as target", () => {+ const input = `source,target,status+/old,//cdn.example.com/asset,301`;++ const result = parseRedirects(input);++ // Protocol-relative URLs start with // and are valid redirect targets+ expect(result.redirects).toHaveLength(1);+ expect(result.redirects[0].new).toBe("//cdn.example.com/asset");+ });++ test("handles unicode paths", () => {+ const input = `source,target,status+/über,/ueber,301+/日本語,/japanese,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ expect(result.redirects[0].old).toBe("/über");+ expect(result.redirects[1].old).toBe("/日本語");+ });++ test("handles very long paths", () => {+ const longPath = "/" + "a".repeat(1000);+ const input = `source,target,status+${longPath},/new,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(1);+ expect(result.redirects[0].old).toBe(longPath);+ });++ test("handles empty lines interspersed in Netlify format", () => {+ const input = `/old1 /new1 301++/old2 /new2 301++`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(2);+ });++ // Status code edge cases+ test("handles numeric string status with leading zeros", () => {+ const input = `source,target,status+/old,/new,0301`;++ const result = parseRedirects(input);++ // 0301 octal would be 193, but parseInt treats it as 301+ expect(result.redirects).toHaveLength(1);+ expect(result.redirects[0].status).toBe(301);+ });++ test("handles status code 303 (See Other)", () => {+ const input = `source,target,status+/old,/new,303`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(0);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("unsupported status code 303");+ });++ test("handles status code 410 (Gone)", () => {+ const input = `source,target,status+/old,/new,410`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(0);+ expect(result.skipped).toHaveLength(1);+ });++ // Wildcard detection edge cases+ test("allows asterisk in query string (not a wildcard)", () => {+ const input = `source,target,status+/search?q=*,/search-all,301`;++ const result = parseRedirects(input);++ // * in query string should NOT be treated as wildcard+ expect(result.redirects).toHaveLength(1);+ });++ test("skips asterisk in path segment", () => {+ const input = `source,target,status+/files/*.txt,/all-files,301`;++ const result = parseRedirects(input);++ expect(result.redirects).toHaveLength(0);+ expect(result.skipped).toHaveLength(1);+ expect(result.skipped[0].reason).toContain("wildcard");+ });+ });+});diff --git a/apps/builder/app/shared/redirects/redirect-parsers.ts b/apps/builder/app/shared/redirects/redirect-parsers.tsnew file mode 100644index 0000000000..339fa2f1da--- /dev/null+++ b/apps/builder/app/shared/redirects/redirect-parsers.ts@@ -0,0 +1,732 @@+import Papa from "papaparse";++export type ParsedRedirect = {+ old: string;+ new: string;+ status: number;+};++export type SkippedLine = {+ line: number;+ content: string;+ reason: string;+};++export type ParseResult = {+ redirects: ParsedRedirect[];+ skipped: SkippedLine[];+};++// Key mappings for normalizing different column/property names+const FROM_KEYS = [+ "from",+ "source",+ "old",+ "redirect from",+ "original url",+] as const;+const TO_KEYS = [+ "to",+ "target",+ "destination",+ "new",+ "redirect to",+ "target url",+] as const;+const STATUS_KEYS = ["status", "code", "statuscode"] as const;++type RawRecord = Record<string, unknown>;++/**+ * Detect format and parse accordingly+ */+const detectFormat = (+ content: string+): "json" | "csv" | "htaccess" | "netlify" | "empty" => {+ const trimmed = content.trim();+ if (trimmed === "") {+ return "empty";+ }++ // JSON: starts with [ or {+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {+ return "json";+ }++ // Split into lines for further detection+ const lines = trimmed.split(/\r\n|\r|\n/);+ const nonEmptyLines = lines.filter(+ (l) => l.trim() !== "" && !l.trim().startsWith("#")+ );++ if (nonEmptyLines.length === 0) {+ return "empty";+ }++ // CSV: Check first line for known column headers (must check BEFORE htaccess)+ // This is important because Shopify uses "Redirect from,Redirect to" headers+ const firstLine = nonEmptyLines[0].toLowerCase();+ const csvHeaders = [+ ...FROM_KEYS,+ ...TO_KEYS,+ ...STATUS_KEYS,+ "permanent",+ ].map((h) => h.toLowerCase());++ // Check if first line looks like CSV headers+ const possibleHeaders = firstLine.split(/[,;\t]/);+ const matchedHeaders = possibleHeaders.filter((h) =>+ csvHeaders.includes(h.trim().toLowerCase())+ );+ if (matchedHeaders.length >= 2) {+ return "csv";+ }++ // htaccess: any line starts with "Redirect" followed by space/tab (but not comma)+ // Also check for RewriteRule or RedirectMatch which are htaccess-specific+ for (const line of nonEmptyLines) {+ const lower = line.trim().toLowerCase();+ // Must be "Redirect " followed by status or path, not "Redirect from," (CSV header)+ if (+ (lower.startsWith("redirect ") || lower.startsWith("redirect\t")) &&+ !lower.includes(",") // Avoid matching CSV headers+ ) {+ return "htaccess";+ }+ if (+ lower.startsWith("rewriterule ") ||+ lower.startsWith("redirectmatch ")+ ) {+ return "htaccess";+ }+ }++ // Check if lines have CSV-like structure (comma/semicolon/tab separated, multiple columns)+ if (+ nonEmptyLines.every((line) => {+ const parts = line.split(/[,;\t]/);+ return parts.length >= 2;+ })+ ) {+ // If first column looks like a path and has delimiters, it's CSV+ const firstPart = nonEmptyLines[0].split(/[,;\t]/)[0].trim();+ if (firstPart.startsWith("/") || firstPart.startsWith("http")) {+ return "csv";+ }+ }++ // Netlify: lines match pattern "/path /path [status]"+ // Check if most non-empty/non-comment lines match this pattern+ const netlifyPattern = /^\/\S+\s+\S+/;+ const matchingLines = nonEmptyLines.filter((line) =>+ netlifyPattern.test(line.trim())+ );+ if (+ matchingLines.length > 0 &&+ matchingLines.length >= nonEmptyLines.length * 0.5+ ) {+ return "netlify";+ }++ // Default to netlify if lines start with /+ if (nonEmptyLines[0].trim().startsWith("/")) {+ return "netlify";+ }++ return "csv"; // fallback+};++/**+ * Check if a path contains unsupported patterns+ */+const hasPlaceholder = (path: string): boolean => {+ // :param placeholders like /blog/:slug+ return /:[a-zA-Z_][a-zA-Z0-9_]*\*?/.test(path);+};++const hasWildcard = (path: string): boolean => {+ // * wildcards but not in query string+ const pathPart = path.split("?")[0];+ return pathPart.includes("*");+};++const hasConditions = (record: RawRecord): boolean => {+ return "has" in record || "missing" in record;+};++/**+ * Normalize status code+ * Returns: 301, 302, or null (for invalid/unsupported codes)+ */+const normalizeStatus = (+ value: unknown+): { status: 301 | 302 } | { skip: string } => {+ if (value === undefined || value === null || value === "") {+ return { status: 301 }; // default+ }++ // Boolean (Vercel permanent flag)+ if (typeof value === "boolean") {+ return { status: value ? 301 : 302 };+ }++ // String+ if (typeof value === "string") {+ const lower = value.toLowerCase().trim();++ if (lower === "permanent" || lower === "true") {+ return { status: 301 };+ }+ if (lower === "temporary" || lower === "temp" || lower === "false") {+ return { status: 302 };+ }++ // Numeric string (possibly with ! suffix for force)+ const numMatch = lower.match(/^(\d+)!?$/);+ if (numMatch) {+ const code = parseInt(numMatch[1], 10);+ if (code === 301 || code === 308) {+ return { status: 301 };+ }+ if (code === 302 || code === 307) {+ return { status: 302 };+ }+ if (code === 200) {+ return { skip: "rewrite (status 200)" };+ }+ return { skip: `unsupported status code ${code}` };+ }+ }++ // Number+ if (typeof value === "number") {+ if (value === 301 || value === 308) {+ return { status: 301 };+ }+ if (value === 302 || value === 307) {+ return { status: 302 };+ }+ if (value === 200) {+ return { skip: "rewrite (status 200)" };+ }+ return { skip: `unsupported status code ${value}` };+ }++ return { skip: `invalid status value` };+};++/**+ * Find a value in a record using multiple possible keys+ */+const findValue = (record: RawRecord, keys: readonly string[]): unknown => {+ for (const key of keys) {+ const lowerKey = key.toLowerCase();+ for (const [k, v] of Object.entries(record)) {+ if (k.toLowerCase() === lowerKey) {+ return v;+ }+ }+ }+ return undefined;+};++/**+ * Normalize a path - strip trailing slashes from source paths+ */+const normalizePath = (path: string, isSource: boolean): string => {+ let normalized = path.trim();+ if (isSource && normalized.length > 1 && normalized.endsWith("/")) {+ normalized = normalized.slice(0, -1);+ }+ return normalized;+};++/**+ * Validate and normalize a single record into a redirect+ */+const normalizeRecord = (+ record: RawRecord,+ lineNumber: number,+ originalContent: string+): { redirect: ParsedRedirect } | { skipped: SkippedLine } => {+ // Check for conditions first (Vercel/Next.js has/missing)+ if (hasConditions(record)) {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: "contains condition (has/missing) - not supported",+ },+ };+ }++ // Find source/from+ const fromValue = findValue(record, FROM_KEYS);+ if (fromValue === undefined || fromValue === null || fromValue === "") {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: "missing source path",+ },+ };+ }+ const from = String(fromValue);++ // Find target/to+ const toValue = findValue(record, TO_KEYS);+ if (toValue === undefined || toValue === null || toValue === "") {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: "missing target path",+ },+ };+ }+ const to = String(toValue);++ // Check for wildcards in source+ if (hasWildcard(from)) {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: "contains wildcard (*) - not supported",+ },+ };+ }++ // Check for placeholders in source or target+ if (hasPlaceholder(from) || hasPlaceholder(to)) {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: "contains placeholder (:param) - not supported",+ },+ };+ }++ // Validate source path+ const normalizedFrom = normalizePath(from, true);+ if (!normalizedFrom.startsWith("/")) {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: "source path must start with /",+ },+ };+ }++ // Validate target path+ const normalizedTo = normalizePath(to, false);+ if (!normalizedTo.startsWith("/") && !normalizedTo.startsWith("http")) {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: "target path must start with / or http",+ },+ };+ }++ // Find and normalize status+ let statusValue = findValue(record, STATUS_KEYS);+ // Check for Vercel-style permanent flag+ if (statusValue === undefined && "permanent" in record) {+ statusValue = record.permanent;+ // Handle the boolean case+ if (typeof statusValue === "boolean") {+ // normalizeStatus will handle this+ }+ }++ const statusResult = normalizeStatus(statusValue);+ if ("skip" in statusResult) {+ return {+ skipped: {+ line: lineNumber,+ content: originalContent,+ reason: statusResult.skip,+ },+ };+ }++ return {+ redirect: {+ old: normalizedFrom,+ new: normalizedTo,+ status: statusResult.status,+ },+ };+};++/**+ * Parse CSV content using papaparse+ */+const parseCSV = (content: string): ParseResult => {+ const redirects: ParsedRedirect[] = [];+ const skipped: SkippedLine[] = [];++ // Remove BOM if present+ const cleanContent = content.replace(/^\uFEFF/, "");++ // Use papaparse for robust CSV parsing+ const parseResult = Papa.parse<Record<string, string>>(cleanContent, {+ header: false, // We'll handle headers ourselves for flexibility+ skipEmptyLines: true,+ comments: "#", // Skip comment lines+ delimiter: "", // Auto-detect delimiter+ transformHeader: (header) => header.trim().toLowerCase(),+ });++ if (parseResult.errors.length > 0 && parseResult.data.length === 0) {+ return {+ redirects: [],+ skipped: [+ {+ line: 1,+ content: cleanContent.slice(0, 100),+ reason: `CSV parse error: ${parseResult.errors[0].message}`,+ },+ ],+ };+ }++ const rows = parseResult.data as unknown as string[][];+ if (rows.length === 0) {+ return { redirects, skipped };+ }++ // Parse header row - check if first row contains known column names+ const firstRow = rows[0].map((cell) =>+ typeof cell === "string" ? cell.trim().toLowerCase() : ""+ );+ const hasHeader = firstRow.some(+ (h) =>+ FROM_KEYS.map((k) => k.toLowerCase()).includes(h) ||+ TO_KEYS.map((k) => k.toLowerCase()).includes(h)+ );++ const headers = hasHeader+ ? firstRow+ : ["source", "target", "status"].slice(0, firstRow.length);++ const startIndex = hasHeader ? 1 : 0;++ for (let i = startIndex; i < rows.length; i++) {+ const row = rows[i];+ const record: RawRecord = {};++ for (let j = 0; j < headers.length && j < row.length; j++) {+ const value = typeof row[j] === "string" ? row[j].trim() : "";+ record[headers[j]] = value;+ }++ // Skip rows that are empty after trimming+ const hasContent = Object.values(record).some((v) => v !== "");+ if (!hasContent) {+ continue;+ }++ // Calculate actual line number (accounting for header and empty lines)+ // This is approximate since papaparse may skip lines+ const lineNumber = i + 1;+ const originalContent = row.join(",");+ const result = normalizeRecord(record, lineNumber, originalContent);++ if ("redirect" in result) {+ redirects.push(result.redirect);+ } else {+ skipped.push(result.skipped);+ }+ }++ return { redirects, skipped };+};++/**+ * Parse JSON content+ */+const parseJSON = (content: string): ParseResult => {+ const redirects: ParsedRedirect[] = [];+ const skipped: SkippedLine[] = [];++ let parsed: unknown;+ try {+ parsed = JSON.parse(content);+ } catch {+ return {+ redirects: [],+ skipped: [+ {+ line: 1,+ content: content.slice(0, 100) + (content.length > 100 ? "..." : ""),+ reason: "Invalid JSON",+ },+ ],+ };+ }++ // Extract redirects array+ let records: unknown[];+ if (Array.isArray(parsed)) {+ records = parsed;+ } else if (+ typeof parsed === "object" &&+ parsed !== null &&+ "redirects" in parsed+ ) {+ const redirectsField = (parsed as { redirects: unknown }).redirects;+ if (Array.isArray(redirectsField)) {+ records = redirectsField;+ } else {+ return { redirects: [], skipped: [] };+ }+ } else {+ return { redirects: [], skipped: [] };+ }++ for (let i = 0; i < records.length; i++) {+ const record = records[i];++ // Skip non-objects and comment objects+ if (typeof record !== "object" || record === null) {+ continue;+ }++ // Skip objects that are just comments+ const keys = Object.keys(record);+ if (keys.length === 1 && keys[0].startsWith("$")) {+ continue;+ }++ const lineNumber = i + 1;+ const originalContent = JSON.stringify(record);+ const result = normalizeRecord(+ record as RawRecord,+ lineNumber,+ originalContent+ );++ if ("redirect" in result) {+ redirects.push(result.redirect);+ } else {+ skipped.push(result.skipped);+ }+ }++ return { redirects, skipped };+};++/**+ * Parse Netlify _redirects format+ */+const parseNetlify = (content: string): ParseResult => {+ const redirects: ParsedRedirect[] = [];+ const skipped: SkippedLine[] = [];++ // Normalize line endings+ const normalizedContent = content.replace(/\r\n|\r/g, "\n");+ const lines = normalizedContent.split("\n");++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const trimmedLine = line.trim();+ const lineNumber = i + 1;++ // Skip empty lines and comments+ if (trimmedLine === "" || trimmedLine.startsWith("#")) {+ continue;+ }++ // Split by whitespace+ const parts = trimmedLine.split(/\s+/);++ if (parts.length < 2) {+ continue; // Not a valid redirect line+ }++ const from = parts[0];+ const to = parts[1];+ const statusPart = parts[2];+ const rest = parts.slice(3).join(" ");++ // Check for conditions in remaining parts+ if (rest && /[A-Za-z]+=/.test(rest)) {+ skipped.push({+ line: lineNumber,+ content: trimmedLine,+ reason: "contains condition - not supported",+ });+ continue;+ }++ // Check for query parameter matching (e.g., /store id=:id)+ if (to.includes("=") && !to.startsWith("http")) {+ // This might be query matching like "/store id=:id /products/:id"+ // Re-parse: /source query=value /target+ skipped.push({+ line: lineNumber,+ content: trimmedLine,+ reason: "contains query parameter matching - not supported",+ });+ continue;+ }++ // Create record and normalize+ const record: RawRecord = {+ from,+ to,+ status: statusPart,+ };++ const result = normalizeRecord(record, lineNumber, trimmedLine);++ if ("redirect" in result) {+ redirects.push(result.redirect);+ } else {+ skipped.push(result.skipped);+ }+ }++ return { redirects, skipped };+};++/**+ * Parse Apache htaccess format+ */+const parseHtaccess = (content: string): ParseResult => {+ const redirects: ParsedRedirect[] = [];+ const skipped: SkippedLine[] = [];++ // Normalize line endings+ const normalizedContent = content.replace(/\r\n|\r/g, "\n");+ const lines = normalizedContent.split("\n");++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const trimmedLine = line.trim();+ const lineNumber = i + 1;++ // Skip empty lines and comments+ if (trimmedLine === "" || trimmedLine.startsWith("#")) {+ continue;+ }++ const lowerLine = trimmedLine.toLowerCase();++ // Handle RewriteRule - skip with warning+ if (+ lowerLine.startsWith("rewriterule ") ||+ lowerLine.startsWith("rewriterule\t")+ ) {+ skipped.push({+ line: lineNumber,+ content: trimmedLine,+ reason: "RewriteRule is not supported - use Redirect directive",+ });+ continue;+ }++ // Handle RedirectMatch - skip with warning+ if (+ lowerLine.startsWith("redirectmatch ") ||+ lowerLine.startsWith("redirectmatch\t")+ ) {+ skipped.push({+ line: lineNumber,+ content: trimmedLine,+ reason:+ "RedirectMatch is not supported - use simple Redirect directive",+ });+ continue;+ }++ // Only process Redirect directive+ if (+ !lowerLine.startsWith("redirect ") &&+ !lowerLine.startsWith("redirect\t")+ ) {+ // Ignore other directives (RewriteEngine, RewriteBase, Options, etc.)+ continue;+ }++ // Parse Redirect directive+ // Format: Redirect [status] source target+ // Status can be: 301, 302, 307, 308, permanent, temp, or omitted (defaults to 302)+ const parts = trimmedLine.split(/\s+/);++ if (parts.length < 3) {+ continue; // Invalid Redirect directive+ }++ // parts[0] is "Redirect"+ let statusPart: string | undefined;+ let from: string;+ let to: string;++ // Check if parts[1] is a status code or keyword+ const part1Lower = parts[1].toLowerCase();+ if (+ /^\d+$/.test(parts[1]) ||+ part1Lower === "permanent" ||+ part1Lower === "temp"+ ) {+ // Redirect status source target+ statusPart = parts[1];+ from = parts[2];+ to = parts.slice(3).join(" ").trim();+ } else {+ // Redirect source target (no status, defaults to 302 in Apache)+ from = parts[1];+ to = parts.slice(2).join(" ").trim();+ statusPart = "302";+ }++ if (!from || !to) {+ continue;+ }++ const record: RawRecord = {+ from,+ to,+ status: statusPart,+ };++ const result = normalizeRecord(record, lineNumber, trimmedLine);++ if ("redirect" in result) {+ redirects.push(result.redirect);+ } else {+ skipped.push(result.skipped);+ }+ }++ return { redirects, skipped };+};++/**+ * Parse redirects from various formats (CSV, JSON, Netlify _redirects, htaccess)+ * Auto-detects format and returns parsed redirects with any skipped lines.+ */+export const parseRedirects = (content: string): ParseResult => {+ const format = detectFormat(content);++ switch (format) {+ case "empty":+ return { redirects: [], skipped: [] };+ case "json":+ return parseJSON(content);+ case "csv":+ return parseCSV(content);+ case "htaccess":+ return parseHtaccess(content);+ case "netlify":+ return parseNetlify(content);+ default:+ return { redirects: [], skipped: [] };+ }+};diff --git a/apps/builder/app/shared/style-source-utils.ts b/apps/builder/app/shared/style-source-utils.tsindex 3a5b9c083d..ea86fdcd3d 100644--- a/apps/builder/app/shared/style-source-utils.ts+++ b/apps/builder/app/shared/style-source-utils.ts@@ -597,7 +597,7 @@ export const validateAndRenameStyleSource = ({return { type: "duplicate", id };}}- return undefined;+ return;};/**diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 675247fb83..7e1d6cf1b9 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -103,6 +103,7 @@"nanoevents": "^9.1.0","nanoid": "^5.1.5","nanostores": "^0.11.3",+ "papaparse": "^5.5.3","parse5": "7.3.0","picocolors": "^1.1.1","pretty-bytes": "^6.1.1",@@ -130,6 +131,7 @@"@remix-run/dev": "^2.16.5","@types/debug": "^4.1.12","@types/dom-navigation": "^1.0.5",+ "@types/papaparse": "^5.5.2","@types/react": "^18.2.70","@types/react-dom": "^18.2.25","@vitest/coverage-v8": "3.1.2",diff --git a/codemod/migrate-css-variables.ts b/codemod/migrate-css-variables.tsindex 53f0687977..a0b6814229 100644--- a/codemod/migrate-css-variables.ts+++ b/codemod/migrate-css-variables.ts@@ -71,7 +71,7 @@ const guessGroupName = (variableName: string) => {if (variableName === "sans" || variableName === "mono") {return "fonts";}- return undefined;+ return;};const migrateVariables = (originalCode: string) => {diff --git a/packages/design-system/bin/transform-figma-tokens.ts b/packages/design-system/bin/transform-figma-tokens.tsindex 22449a3add..9cc88648c6 100644--- a/packages/design-system/bin/transform-figma-tokens.ts+++ b/packages/design-system/bin/transform-figma-tokens.ts@@ -139,7 +139,7 @@ const printLineHeight = (path: string[], unparsedValue: unknown) => {// @todo: figure out how to convert AUTO to pixels or something// https://discord.com/channels/955905230107738152/1065939291479478343if (value === "AUTO") {- return undefined;+ return;}if (value.endsWith("%")) {return value;diff --git a/packages/design-system/src/components/panel-banner.stories.tsx b/packages/design-system/src/components/panel-banner.stories.tsxindex 622f7d375f..5a601ac870 100644--- a/packages/design-system/src/components/panel-banner.stories.tsx+++ b/packages/design-system/src/components/panel-banner.stories.tsx@@ -1,8 +1,15 @@-import { PanelBanner } from "./panel-banner";+import { PanelBanner, panelBannerIconColor } from "./panel-banner";import { StoryGrid, StorySection } from "./storybook";import { Text } from "./text";import { Link } from "./link";+import { Flex } from "./flex";import { buttonStyle } from "./button";+import {+ AlertIcon,+ InfoCircleIcon,+ CheckMarkIcon,+ AlertCircleIcon,+} from "@webstudio-is/icons";export default {title: "Panel Banner",@@ -11,7 +18,7 @@ export default {export const Demo = () => {return (<>- <StorySection title="Panel Banner">+ <StorySection title="Panel Banner - Info (default)"><StoryGrid horizontal><PanelBanner css={{ width: 300 }}><Text variant="regularBold">Free domains limit reached</Text>@@ -34,6 +41,46 @@ export const Demo = () => {</PanelBanner></StoryGrid></StorySection>++ <StorySection title="Panel Banner - Variants with Icons">+ <StoryGrid horizontal>+ <PanelBanner variant="info" css={{ width: 280 }}>+ <Flex align="center" gap={1}>+ <InfoCircleIcon color={panelBannerIconColor} />+ <Text variant="regularBold">Info</Text>+ </Flex>+ <Text variant="regular">This is an informational message.</Text>+ </PanelBanner>+ <PanelBanner variant="warning" css={{ width: 280 }}>+ <Flex align="center" gap={1}>+ <AlertIcon color={panelBannerIconColor} />+ <Text variant="regularBold">Warning</Text>+ </Flex>+ <Text variant="regular">This is a warning message.</Text>+ </PanelBanner>+ <PanelBanner variant="error" css={{ width: 280 }}>+ <Flex align="center" gap={1}>+ <AlertCircleIcon color={panelBannerIconColor} />+ <Text variant="regularBold">Error</Text>+ </Flex>+ <Text variant="regular">This is an error message.</Text>+ </PanelBanner>+ <PanelBanner variant="success" css={{ width: 280 }}>+ <Flex align="center" gap={1}>+ <CheckMarkIcon color={panelBannerIconColor} />+ <Text variant="regularBold">Success</Text>+ </Flex>+ <Text variant="regular">This is a success message.</Text>+ </PanelBanner>+ <PanelBanner variant="neutral" css={{ width: 280 }}>+ <Flex align="center" gap={1}>+ <InfoCircleIcon color={panelBannerIconColor} />+ <Text variant="regularBold">Neutral</Text>+ </Flex>+ <Text variant="regular">This is a neutral message.</Text>+ </PanelBanner>+ </StoryGrid>+ </StorySection></>);};diff --git a/packages/design-system/src/components/panel-banner.tsx b/packages/design-system/src/components/panel-banner.tsxindex cc5ffe87cb..8c776ba4b6 100644--- a/packages/design-system/src/components/panel-banner.tsx+++ b/packages/design-system/src/components/panel-banner.tsx@@ -1,10 +1,37 @@import { styled, theme } from "../stitches.config";import { Box } from "./box";+const iconColor = "--ws-panel-banner-icon-color";++export const panelBannerIconColor = `var(${iconColor})`;+export const PanelBanner = styled(Box, {display: "flex",gap: theme.spacing[7],flexDirection: "column",backgroundColor: theme.colors.backgroundInfoNotification,padding: theme.panel.padding,+ [iconColor]: theme.colors.foregroundInfo,++ variants: {+ variant: {+ info: {},+ warning: {+ backgroundColor: theme.colors.backgroundAlertNotification,+ [iconColor]: theme.colors.backgroundAlertMain,+ },+ error: {+ backgroundColor: theme.colors.backgroundDestructiveNotification,+ [iconColor]: theme.colors.foregroundDestructive,+ },+ success: {+ backgroundColor: theme.colors.backgroundSuccessNotification,+ [iconColor]: theme.colors.foregroundSuccess,+ },+ neutral: {+ backgroundColor: theme.colors.backgroundNeutralNotification,+ [iconColor]: theme.colors.foregroundMain,+ },+ },+ },});diff --git a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsxindex 71f1559bb3..f55cc05a96 100644--- a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx+++ b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx@@ -81,7 +81,7 @@ const idToElement = (}}}- return undefined;+ return;};const mapItems = (@@ -111,7 +111,7 @@ const findItem = (data: ItemData[], id: string): ItemData | undefined => {return found;}}- return undefined;+ return;};const findItemPath = (data: ItemData[], id: string): ItemData[] | undefined => {@@ -124,7 +124,7 @@ const findItemPath = (data: ItemData[], id: string): ItemData[] | undefined => {return [...found, item];}}- return undefined;+ return;};export const Canvas = () => {diff --git a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts b/packages/design-system/src/components/primitives/dnd/geometry-utils.tsindex 336d973eae..461f44093e 100644--- a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts+++ b/packages/design-system/src/components/primitives/dnd/geometry-utils.ts@@ -75,7 +75,7 @@ export const getPlacementBetween = (b: Rect | undefined): Placement | undefined => {if (a === undefined || b === undefined) {- return undefined;+ return;}const [firstY, secondY] = a.top < b.top ? [a, b] : [b, a];@@ -85,13 +85,13 @@ export const getPlacementBetween = (// if rects overlap we don't want to put placement between themif (distanceX < 0 && distanceY < 0) {- return undefined;+ return;}// if rects aren't aligned (vertically or horizontally)// we don't want to put placement between themif (distanceX >= 0 && distanceY >= 0) {- return undefined;+ return;}if (distanceX < 0) {@@ -127,7 +127,7 @@ export const getPlacementNextTo = (padding = 5): Placement | undefined => {if (rect === undefined) {- return undefined;+ return;}const isForward = childrenOrientation.reverse@@ -325,7 +325,7 @@ export const getIndexAdjustment = (// diagonal equationconst getDiagonalY = (diagonalX: number) => {if (width === 0) {- return undefined;+ return;}const slope = height / width;const topRightCorner = { x: left + width, y: top };diff --git a/packages/design-system/src/components/primitives/dnd/use-drop.ts b/packages/design-system/src/components/primitives/dnd/use-drop.tsindex c66085fdb4..cf12b9c82b 100644--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts@@ -218,7 +218,7 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {candidate: PartialDropTarget<Data> | null | undefined) => {if (candidate == null || pointerCoordinates === undefined) {- return undefined;+ return;}return {...candidate,@@ -316,7 +316,7 @@ const findClosestDropTarget = <Data>({}): PartialDropTarget<Data> | undefined => {// The element we get from elementFromPoint() might not be inside the rootif (initialElement === undefined || root.contains(initialElement) === false) {- return undefined;+ return;}let currentElement = initialElement;diff --git a/packages/domain/src/rdap.ts b/packages/domain/src/rdap.tsindex 926079dbea..470444f26e 100644--- a/packages/domain/src/rdap.ts+++ b/packages/domain/src/rdap.ts@@ -91,7 +91,7 @@ export const isDomainUsingCloudflareNameservers = async (domain: string) => {console.error("RDAP Server for the given top level domain could not be found.");- return undefined;+ return;}const data = await fetchRdap(rdapServer, domain);diff --git a/packages/image/src/image-optimize.ts b/packages/image/src/image-optimize.tsindex d5db5e213f..37a839dc68 100644--- a/packages/image/src/image-optimize.ts+++ b/packages/image/src/image-optimize.ts@@ -218,7 +218,7 @@ const getInt = (value: unknown): number | undefined => {}}- return undefined;+ return;};/**diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsxindex 268da7004a..15ba4f023f 100644--- a/packages/react-sdk/src/component-generator.test.tsx+++ b/packages/react-sdk/src/component-generator.test.tsx@@ -41,7 +41,7 @@ const isValidJSX = (code: string): boolean => {ts.ScriptKind.TSX);}- return undefined;+ return;};const program = ts.createProgram(diff --git a/packages/react-sdk/src/remix.test.ts b/packages/react-sdk/src/remix.test.tsindex ad7aaef8fe..a331405e64 100644--- a/packages/react-sdk/src/remix.test.ts+++ b/packages/react-sdk/src/remix.test.ts@@ -1,5 +1,22 @@-import { expect, test } from "vitest";+import { expect, test, describe } from "vitest";import { generateRemixParams, generateRemixRoute } from "./remix";+import { STATIC_PATHS } from "@webstudio-is/sdk/router-paths.test";++/**+ * These tests use the shared test data from @webstudio-is/sdk to ensure+ * route generation is consistent with schema validation and URLPattern matching.+ */+describe("Shared router path tests - Route generation", () => {+ describe("all valid static paths generate valid routes", () => {+ test.each(STATIC_PATHS)("generates route for: %s", (path) => {+ const route = generateRemixRoute(path);+ // Should produce a non-empty route+ expect(route).toBeTruthy();+ // Should not throw+ expect(typeof route).toBe("string");+ });+ });+});test("convert home page to remix route", () => {expect(generateRemixRoute("")).toEqual("_index");@@ -13,6 +30,45 @@ test("convert path to remix route", () => {);});+describe("non-Latin character routes", () => {+ // When users define redirects with non-Latin characters (e.g., Chinese, Japanese),+ // the generateRemixRoute function must produce valid filenames.+ // Note: The actual HTTP request will have URL-encoded paths, but React Router+ // handles the decoding automatically when matching routes.++ test("convert Chinese path to remix route", () => {+ expect(generateRemixRoute("/关于我们")).toEqual("[关于我们]._index");+ expect(generateRemixRoute("/产品/手机")).toEqual("[产品].[手机]._index");+ });++ test("convert Japanese path to remix route", () => {+ expect(generateRemixRoute("/日本語")).toEqual("[日本語]._index");+ expect(generateRemixRoute("/ブログ/記事")).toEqual(+ "[ブログ].[記事]._index"+ );+ });++ test("convert Korean path to remix route", () => {+ expect(generateRemixRoute("/한국어")).toEqual("[한국어]._index");+ });++ test("convert Cyrillic path to remix route", () => {+ expect(generateRemixRoute("/привет")).toEqual("[привет]._index");+ expect(generateRemixRoute("/блог/статья")).toEqual(+ "[блог].[статья]._index"+ );+ });++ test("convert European diacritics to remix route", () => {+ expect(generateRemixRoute("/über-uns")).toEqual("[über-uns]._index");+ expect(generateRemixRoute("/café")).toEqual("[café]._index");+ });++ test("convert mixed Latin and non-Latin path to remix route", () => {+ expect(generateRemixRoute("/blog/关于")).toEqual("[blog].[关于]._index");+ });+});+test("convert wildcard to remix route", () => {expect(generateRemixRoute("/blog/*")).toEqual("[blog].$");});diff --git a/packages/sdk-components-animation/private-src b/packages/sdk-components-animation/private-srcindex a5840a6ffa..ce8f6e6350 160000--- a/packages/sdk-components-animation/private-src+++ b/packages/sdk-components-animation/private-src@@ -1 +1 @@-Subproject commit a5840a6ffa624ee78daa7953b6cf94030aa099b1+Subproject commit ce8f6e635021c0db123e1fac2fee146d4b0bdcdbdiff --git a/packages/sdk-components-react/src/head-slot.template.tsx b/packages/sdk-components-react/src/head-slot.template.tsxindex d66e58fbae..41e577fbab 100644--- a/packages/sdk-components-react/src/head-slot.template.tsx+++ b/packages/sdk-components-react/src/head-slot.template.tsx@@ -3,7 +3,7 @@ import { type TemplateMeta, $ } from "@webstudio-is/template";export const meta: TemplateMeta = {category: "general",description:- "The Head Slot component lets you customize page-specific head elements (like canonical URLs), which merge with your site's global head settings, with Head Slot definitions taking priority over Page Settings. For site-wide head changes, use Project Settings instead.",+ "The Head Slot component lets you customize page-specific head elements (like canonical URLs), which merge with your site's global head settings, with Head Slot definitions taking priority over Page Settings. For site-wide head changes, use project settings instead.",order: 5,template: (<$.HeadSlot>diff --git a/packages/sdk-components-react/src/time.tsx b/packages/sdk-components-react/src/time.tsxindex 77d71f49ec..93c7988c51 100644--- a/packages/sdk-components-react/src/time.tsx+++ b/packages/sdk-components-react/src/time.tsx@@ -307,7 +307,7 @@ const dateStyleOrUndefined = (if (["full", "long", "medium", "short"].includes(value as string)) {return value as Intl.DateTimeFormatOptions["dateStyle"];}- return undefined;+ return;};const timeStyleOrUndefined = (@@ -316,7 +316,7 @@ const timeStyleOrUndefined = (if (["full", "long", "medium", "short"].includes(value as string)) {return value as Intl.DateTimeFormatOptions["timeStyle"];}- return undefined;+ return;};const parseDate = (datetimeString: string) => {diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex f5b3eb3a31..34dc59aee0 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -26,6 +26,9 @@"webstudio": "./src/core-templates.tsx","types": "./lib/types/core-templates.d.ts","import": "./lib/core-templates.js"+ },+ "./router-paths.test": {+ "webstudio": "./src/router-paths.test.ts"}},"files": [diff --git a/packages/sdk/src/router-path-test-data.ts b/packages/sdk/src/router-path-test-data.tsnew file mode 100644index 0000000000..77899fc521--- /dev/null+++ b/packages/sdk/src/router-path-test-data.ts@@ -0,0 +1,231 @@+/**+ * Shared test data for router path validation.+ *+ * This file exports test cases that should be used consistently across:+ * 1. Path schema validation (SDK) - OldPagePath, page paths, etc.+ * 2. URLPattern matching (builder) - used for all page routing+ * 3. Route generation for published sites (react-sdk)+ *+ * These paths are used for pages, redirects, and any routable URL.+ * Add new test cases here to ensure all layers are tested with the same data.+ *+ * Reference: React Router path matching tests+ * https://github.com/remix-run/react-router/tree/main/packages/react-router/__tests__+ */++// These test cases define what paths should be valid/invalid across ALL layers++export const VALID_ROUTER_PATHS = {+ // Basic paths+ basic: ["/about", "/blog", "/contact-us", "/products/item-1"],++ // Deep nesting+ deepNesting: [+ "/a/b/c/d/e",+ "/users/123/posts/456/comments/789",+ "/api/v1/resources/items",+ ],++ // Dynamic segments (React Router: /:param)+ dynamicSegments: [+ "/:id",+ "/users/:id",+ "/users/:userId/posts/:postId",+ "/blog/:year/:month/:day/:slug",+ "/courses/:foo-bar", // params can contain dashes+ ],++ // Optional dynamic segments (React Router: /:param?)+ optionalDynamic: [+ "/:lang?/about",+ "/user/:id/:tab?",+ "/:lang?/user/:id?",+ "/docs/:version?/:page?",+ "/nested/:one?/:two?/:three?/:four?", // up to 4 consecutive optionals+ "/:one?/:two?/:three?", // all optional at root+ ],++ // Optional static segments (React Router: /segment?)+ optionalStatic: [+ "/en?/about",+ "/api/v1?/users",+ "/school?/user/:id",+ "/admin?/dashboard",+ "/nested/one?/two?", // consecutive static optionals+ "/nested/one?/two/three?", // intercalated static optionals+ ],++ // Mixed optional patterns (intercalated static and dynamic)+ mixedOptionals: [+ "/nested/:one?/two/:three?", // optional, required, optional+ "/one?/:two?/three/:four/*", // mixed optionals with splat+ "/one/:two?/three/:four?/:five?", // complex mixed pattern+ ],++ // Wildcard/splat routes (React Router: /*)+ wildcards: ["/*", "/blog/*", "/docs/*", "/files/*", "/users/:id/files/*"],++ // Query strings and fragments+ queryAndFragments: [+ "/search?q=test",+ "/page#section",+ "/path?a=1&b=2#top",+ "/products?category=shoes&sort=price",+ ],++ // URL-encoded characters+ urlEncoded: [+ "/hello%20world",+ "/%E6%B8%AF%E8%81%9E",+ "/path%2Fwith%2Fslash",+ "/users%3Fid%3D123", // ?id=123 encoded+ ],++ // Special characters allowed in paths (from React Router special-characters-test.tsx)+ // Note: Some chars have special meaning in URLPattern regex and must be URL-encoded+ specialChars: [+ "/path-with-dash",+ "/path_with_underscore",+ "/path.with.dots",+ "/path~tilde",+ "/path!exclaim",+ "/path@at",+ "/path$dollar",+ "/path'apostrophe",+ "/path,comma",+ "/path;semicolon",+ "/path=equals",+ ],++ // Characters that are valid in URLs but have special meaning in URLPattern+ // These need to be URL-encoded when used literally (not as pattern syntax)+ specialCharsNeedEncoding: [+ "/path%28parens%29", // parentheses encoded+ "/path%2Bplus", // plus encoded+ ],++ // Non-Latin characters (Unicode/UTF-8)+ chinese: ["/关于我们", "/产品/手机", "/港聞", "/繁體中文"],+ japanese: ["/日本語", "/こんにちは", "/カテゴリ", "/ブログ/記事"],+ korean: ["/한국어", "/블로그/포스트", "/서울"],+ cyrillic: ["/привет", "/о-нас", "/блог/статья"],+ arabic: ["/مرحبا", "/عن-الشركة"],+ hebrew: ["/שלום", "/אודות"],+ thai: ["/สวัสดี", "/ภาษาไทย"],+ greek: ["/γεια", "/σχετικά"],+ european: ["/über-uns", "/café", "/niño", "/résumé", "/naïve"],++ // Mixed Latin and non-Latin+ mixed: ["/blog/关于", "/news/港聞", "/category/日本語", "/user/bücherwurm"],++ // File extensions in paths (from React Router generatePath-test.tsx)+ fileExtensions: [+ "/books/:id.json",+ "/api/:resource.xml",+ "/images/:name.png",+ "/docs/:page.html",+ "/sitemap/:lang.xml", // param before extension+ "/:lang.html", // root level param with extension+ "/files/:name.tar.gz", // multiple extensions+ "/:file.min.js", // minified JS pattern+ ],++ // Base64-like segments (from React Router matchRoutes-test.tsx)+ base64Segments: ["/users/VXNlcnM6MQ==", "/items/YWJjZGVm"],++ // Emoji paths (modern Unicode)+ emoji: ["/🏠", "/blog/🎉", "/products/👟"],+} as const;++export const INVALID_ROUTER_PATHS = {+ // Empty or root only (for redirects, root is not a valid source)+ empty: ["", "/"],++ // Spaces (must be URL-encoded)+ spaces: ["/hello world", "/path with spaces"],++ // URL-unsafe characters (RFC 3986)+ unsafe: [+ "/path<script>",+ "/path>other",+ '/path"quote',+ "/path{test}",+ "/path|other",+ "/path\\other",+ "/path[0]",+ "/path`backtick",+ ],++ // Reserved paths (Webstudio-specific)+ reserved: ["/s", "/s/css", "/s/uploads", "/build", "/build/main.js"],++ // Invalid structure+ structure: [+ "no-leading-slash",+ "/trailing/",+ "/double//slash",+ "//leading-double",+ ],++ // Control characters+ controlChars: ["/path\x00null", "/path\x1fnewline"],+} as const;++// Flattened arrays for convenience+export const ALL_VALID_PATHS = Object.values(VALID_ROUTER_PATHS).flat();+export const ALL_INVALID_PATHS = Object.values(INVALID_ROUTER_PATHS).flat();++// Paths that are specifically for testing URLPattern matching (no query/fragment)+// These are paths that work with URLPattern API+export const VALID_URLPATTERN_PATHS = [+ ...VALID_ROUTER_PATHS.basic,+ ...VALID_ROUTER_PATHS.deepNesting,+ ...VALID_ROUTER_PATHS.dynamicSegments,+ ...VALID_ROUTER_PATHS.optionalDynamic,+ // Note: optionalStatic uses React Router syntax which differs from URLPattern+ ...VALID_ROUTER_PATHS.wildcards,+ ...VALID_ROUTER_PATHS.specialChars,+ ...VALID_ROUTER_PATHS.specialCharsNeedEncoding,+ ...VALID_ROUTER_PATHS.chinese,+ ...VALID_ROUTER_PATHS.japanese,+ ...VALID_ROUTER_PATHS.korean,+ ...VALID_ROUTER_PATHS.cyrillic,+ ...VALID_ROUTER_PATHS.arabic,+ ...VALID_ROUTER_PATHS.hebrew,+ ...VALID_ROUTER_PATHS.thai,+ ...VALID_ROUTER_PATHS.greek,+ ...VALID_ROUTER_PATHS.european,+ ...VALID_ROUTER_PATHS.mixed,+ ...VALID_ROUTER_PATHS.base64Segments,+ ...VALID_ROUTER_PATHS.emoji,+] as const;++// Static paths (no wildcards/params) for testing route generation+export const STATIC_PATHS = [+ ...VALID_ROUTER_PATHS.basic,+ ...VALID_ROUTER_PATHS.deepNesting,+ ...VALID_ROUTER_PATHS.specialChars,+ ...VALID_ROUTER_PATHS.specialCharsNeedEncoding,+ ...VALID_ROUTER_PATHS.chinese,+ ...VALID_ROUTER_PATHS.japanese,+ ...VALID_ROUTER_PATHS.korean,+ ...VALID_ROUTER_PATHS.cyrillic,+ ...VALID_ROUTER_PATHS.arabic,+ ...VALID_ROUTER_PATHS.hebrew,+ ...VALID_ROUTER_PATHS.thai,+ ...VALID_ROUTER_PATHS.greek,+ ...VALID_ROUTER_PATHS.european,+ ...VALID_ROUTER_PATHS.mixed,+ ...VALID_ROUTER_PATHS.base64Segments,+ ...VALID_ROUTER_PATHS.emoji,+] as const;++// Pattern paths (with dynamic segments, wildcards, or optional segments)+export const PATTERN_PATHS = [+ ...VALID_ROUTER_PATHS.dynamicSegments,+ ...VALID_ROUTER_PATHS.optionalDynamic,+ ...VALID_ROUTER_PATHS.optionalStatic,+ ...VALID_ROUTER_PATHS.mixedOptionals,+ ...VALID_ROUTER_PATHS.wildcards,+ ...VALID_ROUTER_PATHS.fileExtensions,+] as const;diff --git a/packages/sdk/src/router-paths.test.ts b/packages/sdk/src/router-paths.test.tsnew file mode 100644index 0000000000..9218fc6de3--- /dev/null+++ b/packages/sdk/src/router-paths.test.ts@@ -0,0 +1,56 @@+/**+ * Shared test suite for router path handling consistency.+ *+ * This ensures that router paths are handled consistently across:+ * 1. Path schema validation (SDK) - OldPagePath, page paths+ * 2. URLPattern matching (builder) - used for all page routing+ * 3. Route generation for published sites (react-sdk)+ *+ * If a path is valid in one layer, it should work in all layers.+ */++import { describe, test, expect } from "vitest";+import { OldPagePath, ProjectNewRedirectPath } from "./schema/pages";+import { ALL_VALID_PATHS, ALL_INVALID_PATHS } from "./router-path-test-data";++// Re-export for use in other packages+export {+ VALID_ROUTER_PATHS,+ INVALID_ROUTER_PATHS,+ ALL_VALID_PATHS,+ ALL_INVALID_PATHS,+ VALID_URLPATTERN_PATHS,+ STATIC_PATHS,+} from "./router-path-test-data";++describe("Router path validation consistency", () => {+ describe("OldPagePath schema - valid paths", () => {+ test.each(ALL_VALID_PATHS)("accepts: %s", (path) => {+ const result = OldPagePath.safeParse(path);+ expect(result.success).toBe(true);+ });+ });++ describe("OldPagePath schema - invalid paths", () => {+ test.each(ALL_INVALID_PATHS)("rejects: %s", (path) => {+ const result = OldPagePath.safeParse(path);+ expect(result.success).toBe(false);+ });+ });++ describe("ProjectNewRedirectPath schema - valid paths", () => {+ // ProjectNewRedirectPath is more permissive (allows / and external URLs)+ const validTargetPaths = [+ "/",+ "/about",+ "/关于我们",+ "https://example.com",+ "https://example.com/path",+ ];++ test.each(validTargetPaths)("accepts: %s", (path) => {+ const result = ProjectNewRedirectPath.safeParse(path);+ expect(result.success).toBe(true);+ });+ });+});diff --git a/packages/sdk/src/schema/pages.test.ts b/packages/sdk/src/schema/pages.test.tsnew file mode 100644index 0000000000..14c8650159--- /dev/null+++ b/packages/sdk/src/schema/pages.test.ts@@ -0,0 +1,225 @@+import { describe, test, expect } from "vitest";+import { OldPagePath, ProjectNewRedirectPath } from "./pages";++describe("OldPagePath", () => {+ describe("basic validation", () => {+ test("accepts valid path", () => {+ expect(OldPagePath.safeParse("/about").success).toBe(true);+ expect(OldPagePath.safeParse("/blog/post").success).toBe(true);+ });++ test("rejects empty string", () => {+ const result = OldPagePath.safeParse("");+ expect(result.success).toBe(false);+ });++ test("rejects just a slash", () => {+ const result = OldPagePath.safeParse("/");+ expect(result.success).toBe(false);+ });++ test("must start with /", () => {+ const result = OldPagePath.safeParse("about");+ expect(result.success).toBe(false);+ });++ test("cannot end with /", () => {+ const result = OldPagePath.safeParse("/about/");+ expect(result.success).toBe(false);+ });++ test("cannot contain //", () => {+ const result = OldPagePath.safeParse("/about//page");+ expect(result.success).toBe(false);+ });++ test("rejects /s prefix (reserved)", () => {+ expect(OldPagePath.safeParse("/s").success).toBe(false);+ expect(OldPagePath.safeParse("/s/css").success).toBe(false);+ });++ test("rejects /build prefix (reserved)", () => {+ expect(OldPagePath.safeParse("/build").success).toBe(false);+ expect(OldPagePath.safeParse("/build/main.js").success).toBe(false);+ });+ });++ describe("special characters", () => {+ test("accepts wildcards", () => {+ expect(OldPagePath.safeParse("/blog/*").success).toBe(true);+ });++ test("accepts dynamic segments", () => {+ expect(OldPagePath.safeParse("/:slug").success).toBe(true);+ expect(OldPagePath.safeParse("/blog/:id").success).toBe(true);+ });++ test("accepts optional segments", () => {+ expect(OldPagePath.safeParse("/:id?").success).toBe(true);+ });++ test("accepts query strings", () => {+ expect(OldPagePath.safeParse("/search?q=test").success).toBe(true);+ });++ test("accepts URL-encoded characters", () => {+ expect(OldPagePath.safeParse("/hello%20world").success).toBe(true);+ expect(OldPagePath.safeParse("/%E6%B8%AF%E8%81%9E").success).toBe(true);+ });+ });++ describe("invalid characters", () => {+ test("rejects spaces", () => {+ const result = OldPagePath.safeParse("/hello world");+ expect(result.success).toBe(false);+ });++ test("rejects angle brackets", () => {+ expect(OldPagePath.safeParse("/path<script>").success).toBe(false);+ expect(OldPagePath.safeParse("/path>other").success).toBe(false);+ });++ test("rejects quotes", () => {+ expect(OldPagePath.safeParse('/path"quote').success).toBe(false);+ });++ test("rejects curly braces", () => {+ expect(OldPagePath.safeParse("/path{test}").success).toBe(false);+ });++ test("rejects pipe", () => {+ expect(OldPagePath.safeParse("/path|other").success).toBe(false);+ });++ test("rejects backslash", () => {+ expect(OldPagePath.safeParse("/path\\other").success).toBe(false);+ });++ test("rejects square brackets", () => {+ expect(OldPagePath.safeParse("/path[0]").success).toBe(false);+ });+ });++ describe("non-Latin characters (Unicode/UTF-8)", () => {+ // Chinese characters - common in Chinese websites+ // Examples from https://aubreyyung.com/chinese-url-seo/+ test("accepts Chinese characters (Simplified)", () => {+ expect(OldPagePath.safeParse("/关于我们").success).toBe(true);+ expect(OldPagePath.safeParse("/产品/手机").success).toBe(true);+ expect(OldPagePath.safeParse("/新闻").success).toBe(true);+ });++ test("accepts Chinese characters (Traditional)", () => {+ expect(OldPagePath.safeParse("/關於我們").success).toBe(true);+ expect(OldPagePath.safeParse("/港聞").success).toBe(true);+ expect(OldPagePath.safeParse("/繁體中文").success).toBe(true);+ });++ // Japanese characters+ test("accepts Japanese characters (Hiragana)", () => {+ expect(OldPagePath.safeParse("/こんにちは").success).toBe(true);+ expect(OldPagePath.safeParse("/ブログ/記事").success).toBe(true);+ });++ test("accepts Japanese characters (Katakana)", () => {+ expect(OldPagePath.safeParse("/カテゴリ").success).toBe(true);+ });++ test("accepts Japanese characters (Kanji)", () => {+ expect(OldPagePath.safeParse("/日本語").success).toBe(true);+ expect(OldPagePath.safeParse("/東京").success).toBe(true);+ });++ // Korean characters+ test("accepts Korean characters (Hangul)", () => {+ expect(OldPagePath.safeParse("/한국어").success).toBe(true);+ expect(OldPagePath.safeParse("/블로그/포스트").success).toBe(true);+ expect(OldPagePath.safeParse("/서울").success).toBe(true);+ });++ // Cyrillic characters (Russian, etc.)+ test("accepts Cyrillic characters", () => {+ expect(OldPagePath.safeParse("/привет").success).toBe(true);+ expect(OldPagePath.safeParse("/о-нас").success).toBe(true);+ expect(OldPagePath.safeParse("/блог/статья").success).toBe(true);+ });++ // Arabic characters+ test("accepts Arabic characters", () => {+ expect(OldPagePath.safeParse("/مرحبا").success).toBe(true);+ expect(OldPagePath.safeParse("/عن-الشركة").success).toBe(true);+ });++ // Hebrew characters+ test("accepts Hebrew characters", () => {+ expect(OldPagePath.safeParse("/שלום").success).toBe(true);+ expect(OldPagePath.safeParse("/אודות").success).toBe(true);+ });++ // Thai characters+ test("accepts Thai characters", () => {+ expect(OldPagePath.safeParse("/สวัสดี").success).toBe(true);+ expect(OldPagePath.safeParse("/เกี่ยวกับเรา").success).toBe(true);+ });++ // Greek characters+ test("accepts Greek characters", () => {+ expect(OldPagePath.safeParse("/γεια").success).toBe(true);+ expect(OldPagePath.safeParse("/σχετικά").success).toBe(true);+ });++ // Mixed Latin and non-Latin+ test("accepts mixed Latin and non-Latin characters", () => {+ expect(OldPagePath.safeParse("/blog/关于").success).toBe(true);+ expect(OldPagePath.safeParse("/news/港聞").success).toBe(true);+ expect(OldPagePath.safeParse("/category/日本語").success).toBe(true);+ });++ // European characters with diacritics+ test("accepts European characters with diacritics", () => {+ expect(OldPagePath.safeParse("/über-uns").success).toBe(true);+ expect(OldPagePath.safeParse("/café").success).toBe(true);+ expect(OldPagePath.safeParse("/niño").success).toBe(true);+ expect(OldPagePath.safeParse("/naïve").success).toBe(true);+ expect(OldPagePath.safeParse("/résumé").success).toBe(true);+ });++ // Emoji (while unusual, they are valid Unicode)+ test("accepts emoji characters", () => {+ expect(OldPagePath.safeParse("/🎉").success).toBe(true);+ expect(OldPagePath.safeParse("/hello-🌍").success).toBe(true);+ });+ });+});++describe("ProjectNewRedirectPath", () => {+ test("accepts relative paths", () => {+ expect(ProjectNewRedirectPath.safeParse("/about").success).toBe(true);+ expect(ProjectNewRedirectPath.safeParse("/").success).toBe(true);+ });++ test("accepts absolute URLs", () => {+ expect(+ ProjectNewRedirectPath.safeParse("https://example.com/page").success+ ).toBe(true);+ });++ test("accepts non-Latin character paths", () => {+ expect(ProjectNewRedirectPath.safeParse("/关于我们").success).toBe(true);+ expect(ProjectNewRedirectPath.safeParse("/日本語").success).toBe(true);+ expect(ProjectNewRedirectPath.safeParse("/한국어").success).toBe(true);+ });++ test("rejects empty string", () => {+ expect(ProjectNewRedirectPath.safeParse("").success).toBe(false);+ });++ test("rejects truly invalid URLs", () => {+ // Note: ProjectNewRedirectPath uses new URL(data, baseURL) which is very permissive+ // It treats most strings as valid relative paths. The only truly invalid inputs+ // are those that cannot be parsed as URLs at all.+ expect(ProjectNewRedirectPath.safeParse("http://[invalid").success).toBe(+ false+ );+ });+});diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.tsindex 521ed21cf2..90ba2cf84f 100644--- a/packages/sdk/src/schema/pages.ts+++ b/packages/sdk/src/schema/pages.ts@@ -121,10 +121,18 @@ export const OldPagePath = z).refine((path) => path.endsWith("/") === false, "Can't end with a /").refine((path) => path.includes("//") === false, "Can't contain repeating /")- .refine(- (path) => /^[-_a-zA-Z0-9*:?\\/.]*$/.test(path), // Allow uppercase letters (A-Z)- "Only a-z, A-Z, 0-9, -, _, /, :, ?, . and * are allowed"- )+ .refine((path) => {+ // Disallow specific problematic characters that should never appear in paths:+ // - Spaces and whitespace+ // - URL-unsafe characters: < > " { } | \ ^ ` [ ]+ // - Control characters+ // All other characters (including non-Latin Unicode like Chinese, Japanese,+ // Korean, Cyrillic, Arabic, etc.) are allowed as they are valid in modern URLs+ // when properly encoded by the browser+ // eslint-disable-next-line no-control-regex+ const disallowedChars = /[\s<>"{}|\\^`[\]\u0000-\u001f\u007f]/;+ return !disallowedChars.test(path);+ }, "Path contains invalid characters (spaces or URL-unsafe characters are not allowed)").refine((path) => path !== "/s" && path.startsWith("/s/") === false,"/s prefix is reserved for the system"@@ -153,16 +161,19 @@ const ProjectMeta = z.object({});export type ProjectMeta = z.infer<typeof ProjectMeta>;-export const ProjectNewRedirectPath = z.string().refine((data) => {- // Users should be able to redirect from any old-path to the home page in the new project.- try {- // can be relative and absolute paths- new URL(data, "http://url.com");- return true;- } catch {- return false;- }-}, "Must be a valid URL");+export const ProjectNewRedirectPath = z+ .string()+ .min(1, "Path is required")+ .refine((data) => {+ // Users should be able to redirect from any old-path to the home page in the new project.+ try {+ // can be relative and absolute paths+ new URL(data, "http://url.com");+ return true;+ } catch {+ return false;+ }+ }, "Must be a valid URL");export const PageRedirect = z.object({old: OldPagePath,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7d6087cb0d..92f6eb50ea 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -364,6 +364,9 @@ importers:nanostores:specifier: ^0.11.3version: 0.11.3+ papaparse:+ specifier: ^5.5.3+ version: 5.5.3parse5:specifier: 7.3.0version: 7.3.0@@ -440,6 +443,9 @@ importers:'@types/dom-navigation':specifier: ^1.0.5version: 1.0.5+ '@types/papaparse':+ specifier: ^5.5.2+ version: 5.5.2'@types/react':specifier: ^18.2.70version: 18.2.79@@ -5427,6 +5433,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==}+'@types/[email protected]':resolution: {integrity: sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==}@@ -7951,6 +7960,9 @@ packages:resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==}+ resolution: {integrity: sha512-5QvjGxYVjxO59MGU2lHVYpRWBBtKHnlIAcSe1uNFCkkptUh63NFRj0FJQm7nR67puEruUci/ZkjmEFrjCAyP4A==}+resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}engines: {node: '>=6'}@@ -12834,6 +12846,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/node': 22.13.10+'@types/[email protected]': {}'@types/[email protected]':@@ -15992,6 +16008,8 @@ snapshots:+ [email protected]: {}+dependencies:callsites: 3.1.0