Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

refactor: clarify pathname rule matchers (#6446)

Oleg Isonendf7ed327ab64
diff --git a/apps/builder/app/builder/features/address-bar.tsx b/apps/builder/app/builder/features/address-bar.tsx
index c94aa28215..3cf2711748 100644
--- a/apps/builder/app/builder/features/address-bar.tsx
+++ b/apps/builder/app/builder/features/address-bar.tsx
@@ -29,7 +29,7 @@ import { CheckMarkIcon, CopyIcon, DynamicPageIcon } from "@webstudio-is/icons";
import {
compilePathnamePattern,
isPathnamePattern,
- matchPathnamePattern,
+ matchUrlPattern,
tokenizePathnamePattern,
} from "@webstudio-is/project-build/runtime";
import {
@@ -260,7 +260,7 @@ const AddressBar = forwardRef<
const path = useStore($selectedPagePath);
let history = useStore($selectedPageHistory);
history = useMemo(() => {
- return history.filter((item) => matchPathnamePattern(path, item));
+ return history.filter((item) => matchUrlPattern(path, item));
}, [history, path]);
const [pathParams, setPathParams] = useState(
() => $currentSystem.get().params
@@ -308,7 +308,7 @@ const AddressBar = forwardRef<
options={history}
onSelect={(option) => {
flushSync(() => {
- setPathParams(matchPathnamePattern(path, option) ?? {});
+ setPathParams(matchUrlPattern(path, option) ?? {});
});
containerRef.current?.requestSubmit();
}}
diff --git a/apps/builder/app/canvas/interceptor.ts b/apps/builder/app/canvas/interceptor.ts
index 23e28ec8b3..0a122f5a4f 100644
--- a/apps/builder/app/canvas/interceptor.ts
+++ b/apps/builder/app/canvas/interceptor.ts
@@ -1,7 +1,7 @@
import { getAllPages, getPagePath, isAbsoluteUrl } from "@webstudio-is/sdk";
import {
compilePathnamePattern,
- matchPathnamePattern,
+ matchUrlPattern,
tokenizePathnamePattern,
} from "@webstudio-is/project-build/runtime";
import { $selectedPage } from "~/shared/nano-states";
@@ -51,7 +51,7 @@ const switchPageAndUpdateSystem = (href: string, formData?: FormData) => {
);
for (const page of sortedPages) {
const pagePath = getPagePath(page.id, pages);
- const params = matchPathnamePattern(pagePath, pageHref.pathname);
+ const params = matchUrlPattern(pagePath, pageHref.pathname);
if (params) {
// populate search params with form data values if available
if (formData) {
diff --git a/apps/builder/app/shared/project-settings/section-headers.tsx b/apps/builder/app/shared/project-settings/section-headers.tsx
index d377357a71..2a4122c12d 100644
--- a/apps/builder/app/shared/project-settings/section-headers.tsx
+++ b/apps/builder/app/shared/project-settings/section-headers.tsx
@@ -18,7 +18,7 @@ import {
editCustomResponseHeaders,
type CustomResponseHeader,
} from "@webstudio-is/sdk";
-import { validateWsAuthRoute } from "@webstudio-is/wsauth";
+import { validatePathnamePattern } from "@webstudio-is/wsauth";
import { $pages, $projectSettings } from "~/shared/sync/data-stores";
import { $permissions } from "~/shared/nano-states";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
@@ -161,7 +161,7 @@ export const SectionHeaders = ({
const name = values.name?.trim() ?? "";
const value = values.value?.trim() ?? "";
const errors: Record<string, string[]> = {};
- const routeError = validateWsAuthRoute(route);
+ const routeError = validatePathnamePattern(route);
if (routeError) {
errors.route = [routeError];
}
diff --git a/apps/builder/app/shared/system.ts b/apps/builder/app/shared/system.ts
index 3a856a0135..aa818d88f4 100644
--- a/apps/builder/app/shared/system.ts
+++ b/apps/builder/app/shared/system.ts
@@ -2,7 +2,7 @@ import { atom, computed } from "nanostores";
import { getPagePath, isPage, type Page, type System } from "@webstudio-is/sdk";
import {
compilePathnamePattern,
- matchPathnamePattern,
+ matchUrlPattern,
tokenizePathnamePattern,
} from "@webstudio-is/project-build/runtime";
import { $selectedPage } from "./nano-states/pages";
@@ -25,10 +25,8 @@ const extractParams = (
// see the page without manually entering params
// or selecting them in address bar
const matchedParams = path
- ? (matchPathnamePattern(pattern, path) ??
- (fallbackPattern
- ? matchPathnamePattern(fallbackPattern, path)
- : undefined))
+ ? (matchUrlPattern(pattern, path) ??
+ (fallbackPattern ? matchUrlPattern(fallbackPattern, path) : undefined))
: undefined;
for (const token of tokens) {
if (token.type === "param") {
diff --git a/packages/project-build/src/runtime/redirect-source.ts b/packages/project-build/src/runtime/redirect-source.ts
index 22bcf95471..d8f79881e1 100644
--- a/packages/project-build/src/runtime/redirect-source.ts
+++ b/packages/project-build/src/runtime/redirect-source.ts
@@ -1,4 +1,4 @@
-import { matchPathnamePattern } from "./url-pattern";
+import { matchUrlPattern } from "./url-pattern";
const isOptionalSegmentMarker = (source: string, index: number) => {
const nextChar = source[index + 1];
@@ -179,7 +179,7 @@ const getOptionalStaticSegmentVariants = (pathname: string) => {
const doesPathnamePatternOverlap = (pattern: string, pathname: string) => {
for (const patternVariant of getOptionalStaticSegmentVariants(pattern)) {
for (const pathnameVariant of getOptionalStaticSegmentVariants(pathname)) {
- if (matchPathnamePattern(patternVariant, pathnameVariant) !== undefined) {
+ if (matchUrlPattern(patternVariant, pathnameVariant) !== undefined) {
return true;
}
}
@@ -209,7 +209,7 @@ export const doesRedirectSourceMatchLocalUrl = (
for (const urlVariant of getOptionalStaticSegmentVariants(
normalizedUrlPathname
)) {
- if (matchPathnamePattern(sourceVariant, urlVariant) !== undefined) {
+ if (matchUrlPattern(sourceVariant, urlVariant) !== undefined) {
return true;
}
}
diff --git a/packages/project-build/src/runtime/url-pattern.test.ts b/packages/project-build/src/runtime/url-pattern.test.ts
index dbf1479590..a2bdb1a251 100644
--- a/packages/project-build/src/runtime/url-pattern.test.ts
+++ b/packages/project-build/src/runtime/url-pattern.test.ts
@@ -2,7 +2,7 @@ import { expect, test, describe } from "vitest";
import {
compilePathnamePattern,
isPathnamePattern,
- matchPathnamePattern,
+ matchUrlPattern,
tokenizePathnamePattern,
validatePathnamePattern,
} from "./url-pattern";
@@ -18,7 +18,7 @@ describe("Shared router path tests - URLPattern matching", () => {
// 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();
+ expect(() => matchUrlPattern(pattern, pattern)).not.toThrow();
});
});
@@ -29,26 +29,28 @@ describe("Shared router path tests - URLPattern matching", () => {
);
test.each(staticPaths)("matches exactly: %s", (path) => {
- const result = matchPathnamePattern(path, path);
+ const result = matchUrlPattern(path, path);
expect(result).toEqual({});
});
});
});
test("decode matched params", () => {
- expect(matchPathnamePattern("/blog/:slug", "/blog/привет")).toEqual({
+ expect(matchUrlPattern("/blog/:slug", "/blog/привет")).toEqual({
slug: "привет",
});
expect(
- matchPathnamePattern(
- "/blog/:slug",
- "/blog/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82"
- )
+ matchUrlPattern("/blog/:slug", "/blog/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82")
).toEqual({
slug: "привет",
});
});
+test("URLPattern wildcard requires the slash after its base path", () => {
+ expect(matchUrlPattern("/docs/*", "/docs")).toBeUndefined();
+ expect(matchUrlPattern("/docs/*", "/docs/")).toEqual({});
+});
+
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
@@ -56,69 +58,65 @@ describe("URLPattern Unicode/non-Latin character support", () => {
describe("exact path matching with non-Latin characters", () => {
test("matches Chinese Simplified paths", () => {
- expect(matchPathnamePattern("/关于我们", "/关于我们")).toEqual({});
- expect(matchPathnamePattern("/产品/手机", "/产品/手机")).toEqual({});
+ expect(matchUrlPattern("/关于我们", "/关于我们")).toEqual({});
+ expect(matchUrlPattern("/产品/手机", "/产品/手机")).toEqual({});
});
test("matches Chinese Traditional paths", () => {
- expect(matchPathnamePattern("/關於我們", "/關於我們")).toEqual({});
- expect(matchPathnamePattern("/港聞", "/港聞")).toEqual({});
+ expect(matchUrlPattern("/關於我們", "/關於我們")).toEqual({});
+ expect(matchUrlPattern("/港聞", "/港聞")).toEqual({});
});
test("matches Japanese paths (Hiragana, Katakana, Kanji)", () => {
- expect(matchPathnamePattern("/こんにちは", "/こんにちは")).toEqual({});
- expect(matchPathnamePattern("/カテゴリ", "/カテゴリ")).toEqual({});
- expect(matchPathnamePattern("/日本語", "/日本語")).toEqual({});
+ expect(matchUrlPattern("/こんにちは", "/こんにちは")).toEqual({});
+ expect(matchUrlPattern("/カテゴリ", "/カテゴリ")).toEqual({});
+ expect(matchUrlPattern("/日本語", "/日本語")).toEqual({});
});
test("matches Korean paths (Hangul)", () => {
- expect(matchPathnamePattern("/한국어", "/한국어")).toEqual({});
- expect(matchPathnamePattern("/블로그/포스트", "/블로그/포스트")).toEqual(
- {}
- );
+ expect(matchUrlPattern("/한국어", "/한국어")).toEqual({});
+ expect(matchUrlPattern("/블로그/포스트", "/블로그/포스트")).toEqual({});
});
test("matches Cyrillic paths", () => {
- expect(matchPathnamePattern("/о-нас", "/о-нас")).toEqual({});
- expect(matchPathnamePattern("/блог/статья", "/блог/статья")).toEqual({});
+ expect(matchUrlPattern("/о-нас", "/о-нас")).toEqual({});
+ expect(matchUrlPattern("/блог/статья", "/блог/статья")).toEqual({});
});
test("matches Arabic paths", () => {
- expect(matchPathnamePattern("/مرحبا", "/مرحبا")).toEqual({});
+ expect(matchUrlPattern("/مرحبا", "/مرحبا")).toEqual({});
});
test("matches Hebrew paths", () => {
- expect(matchPathnamePattern("/שלום", "/שלום")).toEqual({});
+ expect(matchUrlPattern("/שלום", "/שלום")).toEqual({});
});
test("matches Greek paths", () => {
- expect(matchPathnamePattern("/σχετικά", "/σχετικά")).toEqual({});
+ expect(matchUrlPattern("/σχετικά", "/σχετικά")).toEqual({});
});
test("matches European diacritics", () => {
- expect(matchPathnamePattern("/über-uns", "/über-uns")).toEqual({});
- expect(matchPathnamePattern("/café", "/café")).toEqual({});
- expect(matchPathnamePattern("/niño", "/niño")).toEqual({});
+ expect(matchUrlPattern("/über-uns", "/über-uns")).toEqual({});
+ expect(matchUrlPattern("/café", "/café")).toEqual({});
+ expect(matchUrlPattern("/niño", "/niño")).toEqual({});
});
});
describe("dynamic segments with non-Latin characters", () => {
test("captures Chinese characters in :slug parameter", () => {
- expect(matchPathnamePattern("/:slug", "/关于我们")).toEqual({
+ expect(matchUrlPattern("/:slug", "/关于我们")).toEqual({
slug: "关于我们",
});
});
test("captures Japanese characters in :slug parameter", () => {
- expect(matchPathnamePattern("/blog/:slug", "/blog/日本語")).toEqual({
+ expect(matchUrlPattern("/blog/:slug", "/blog/日本語")).toEqual({
slug: "日本語",
});
});
test("captures Korean characters in :slug parameter", () => {
- expect(
- matchPathnamePattern("/:category/:post", "/블로그/포스트")
- ).toEqual({
+ expect(matchUrlPattern("/:category/:post", "/블로그/포스트")).toEqual({
category: "블로그",
post: "포스트",
});
@@ -127,15 +125,13 @@ describe("URLPattern Unicode/non-Latin character support", () => {
describe("wildcard patterns with non-Latin characters", () => {
test("matches wildcard with Chinese paths", () => {
- expect(matchPathnamePattern("/blog/*", "/blog/中文/测试")).toEqual({
+ expect(matchUrlPattern("/blog/*", "/blog/中文/测试")).toEqual({
0: "中文/测试",
});
});
test("matches wildcard with Japanese paths", () => {
- expect(
- matchPathnamePattern("/カテゴリ/*", "/カテゴリ/記事/詳細")
- ).toEqual({
+ expect(matchUrlPattern("/カテゴリ/*", "/カテゴリ/記事/詳細")).toEqual({
0: "記事/詳細",
});
});
@@ -144,14 +140,14 @@ describe("URLPattern Unicode/non-Latin character support", () => {
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({
+ expect(matchUrlPattern("/: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({
+ expect(matchUrlPattern("/blog/关于", "/blog/关于")).toEqual({});
+ expect(matchUrlPattern("/news/:slug", "/news/港聞")).toEqual({
slug: "港聞",
});
});
diff --git a/packages/project-build/src/runtime/url-pattern.ts b/packages/project-build/src/runtime/url-pattern.ts
index 8ca312904b..ec50daf005 100644
--- a/packages/project-build/src/runtime/url-pattern.ts
+++ b/packages/project-build/src/runtime/url-pattern.ts
@@ -13,7 +13,12 @@ const tryDecode = (encoded: string) => {
}
};
-export const matchPathnamePattern = (pattern: string, pathname: string) => {
+/**
+ * Match a page or redirect path using URLPattern. Returns decoded parameters
+ * (`{}` for a static match) or `undefined` when it does not match. Unlike the
+ * wsauth's `matchesPathnamePattern`, `/docs/*` does not match `/docs` here.
+ */
+export const matchUrlPattern = (pattern: string, pathname: string) => {
try {
const groups = new URLPattern({ pathname: pattern }).exec({ pathname })
?.pathname.groups;
diff --git a/packages/sdk/src/schema/response-headers.ts b/packages/sdk/src/schema/response-headers.ts
index 1e2011aa35..2014c24a64 100644
--- a/packages/sdk/src/schema/response-headers.ts
+++ b/packages/sdk/src/schema/response-headers.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { validateWsAuthRoute } from "@webstudio-is/wsauth";
+import { validatePathnamePattern } from "@webstudio-is/wsauth";
// Keep fallback defaults in sync with the Cloud dispatcher.
export const responseHeaderDefinitions = [
@@ -60,7 +60,7 @@ export const customResponseHeader = z.object({
.string()
.max(2048)
.refine(
- (route) => validateWsAuthRoute(route) === undefined,
+ (route) => validatePathnamePattern(route) === undefined,
"Invalid route"
)
.optional(),
diff --git a/packages/wsauth/src/index.test.ts b/packages/wsauth/src/index.test.ts
index 0180997e2c..4704de9ec1 100644
--- a/packages/wsauth/src/index.test.ts
+++ b/packages/wsauth/src/index.test.ts
@@ -6,9 +6,10 @@ import {
createWsAuthResources,
findWsAuthRoute,
getBasicAuthCredentials,
+ matchesPathnamePattern,
parseWsAuth,
validateBasicAuth,
- validateWsAuthRoute,
+ validatePathnamePattern,
} from "./index";
describe("wsauth", () => {
@@ -121,14 +122,36 @@ describe("wsauth", () => {
});
test("validates route syntax", () => {
- expect(validateWsAuthRoute("/private")).toBeUndefined();
- expect(validateWsAuthRoute("/docs/*")).toBeUndefined();
- expect(validateWsAuthRoute("private")).toBe('Route must start with "/"');
- expect(validateWsAuthRoute("/docs/*/page")).toBe(
+ expect(validatePathnamePattern("/private")).toBeUndefined();
+ expect(validatePathnamePattern("/docs/*")).toBeUndefined();
+ expect(validatePathnamePattern("private")).toBe(
+ 'Route must start with "/"'
+ );
+ expect(validatePathnamePattern("/docs/*/page")).toBe(
"Wildcard route segment must be the last segment"
);
});
+ test.each([
+ ["/", "/", true],
+ ["/", "/docs", false],
+ ["/*", "/", true],
+ ["/*", "/docs/a", true],
+ ["/docs/*", "/docs", true],
+ ["/docs/*", "/docs/a", true],
+ ["/docs", "/docs/a", false],
+ ["/docs/:id", "/docs/a", true],
+ ["/docs/:id", "/docs", false],
+ ["/docs/:id?", "/docs", true],
+ ["/docs/:id?", "/docs/a", true],
+ ["/docs/:id?", "/docs/a/b", false],
+ ["/docs/:rest*", "/docs/a/b", true],
+ ["/Docs", "/docs", false],
+ ["/docs", "/docs/", true],
+ ] as const)("matches %s against %s: %s", (pattern, pathname, expected) => {
+ expect(matchesPathnamePattern(pattern, pathname)).toBe(expected);
+ });
+
test("builds content from JSON and route sources", () => {
const result = buildWsAuth([
{
diff --git a/packages/wsauth/src/index.ts b/packages/wsauth/src/index.ts
index d38da8f774..fc79fe4253 100644
--- a/packages/wsauth/src/index.ts
+++ b/packages/wsauth/src/index.ts
@@ -154,7 +154,7 @@ export const createBasicAuthRoute = ({
login: string;
password: string;
}): WsAuthRoute => {
- const routeError = validateWsAuthRoute(route);
+ const routeError = validatePathnamePattern(route);
if (routeError) {
throw new Error(routeError);
}
@@ -197,7 +197,8 @@ const isRecord = (value: unknown): value is Record<string, unknown> => {
const parameterSegment = /^:\w+[?*]?$/;
-export const validateWsAuthRoute = (route: string) => {
+/** Validate the route-rule syntax shared by authentication and response headers. */
+export const validatePathnamePattern = (route: string) => {
if (route.startsWith("/") === false) {
return 'Route must start with "/"';
}
@@ -265,7 +266,7 @@ export const parseWsAuth = (content: string): WsAuthParseResult => {
}
for (const [route, authInput] of Object.entries(json.routes)) {
- const routeError = validateWsAuthRoute(route);
+ const routeError = validatePathnamePattern(route);
if (routeError) {
errors.push({
path: `routes.${JSON.stringify(route)}`,
@@ -434,7 +435,13 @@ const normalizePathname = (pathname: string) => {
return pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
};
-export const matchWsAuthRoute = (route: string, pathname: string) => {
+/**
+ * Boolean matcher for auth and response-header rules. A trailing wildcard also
+ * matches its base path (`/docs/*` matches `/docs`). Page routing instead uses
+ * project-build's `matchUrlPattern`, which returns decoded path parameters and
+ * does not match `/docs` for that pattern.
+ */
+export const matchesPathnamePattern = (route: string, pathname: string) => {
const routeSegments = normalizePathname(route).slice(1).split("/");
const pathnameSegments = normalizePathname(pathname).slice(1).split("/");
const matchSegments = (
@@ -471,7 +478,7 @@ export const matchWsAuthRoute = (route: string, pathname: string) => {
};
export const findWsAuthRoute = (authRoutes: WsAuthRoute[], pathname: string) =>
- authRoutes.find(({ route }) => matchWsAuthRoute(route, pathname));
+ authRoutes.find(({ route }) => matchesPathnamePattern(route, pathname));
export const authenticateRequest = (
request: Request,
diff --git a/packages/wsauth/src/package.test.ts b/packages/wsauth/src/package.test.ts
index 6ad630fc37..1037970afe 100644
--- a/packages/wsauth/src/package.test.ts
+++ b/packages/wsauth/src/package.test.ts
@@ -100,12 +100,15 @@ test("publishes type declarations for every public entrypoint", async () => {
);
await writeFile(
join(projectDirectory, "index.ts"),
- `import type { WsAuthResources } from "@webstudio-is/wsauth";
+ `import { matchesPathnamePattern, validatePathnamePattern } from "@webstudio-is/wsauth";
+import type { WsAuthResources } from "@webstudio-is/wsauth";
import type { WsAuthConfig } from "@webstudio-is/wsauth/schema";
const routes: WsAuthResources["routes"] = [];
const config: WsAuthConfig = { version: 1, routes: {} };
-void [routes, config];
+const matches: boolean = matchesPathnamePattern("/*", "/docs");
+const routeError: string | undefined = validatePathnamePattern("/docs/*");
+void [routes, config, matches, routeError];
`,
"utf8"
);