@ecomweb/storefront-kit 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/public.js +9 -2
- package/dist/config/public.js.map +1 -1
- package/dist/config.d.ts +3 -3
- package/dist/index.d.ts +27 -16
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -1
- package/dist/middleware/create-storefront-middleware.js +12 -0
- package/dist/middleware/create-storefront-middleware.js.map +1 -1
- package/dist/middleware.d.ts +2 -2
- package/dist/{mode-1ZKDELPZ.d.ts → mode-YNx2aOtQ.d.ts} +1 -1
- package/dist/server.d.ts +5 -2
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/store/store-context.js.map +1 -1
- package/dist/stores/basic-settings.js +4 -48
- package/dist/stores/basic-settings.js.map +1 -1
- package/dist/theme/define.js +11 -0
- package/dist/theme/define.js.map +1 -0
- package/dist/theme/index.js +6 -0
- package/dist/theme/index.js.map +1 -0
- package/dist/theme/preview-cookie.js +32 -0
- package/dist/theme/preview-cookie.js.map +1 -0
- package/dist/theme/read-preview-token.js +10 -0
- package/dist/theme/read-preview-token.js.map +1 -0
- package/dist/theme/settings-context.js +33 -0
- package/dist/theme/settings-context.js.map +1 -0
- package/dist/theme/style.js +21 -0
- package/dist/theme/style.js.map +1 -0
- package/dist/theme.d.ts +53 -0
- package/package.json +6 -2
- package/dist/{schema-CEMKsCwh.d.ts → schema-Tc0qRs-Q.d.ts} +2 -2
package/dist/config/public.js
CHANGED
|
@@ -19,7 +19,14 @@ const SINGLE_ENV_NAME_OF = {
|
|
|
19
19
|
apiUrl: "ECOMWEB_API_URL",
|
|
20
20
|
appUrl: "SITE_URL"
|
|
21
21
|
};
|
|
22
|
-
const DEFAULT_SINGLE_API_URL = "https://apibase.ecomweb.app";
|
|
22
|
+
const DEFAULT_SINGLE_API_URL = "https://apibase.ecomweb.app/api/v1";
|
|
23
|
+
function originOf(url) {
|
|
24
|
+
try {
|
|
25
|
+
return new URL(url).origin;
|
|
26
|
+
} catch {
|
|
27
|
+
return url;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
23
30
|
function parseMulti(env) {
|
|
24
31
|
return parseOrThrow(
|
|
25
32
|
publicConfigSchema,
|
|
@@ -57,7 +64,7 @@ function parseSingle(env) {
|
|
|
57
64
|
mode: "single",
|
|
58
65
|
storeRef: envValue(env, "NEXT_PUBLIC_ECOMWEB_STORE_REF"),
|
|
59
66
|
apiUrl,
|
|
60
|
-
assetBaseUrl: (envValue(env, "NEXT_PUBLIC_ECOMWEB_ASSET_URL") ?? apiUrl).replace(/\/$/, ""),
|
|
67
|
+
assetBaseUrl: (envValue(env, "NEXT_PUBLIC_ECOMWEB_ASSET_URL") ?? originOf(apiUrl)).replace(/\/$/, ""),
|
|
61
68
|
appUrl: envValue(env, "NEXT_PUBLIC_SITE_URL")?.replace(/\/$/, ""),
|
|
62
69
|
storefrontApiKey: envValue(env, "NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY"),
|
|
63
70
|
platformDomainSuffix: null,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/public.ts"],"sourcesContent":["import { resolveMode } from \"./mode\";\nimport {\n envValue,\n logLevelOf,\n parseOrThrow,\n publicConfigSchema,\n sampleRateOf,\n type EnvSource,\n type PublicConfig,\n} from \"./schema\";\n\nconst MULTI_ENV_NAME_OF: Record<string, string> = {\n apiUrl: \"NEXT_PUBLIC_API_URL\",\n storefrontApiKey: \"NEXT_PUBLIC_PLATFORM_API_KEY\",\n appUrl: \"NEXT_PUBLIC_APP_URL\",\n platformDomainSuffix: \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\",\n primaryMenuRef: \"NEXT_PUBLIC_PRIMARY_MENU_REF\",\n};\n\n/** next.config.mjs derives these NEXT_PUBLIC_ names from ECOMWEB_* / SITE_URL. */\nconst SINGLE_ENV_NAME_OF: Record<string, string> = {\n storeRef: \"ECOMWEB_STORE_REF\",\n storefrontApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n apiUrl: \"ECOMWEB_API_URL\",\n appUrl: \"SITE_URL\",\n};\n\nconst DEFAULT_SINGLE_API_URL = \"https://apibase.ecomweb.app\";\n\nfunction parseMulti(env: EnvSource): PublicConfig {\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"multi\",\n storeRef: null,\n apiUrl: envValue(env, \"NEXT_PUBLIC_API_URL\")?.replace(/\\/$/, \"\"),\n assetBaseUrl: (envValue(env, \"NEXT_PUBLIC_ASSET_BASE_URL\") ?? \"\").replace(\n /\\/$/,\n \"\"\n ),\n appUrl: envValue(env, \"NEXT_PUBLIC_APP_URL\") ?? \"https://ecomweb.app\",\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n platformDomainSuffix:\n envValue(env, \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\") ?? \"ecomsite.app\",\n appBaseUrlFlag: envValue(env, \"NEXT_PUBLIC_APP_BASE_URL\"),\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef:\n envValue(env, \"NEXT_PUBLIC_PRIMARY_MENU_REF\") ?? \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n MULTI_ENV_NAME_OF\n );\n}\n\nfunction parseSingle(env: EnvSource): PublicConfig {\n const apiUrl = (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_API_URL\") ?? DEFAULT_SINGLE_API_URL\n ).replace(/\\/$/, \"\");\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"single\",\n storeRef: envValue(env, \"NEXT_PUBLIC_ECOMWEB_STORE_REF\"),\n apiUrl,\n assetBaseUrl: (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_ASSET_URL\") ?? apiUrl\n ).replace(/\\/$/, \"\"),\n appUrl: envValue(env, \"NEXT_PUBLIC_SITE_URL\")?.replace(/\\/$/, \"\"),\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n platformDomainSuffix: null,\n appBaseUrlFlag: undefined,\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef: \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n SINGLE_ENV_NAME_OF\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parsePublicConfig(env: EnvSource): PublicConfig {\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: PublicConfig | undefined;\n\n/** Specs that stub env per test call this in beforeEach. */\nexport function resetPublicConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * Every NEXT_PUBLIC_ var is spelled out literally: Next inlines only literal\n * `process.env.NEXT_PUBLIC_X` reads into client bundles.\n */\nexport function publicConfig(): PublicConfig {\n return (cached ??= parsePublicConfig({\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n ECOMWEB_MODE:\n typeof window === \"undefined\" ? process.env.ECOMWEB_MODE : undefined,\n // multi\n NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,\n NEXT_PUBLIC_ASSET_BASE_URL: process.env.NEXT_PUBLIC_ASSET_BASE_URL,\n NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,\n NEXT_PUBLIC_PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY,\n NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX:\n process.env.NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX,\n NEXT_PUBLIC_APP_BASE_URL: process.env.NEXT_PUBLIC_APP_BASE_URL,\n NEXT_PUBLIC_PRIMARY_MENU_REF: process.env.NEXT_PUBLIC_PRIMARY_MENU_REF,\n // single\n NEXT_PUBLIC_ECOMWEB_STORE_REF: process.env.NEXT_PUBLIC_ECOMWEB_STORE_REF,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n NEXT_PUBLIC_ECOMWEB_API_URL: process.env.NEXT_PUBLIC_ECOMWEB_API_URL,\n NEXT_PUBLIC_ECOMWEB_ASSET_URL: process.env.NEXT_PUBLIC_ECOMWEB_ASSET_URL,\n NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,\n // both\n NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS:\n process.env.NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS,\n NEXT_PUBLIC_LOG_LEVEL: process.env.NEXT_PUBLIC_LOG_LEVEL,\n NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE:\n process.env.NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE,\n }));\n}\n"],"mappings":"AAAA,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,MAAM,oBAA4C;AAAA,EAChD,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,QAAQ;AAAA,EACR,sBAAsB;AAAA,EACtB,gBAAgB;AAClB;AAGA,MAAM,qBAA6C;AAAA,EACjD,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,QAAQ;AAAA,EACR,QAAQ;AACV;
|
|
1
|
+
{"version":3,"sources":["../../src/config/public.ts"],"sourcesContent":["import { resolveMode } from \"./mode\";\nimport {\n envValue,\n logLevelOf,\n parseOrThrow,\n publicConfigSchema,\n sampleRateOf,\n type EnvSource,\n type PublicConfig,\n} from \"./schema\";\n\nconst MULTI_ENV_NAME_OF: Record<string, string> = {\n apiUrl: \"NEXT_PUBLIC_API_URL\",\n storefrontApiKey: \"NEXT_PUBLIC_PLATFORM_API_KEY\",\n appUrl: \"NEXT_PUBLIC_APP_URL\",\n platformDomainSuffix: \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\",\n primaryMenuRef: \"NEXT_PUBLIC_PRIMARY_MENU_REF\",\n};\n\n/** next.config.mjs derives these NEXT_PUBLIC_ names from ECOMWEB_* / SITE_URL. */\nconst SINGLE_ENV_NAME_OF: Record<string, string> = {\n storeRef: \"ECOMWEB_STORE_REF\",\n storefrontApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n apiUrl: \"ECOMWEB_API_URL\",\n appUrl: \"SITE_URL\",\n};\n\n// Production serves the API under /api/v1 (Kong strips the prefix) and stored\n// assets at the origin's /storage/v1.\nconst DEFAULT_SINGLE_API_URL = \"https://apibase.ecomweb.app/api/v1\";\n\n/** Stored assets live at the API host's /storage/v1, whatever path the API has. */\nfunction originOf(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return url; // the schema reports the invalid API URL\n }\n}\n\nfunction parseMulti(env: EnvSource): PublicConfig {\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"multi\",\n storeRef: null,\n apiUrl: envValue(env, \"NEXT_PUBLIC_API_URL\")?.replace(/\\/$/, \"\"),\n assetBaseUrl: (envValue(env, \"NEXT_PUBLIC_ASSET_BASE_URL\") ?? \"\").replace(\n /\\/$/,\n \"\"\n ),\n appUrl: envValue(env, \"NEXT_PUBLIC_APP_URL\") ?? \"https://ecomweb.app\",\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n platformDomainSuffix:\n envValue(env, \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\") ?? \"ecomsite.app\",\n appBaseUrlFlag: envValue(env, \"NEXT_PUBLIC_APP_BASE_URL\"),\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef:\n envValue(env, \"NEXT_PUBLIC_PRIMARY_MENU_REF\") ?? \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n MULTI_ENV_NAME_OF\n );\n}\n\nfunction parseSingle(env: EnvSource): PublicConfig {\n const apiUrl = (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_API_URL\") ?? DEFAULT_SINGLE_API_URL\n ).replace(/\\/$/, \"\");\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"single\",\n storeRef: envValue(env, \"NEXT_PUBLIC_ECOMWEB_STORE_REF\"),\n apiUrl,\n assetBaseUrl: (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_ASSET_URL\") ?? originOf(apiUrl)\n ).replace(/\\/$/, \"\"),\n appUrl: envValue(env, \"NEXT_PUBLIC_SITE_URL\")?.replace(/\\/$/, \"\"),\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n platformDomainSuffix: null,\n appBaseUrlFlag: undefined,\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef: \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n SINGLE_ENV_NAME_OF\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parsePublicConfig(env: EnvSource): PublicConfig {\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: PublicConfig | undefined;\n\n/** Specs that stub env per test call this in beforeEach. */\nexport function resetPublicConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * Every NEXT_PUBLIC_ var is spelled out literally: Next inlines only literal\n * `process.env.NEXT_PUBLIC_X` reads into client bundles.\n */\nexport function publicConfig(): PublicConfig {\n return (cached ??= parsePublicConfig({\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n ECOMWEB_MODE:\n typeof window === \"undefined\" ? process.env.ECOMWEB_MODE : undefined,\n // multi\n NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,\n NEXT_PUBLIC_ASSET_BASE_URL: process.env.NEXT_PUBLIC_ASSET_BASE_URL,\n NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,\n NEXT_PUBLIC_PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY,\n NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX:\n process.env.NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX,\n NEXT_PUBLIC_APP_BASE_URL: process.env.NEXT_PUBLIC_APP_BASE_URL,\n NEXT_PUBLIC_PRIMARY_MENU_REF: process.env.NEXT_PUBLIC_PRIMARY_MENU_REF,\n // single\n NEXT_PUBLIC_ECOMWEB_STORE_REF: process.env.NEXT_PUBLIC_ECOMWEB_STORE_REF,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n NEXT_PUBLIC_ECOMWEB_API_URL: process.env.NEXT_PUBLIC_ECOMWEB_API_URL,\n NEXT_PUBLIC_ECOMWEB_ASSET_URL: process.env.NEXT_PUBLIC_ECOMWEB_ASSET_URL,\n NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBL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AAI;AAAA,IACjC,8BAA8B,QAAQ,IAAI;AAAA,IAC1C,oCACE,QAAQ,IAAI;AAAA,IACd,0BAA0B,QAAQ,IAAI;AAAA,IACtC,8BAA8B,QAAQ,IAAI;AAAA;AAAA,IAE1C,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,qCACE,QAAQ,IAAI;AAAA,IACd,6BAA6B,QAAQ,IAAI;AAAA,IACzC,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,sBAAsB,QAAQ,IAAI;AAAA;AAAA,IAElC,0CACE,QAAQ,IAAI;AAAA,IACd,uBAAuB,QAAQ,IAAI;AAAA,IACnC,oCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
|
package/dist/config.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { E as EnvSource, P as PublicConfig } from './schema-
|
|
2
|
-
export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-
|
|
3
|
-
export { S as StorefrontMode, r as resolveMode } from './mode-
|
|
1
|
+
import { E as EnvSource, P as PublicConfig } from './schema-Tc0qRs-Q.js';
|
|
2
|
+
export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-Tc0qRs-Q.js';
|
|
3
|
+
export { S as StorefrontMode, r as resolveMode } from './mode-YNx2aOtQ.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/** Parses the variables of the mode `env` selects (see resolveMode). */
|
package/dist/index.d.ts
CHANGED
|
@@ -2,9 +2,10 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
2
2
|
import * as react from 'react';
|
|
3
3
|
import { ReactNode } from 'react';
|
|
4
4
|
import * as _ecomweb_sdk from '@ecomweb/sdk';
|
|
5
|
-
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, OrderStatus, Order, CreateOrderRequest, LocationAreasResponse, LocationArea, StoreConfig } from '@ecomweb/sdk';
|
|
5
|
+
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, OrderStatus, Order, CreateOrderRequest, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues } from '@ecomweb/sdk';
|
|
6
6
|
import currencyJs from 'currency.js';
|
|
7
7
|
import { AxiosRequestConfig, AxiosInstance } from 'axios';
|
|
8
|
+
export { AnyThemeDefinition, HomePageSlotProps, LayoutSlotProps, ThemeComponents, ThemeDefinition, ThemeInfo, ThemeSlot, ThemeSlotName, ThemeSlotProps, defineSchema, defineTheme } from './theme.js';
|
|
8
9
|
import { Metadata } from 'next';
|
|
9
10
|
|
|
10
11
|
type NoticeKind = "success" | "error" | "info";
|
|
@@ -687,6 +688,7 @@ declare const sdk: {
|
|
|
687
688
|
orders: _ecomweb_sdk.OrdersApi;
|
|
688
689
|
blog: _ecomweb_sdk.BlogApi;
|
|
689
690
|
stores: _ecomweb_sdk.StoresApi;
|
|
691
|
+
themes: _ecomweb_sdk.ThemesApi;
|
|
690
692
|
search: _ecomweb_sdk.SearchApi;
|
|
691
693
|
banners: _ecomweb_sdk.BannersApi;
|
|
692
694
|
shipping: _ecomweb_sdk.ShippingApi;
|
|
@@ -716,6 +718,7 @@ declare function createStoreSdk(storeRef: string): {
|
|
|
716
718
|
orders: _ecomweb_sdk.OrdersApi;
|
|
717
719
|
blog: _ecomweb_sdk.BlogApi;
|
|
718
720
|
stores: _ecomweb_sdk.StoresApi;
|
|
721
|
+
themes: _ecomweb_sdk.ThemesApi;
|
|
719
722
|
search: _ecomweb_sdk.SearchApi;
|
|
720
723
|
banners: _ecomweb_sdk.BannersApi;
|
|
721
724
|
shipping: _ecomweb_sdk.ShippingApi;
|
|
@@ -878,34 +881,42 @@ declare function buildStoreUrl(store: {
|
|
|
878
881
|
} | StoreConfig | StoreConfigurationInfo, path?: string): string;
|
|
879
882
|
|
|
880
883
|
/**
|
|
881
|
-
* The store
|
|
882
|
-
*
|
|
883
|
-
*
|
|
884
|
+
* The store's checkout and register legal links, from `settings.legal_links`.
|
|
885
|
+
* Everything else the page builder's theme_config held is a theme setting
|
|
886
|
+
* now (`useThemeSettings`).
|
|
884
887
|
*/
|
|
885
888
|
type Loose = Record<string, any>;
|
|
886
889
|
interface StoreLike {
|
|
887
890
|
settings?: Loose | null;
|
|
888
|
-
theme_config?: Loose | null;
|
|
889
891
|
}
|
|
890
892
|
interface BasicSettings {
|
|
891
|
-
brandColor: string | null;
|
|
892
|
-
backgroundColor: string | null;
|
|
893
|
-
navigation: {
|
|
894
|
-
mainMenuRef: string | null;
|
|
895
|
-
topbarMessage: string | null;
|
|
896
|
-
customerSupportMenuRef: string | null;
|
|
897
|
-
aboutUsMenuRef: string | null;
|
|
898
|
-
copyrightText: string | null;
|
|
899
|
-
};
|
|
900
893
|
legalLinks: {
|
|
901
894
|
termsLink: string | null;
|
|
902
895
|
policyLink: string | null;
|
|
903
896
|
};
|
|
904
|
-
homepageCollectionSlug: string | null;
|
|
905
897
|
}
|
|
898
|
+
/** @deprecated Read `store.settings.legal_links` directly. */
|
|
906
899
|
declare function readBasicSettings(store: StoreLike): BasicSettings;
|
|
907
900
|
declare function resolveLegalHref(link: string | null, fallbackPath: string | null, toStoreUrl: (path: string) => string): string;
|
|
908
901
|
|
|
902
|
+
interface ThemeSettingsContextValue {
|
|
903
|
+
themeId: string;
|
|
904
|
+
settings: ThemeValues;
|
|
905
|
+
}
|
|
906
|
+
/** The published (or previewed) theme's resolved settings, for client components. */
|
|
907
|
+
declare function ThemeSettingsProvider({ themeId, settings, children, }: ThemeSettingsContextValue & {
|
|
908
|
+
children: ReactNode;
|
|
909
|
+
}): react_jsx_runtime.JSX.Element;
|
|
910
|
+
/** Pass the theme's settings type: `useThemeSettings<MyThemeSettings>()`. */
|
|
911
|
+
declare function useThemeSettings<T = ThemeValues>(): T;
|
|
912
|
+
declare function useThemeId(): string;
|
|
913
|
+
|
|
914
|
+
/** A `:root{…}` rule from a theme's custom properties; null when empty. */
|
|
915
|
+
declare function themeStyleCss(vars: Record<string, string> | null | undefined): string | null;
|
|
916
|
+
declare function ThemeStyle({ vars, }: {
|
|
917
|
+
vars: Record<string, string> | null | undefined;
|
|
918
|
+
}): react_jsx_runtime.JSX.Element | null;
|
|
919
|
+
|
|
909
920
|
declare const getCachedStore: (storeRef: string, options?: {
|
|
910
921
|
includeConfig?: boolean;
|
|
911
922
|
includeSettings?: boolean;
|
|
@@ -965,4 +976,4 @@ declare function getLogLevel(): LogLevel;
|
|
|
965
976
|
declare function shouldLog(currentLevel: LogLevel, messageLevel: LogLevel): boolean;
|
|
966
977
|
declare function applyConsoleFilter(level?: LogLevel): void;
|
|
967
978
|
|
|
968
|
-
export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, createStoreSdk, deriveOrderProgress, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isStoreSuspendedError, loadWards, money, pollPaymentState, publicApiClient, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
|
|
979
|
+
export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, createStoreSdk, deriveOrderProgress, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isStoreSuspendedError, loadWards, money, pollPaymentState, publicApiClient, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
|
package/dist/index.js
CHANGED
|
@@ -65,6 +65,13 @@ import {
|
|
|
65
65
|
import { resolveStoreRef, storeApiPath, storePath } from "./store-scope/index.js";
|
|
66
66
|
import { buildStoreUrl } from "./store-scope/store-url.js";
|
|
67
67
|
import { readBasicSettings, resolveLegalHref } from "./stores/basic-settings.js";
|
|
68
|
+
import { defineSchema, defineTheme } from "./theme/define.js";
|
|
69
|
+
import {
|
|
70
|
+
ThemeSettingsProvider,
|
|
71
|
+
useThemeId,
|
|
72
|
+
useThemeSettings
|
|
73
|
+
} from "./theme/settings-context.js";
|
|
74
|
+
import { ThemeStyle, themeStyleCss } from "./theme/style.js";
|
|
68
75
|
import { getCachedStore } from "./stores/cached.js";
|
|
69
76
|
import {
|
|
70
77
|
SUSPENDED_STORE_METADATA,
|
|
@@ -81,9 +88,13 @@ export {
|
|
|
81
88
|
STOCK_ISSUE_TOAST_DESCRIPTION,
|
|
82
89
|
SUSPENDED_STORE_METADATA,
|
|
83
90
|
StorefrontKitProvider,
|
|
91
|
+
ThemeSettingsProvider,
|
|
92
|
+
ThemeStyle,
|
|
84
93
|
applyConsoleFilter,
|
|
85
94
|
buildStoreUrl,
|
|
86
95
|
createStoreSdk,
|
|
96
|
+
defineSchema,
|
|
97
|
+
defineTheme,
|
|
87
98
|
deriveOrderProgress,
|
|
88
99
|
errorCopy,
|
|
89
100
|
errorCopyFor,
|
|
@@ -123,6 +134,7 @@ export {
|
|
|
123
134
|
shouldPollForConfirmation,
|
|
124
135
|
storeApiPath,
|
|
125
136
|
storePath,
|
|
137
|
+
themeStyleCss,
|
|
126
138
|
unwrap,
|
|
127
139
|
unwrapOrNull,
|
|
128
140
|
useAuth,
|
|
@@ -139,6 +151,8 @@ export {
|
|
|
139
151
|
useStoreData,
|
|
140
152
|
useStoreId,
|
|
141
153
|
useStoreLocale,
|
|
154
|
+
useThemeId,
|
|
155
|
+
useThemeSettings,
|
|
142
156
|
useWards,
|
|
143
157
|
validatePasswordAgainstPolicy,
|
|
144
158
|
withSuspendedStoreMetadataFallback
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type { OrderHandoff } from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport { formatShippingAmount } from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAEjC,SAAS,wBAAwB;AACjC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type { OrderHandoff } from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport { formatShippingAmount } from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAEjC,SAAS,wBAAwB;AACjC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAY1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,qBAAqB;AAC1C,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { publicNextUrl } from "../request/public-url.js";
|
|
2
|
+
import { applyThemePreview, hasThemePreview } from "../theme/preview-cookie.js";
|
|
2
3
|
import { NextResponse } from "next/server";
|
|
3
4
|
import { authCookiePath, writeAuthCookies } from "../auth/cookies.js";
|
|
4
5
|
import {
|
|
@@ -71,6 +72,13 @@ async function multiTenant(req) {
|
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
74
|
const storeRef = hostStoreRef ?? storeRefFromPath(pathname);
|
|
75
|
+
if (storeRef) {
|
|
76
|
+
const preview = applyThemePreview(
|
|
77
|
+
req,
|
|
78
|
+
authCookiePath(storeRef, !!hostStoreRef)
|
|
79
|
+
);
|
|
80
|
+
if (preview) return preview;
|
|
81
|
+
}
|
|
74
82
|
if (!hostStoreRef && storeRef) {
|
|
75
83
|
const prefix = multiTenantStorePath(storeRef);
|
|
76
84
|
if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {
|
|
@@ -112,6 +120,7 @@ async function multiTenant(req) {
|
|
|
112
120
|
} else {
|
|
113
121
|
response = NextResponse.next(init);
|
|
114
122
|
}
|
|
123
|
+
if (hasThemePreview(req)) response.headers.set("x-robots-tag", "noindex");
|
|
115
124
|
if (rotated && storeRef) {
|
|
116
125
|
writeAuthCookies(
|
|
117
126
|
response,
|
|
@@ -126,6 +135,8 @@ async function singleStore(req) {
|
|
|
126
135
|
const pathname = req.nextUrl.pathname;
|
|
127
136
|
if (METADATA_FILES.includes(pathname)) return NextResponse.next();
|
|
128
137
|
const storeRef = publicConfig().storeRef;
|
|
138
|
+
const preview = applyThemePreview(req, authCookiePath(storeRef, true));
|
|
139
|
+
if (preview) return preview;
|
|
129
140
|
try {
|
|
130
141
|
const redirect = await lookupRedirect(storeRef, pathname);
|
|
131
142
|
if (redirect) {
|
|
@@ -142,6 +153,7 @@ async function singleStore(req) {
|
|
|
142
153
|
headers: downstreamRequestHeaders(req, true, storeRef, rotated)
|
|
143
154
|
}
|
|
144
155
|
});
|
|
156
|
+
if (hasThemePreview(req)) response.headers.set("x-robots-tag", "noindex");
|
|
145
157
|
if (rotated) {
|
|
146
158
|
writeAuthCookies(
|
|
147
159
|
response,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level\n if (METADATA_FILES.includes(pathname)) {\n return NextResponse.next();\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n\n if (hostIdentifiesStore) {\n try {\n const { storeRef, domain, isSubDomain, suspended } =\n await getStoreByHost(host);\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to custom domain\n if (isSubDomain && domain && domain !== host) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated = storeRef ? await refreshIfNearExpiry(req, storeRef) : null;\n const init = {\n request: {\n headers: downstreamRequestHeaders(req, !!hostStoreRef, storeRef, rotated),\n },\n };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n if (rotated && storeRef) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (rotated) {\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, true)\n );\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, redirects, session refresh.\n * - single: redirects and session refresh only.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB;AAG/B,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AASA,SAAS,iBAAiB,UAAiC;AACzD,QAAM,QAAQ,oBAAoB,KAAK,QAAQ;AAC/C,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,WAAO,mBAAmB,MAAM,CAAC,CAAC,KAAK;AAAA,EACzC,QAAQ;AACN,WAAO,MAAM,CAAC;AAAA,EAChB;AACF;AASA,SAAS,sBACP,KACA,UACA,aAAa,IACC;AACd,QAAM,cAAc,cAAc,GAAG;AACrC,cAAY,WAAW,GAAG,UAAU,GAAG,SAAS,gBAAgB;AAChE,SAAO,aAAa,SAAS,aAAa,EAAE,QAAQ,SAAS,cAAc,CAAC;AAC9E;AAEA,eAAe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Y,KAAyC;AAClE,QAAM,WAAW,IAAI,QAAQ;AAC7B,MAAI,eAAe,SAAS,QAAQ,EAAG,QAAO,aAAa,KAAK;AAEhE,QAAM,WAAW,aAAa,EAAE;AAEhC,MAAI;AACF,UAAM,WAAW,MAAM,eAAe,UAAU,QAAQ;AACxD,QAAI,UAAU;AACZ,YAAM,MAAM,cAAc,GAAG;AAC7B,UAAI,WAAW,SAAS;AACxB,aAAO,aAAa,SAAS,KAAK,EAAE,QAAQ,SAAS,cAAc,CAAC;AAAA,IACtE;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,QAAQ;AACvD,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,SAAS;AACX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe,UAAU,IAAI;AAAA,IAC/B;AAAA,EACF;AACA,SAAO;AACT;AASO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { applyThemePreview, hasThemePreview } from \"../theme/preview-cookie\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level\n if (METADATA_FILES.includes(pathname)) {\n return NextResponse.next();\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n\n if (hostIdentifiesStore) {\n try {\n const { storeRef, domain, isSubDomain, suspended } =\n await getStoreByHost(host);\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to custom domain\n if (isSubDomain && domain && domain !== host) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1).\n if (storeRef) {\n const preview = applyThemePreview(\n req,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n if (preview) return preview;\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated = storeRef ? await refreshIfNearExpiry(req, storeRef) : null;\n const init = {\n request: {\n headers: downstreamRequestHeaders(req, !!hostStoreRef, storeRef, rotated),\n },\n };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n\n if (rotated && storeRef) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const preview = applyThemePreview(req, authCookiePath(storeRef, true));\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, true)\n );\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, redirects, session refresh.\n * - single: redirects and session refresh only.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)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,QAAI,UAAU;AACZ,YAAM,MAAM,cAAc,GAAG;AAC7B,UAAI,WAAW,SAAS;AACxB,aAAO,aAAa,SAAS,KAAK,EAAE,QAAQ,SAAS,cAAc,CAAC;AAAA,IACtE;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,QAAQ;AACvD,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,GAAG,EAAG,UAAS,QAAQ,IAAI,gBAAgB,SAAS;AACxE,MAAI,SAAS;AACX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe,UAAU,IAAI;AAAA,IAC/B;AAAA,EACF;AACA,SAAO;AACT;AASO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
|
package/dist/middleware.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
-
import { S as StorefrontMode } from './mode-
|
|
3
|
-
import './schema-
|
|
2
|
+
import { S as StorefrontMode } from './mode-YNx2aOtQ.js';
|
|
3
|
+
import './schema-Tc0qRs-Q.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/**
|
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextRequest } from 'next/server';
|
|
2
2
|
import { CurrentIdentity } from '@ecomweb/sdk';
|
|
3
|
-
import { E as EnvSource, S as ServerConfig } from './schema-
|
|
3
|
+
import { E as EnvSource, S as ServerConfig } from './schema-Tc0qRs-Q.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -55,4 +55,7 @@ declare function serverConfig(): ServerConfig;
|
|
|
55
55
|
*/
|
|
56
56
|
declare function resolveRootStoreRef(): Promise<string | null>;
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
/** The open theme preview's token, if any (server components only). */
|
|
59
|
+
declare function readThemePreviewToken(): Promise<string | null>;
|
|
60
|
+
|
|
61
|
+
export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, hasCustomerSession, parseServerConfig, readThemePreviewToken, requireSession, resolveRootStoreRef, serverConfig };
|
package/dist/server.js
CHANGED
|
@@ -7,11 +7,13 @@ import {
|
|
|
7
7
|
import { hasCustomerSession } from "./auth/session.js";
|
|
8
8
|
import { parseServerConfig, serverConfig } from "./config/server.js";
|
|
9
9
|
import { resolveRootStoreRef } from "./store-scope/root.js";
|
|
10
|
+
import { readThemePreviewToken } from "./theme/read-preview-token.js";
|
|
10
11
|
export {
|
|
11
12
|
createAuthRoutes,
|
|
12
13
|
createBackendProxy,
|
|
13
14
|
hasCustomerSession,
|
|
14
15
|
parseServerConfig,
|
|
16
|
+
readThemePreviewToken,
|
|
15
17
|
requireSession,
|
|
16
18
|
resolveRootStoreRef,
|
|
17
19
|
serverConfig
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/store/store-context.tsx"],"sourcesContent":["\"use client\";\n\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { createContext, useContext, ReactNode } from \"react\";\n\nimport {\n SupportedCurrency,\n getDefaultLocale,\n isSupportedCurrency,\n} from \"../currency\";\n\ninterface StoreContextData {\n store: StoreConfigurationInfo;\n}\n\ninterface StoreProviderProps {\n children: ReactNode;\n store: StoreConfigurationInfo;\n}\n\nconst StoreContext = createContext<StoreContextData | undefined>(undefined);\n\nexport function StoreProvider({ children, store }: StoreProviderProps) {\n const value: StoreContextData = {\n store,\n };\n\n return (\n <StoreContext.Provider value={value}>{children}</StoreContext.Provider>\n );\n}\n\nexport function useStore() {\n const context = useContext(StoreContext);\n if (!context) {\n throw new Error(\"useStore must be used within a StoreProvider\");\n }\n return context;\n}\n\n// Export specific hooks for convenience\nexport function useStoreData() {\n const { store } = useStore();\n return store;\n}\n\n/** The store ref, or null outside a StoreProvider (e.g. a store-level 404). */\nexport function useOptionalStoreId(): string | null {\n return useContext(StoreContext)?.store.ref ?? null;\n}\n\nexport function useStoreId() {\n const { store } = useStore();\n return store.ref;\n}\n\nexport function useStoreSettings() {\n const { store } = useStore();\n return store.settings;\n}\n\nexport function useStoreConfig() {\n const { store } = useStore();\n return store.config;\n}\n\nexport function useBlogSettings() {\n const { store } = useStore();\n\n // Blog settings
|
|
1
|
+
{"version":3,"sources":["../../src/store/store-context.tsx"],"sourcesContent":["\"use client\";\n\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { createContext, useContext, ReactNode } from \"react\";\n\nimport {\n SupportedCurrency,\n getDefaultLocale,\n isSupportedCurrency,\n} from \"../currency\";\n\ninterface StoreContextData {\n store: StoreConfigurationInfo;\n}\n\ninterface StoreProviderProps {\n children: ReactNode;\n store: StoreConfigurationInfo;\n}\n\nconst StoreContext = createContext<StoreContextData | undefined>(undefined);\n\nexport function StoreProvider({ children, store }: StoreProviderProps) {\n const value: StoreContextData = {\n store,\n };\n\n return (\n <StoreContext.Provider value={value}>{children}</StoreContext.Provider>\n );\n}\n\nexport function useStore() {\n const context = useContext(StoreContext);\n if (!context) {\n throw new Error(\"useStore must be used within a StoreProvider\");\n }\n return context;\n}\n\n// Export specific hooks for convenience\nexport function useStoreData() {\n const { store } = useStore();\n return store;\n}\n\n/** The store ref, or null outside a StoreProvider (e.g. a store-level 404). */\nexport function useOptionalStoreId(): string | null {\n return useContext(StoreContext)?.store.ref ?? null;\n}\n\nexport function useStoreId() {\n const { store } = useStore();\n return store.ref;\n}\n\nexport function useStoreSettings() {\n const { store } = useStore();\n return store.settings;\n}\n\nexport function useStoreConfig() {\n const { store } = useStore();\n return store.config;\n}\n\nexport function useBlogSettings() {\n const { store } = useStore();\n\n // Blog settings live in store settings.\n return {\n blogEnabled: store.settings?.is_blog_enabled ?? false,\n blogTitle: store.settings?.blog_title ?? \"Blog\",\n };\n}\n\nexport function useStoreCurrency(): SupportedCurrency {\n const { store } = useStore();\n const currencyCode = store.settings?.currency_code;\n\n // Default to VND for anything we cannot price in.\n if (!currencyCode || !isSupportedCurrency(currencyCode)) {\n return \"VND\";\n }\n\n return currencyCode;\n}\n\nexport function useStoreLocale(): string {\n const currency = useStoreCurrency();\n return getDefaultLocale(currency);\n}\n"],"mappings":";AA4BI;AAzBJ,SAAS,eAAe,kBAA6B;AAErD;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AAWP,MAAM,eAAe,cAA4C,MAAS;AAEnE,SAAS,cAAc,EAAE,UAAU,MAAM,GAAuB;AACrE,QAAM,QAA0B;AAAA,IAC9B;AAAA,EACF;AAEA,SACE,oBAAC,aAAa,UAAb,EAAsB,OAAe,UAAS;AAEnD;AAEO,SAAS,WAAW;AACzB,QAAM,UAAU,WAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO;AACT;AAGO,SAAS,eAAe;AAC7B,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO;AACT;AAGO,SAAS,qBAAoC;AAClD,SAAO,WAAW,YAAY,GAAG,MAAM,OAAO;AAChD;AAEO,SAAS,aAAa;AAC3B,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO,MAAM;AACf;AAEO,SAAS,mBAAmB;AACjC,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO,MAAM;AACf;AAEO,SAAS,iBAAiB;AAC/B,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO,MAAM;AACf;AAEO,SAAS,kBAAkB;AAChC,QAAM,EAAE,MAAM,IAAI,SAAS;AAG3B,SAAO;AAAA,IACL,aAAa,MAAM,UAAU,mBAAmB;AAAA,IAChD,WAAW,MAAM,UAAU,cAAc;AAAA,EAC3C;AACF;AAEO,SAAS,mBAAsC;AACpD,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,QAAM,eAAe,MAAM,UAAU;AAGrC,MAAI,CAAC,gBAAgB,CAAC,oBAAoB,YAAY,GAAG;AACvD,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEO,SAAS,iBAAyB;AACvC,QAAM,WAAW,iBAAiB;AAClC,SAAO,iBAAiB,QAAQ;AAClC;","names":[]}
|
|
@@ -1,57 +1,13 @@
|
|
|
1
1
|
function str(v) {
|
|
2
2
|
return typeof v === "string" && v.trim() !== "" ? v.trim() : null;
|
|
3
3
|
}
|
|
4
|
-
const HEX_COLOR = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
|
5
|
-
function color(v) {
|
|
6
|
-
const s = str(v);
|
|
7
|
-
return s && HEX_COLOR.test(s) ? s : null;
|
|
8
|
-
}
|
|
9
|
-
function first(...values) {
|
|
10
|
-
for (const v of values) if (v !== null) return v;
|
|
11
|
-
return null;
|
|
12
|
-
}
|
|
13
4
|
function readBasicSettings(store) {
|
|
14
|
-
const
|
|
15
|
-
const theme = store.theme_config ?? settings.theme_config ?? {};
|
|
16
|
-
const nav = settings.navigation ?? {};
|
|
17
|
-
const legal = settings.legal_links ?? {};
|
|
5
|
+
const legal = store.settings?.legal_links ?? {};
|
|
18
6
|
return {
|
|
19
|
-
brandColor: first(color(settings.brand_color), color(theme.theme_color)),
|
|
20
|
-
backgroundColor: color(theme.background_color),
|
|
21
|
-
navigation: {
|
|
22
|
-
mainMenuRef: first(
|
|
23
|
-
str(nav.main_menu_ref),
|
|
24
|
-
str(theme.header?.main_menu_ref),
|
|
25
|
-
str(theme.menu?.main_menu)
|
|
26
|
-
),
|
|
27
|
-
topbarMessage: first(
|
|
28
|
-
str(nav.topbar_message),
|
|
29
|
-
str(theme.header?.topbar_message),
|
|
30
|
-
str(theme.topbar?.message)
|
|
31
|
-
),
|
|
32
|
-
customerSupportMenuRef: first(
|
|
33
|
-
str(nav.customer_support_menu_ref),
|
|
34
|
-
str(theme.footer?.customer_support_menu_ref),
|
|
35
|
-
str(theme.menu?.customer_support_menu)
|
|
36
|
-
),
|
|
37
|
-
aboutUsMenuRef: first(
|
|
38
|
-
str(nav.about_us_menu_ref),
|
|
39
|
-
str(theme.footer?.about_us_menu_ref),
|
|
40
|
-
str(theme.menu?.about_us_menu)
|
|
41
|
-
),
|
|
42
|
-
copyrightText: first(
|
|
43
|
-
str(nav.copyright_text),
|
|
44
|
-
str(theme.footer?.copyright_text)
|
|
45
|
-
)
|
|
46
|
-
},
|
|
47
7
|
legalLinks: {
|
|
48
|
-
termsLink:
|
|
49
|
-
policyLink:
|
|
50
|
-
}
|
|
51
|
-
homepageCollectionSlug: first(
|
|
52
|
-
str(settings.homepage_collection_slug),
|
|
53
|
-
str(theme.homepage?.collection_slug)
|
|
54
|
-
)
|
|
8
|
+
termsLink: str(legal.terms),
|
|
9
|
+
policyLink: str(legal.privacy)
|
|
10
|
+
}
|
|
55
11
|
};
|
|
56
12
|
}
|
|
57
13
|
function resolveLegalHref(link, fallbackPath, toStoreUrl) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/stores/basic-settings.ts"],"sourcesContent":["/**\n * The store
|
|
1
|
+
{"version":3,"sources":["../../src/stores/basic-settings.ts"],"sourcesContent":["/**\n * The store's checkout and register legal links, from `settings.legal_links`.\n * Everything else the page builder's theme_config held is a theme setting\n * now (`useThemeSettings`).\n */\n\ntype Loose = Record<string, any>;\n\nexport interface StoreLike {\n settings?: Loose | null;\n}\n\nexport interface BasicSettings {\n legalLinks: { termsLink: string | null; policyLink: string | null };\n}\n\nfunction str(v: unknown): string | null {\n return typeof v === \"string\" && v.trim() !== \"\" ? v.trim() : null;\n}\n\n/** @deprecated Read `store.settings.legal_links` directly. */\nexport function readBasicSettings(store: StoreLike): BasicSettings {\n const legal: Loose = store.settings?.legal_links ?? {};\n return {\n legalLinks: {\n termsLink: str(legal.terms),\n policyLink: str(legal.privacy),\n },\n };\n}\n\nexport function resolveLegalHref(\n link: string | null,\n fallbackPath: string | null,\n toStoreUrl: (path: string) => string\n): string {\n const target = link ?? fallbackPath;\n if (!target) return \"#\";\n if (/^https?:\\/\\//i.test(target)) return target;\n return toStoreUrl(target.startsWith(\"/\") ? target : `/${target}`);\n}\n"],"mappings":"AAgBA,SAAS,IAAI,GAA2B;AACtC,SAAO,OAAO,MAAM,YAAY,EAAE,KAAK,MAAM,KAAK,EAAE,KAAK,IAAI;AAC/D;AAGO,SAAS,kBAAkB,OAAiC;AACjE,QAAM,QAAe,MAAM,UAAU,eAAe,CAAC;AACrD,SAAO;AAAA,IACL,YAAY;AAAA,MACV,WAAW,IAAI,MAAM,KAAK;AAAA,MAC1B,YAAY,IAAI,MAAM,OAAO;AAAA,IAC/B;AAAA,EACF;AACF;AAEO,SAAS,iBACd,MACA,cACA,YACQ;AACR,QAAM,SAAS,QAAQ;AACvB,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,gBAAgB,KAAK,MAAM,EAAG,QAAO;AACzC,SAAO,WAAW,OAAO,WAAW,GAAG,IAAI,SAAS,IAAI,MAAM,EAAE;AAClE;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/theme/define.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport type {\n Banner,\n StoreConfigurationInfo,\n ThemeSchema,\n ThemeSettingsOf,\n} from \"@ecomweb/sdk\";\n\n/**\n * The theme contract (spec: schema-driven themes §5.2). A theme declares its\n * settings with `defineSchema` and fills the slots the shared routes render.\n * Routes load data through the kit and pass it in: a theme is presentation.\n */\n\nexport function defineSchema<const S extends ThemeSchema>(schema: S): S {\n return schema;\n}\n\nexport interface ThemeInfo {\n id: string;\n name: string;\n version: string;\n author: string;\n}\n\n/** A slot may be a server component (async) or a plain one. */\nexport type ThemeSlot<P> = (props: P) => ReactNode | Promise<ReactNode>;\n\nexport interface ThemeSlotProps<V> {\n store: StoreConfigurationInfo;\n storeRef: string;\n settings: V;\n}\n\nexport interface LayoutSlotProps<V> extends ThemeSlotProps<V> {\n children: ReactNode;\n}\n\nexport interface HomePageSlotProps<V> extends ThemeSlotProps<V> {\n banners: Banner[];\n}\n\nexport interface ThemeComponents<V> {\n Layout?: ThemeSlot<LayoutSlotProps<V>>;\n HomePage?: ThemeSlot<HomePageSlotProps<V>>;\n}\n\nexport type ThemeSlotName = keyof ThemeComponents<unknown>;\n\nexport interface ThemeDefinition<S extends ThemeSchema = ThemeSchema> {\n info: ThemeInfo;\n schema: S;\n components: ThemeComponents<ThemeSettingsOf<S>>;\n /** CSS custom properties for :root, from the resolved settings. */\n styles?: (settings: ThemeSettingsOf<S>) => Record<string, string>;\n}\n\n/**\n * A theme of unknown schema, as the registry holds it. Its slots are called\n * with settings resolved against its own schema.\n */\nexport interface AnyThemeDefinition {\n info: ThemeInfo;\n schema: ThemeSchema;\n components: ThemeComponents<any>;\n styles?: (settings: any) => Record<string, string>;\n}\n\nexport function defineTheme<const S extends ThemeSchema>(\n theme: ThemeDefinition<S>\n): ThemeDefinition<S> {\n return theme;\n}\n"],"mappings":"AAcO,SAAS,aAA0C,QAAc;AACtE,SAAO;AACT;AAoDO,SAAS,YACd,OACoB;AACpB,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/theme/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit/theme: authoring a theme (schema, definition, slot\n// types). No side effects, so build tools such as CI's theme export can import\n// it without a storefront configuration.\nexport { defineSchema, defineTheme } from \"./define\";\nexport type {\n AnyThemeDefinition,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./define\";\n"],"mappings":"AAGA,SAAS,cAAc,mBAAmB;","names":[]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { NextResponse } from "next/server";
|
|
2
|
+
import { publicNextUrl } from "../request/public-url.js";
|
|
3
|
+
const THEME_PREVIEW_COOKIE = "ecomweb_theme_preview";
|
|
4
|
+
const THEME_PREVIEW_PARAM = "preview_theme";
|
|
5
|
+
const MAX_TOKEN_LENGTH = 2048;
|
|
6
|
+
const MAX_AGE_SECONDS = 24 * 60 * 60;
|
|
7
|
+
function applyThemePreview(req, cookiePath) {
|
|
8
|
+
const value = req.nextUrl.searchParams.get(THEME_PREVIEW_PARAM);
|
|
9
|
+
if (value === null) return null;
|
|
10
|
+
const url = publicNextUrl(req);
|
|
11
|
+
url.searchParams.delete(THEME_PREVIEW_PARAM);
|
|
12
|
+
const res = NextResponse.redirect(url, 307);
|
|
13
|
+
const valid = value !== "exit" && value.length > 0 && value.length <= MAX_TOKEN_LENGTH;
|
|
14
|
+
res.cookies.set(THEME_PREVIEW_COOKIE, valid ? value : "", {
|
|
15
|
+
httpOnly: true,
|
|
16
|
+
secure: process.env.NODE_ENV === "production",
|
|
17
|
+
sameSite: "lax",
|
|
18
|
+
path: cookiePath,
|
|
19
|
+
maxAge: valid ? MAX_AGE_SECONDS : 0
|
|
20
|
+
});
|
|
21
|
+
return res;
|
|
22
|
+
}
|
|
23
|
+
function hasThemePreview(req) {
|
|
24
|
+
return !!req.cookies.get(THEME_PREVIEW_COOKIE)?.value;
|
|
25
|
+
}
|
|
26
|
+
export {
|
|
27
|
+
THEME_PREVIEW_COOKIE,
|
|
28
|
+
THEME_PREVIEW_PARAM,
|
|
29
|
+
applyThemePreview,
|
|
30
|
+
hasThemePreview
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=preview-cookie.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/theme/preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { publicNextUrl } from \"../request/public-url\";\n\nexport const THEME_PREVIEW_COOKIE = \"ecomweb_theme_preview\";\nexport const THEME_PREVIEW_PARAM = \"preview_theme\";\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/**\n * A dashboard preview link (`?preview_theme=<token>`) becomes an httpOnly\n * cookie scoped to the store, then a redirect to the clean URL, so the token\n * never stays in the address bar or in shared links. `preview_theme=exit`\n * clears it. The API validates the token on every render (themes spec §6.1).\n */\nexport function applyThemePreview(\n req: NextRequest,\n cookiePath: string\n): NextResponse | null {\n const value = req.nextUrl.searchParams.get(THEME_PREVIEW_PARAM);\n if (value === null) return null;\n const url = publicNextUrl(req);\n url.searchParams.delete(THEME_PREVIEW_PARAM);\n const res = NextResponse.redirect(url, 307);\n const valid =\n value !== \"exit\" && value.length > 0 && value.length <= MAX_TOKEN_LENGTH;\n res.cookies.set(THEME_PREVIEW_COOKIE, valid ? value : \"\", {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\nexport function hasThemePreview(req: NextRequest): boolean {\n return !!req.cookies.get(THEME_PREVIEW_COOKIE)?.value;\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAEvB,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AACnC,MAAM,mBAAmB;AACzB,MAAM,kBAAkB,KAAK,KAAK;AAQ3B,SAAS,kBACd,KACA,YACqB;AACrB,QAAM,QAAQ,IAAI,QAAQ,aAAa,IAAI,mBAAmB;AAC9D,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,MAAM,cAAc,GAAG;AAC7B,MAAI,aAAa,OAAO,mBAAmB;AAC3C,QAAM,MAAM,aAAa,SAAS,KAAK,GAAG;AAC1C,QAAM,QACJ,UAAU,UAAU,MAAM,SAAS,KAAK,MAAM,UAAU;AAC1D,MAAI,QAAQ,IAAI,sBAAsB,QAAQ,QAAQ,IAAI;AAAA,IACxD,UAAU;AAAA,IACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,IACjC,UAAU;AAAA,IACV,MAAM;AAAA,IACN,QAAQ,QAAQ,kBAAkB;AAAA,EACpC,CAAC;AACD,SAAO;AACT;AAEO,SAAS,gBAAgB,KAA2B;AACzD,SAAO,CAAC,CAAC,IAAI,QAAQ,IAAI,oBAAoB,GAAG;AAClD;","names":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { cookies } from "next/headers";
|
|
3
|
+
import { THEME_PREVIEW_COOKIE } from "./preview-cookie.js";
|
|
4
|
+
async function readThemePreviewToken() {
|
|
5
|
+
return (await cookies()).get(THEME_PREVIEW_COOKIE)?.value || null;
|
|
6
|
+
}
|
|
7
|
+
export {
|
|
8
|
+
readThemePreviewToken
|
|
9
|
+
};
|
|
10
|
+
//# sourceMappingURL=read-preview-token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/theme/read-preview-token.ts"],"sourcesContent":["import \"server-only\";\nimport { cookies } from \"next/headers\";\nimport { THEME_PREVIEW_COOKIE } from \"./preview-cookie\";\n\n/** The open theme preview's token, if any (server components only). */\nexport async function readThemePreviewToken(): Promise<string | null> {\n return (await cookies()).get(THEME_PREVIEW_COOKIE)?.value || null;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,eAAe;AACxB,SAAS,4BAA4B;AAGrC,eAAsB,wBAAgD;AACpE,UAAQ,MAAM,QAAQ,GAAG,IAAI,oBAAoB,GAAG,SAAS;AAC/D;","names":[]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx } from "react/jsx-runtime";
|
|
3
|
+
import { createContext, useContext, useMemo } from "react";
|
|
4
|
+
const ThemeSettingsContext = createContext(
|
|
5
|
+
null
|
|
6
|
+
);
|
|
7
|
+
function ThemeSettingsProvider({
|
|
8
|
+
themeId,
|
|
9
|
+
settings,
|
|
10
|
+
children
|
|
11
|
+
}) {
|
|
12
|
+
const value = useMemo(() => ({ themeId, settings }), [themeId, settings]);
|
|
13
|
+
return /* @__PURE__ */ jsx(ThemeSettingsContext.Provider, { value, children });
|
|
14
|
+
}
|
|
15
|
+
function useThemeSettingsContext(hook) {
|
|
16
|
+
const ctx = useContext(ThemeSettingsContext);
|
|
17
|
+
if (!ctx) {
|
|
18
|
+
throw new Error(`${hook} must be used inside a ThemeSettingsProvider`);
|
|
19
|
+
}
|
|
20
|
+
return ctx;
|
|
21
|
+
}
|
|
22
|
+
function useThemeSettings() {
|
|
23
|
+
return useThemeSettingsContext("useThemeSettings").settings;
|
|
24
|
+
}
|
|
25
|
+
function useThemeId() {
|
|
26
|
+
return useThemeSettingsContext("useThemeId").themeId;
|
|
27
|
+
}
|
|
28
|
+
export {
|
|
29
|
+
ThemeSettingsProvider,
|
|
30
|
+
useThemeId,
|
|
31
|
+
useThemeSettings
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=settings-context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/theme/settings-context.tsx"],"sourcesContent":["\"use client\";\n\nimport { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type { ThemeValues } from \"@ecomweb/sdk\";\n\ninterface ThemeSettingsContextValue {\n themeId: string;\n settings: ThemeValues;\n}\n\nconst ThemeSettingsContext = createContext<ThemeSettingsContextValue | null>(\n null\n);\n\n/** The published (or previewed) theme's resolved settings, for client components. */\nexport function ThemeSettingsProvider({\n themeId,\n settings,\n children,\n}: ThemeSettingsContextValue & { children: ReactNode }) {\n const value = useMemo(() => ({ themeId, settings }), [themeId, settings]);\n return (\n <ThemeSettingsContext.Provider value={value}>\n {children}\n </ThemeSettingsContext.Provider>\n );\n}\n\nfunction useThemeSettingsContext(hook: string): ThemeSettingsContextValue {\n const ctx = useContext(ThemeSettingsContext);\n if (!ctx) {\n throw new Error(`${hook} must be used inside a ThemeSettingsProvider`);\n }\n return ctx;\n}\n\n/** Pass the theme's settings type: `useThemeSettings<MyThemeSettings>()`. */\nexport function useThemeSettings<T = ThemeValues>(): T {\n return useThemeSettingsContext(\"useThemeSettings\").settings as T;\n}\n\nexport function useThemeId(): string {\n return useThemeSettingsContext(\"useThemeId\").themeId;\n}\n"],"mappings":";AAsBI;AApBJ,SAAS,eAAe,YAAY,eAA+B;AAQnE,MAAM,uBAAuB;AAAA,EAC3B;AACF;AAGO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AACF,GAAwD;AACtD,QAAM,QAAQ,QAAQ,OAAO,EAAE,SAAS,SAAS,IAAI,CAAC,SAAS,QAAQ,CAAC;AACxE,SACE,oBAAC,qBAAqB,UAArB,EAA8B,OAC5B,UACH;AAEJ;AAEA,SAAS,wBAAwB,MAAyC;AACxE,QAAM,MAAM,WAAW,oBAAoB;AAC3C,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,GAAG,IAAI,8CAA8C;AAAA,EACvE;AACA,SAAO;AACT;AAGO,SAAS,mBAAuC;AACrD,SAAO,wBAAwB,kBAAkB,EAAE;AACrD;AAEO,SAAS,aAAqB;AACnC,SAAO,wBAAwB,YAAY,EAAE;AAC/C;","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { jsx } from "react/jsx-runtime";
|
|
2
|
+
const VAR_NAME = /^--[a-zA-Z0-9-]+$/;
|
|
3
|
+
const UNSAFE_VALUE = /[<>{};\\\r\n]/;
|
|
4
|
+
function themeStyleCss(vars) {
|
|
5
|
+
if (!vars) return null;
|
|
6
|
+
const declarations = Object.entries(vars).filter(
|
|
7
|
+
([name, value]) => VAR_NAME.test(name) && typeof value === "string" && value.trim() !== "" && !UNSAFE_VALUE.test(value)
|
|
8
|
+
).map(([name, value]) => `${name}:${value.trim()}`);
|
|
9
|
+
return declarations.length ? `:root{${declarations.join(";")}}` : null;
|
|
10
|
+
}
|
|
11
|
+
function ThemeStyle({
|
|
12
|
+
vars
|
|
13
|
+
}) {
|
|
14
|
+
const css = themeStyleCss(vars);
|
|
15
|
+
return css ? /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: css } }) : null;
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
ThemeStyle,
|
|
19
|
+
themeStyleCss
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=style.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/theme/style.tsx"],"sourcesContent":["const VAR_NAME = /^--[a-zA-Z0-9-]+$/;\n/** Anything that could end the declaration, the rule or the <style> tag. */\nconst UNSAFE_VALUE = /[<>{};\\\\\\r\\n]/;\n\n/** A `:root{…}` rule from a theme's custom properties; null when empty. */\nexport function themeStyleCss(\n vars: Record<string, string> | null | undefined\n): string | null {\n if (!vars) return null;\n const declarations = Object.entries(vars)\n .filter(\n ([name, value]) =>\n VAR_NAME.test(name) &&\n typeof value === \"string\" &&\n value.trim() !== \"\" &&\n !UNSAFE_VALUE.test(value)\n )\n .map(([name, value]) => `${name}:${value.trim()}`);\n return declarations.length ? `:root{${declarations.join(\";\")}}` : null;\n}\n\nexport function ThemeStyle({\n vars,\n}: {\n vars: Record<string, string> | null | undefined;\n}) {\n const css = themeStyleCss(vars);\n return css ? <style dangerouslySetInnerHTML={{ __html: css }} /> : null;\n}\n"],"mappings":"AA2Be;AA3Bf,MAAM,WAAW;AAEjB,MAAM,eAAe;AAGd,SAAS,cACd,MACe;AACf,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,eAAe,OAAO,QAAQ,IAAI,EACrC;AAAA,IACC,CAAC,CAAC,MAAM,KAAK,MACX,SAAS,KAAK,IAAI,KAClB,OAAO,UAAU,YACjB,MAAM,KAAK,MAAM,MACjB,CAAC,aAAa,KAAK,KAAK;AAAA,EAC5B,EACC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,MAAM,KAAK,CAAC,EAAE;AACnD,SAAO,aAAa,SAAS,SAAS,aAAa,KAAK,GAAG,CAAC,MAAM;AACpE;AAEO,SAAS,WAAW;AAAA,EACzB;AACF,GAEG;AACD,QAAM,MAAM,cAAc,IAAI;AAC9B,SAAO,MAAM,oBAAC,WAAM,yBAAyB,EAAE,QAAQ,IAAI,GAAG,IAAK;AACrE;","names":[]}
|
package/dist/theme.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
import { ThemeSchema, StoreConfigurationInfo, Banner, ThemeSettingsOf } from '@ecomweb/sdk';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The theme contract (spec: schema-driven themes §5.2). A theme declares its
|
|
6
|
+
* settings with `defineSchema` and fills the slots the shared routes render.
|
|
7
|
+
* Routes load data through the kit and pass it in: a theme is presentation.
|
|
8
|
+
*/
|
|
9
|
+
declare function defineSchema<const S extends ThemeSchema>(schema: S): S;
|
|
10
|
+
interface ThemeInfo {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
version: string;
|
|
14
|
+
author: string;
|
|
15
|
+
}
|
|
16
|
+
/** A slot may be a server component (async) or a plain one. */
|
|
17
|
+
type ThemeSlot<P> = (props: P) => ReactNode | Promise<ReactNode>;
|
|
18
|
+
interface ThemeSlotProps<V> {
|
|
19
|
+
store: StoreConfigurationInfo;
|
|
20
|
+
storeRef: string;
|
|
21
|
+
settings: V;
|
|
22
|
+
}
|
|
23
|
+
interface LayoutSlotProps<V> extends ThemeSlotProps<V> {
|
|
24
|
+
children: ReactNode;
|
|
25
|
+
}
|
|
26
|
+
interface HomePageSlotProps<V> extends ThemeSlotProps<V> {
|
|
27
|
+
banners: Banner[];
|
|
28
|
+
}
|
|
29
|
+
interface ThemeComponents<V> {
|
|
30
|
+
Layout?: ThemeSlot<LayoutSlotProps<V>>;
|
|
31
|
+
HomePage?: ThemeSlot<HomePageSlotProps<V>>;
|
|
32
|
+
}
|
|
33
|
+
type ThemeSlotName = keyof ThemeComponents<unknown>;
|
|
34
|
+
interface ThemeDefinition<S extends ThemeSchema = ThemeSchema> {
|
|
35
|
+
info: ThemeInfo;
|
|
36
|
+
schema: S;
|
|
37
|
+
components: ThemeComponents<ThemeSettingsOf<S>>;
|
|
38
|
+
/** CSS custom properties for :root, from the resolved settings. */
|
|
39
|
+
styles?: (settings: ThemeSettingsOf<S>) => Record<string, string>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A theme of unknown schema, as the registry holds it. Its slots are called
|
|
43
|
+
* with settings resolved against its own schema.
|
|
44
|
+
*/
|
|
45
|
+
interface AnyThemeDefinition {
|
|
46
|
+
info: ThemeInfo;
|
|
47
|
+
schema: ThemeSchema;
|
|
48
|
+
components: ThemeComponents<any>;
|
|
49
|
+
styles?: (settings: any) => Record<string, string>;
|
|
50
|
+
}
|
|
51
|
+
declare function defineTheme<const S extends ThemeSchema>(theme: ThemeDefinition<S>): ThemeDefinition<S>;
|
|
52
|
+
|
|
53
|
+
export { type AnyThemeDefinition, type HomePageSlotProps, type LayoutSlotProps, type ThemeComponents, type ThemeDefinition, type ThemeInfo, type ThemeSlot, type ThemeSlotName, type ThemeSlotProps, defineSchema, defineTheme };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecomweb/storefront-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -28,6 +28,10 @@
|
|
|
28
28
|
"./config": {
|
|
29
29
|
"types": "./dist/config.d.ts",
|
|
30
30
|
"import": "./dist/config.js"
|
|
31
|
+
},
|
|
32
|
+
"./theme": {
|
|
33
|
+
"types": "./dist/theme.d.ts",
|
|
34
|
+
"import": "./dist/theme/index.js"
|
|
31
35
|
}
|
|
32
36
|
},
|
|
33
37
|
"publishConfig": {
|
|
@@ -43,7 +47,7 @@
|
|
|
43
47
|
"currency.js": "^2.0.4",
|
|
44
48
|
"server-only": "^0.0.1",
|
|
45
49
|
"zod": "^4.1.12",
|
|
46
|
-
"@ecomweb/sdk": "^0.
|
|
50
|
+
"@ecomweb/sdk": "^0.4.0"
|
|
47
51
|
},
|
|
48
52
|
"peerDependencies": {
|
|
49
53
|
"next": ">=16",
|
|
@@ -18,9 +18,9 @@ declare const publicConfigSchema: z.ZodObject<{
|
|
|
18
18
|
primaryMenuRef: z.ZodString;
|
|
19
19
|
logLevel: z.ZodOptional<z.ZodEnum<{
|
|
20
20
|
error: "error";
|
|
21
|
+
info: "info";
|
|
21
22
|
silent: "silent";
|
|
22
23
|
warn: "warn";
|
|
23
|
-
info: "info";
|
|
24
24
|
debug: "debug";
|
|
25
25
|
}>>;
|
|
26
26
|
webVitalsSampleRate: z.ZodNumber;
|
|
@@ -34,9 +34,9 @@ declare const serverConfigSchema: z.ZodObject<{
|
|
|
34
34
|
googleVerification: z.ZodOptional<z.ZodString>;
|
|
35
35
|
logLevel: z.ZodOptional<z.ZodEnum<{
|
|
36
36
|
error: "error";
|
|
37
|
+
info: "info";
|
|
37
38
|
silent: "silent";
|
|
38
39
|
warn: "warn";
|
|
39
|
-
info: "info";
|
|
40
40
|
debug: "debug";
|
|
41
41
|
}>>;
|
|
42
42
|
clientIpHeader: z.ZodEnum<{
|