From 150d3d8d921f8daf982cca09ff44c7b86a7ffcad Mon Sep 17 00:00:00 2001 From: Ys-sudo Date: Sat, 21 Nov 2026 17:23:52 +0100 Subject: [PATCH] Agent Host changes for agents/graphql-polylang-cors-issue-debugging --- apps/storefront/scripts/artifact-publish.mjs | 2 +- .../storefront/scripts/generate-seo-files.mjs | 6 ++- apps/storefront/scripts/prerender.mjs | 11 +++-- apps/storefront/src/App.tsx | 2 + .../src/components/ChatAssistantShortcode.tsx | 13 +++++- .../src/components/CmsPageContent.tsx | 2 +- .../src/components/SmartLinkNavigation.tsx | 3 +- apps/storefront/src/lib/blikPayment.ts | 4 +- apps/storefront/src/lib/blog.ts | 6 ++- apps/storefront/src/lib/chatAssistant.ts | 11 +++-- apps/storefront/src/lib/checkoutAccount.ts | 6 +-- .../src/lib/checkoutAccountRequest.ts | 4 +- apps/storefront/src/lib/cmsBehaviors.ts | 1 + apps/storefront/src/lib/commerce.ts | 12 ++--- .../src/lib/commerceCompatibility.test.ts | 1 + apps/storefront/src/lib/downloads.ts | 6 +-- apps/storefront/src/lib/internalLinks.ts | 12 ++++- apps/storefront/src/lib/navigation.test.ts | 4 +- apps/storefront/src/lib/navigation.ts | 7 +-- apps/storefront/src/lib/pageStyles.test.ts | 26 +++++++++++ apps/storefront/src/lib/pageStyles.ts | 45 ++++++++++++++++-- apps/storefront/src/lib/payments.ts | 10 ++-- apps/storefront/src/lib/postArchives.ts | 3 +- .../storefront/src/lib/productInquiry.test.ts | 7 +-- apps/storefront/src/lib/productPriceMode.ts | 11 ++--- apps/storefront/src/lib/protectedPages.ts | 4 +- .../src/lib/restRouteAvailability.ts | 12 ++--- apps/storefront/src/lib/searchRest.ts | 7 ++- apps/storefront/src/lib/stripePaymentData.ts | 4 +- apps/storefront/src/lib/wcStoreApi.ts | 6 +-- apps/storefront/src/main.tsx | 16 ++++--- packages/sdk/src/environment.ts | 46 ++++++++++++++++++- packages/sdk/src/index.ts | 4 ++ packages/ui/src/catalog/ProductCard.tsx | 26 ++++++----- .../ui/src/catalog/productCardPrice.test.ts | 3 +- packages/ui/src/catalog/productCardPrice.ts | 11 +++-- 36 files changed, 251 insertions(+), 103 deletions(-) diff --git a/apps/storefront/scripts/artifact-publish.mjs b/apps/storefront/scripts/artifact-publish.mjs index bb9a677..f7bd085 100644 --- a/apps/storefront/scripts/artifact-publish.mjs +++ b/apps/storefront/scripts/artifact-publish.mjs @@ -50,7 +50,7 @@ export function artifactConfigFromEnvironment(environment = process.env) { return { mode, delivery, - origin: origin.origin, + origin: origin.toString().replace(/\/+$/, ""), siteKey, signingSecret, }; diff --git a/apps/storefront/scripts/generate-seo-files.mjs b/apps/storefront/scripts/generate-seo-files.mjs index 8f70dca..c8f16c7 100644 --- a/apps/storefront/scripts/generate-seo-files.mjs +++ b/apps/storefront/scripts/generate-seo-files.mjs @@ -54,7 +54,7 @@ export async function fetchDocument(path, { } attemptsMade = attempt; try { - const response = await fetchImpl(new URL(path, backendOrigin), { + const response = await fetchImpl(new URL(path.replace(/^\/+/, ""), backendOrigin), { headers: { "User-Agent": "FunkyCommerce-Static-SEO/1.0" }, redirect: "follow", signal: signal @@ -243,7 +243,9 @@ export async function generateSeoFiles({ return; } - const backendOrigin = new URL(graphqlEndpoint).origin; + const backendUrl = new URL(graphqlEndpoint); + backendUrl.pathname = backendUrl.pathname.replace(/\/+$/, ""); + const backendOrigin = new URL(".", backendUrl).toString(); const frontendOrigin = siteUrl ? new URL(siteUrl).origin : null; const signal = AbortSignal.timeout(budgetMs); const fetchFromBackend = (path) => fetchDocument(path, { diff --git a/apps/storefront/scripts/prerender.mjs b/apps/storefront/scripts/prerender.mjs index e461522..398608d 100644 --- a/apps/storefront/scripts/prerender.mjs +++ b/apps/storefront/scripts/prerender.mjs @@ -76,6 +76,11 @@ const hasInteractiveStaticChrome = [configuredSiteHostname, configuredBackendHos ); const graphqlEndpoint = process.env.VITE_GRAPHQL_ENDPOINT?.trim() || "https://dev.superfunky.pro/graphql"; +const backendBaseUrl = (() => { + const endpoint = new URL(graphqlEndpoint); + endpoint.pathname = endpoint.pathname.replace(/\/+$/, ""); + return new URL(".", endpoint).toString(); +})(); let defaultLanguage = process.env.VITE_DEFAULT_LANGUAGE?.trim().toLowerCase() || "en"; const configuredBackendProfile = process.env.VITE_BACKEND_PROFILE?.trim().toLowerCase() || "full"; const backendProfile = ["shell", "blog", "shop", "full"].includes(configuredBackendProfile) @@ -1084,7 +1089,7 @@ async function discoverLanguages() { })); } try { - const response = await fetch(new URL("/wp-json/pll/v1/languages", graphqlEndpoint)); + const response = await fetch(new URL("wp-json/pll/v1/languages", backendBaseUrl)); if (response.ok) { const restLanguages = await response.json(); if (!Array.isArray(restLanguages)) { @@ -1141,7 +1146,7 @@ async function discoverLanguages() { } } try { - const response = await fetch(new URL("/wp-json/pll/v1/languages", graphqlEndpoint), { + const response = await fetch(new URL("wp-json/pll/v1/languages", backendBaseUrl), { signal: AbortSignal.timeout(10_000), }); if (response.ok) { @@ -1523,7 +1528,7 @@ async function discoverCmsRoutes({ } async function discoverStoreApiProductRouteNodes() { - const endpoint = new URL("/wp-json/wc/store/v1/products?per_page=100", graphqlEndpoint); + const endpoint = new URL("wp-json/wc/store/v1/products?per_page=100", backendBaseUrl); const response = await fetch(endpoint, { signal: AbortSignal.timeout(20_000) }); if (response.status === 404) return []; if (!response.ok) { diff --git a/apps/storefront/src/App.tsx b/apps/storefront/src/App.tsx index ed2cad2..7501cc7 100644 --- a/apps/storefront/src/App.tsx +++ b/apps/storefront/src/App.tsx @@ -802,6 +802,8 @@ export function App() { } /> } /> } /> + } /> + } /> } /> } /> } /> diff --git a/apps/storefront/src/components/ChatAssistantShortcode.tsx b/apps/storefront/src/components/ChatAssistantShortcode.tsx index 4c93f84..6262c56 100644 --- a/apps/storefront/src/components/ChatAssistantShortcode.tsx +++ b/apps/storefront/src/components/ChatAssistantShortcode.tsx @@ -1,4 +1,4 @@ -import { BACKEND_ORIGIN } from "@funky/sdk"; +import { BACKEND_BASE_URL } from "@funky/sdk"; import { Bot, MessageCircle, Send, Sparkles } from "lucide-react"; import { useEffect, useMemo, useState, type FormEvent } from "react"; import { chatAssistantEndpoints, resolveFlatAssistantIcon, type FlatAssistantIcon } from "../lib/chatAssistant"; @@ -33,7 +33,7 @@ function ConfiguredIcon({ config }: { config: AssistantConfig | null }) { } export function ChatAssistantShortcode() { - const endpoints = useMemo(() => chatAssistantEndpoints(BACKEND_ORIGIN), []); + const endpoints = useMemo(() => chatAssistantEndpoints(BACKEND_BASE_URL), []); const clientId = useMemo(() => crypto.randomUUID(), []); const [config, setConfig] = useState(null); const [messages, setMessages] = useState([]); @@ -42,6 +42,10 @@ export function ChatAssistantShortcode() { const [error, setError] = useState(""); useEffect(() => { + if (!endpoints) { + setError("The assistant backend is not configured."); + return; + } const controller = new AbortController(); fetch(endpoints.config, { signal: controller.signal }) .then((response) => response.ok ? response.json() : Promise.reject(new Error("Assistant configuration is unavailable."))) @@ -61,6 +65,11 @@ export function ChatAssistantShortcode() { setInput(""); setBusy(true); setError(""); + if (!endpoints) { + setError("The assistant backend is not configured."); + setBusy(false); + return; + } try { const response = await fetch(endpoints.chat, { method: "POST", diff --git a/apps/storefront/src/components/CmsPageContent.tsx b/apps/storefront/src/components/CmsPageContent.tsx index 07d46ea..a338657 100644 --- a/apps/storefront/src/components/CmsPageContent.tsx +++ b/apps/storefront/src/components/CmsPageContent.tsx @@ -368,7 +368,7 @@ function NestedWordPressShortcodes({ html, slots }: { html: string; slots: Neste setTargets(slots.map(({ marker }) => contentRef.current?.querySelector(`[data-funkycommerce-render-slot="${marker.slotId}"]`) || null, )); - }, [slots]); + }, [html, slots]); return ( <> diff --git a/apps/storefront/src/components/SmartLinkNavigation.tsx b/apps/storefront/src/components/SmartLinkNavigation.tsx index 9a7b780..e6ca610 100644 --- a/apps/storefront/src/components/SmartLinkNavigation.tsx +++ b/apps/storefront/src/components/SmartLinkNavigation.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef } from "react"; import { useLocation, useNavigate, useNavigationType } from "react-router-dom"; import { normalizeLanguagePath, useLanguage } from "@funky/ui"; -import { BACKEND_ORIGIN } from "@funky/sdk"; +import { BACKEND_BASE_PATH, BACKEND_ORIGIN } from "@funky/sdk"; import { mountHashAnchorScroll, mountSmartLinkNavigation } from "../lib/internalLinks"; import { prefetchStorefrontRoute } from "../lib/routePrefetch"; import { artifactRouteHydrationEnabled } from "../lib/storefrontDocumentWarmup"; @@ -24,6 +24,7 @@ export function SmartLinkNavigation() { document, window, backendOrigin: BACKEND_ORIGIN, + backendBasePath: BACKEND_BASE_PATH, normalizeTo: (to) => normalizeLanguagePath(to, languageCode, configuredLanguageCodes), navigate: artifactRouteHydrationEnabled ? (to) => void prefetch(to).then(() => navigate(to), () => navigate(to)) diff --git a/apps/storefront/src/lib/blikPayment.ts b/apps/storefront/src/lib/blikPayment.ts index 74a6d05..90ff468 100644 --- a/apps/storefront/src/lib/blikPayment.ts +++ b/apps/storefront/src/lib/blikPayment.ts @@ -9,11 +9,11 @@ export type BlikReconciliationResponse = { }; export function buildBlikReconciliationRequest( - backendOrigin: string, + backendBaseUrl: string, order: Pick, billingEmail: string, ): { url: string; body: Record } { - const url = new URL(`${backendOrigin}/index.php`); + const url = new URL("index.php", backendBaseUrl); url.searchParams.set( "rest_route", `/funkycommerce/v1/orders/${order.order_id}/reconcile-blik`, diff --git a/apps/storefront/src/lib/blog.ts b/apps/storefront/src/lib/blog.ts index 4e17d26..0553639 100644 --- a/apps/storefront/src/lib/blog.ts +++ b/apps/storefront/src/lib/blog.ts @@ -1,6 +1,8 @@ import type { PostCardData } from "@funky/ui"; import { + BACKEND_BASE_URL, BACKEND_ORIGIN, + backendPathFromUrl, graphqlRequest, STOREFRONT_BACKEND_PROFILE, type GraphqlResponse, @@ -464,7 +466,7 @@ async function getRestListingTerms( if (!BACKEND_ORIGIN) { throw new Error("The blog taxonomy endpoint is unavailable because no backend origin is configured"); } - const url = new URL(`/wp-json/wp/v2/${resource}`, BACKEND_ORIGIN); + const url = new URL(`wp-json/wp/v2/${resource}`, BACKEND_BASE_URL); url.searchParams.set("per_page", "100"); url.searchParams.set("hide_empty", "true"); url.searchParams.set("lang", languageCode); @@ -487,7 +489,7 @@ async function getRestListingTerms( id: String(term.id), name: htmlToPlainText(term.name), slug: term.slug, - uri: new URL(term.link, BACKEND_ORIGIN).pathname, + uri: backendPathFromUrl(term.link, ""), count: Number.isFinite(term.count) ? term.count : 0, description: htmlToPlainText(description), }]; diff --git a/apps/storefront/src/lib/chatAssistant.ts b/apps/storefront/src/lib/chatAssistant.ts index 7aa5dbd..3240ba0 100644 --- a/apps/storefront/src/lib/chatAssistant.ts +++ b/apps/storefront/src/lib/chatAssistant.ts @@ -1,10 +1,11 @@ -export const CHAT_ASSISTANT_REST_NAMESPACE = "/wp-json/funkycommerce-ai-assistant/v1"; +export const CHAT_ASSISTANT_REST_NAMESPACE = "wp-json/funkycommerce-ai-assistant/v1"; -export function chatAssistantEndpoints(backendOrigin: string) { - const origin = backendOrigin.replace(/\/+$/, ""); +export function chatAssistantEndpoints(backendBaseUrl: string | undefined) { + if (!backendBaseUrl) return null; + const baseUrl = backendBaseUrl.replace(/\/+$/, "") + "/"; return { - config: `${origin}${CHAT_ASSISTANT_REST_NAMESPACE}/config`, - chat: `${origin}${CHAT_ASSISTANT_REST_NAMESPACE}/chat`, + config: `${baseUrl}${CHAT_ASSISTANT_REST_NAMESPACE}/config`, + chat: `${baseUrl}${CHAT_ASSISTANT_REST_NAMESPACE}/chat`, }; } diff --git a/apps/storefront/src/lib/checkoutAccount.ts b/apps/storefront/src/lib/checkoutAccount.ts index bfd2d77..15e482b 100644 --- a/apps/storefront/src/lib/checkoutAccount.ts +++ b/apps/storefront/src/lib/checkoutAccount.ts @@ -1,5 +1,5 @@ import { normalizeBackendError } from "@funky/ui"; -import { BACKEND_ORIGIN } from "@funky/sdk"; +import { BACKEND_BASE_URL } from "@funky/sdk"; import type { StoreApiCheckoutResult } from "./wcStoreApi"; import { buildCheckoutOrderClaimRequest } from "./checkoutAccountRequest"; @@ -8,11 +8,11 @@ export async function claimCheckoutOrder( billingEmail: string, authToken: string, ): Promise { - if (!BACKEND_ORIGIN || !order.order_key) { + if (!BACKEND_BASE_URL || !order.order_key) { throw new Error("The store did not return the credentials needed to link this order."); } - const request = buildCheckoutOrderClaimRequest(BACKEND_ORIGIN, order, billingEmail); + const request = buildCheckoutOrderClaimRequest(BACKEND_BASE_URL, order, billingEmail); const response = await fetch(request.url, { method: "POST", cache: "no-store", diff --git a/apps/storefront/src/lib/checkoutAccountRequest.ts b/apps/storefront/src/lib/checkoutAccountRequest.ts index 00f6f11..eaaa191 100644 --- a/apps/storefront/src/lib/checkoutAccountRequest.ts +++ b/apps/storefront/src/lib/checkoutAccountRequest.ts @@ -4,11 +4,11 @@ type CheckoutOrderClaim = { }; export function buildCheckoutOrderClaimRequest( - backendOrigin: string, + backendBaseUrl: string, order: CheckoutOrderClaim, billingEmail: string, ): { url: string; body: Record } { - const url = new URL(`${backendOrigin}/index.php`); + const url = new URL("index.php", backendBaseUrl); url.searchParams.set( "rest_route", `/funkycommerce/v1/orders/${order.order_id}/claim-customer`, diff --git a/apps/storefront/src/lib/cmsBehaviors.ts b/apps/storefront/src/lib/cmsBehaviors.ts index 14745a6..f5ca00c 100644 --- a/apps/storefront/src/lib/cmsBehaviors.ts +++ b/apps/storefront/src/lib/cmsBehaviors.ts @@ -452,6 +452,7 @@ export function mountCmsBehaviors(container: HTMLElement, showCodeControls = tru pendingCleanup?.(); }); } + const requests = new Map>(); const addRequest = (element: HTMLElement, id: string) => { diff --git a/apps/storefront/src/lib/commerce.ts b/apps/storefront/src/lib/commerce.ts index b3423e4..8a7a39f 100644 --- a/apps/storefront/src/lib/commerce.ts +++ b/apps/storefront/src/lib/commerce.ts @@ -5,6 +5,7 @@ import type { ProductReview, ProductVariationCombo, ProductVariationOption } fro import { graphqlRequest, hasOnlyMissingGraphqlFields, + backendPathFromUrl, restUrl, STOREFRONT_BACKEND_PROFILE, } from "@funky/sdk"; @@ -1267,12 +1268,7 @@ async function getOptionalStoreApiCatalogProducts(context: string): Promise term.slug ? [term.slug] : []) || [], tagSlugs: product.productTags?.nodes.flatMap((term) => term.slug ? [term.slug] : []) || [], brandSlugs: product.productBrands?.nodes.flatMap((term) => term.slug ? [term.slug] : []) || [], diff --git a/apps/storefront/src/lib/commerceCompatibility.test.ts b/apps/storefront/src/lib/commerceCompatibility.test.ts index ddd1dca..2fe36a3 100644 --- a/apps/storefront/src/lib/commerceCompatibility.test.ts +++ b/apps/storefront/src/lib/commerceCompatibility.test.ts @@ -38,6 +38,7 @@ const appSource = readFileSync(new URL("../App.tsx", import.meta.url), "utf8"); test("localized Woo product permalinks route to product details", () => { assert.match(appSource, /path="\/sklep\/:slug" element=\{}/); + assert.match(appSource, /path="\/produkt\/:slug" element=\{}/); assert.match(appSource, /path="\/kategoria-produktu\/\*" element=\{}/); }); diff --git a/apps/storefront/src/lib/downloads.ts b/apps/storefront/src/lib/downloads.ts index 07ef21a..14a9c93 100644 --- a/apps/storefront/src/lib/downloads.ts +++ b/apps/storefront/src/lib/downloads.ts @@ -1,5 +1,5 @@ import { normalizeBackendError } from "@funky/ui"; -import { BACKEND_ORIGIN } from "@funky/sdk"; +import { BACKEND_BASE_URL } from "@funky/sdk"; import { HttpRequestError } from "./requestRetry"; export type OrderDownload = { @@ -67,9 +67,9 @@ export async function getOrderDownloadAccess(input: { billingEmail?: string; accessToken?: string; }): Promise { - if (!BACKEND_ORIGIN) throw new Error("The download service is not configured."); + if (!BACKEND_BASE_URL) throw new Error("The download service is not configured."); - const url = new URL(`${BACKEND_ORIGIN}/index.php`); + const url = new URL("index.php", BACKEND_BASE_URL); url.searchParams.set("rest_route", `/funkycommerce/v1/orders/${input.orderId}/downloads`); if (input.orderKey) url.searchParams.set("key", input.orderKey); if (input.billingEmail) url.searchParams.set("email", input.billingEmail); diff --git a/apps/storefront/src/lib/internalLinks.ts b/apps/storefront/src/lib/internalLinks.ts index f3b01c6..820afc0 100644 --- a/apps/storefront/src/lib/internalLinks.ts +++ b/apps/storefront/src/lib/internalLinks.ts @@ -17,6 +17,7 @@ export type LinkEnvironment = { currentUrl: string; storefrontOrigin: string; backendOrigin?: string; + backendBasePath?: string; }; const NATIVE_PROTOCOLS = new Set(["mailto:", "tel:", "javascript:", "data:", "blob:"]); @@ -31,7 +32,7 @@ const NON_CONTENT_BACKEND_PATHS = [ export function normalizeContentHref( href: string, - environment: Pick & { baseUrl?: string }, + environment: Pick & { baseUrl?: string }, ): string { const value = href.trim(); if (!value) return value; @@ -43,7 +44,11 @@ export function normalizeContentHref( url.origin === environment.storefrontOrigin || (url.origin === environment.backendOrigin && isBackendContentUrl(url)) ) { - return `${url.pathname}${url.search}${url.hash}`; + const basePath = environment.backendBasePath?.replace(/\/+$/, "") || ""; + const path = basePath && (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`)) + ? url.pathname.slice(basePath.length) || "/" + : url.pathname; + return `${path.startsWith("/") ? path : `/${path}`}${url.search}${url.hash}`; } return url.href; } catch { @@ -200,6 +205,7 @@ type SmartLinkControllerOptions = { document: Document; window: Window; backendOrigin?: string; + backendBasePath?: string; normalizeTo?: (to: string) => string; navigate: (to: string) => void; prefetch: (to: string) => Promise | unknown; @@ -213,6 +219,7 @@ export function mountSmartLinkNavigation({ document, window, backendOrigin, + backendBasePath, normalizeTo = (to) => to, navigate, prefetch, @@ -247,6 +254,7 @@ export function mountSmartLinkNavigation({ const mapped = normalizeContentHref(rawHref, { storefrontOrigin: window.location.origin, backendOrigin, + backendBasePath, baseUrl: window.location.href, }); if (!mapped.startsWith("/") || mapped.startsWith("//")) continue; diff --git a/apps/storefront/src/lib/navigation.test.ts b/apps/storefront/src/lib/navigation.test.ts index dd1375f..0921a4e 100644 --- a/apps/storefront/src/lib/navigation.test.ts +++ b/apps/storefront/src/lib/navigation.test.ts @@ -147,7 +147,7 @@ test("optional language discovery cannot invalidate layout configuration", () => assert.doesNotMatch(navigationQuery, /languages\s*\{/); assert.match(navigationSource, /getStorefrontLanguages\(\)/); assert.match(navigationSource, /getPolylangRestLanguages\(AbortSignal\.timeout\(3_000\)\)/); - assert.match(navigationSource, /new URL\("\/wp-json\/", BACKEND_ORIGIN\)/); + assert.match(navigationSource, /new URL\("wp-json\/", BACKEND_BASE_URL\)/); assert.match(navigationSource, /restIndex\.namespaces\.some\(\(namespace\) => namespace === "pll\/v1"\)/); assert.doesNotMatch(navigationSource, /const \[graphqlResponse, restLanguageResult\] = await Promise\.all\(/); assert.match( @@ -212,7 +212,7 @@ test("navigation compatibility fallback is explicit for minimal backends without assert.match(navigationSource, /"promoHtml"/); assert.match(navigationSource, /"headerIconMedia"/); assert.match(navigationSource, /"aiAssistant"/); - assert.match(navigationSource, /\/wp-json\/pll\/v1\/languages/); + assert.match(navigationSource, /wp-json\/pll\/v1\/languages/); assert.match(navigationSource, /getOptionalPolylangRestLanguages\(\)/); assert.doesNotMatch(navigationSource, /query StorefrontNavigationCompatible \{\s*menus\(first: 100\) \{\s*nodes \{\s*id\s*databaseId\s*name\s*slug\s*locations/); assert.match(navigationSource, /return \[];\n\s*\}/); diff --git a/apps/storefront/src/lib/navigation.ts b/apps/storefront/src/lib/navigation.ts index 305ee10..7837afb 100644 --- a/apps/storefront/src/lib/navigation.ts +++ b/apps/storefront/src/lib/navigation.ts @@ -26,7 +26,7 @@ import type { NewsletterPopupVariant } from "@funky/ui/src/layout/NewsletterSign import type { CurrencyOption, LanguageOption, SocialPlatform } from "@funky/ui/src/locale/options.ts"; import type { ProductPageLayout } from "@funky/ui/src/state/productPageLayout.ts"; import type { RelatedProductsColumns } from "@funky/ui/src/state/LayoutPreferencesContext.tsx"; -import { BACKEND_ORIGIN, graphqlRequest, hasOnlyMissingGraphqlFields, STOREFRONT_BACKEND_PROFILE } from "@funky/sdk"; +import { BACKEND_BASE_PATH, BACKEND_BASE_URL, BACKEND_ORIGIN, graphqlRequest, hasOnlyMissingGraphqlFields, STOREFRONT_BACKEND_PROFILE } from "@funky/sdk"; import { mapBackendLanguages, mapBackendSiteLanguages } from "./languageMapping.ts"; import { normalizeContentHref } from "./internalLinks.ts"; import { mapFooterColumns, mapMenuItems, type RawMenuItem } from "./menuMapping.ts"; @@ -1119,7 +1119,7 @@ async function getPolylangRestLanguages( signal?: AbortSignal, ): Promise { const restIndexResponse = await fetch( - new URL("/wp-json/", BACKEND_ORIGIN), + new URL("wp-json/", BACKEND_BASE_URL), signal ? { signal } : undefined, ); if (!restIndexResponse.ok) { @@ -1132,7 +1132,7 @@ async function getPolylangRestLanguages( if (!restIndex.namespaces.some((namespace) => namespace === "pll/v1")) return []; const response = await fetch( - new URL("/wp-json/pll/v1/languages", BACKEND_ORIGIN), + new URL("wp-json/pll/v1/languages", BACKEND_BASE_URL), signal ? { signal } : undefined, ); if (response.status === 404) return []; @@ -2046,6 +2046,7 @@ function normalizeMenuHref(value: string | null, parentHref: string | undefined) return normalizeContentHref(href, { storefrontOrigin, backendOrigin: BACKEND_ORIGIN, + backendBasePath: BACKEND_BASE_PATH, baseUrl: BACKEND_ORIGIN || storefrontOrigin, }); } diff --git a/apps/storefront/src/lib/pageStyles.test.ts b/apps/storefront/src/lib/pageStyles.test.ts index 1eeb586..2d3097b 100644 --- a/apps/storefront/src/lib/pageStyles.test.ts +++ b/apps/storefront/src/lib/pageStyles.test.ts @@ -7,6 +7,7 @@ import { applyThemePresetVariables, createWordPressElementTypographyCss, mountPageStyles, + rebaseWordPressCssUrls, sanitizeWordPressFontFaces, sanitizeWordPressStylesheetUrls, WORDPRESS_BLOCK_COMPATIBILITY_CSS, @@ -18,6 +19,31 @@ const photoHeroSource = readFileSync(new URL("../components/HeroMock.tsx", impor const videoHeroSource = readFileSync(new URL("../components/VideoHero.tsx", import.meta.url), "utf8"); const themeProviderSource = readFileSync(new URL("../state/wordpressThemeStyles.tsx", import.meta.url), "utf8"); +test("rebases WordPress CSS asset URLs against the installation base", () => { + const css = rebaseWordPressCssUrls( + ".hero{background-image:url('/wp-content/uploads/hero.webp')} .icon{src:url(data:image/svg+xml;base64,abc)}", + "https://colorcloud.dev/aqua-bar-wp/", + ); + assert.match(css, /https:\/\/colorcloud\.dev\/aqua-bar-wp\/wp-content\/uploads\/hero\.webp/); + assert.match(css, /url\(data:image\/svg\+xml;base64,abc\)/); +}); + +test("keeps root-install and already-prefixed CSS URLs stable", () => { + const css = rebaseWordPressCssUrls( + ".root{background:url('/wp-content/a.png')} .prefixed{background:url('/aqua-bar-wp/wp-content/b.png')} .cdn{background:url('//cdn.example.test/a.png')}", + "https://colorcloud.dev/aqua-bar-wp/", + ); + assert.match(css, /https:\/\/colorcloud\.dev\/aqua-bar-wp\/wp-content\/a\.png/); + assert.match(css, /https:\/\/colorcloud\.dev\/aqua-bar-wp\/wp-content\/b\.png/); + assert.match(css, /url\(['"]?\/\/cdn\.example\.test\/a\.png['"]?\)/); + + const rootInstallCss = rebaseWordPressCssUrls( + ".root{background:url('/wp-content/a.png')}", + "https://root.example.test/", + ); + assert.match(rootInstallCss, /https:\/\/root\.example\.test\/wp-content\/a\.png/); +}); + test("applied theme CSS does not wait for background data revalidation", () => { assert.match(themeProviderSource, /Boolean\(data\) && appliedData === data/); assert.doesNotMatch(themeProviderSource, /\bisLoading\b|\bisRevalidating\b/); diff --git a/apps/storefront/src/lib/pageStyles.ts b/apps/storefront/src/lib/pageStyles.ts index aa85019..2bca15f 100644 --- a/apps/storefront/src/lib/pageStyles.ts +++ b/apps/storefront/src/lib/pageStyles.ts @@ -1,5 +1,6 @@ import type { CmsThemeStyles } from "./pages"; import { splitCustomCss } from "./customCssLayers.mjs"; +import { BACKEND_BASE_URL } from "@funky/sdk"; type MountedStyle = { count: number; @@ -644,18 +645,18 @@ export function mountPageStyles(styles: CmsThemeStyles | null | undefined, trust ? [] : [ mountInlineStyle("wordpress-font-faces", sanitizeWordPressFontFaces(styles?.fontFaceStyles || "")), - mountInlineStyle("wordpress-global-styles", sanitizeWordPressGlobalStyles(styles?.globalStyles || "")), + mountInlineStyle("wordpress-global-styles", sanitizeWordPressGlobalStyles(styles?.globalStyles || "", BACKEND_BASE_URL)), // Core block styles must follow global element defaults so variants such as // Button "Outline" can override the generic button background and border. ...stylesheets.map(mountStylesheet), - mountInlineStyle("wordpress-custom-css", customCss.critical), + mountInlineStyle("wordpress-custom-css", rebaseWordPressCssUrls(customCss.critical, BACKEND_BASE_URL)), // Always mounted last so block semantics survive Tailwind and theme collisions. mountInlineStyle("wordpress-block-compatibility", WORDPRESS_BLOCK_COMPATIBILITY_CSS, true), ].filter((key): key is string => Boolean(key)); orderMountedPageStyles(); const deferredTimer = !hasStaticStyles && customCss.deferred ? setTimeout(() => { - const key = mountInlineStyle("wordpress-custom-css-deferred", customCss.deferred); + const key = mountInlineStyle("wordpress-custom-css-deferred", rebaseWordPressCssUrls(customCss.deferred, BACKEND_BASE_URL)); if (key) keys.push(key); orderMountedPageStyles(); }, 2_000) @@ -928,8 +929,42 @@ export function createWordPressElementTypographyCss(globalStyles: string): strin return rules.join(""); } -export function sanitizeWordPressGlobalStyles(css: string): string { - return css; +export function sanitizeWordPressGlobalStyles(css: string, backendBaseUrl?: string): string { + return rebaseWordPressCssUrls(css, backendBaseUrl); +} + +/** CSS returned by WordPress is mounted inline, so root-relative assets would + * otherwise resolve against the storefront origin instead of the WP install. */ +export function rebaseWordPressCssUrls(css: string, backendBaseUrl?: string): string { + if (!backendBaseUrl || !css) return css; + return css.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (match, quote: string, value: string) => { + const trimmed = value.trim(); + if ( + !trimmed + || trimmed.startsWith("#") + || trimmed.startsWith("data:") + || trimmed.startsWith("blob:") + || trimmed.startsWith("//") + || /^[a-z][a-z\d+\-.]*:/i.test(trimmed) + ) { + return match; + } + try { + const base = new URL(backendBaseUrl); + const basePath = base.pathname.replace(/\/+$/, ""); + const resolved = trimmed.startsWith("/") + ? new URL( + trimmed === basePath || (basePath && trimmed.startsWith(`${basePath}/`)) + ? trimmed + : `${basePath}/${trimmed.replace(/^\/+/, "")}`, + base.origin, + ).toString() + : new URL(trimmed, backendBaseUrl).toString(); + return `url(${quote}${resolved}${quote})`; + } catch { + return match; + } + }); } function presetVariable(category: string, slug: string): string { diff --git a/apps/storefront/src/lib/payments.ts b/apps/storefront/src/lib/payments.ts index 0bf7974..6f6b9db 100644 --- a/apps/storefront/src/lib/payments.ts +++ b/apps/storefront/src/lib/payments.ts @@ -14,7 +14,7 @@ import { withDigitalCheckoutAddress, withDigitalGatewayAddress, } from "./checkoutContext"; -import { BACKEND_ORIGIN, graphqlRequest, isBackendConfigured } from "@funky/sdk"; +import { BACKEND_BASE_URL, graphqlRequest, isBackendConfigured } from "@funky/sdk"; import { getStripe } from "./stripe"; import { type CryptoAsset, @@ -410,7 +410,7 @@ export async function completeStripePayment( ("paymentIntent" in result ? result.paymentIntent?.id : result.setupIntent?.id) || confirmation.clientSecret.split("_secret_", 1)[0]; - if (!intentId || !BACKEND_ORIGIN) { + if (!intentId || !BACKEND_BASE_URL) { return { ok: false, error: result.error?.message || "Stripe did not return the payment intent needed to finish the order.", @@ -419,7 +419,7 @@ export async function completeStripePayment( } const verificationRequest = buildStripeOrderStatusRequest( - BACKEND_ORIGIN, + BACKEND_BASE_URL, confirmation, intentId, order.order_key, @@ -481,7 +481,7 @@ export async function completeBlikPayment( order: StoreApiCheckoutResult, billingEmail: string, ): Promise { - if (!BACKEND_ORIGIN || !order.order_key) { + if (!BACKEND_BASE_URL || !order.order_key) { return { ok: false, error: "The store did not return the credentials needed to verify the BLIK payment.", @@ -489,7 +489,7 @@ export async function completeBlikPayment( }; } - const request = buildBlikReconciliationRequest(BACKEND_ORIGIN, order, billingEmail); + const request = buildBlikReconciliationRequest(BACKEND_BASE_URL, order, billingEmail); const deadline = Date.now() + BLIK_RECONCILIATION_TIMEOUT_MS; while (Date.now() < deadline) { diff --git a/apps/storefront/src/lib/postArchives.ts b/apps/storefront/src/lib/postArchives.ts index 0ee31be..21f6229 100644 --- a/apps/storefront/src/lib/postArchives.ts +++ b/apps/storefront/src/lib/postArchives.ts @@ -1,5 +1,6 @@ import type { PostCardData } from "@funky/ui"; import { + BACKEND_BASE_URL, BACKEND_ORIGIN, graphqlRequest, STOREFRONT_BACKEND_PROFILE, @@ -440,7 +441,7 @@ export async function getPostTaxonomyArchive( async function getRestTerms(taxonomy: PostTaxonomy, languageCode: string): Promise { const resource = taxonomy === "category" ? "categories" : "tags"; - const url = new URL(`/wp-json/wp/v2/${resource}`, BACKEND_ORIGIN); + const url = new URL(`wp-json/wp/v2/${resource}`, BACKEND_BASE_URL); url.searchParams.set("per_page", "100"); url.searchParams.set("hide_empty", "true"); url.searchParams.set("lang", languageCode); diff --git a/apps/storefront/src/lib/productInquiry.test.ts b/apps/storefront/src/lib/productInquiry.test.ts index ed2c2fb..d15444b 100644 --- a/apps/storefront/src/lib/productInquiry.test.ts +++ b/apps/storefront/src/lib/productInquiry.test.ts @@ -26,10 +26,11 @@ test("resolveProductPriceMode: a positive price always resolves to purchase", () assert.equal(resolveProductPriceMode(19.99, "inquiry", "inquiry"), "purchase"); }); -test("resolveProductPriceMode: an explicit price of 0 is always preserved as free, even under an inquiry default", () => { - assert.equal(resolveProductPriceMode(0, "inherit", "inquiry"), "free"); - assert.equal(resolveProductPriceMode(0, "inquiry", "inquiry"), "free"); +test("resolveProductPriceMode: a zero price follows the effective no-price behavior", () => { + assert.equal(resolveProductPriceMode(0, "inherit", "inquiry"), "inquiry"); + assert.equal(resolveProductPriceMode(0, "inquiry", "inquiry"), "inquiry"); assert.equal(resolveProductPriceMode(0, "free", "inquiry"), "free"); + assert.equal(resolveProductPriceMode(0, "inherit", "free"), "free"); }); test("resolveProductPriceMode: no price data defers to the per-product override when set", () => { diff --git a/apps/storefront/src/lib/productPriceMode.ts b/apps/storefront/src/lib/productPriceMode.ts index 1c4391e..d6895a9 100644 --- a/apps/storefront/src/lib/productPriceMode.ts +++ b/apps/storefront/src/lib/productPriceMode.ts @@ -14,18 +14,17 @@ export type ProductPriceBehavior = "inherit" | "free" | "inquiry"; * override, and the store-wide default have all been reconciled. */ export type ResolvedProductPriceMode = "purchase" | "free" | "inquiry"; -/** Resolve how a product's pricing should be presented, preserving explicit free - * products (an actual price of 0) even when the effective no-price behaviour is - * "inquiry" — only products with *no* price data at all are subject to the - * no-price behaviour. Per-product `priceBehavior` overrides take precedence over - * the store-wide `noPriceBehavior` default unless it is `"inherit"`. */ +/** Resolve how a product's pricing should be presented. WooCommerce commonly + * exposes an unpriced product as `0`, so zero follows the effective no-price + * behaviour. Per-product `priceBehavior` overrides take precedence over the + * store-wide `noPriceBehavior` default unless it is `"inherit"`. */ export function resolveProductPriceMode( priceAmount: number | undefined, priceBehavior: ProductPriceBehavior, noPriceBehavior: NoPriceBehavior, ): ResolvedProductPriceMode { if (priceAmount !== undefined && priceAmount > 0) return "purchase"; - if (priceAmount === 0) return "free"; + if (priceAmount === 0 && priceBehavior === "free") return "free"; const effective = priceBehavior === "inherit" ? noPriceBehavior : priceBehavior; return effective === "inquiry" ? "inquiry" : "free"; } diff --git a/apps/storefront/src/lib/protectedPages.ts b/apps/storefront/src/lib/protectedPages.ts index 0c2e5c5..8b0723c 100644 --- a/apps/storefront/src/lib/protectedPages.ts +++ b/apps/storefront/src/lib/protectedPages.ts @@ -1,4 +1,4 @@ -import { BACKEND_ORIGIN } from "@funky/sdk"; +import { BACKEND_BASE_URL, BACKEND_ORIGIN } from "@funky/sdk"; import { authStore } from "./auth.ts"; import type { CmsPage } from "./pages.ts"; import { shouldProbeProtectedPage } from "./protectedPageEligibility.ts"; @@ -36,7 +36,7 @@ async function protectedPageRequest(uri: string, password?: string): Promise = { Accept: "application/json", diff --git a/apps/storefront/src/lib/restRouteAvailability.ts b/apps/storefront/src/lib/restRouteAvailability.ts index 1bc46e7..8802487 100644 --- a/apps/storefront/src/lib/restRouteAvailability.ts +++ b/apps/storefront/src/lib/restRouteAvailability.ts @@ -1,4 +1,4 @@ -import { BACKEND_ORIGIN } from "@funky/sdk"; +import { BACKEND_BASE_URL } from "@funky/sdk"; type RestEndpoint = { methods?: string[]; @@ -28,16 +28,16 @@ export function restIndexHasRoute(index: unknown, route: string, method = "GET") } export function createRestRouteAvailability( - backendOrigin: string | undefined, + backendBaseUrl: string | undefined, request: typeof fetch = fetch, ) { const unavailableRoutes = new Set(); let restIndexRequest: Promise | undefined; function getRestIndex(): Promise { - if (!backendOrigin) return Promise.resolve(null); + if (!backendBaseUrl) return Promise.resolve(null); if (!restIndexRequest) { - restIndexRequest = request(new URL("/wp-json/", backendOrigin), { + restIndexRequest = request(new URL("wp-json/", backendBaseUrl), { headers: { Accept: "application/json" }, cache: "no-store", }) @@ -52,7 +52,7 @@ export function createRestRouteAvailability( } async function isAvailable(route: string, method = "GET"): Promise { - if (!backendOrigin) return false; + if (!backendBaseUrl) return false; const normalizedMethod = method.toUpperCase(); const key = `${normalizedMethod}:${normalizeRoute(route)}`; if (unavailableRoutes.has(key)) return false; @@ -74,7 +74,7 @@ export function createRestRouteAvailability( return { isAvailable, cacheUnavailableFromResponse }; } -const backendRestRoutes = createRestRouteAvailability(BACKEND_ORIGIN); +const backendRestRoutes = createRestRouteAvailability(BACKEND_BASE_URL); export const isRestRouteAvailable = backendRestRoutes.isAvailable; export const cacheRestRouteUnavailableFromResponse = backendRestRoutes.cacheUnavailableFromResponse; diff --git a/apps/storefront/src/lib/searchRest.ts b/apps/storefront/src/lib/searchRest.ts index 1dec9b2..94347bf 100644 --- a/apps/storefront/src/lib/searchRest.ts +++ b/apps/storefront/src/lib/searchRest.ts @@ -1,5 +1,6 @@ import type { SearchResultItem } from "@funky/ui"; import { + backendPathFromUrl, BACKEND_ORIGIN, STOREFRONT_DEFAULT_LANGUAGE, STOREFRONT_EXPECTED_LOCALES, @@ -78,7 +79,7 @@ async function searchRestResource( backendOrigin: string, fetchImpl: typeof fetch, ): Promise { - const url = new URL(`/wp-json/wp/v2/${resource}`, backendOrigin); + const url = new URL(`wp-json/wp/v2/${resource}`, backendOrigin); url.searchParams.set("search", query); url.searchParams.set("per_page", resource === "posts" ? "6" : "4"); if (languageCode) url.searchParams.set("lang", languageCode); @@ -125,7 +126,9 @@ function restPathname(link: string | undefined, backendOrigin: string): string | if (!link) return null; try { const url = new URL(link, backendOrigin); - return url.origin === new URL(backendOrigin).origin ? url.pathname : null; + return url.origin === new URL(backendOrigin).origin + ? backendPathFromUrl(url.toString(), "") + : null; } catch { return null; } diff --git a/apps/storefront/src/lib/stripePaymentData.ts b/apps/storefront/src/lib/stripePaymentData.ts index 91bfd8e..9393266 100644 --- a/apps/storefront/src/lib/stripePaymentData.ts +++ b/apps/storefront/src/lib/stripePaymentData.ts @@ -105,13 +105,13 @@ export function parseStripeConfirmationRedirect( } export function buildStripeOrderStatusRequest( - backendOrigin: string, + backendBaseUrl: string, confirmation: StripeConfirmationRedirect, intentId: string, orderKey: string, paymentMethodId?: string, ): { url: string; body: URLSearchParams } { - const url = new URL(backendOrigin); + const url = new URL(".", backendBaseUrl); url.searchParams.set("wc-ajax", "wc_stripe_update_order_status"); const body = new URLSearchParams({ diff --git a/apps/storefront/src/lib/wcStoreApi.ts b/apps/storefront/src/lib/wcStoreApi.ts index 4ae7f8e..24ae265 100644 --- a/apps/storefront/src/lib/wcStoreApi.ts +++ b/apps/storefront/src/lib/wcStoreApi.ts @@ -9,7 +9,7 @@ * A `Nonce` is only needed when there is not yet a Cart-Token; sending both can make * concurrent requests race on a rotating nonce. */ -import { BACKEND_ORIGIN, isBackendConfigured } from "@funky/sdk"; +import { BACKEND_BASE_URL, isBackendConfigured } from "@funky/sdk"; import { normalizeBackendError } from "@funky/ui"; import { getAuthTokenForRequest } from "./auth"; import { buildStoreApiHeaders, isStoreApiNonceError } from "./storeApiAuth"; @@ -22,9 +22,9 @@ let mutationQueue: Promise = Promise.resolve(); let sessionInitialization: Promise> | null = null; function storeApiUrl(route: string): string | undefined { - if (!BACKEND_ORIGIN) return undefined; + if (!BACKEND_BASE_URL) return undefined; const [path, query = ""] = route.split("?", 2); - const url = new URL(`${BACKEND_ORIGIN}/index.php`); + const url = new URL("index.php", BACKEND_BASE_URL); url.searchParams.set("rest_route", `/wc/store/v1/${path.replace(/^\/+/, "")}`); new URLSearchParams(query).forEach((value, key) => url.searchParams.append(key, value)); return url.toString(); diff --git a/apps/storefront/src/main.tsx b/apps/storefront/src/main.tsx index 57eefb8..1823d72 100644 --- a/apps/storefront/src/main.tsx +++ b/apps/storefront/src/main.tsx @@ -4,6 +4,7 @@ import { activatePrerenderImages } from "./lib/prerenderImages"; import { captureInitialCmsPageMarkup } from "./lib/prerenderSnapshot"; import { installStaticDocumentWarmup } from "./lib/storefrontDocumentWarmup"; import { startRecentOrdersNotifier } from "./lib/recentOrders"; +import { backendUrl } from "@funky/sdk"; activateDeferredThemeStyles(document); @@ -132,12 +133,12 @@ const initialFontsReady = document.fonts.status === "loaded" }); const initialVisualsReady = Promise.all([domReady, initialFontsReady]); if (prerenderedChrome?.dataset.recentOrdersEnabled === "true") { - const endpoint = new URL( - "/wp-json/funkycommerce/v1/recent-orders", - import.meta.env.VITE_GRAPHQL_ENDPOINT?.trim() || location.origin, - ).toString(); - window.setTimeout(() => { - void startRecentOrdersNotifier({ + const endpoint = backendUrl("wp-json/funkycommerce/v1/recent-orders"); + if (!endpoint) { + console.warn("Recent-order notifications are enabled but no backend is configured."); + } else { + window.setTimeout(() => { + void startRecentOrdersNotifier({ enabled: true, itemCount: Number(prerenderedChrome.dataset.recentOrdersCount), intervalSeconds: Number(prerenderedChrome.dataset.recentOrdersInterval), @@ -148,7 +149,8 @@ if (prerenderedChrome?.dataset.recentOrdersEnabled === "true") { .catch((error) => { console.error("Recent-order notifications could not start.", error); }); - }, deferFlagshipHomeHydration ? 10_000 : 2_000); + }, deferFlagshipHomeHydration ? 10_000 : 2_000); + } } const currentDocumentKey = `${location.pathname}${location.search}${location.hash}`; let savedReloadScrollY = 0; diff --git a/packages/sdk/src/environment.ts b/packages/sdk/src/environment.ts index 3dff882..8f9dd62 100644 --- a/packages/sdk/src/environment.ts +++ b/packages/sdk/src/environment.ts @@ -57,12 +57,54 @@ export const BACKEND_ORIGIN: string | undefined = GRAPHQL_ENDPOINT ? new URL(GRAPHQL_ENDPOINT, typeof window === "undefined" ? "http://localhost" : window.location.origin).origin : undefined; +/** The WordPress installation base URL, preserving a subdirectory such as + * `https://example.test/aqua-bar-wp/` from a GraphQL endpoint below it. */ +export const BACKEND_BASE_URL: string | undefined = GRAPHQL_ENDPOINT + ? (() => { + const endpoint = new URL( + GRAPHQL_ENDPOINT, + typeof window === "undefined" ? "http://localhost" : window.location.origin, + ); + endpoint.pathname = endpoint.pathname.replace(/\/+$/, ""); + return new URL(".", endpoint).toString(); + })() + : undefined; +export const BACKEND_BASE_PATH = BACKEND_BASE_URL + ? new URL(BACKEND_BASE_URL).pathname.replace(/\/+$/, "") + : ""; + /** Builds an absolute REST URL on the backend origin from a `wp-json`-relative path, * e.g. `restUrl("custom/v1/abandoned-cart")` → * `https://v1.superfunky.pro/wp-json/custom/v1/abandoned-cart`. Returns `undefined` * when no backend is configured. */ export function restUrl(path: string): string | undefined { - if (!BACKEND_ORIGIN) return undefined; + if (!BACKEND_BASE_URL) return undefined; const cleanPath = path.replace(/^\/+/, ""); - return `${BACKEND_ORIGIN}/wp-json/${cleanPath}`; + return new URL(`wp-json/${cleanPath}`, BACKEND_BASE_URL).toString(); +} + +/** Builds an absolute URL relative to the WordPress installation base. */ +export function backendUrl(path: string): string | undefined { + if (!BACKEND_BASE_URL) return undefined; + return new URL(path.replace(/^\/+/, ""), BACKEND_BASE_URL).toString(); +} + +/** Converts a backend permalink into a storefront path by removing the + * WordPress installation directory from its pathname. */ +export function backendPathFromUrl(value: string | undefined, fallback: string): string { + if (!value) return fallback; + try { + const url = new URL(value, BACKEND_BASE_URL || "http://localhost"); + const basePath = BACKEND_BASE_PATH; + if ( + basePath + && (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`)) + ) { + const path = url.pathname.slice(basePath.length) || "/"; + return path.startsWith("/") ? path : `/${path}`; + } + return url.pathname || fallback; + } catch { + return fallback; + } } diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index f42039b..d5eadc9 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -4,6 +4,10 @@ export type { } from "@funky/shared"; export { BACKEND_ORIGIN, + BACKEND_BASE_URL, + BACKEND_BASE_PATH, + backendPathFromUrl, + backendUrl, GRAPHQL_ENDPOINT, isBackendConfigured, restUrl, diff --git a/packages/ui/src/catalog/ProductCard.tsx b/packages/ui/src/catalog/ProductCard.tsx index 2297271..708c2d8 100644 --- a/packages/ui/src/catalog/ProductCard.tsx +++ b/packages/ui/src/catalog/ProductCard.tsx @@ -518,18 +518,20 @@ export function ProductCard({ ) : null} -
- {convertedRangeLabel && !selectedVariation ? ( - {convertedRangeLabel} - ) : ( - <> - {selectedPriceLabel} - {selectedCompareAtPriceLabel ? ( - {selectedCompareAtPriceLabel} - ) : null} - - )} -
+ {hasPrice ? ( +
+ {convertedRangeLabel && !selectedVariation ? ( + {convertedRangeLabel} + ) : ( + <> + {selectedPriceLabel} + {selectedCompareAtPriceLabel ? ( + {selectedCompareAtPriceLabel} + ) : null} + + )} +
+ ) : null} {(isVariation || product.productType === "variable") && product.variationOptions?.length ? (
diff --git a/packages/ui/src/catalog/productCardPrice.test.ts b/packages/ui/src/catalog/productCardPrice.test.ts index 613ffd3..5a4d552 100644 --- a/packages/ui/src/catalog/productCardPrice.test.ts +++ b/packages/ui/src/catalog/productCardPrice.test.ts @@ -3,7 +3,8 @@ import test from "node:test"; import { hasProductCardPrice } from "./productCardPrice.ts"; test("recognizes explicit zero as a valid product price", () => { - assert.equal(hasProductCardPrice({ priceAmount: 0, priceLabel: "" }), true); + assert.equal(hasProductCardPrice({ priceAmount: 0, priceLabel: "" }), false); + assert.equal(hasProductCardPrice({ priceAmount: 0, priceLabel: "0,00 zł" }), false); }); test("recognizes numeric, range, variation, and legacy label prices", () => { diff --git a/packages/ui/src/catalog/productCardPrice.ts b/packages/ui/src/catalog/productCardPrice.ts index 9a2f0dd..1ca5614 100644 --- a/packages/ui/src/catalog/productCardPrice.ts +++ b/packages/ui/src/catalog/productCardPrice.ts @@ -5,15 +5,18 @@ export type ProductCardPriceInput = { variationPriceAmounts?: number[]; }; -/** Treat an explicit zero as a real price while rejecting products whose pricing data - * is entirely absent. Labels remain supported for legacy/mock card data. */ +/** Treat zero as missing pricing data so unpriced products use their learn-more + * action instead of showing a misleading free price. Labels remain supported for + * legacy/mock card data when no numeric amount is available. */ export function hasProductCardPrice({ priceAmount, priceLabel, priceRangeLabel, variationPriceAmounts = [], }: ProductCardPriceInput): boolean { - if (Number.isFinite(priceAmount) && (priceAmount ?? -1) >= 0) return true; - if (variationPriceAmounts.some((amount) => Number.isFinite(amount) && amount >= 0)) return true; + if (Number.isFinite(priceAmount)) return (priceAmount ?? 0) > 0; + if (variationPriceAmounts.length) { + return variationPriceAmounts.some((amount) => Number.isFinite(amount) && amount > 0); + } return Boolean(priceRangeLabel?.trim() || priceLabel?.trim()); }